w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How to deploy my spray API into production?
You should build a jar with the plugin sbt-assembly addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.9.0") Then you can run the jar in production with java -jar If you give version number to your project, this is a rather classic process. Hope it helps.

Categories : Scala

Mapping Spray Parameters
I am new to Scala/Akka etc and spent a bit of time stuck on a parameter mapping problem earlier this week. I will share what I have which is working and perhaps it can guide you down the correct path. By no-way is this telling you why Scala is choking on that symbol, but hopefully is helpful in some way. My GET directive looks like this: get { parameters('filter, 'sort ?, 'skip ?, 'take ?).as(Search) { model => complete { (account ? UserSearchReq(model)).mapTo[SearchResult[User]] } } } ~ And my search model looks like this: case class Search(filter: String, sort: Option[String], skip: Option[Int], take: Option[Int]) As you can see, the filter is required, but the remaining parameters are optional. I have not specified the type, but everything works just fine. Best of luck.

Categories : Scala

How can I deconstruct a Spray API HTTPResponse?
The main issue I see with your code is that you are expecting mapTo to automatically unmarshall the http response body into your case class structure. The mapTo method belongs to the Future class and has no idea about json unmarshalling. You use mapTo within an Akka request (which ? is doing under the hood) to basically "cast" a Future[Any] (which is the default response type from ?) into the type that will actually be returned. This has nothing to do with json unmarshalling. I believe in order to achieve what you want, you should create a pipeline for spray that will both send the request and unmarshall the response. The documentation showing examples of that are here. I think for your example, it would look something like this (code may not be 100% right, just trying to show genera

Categories : Scala

Sending post with json using spray?
Sorry, but you question is a bit cumbersome, for me at least. If you want to make a POST request in Spray with some Json as HttpEntity, then you should try to do it with Spray-Clients pipelining, it's drop dead simple. You need to create a simple pipe: val pipe: HttpRequest => Future[HttpResponse] = sendReceive and then build a request: import spray.json.SprayJsonSupport._ pipe(Post("/api/1.0/users/ping", """{ "key"="whatever" }""".asJson)) This will return you a Future with HttpResponse, if you want some specific result, let's say, for example, some confirmation code, then add unmarshall step to your pipe: val pipe: HttpRequest => Future[ConfCode] = sendReceive ~> unmarshal[ConfCode]

Categories : Scala

Spray Client Post Multipart
@grandes Thanks for responding. I used the newman rest client library (https://github.com/stackmob/newman) to send http requests, but had to create the MultipartFormData manually and it worked. This will be fixed in newman in the near future. Here's the link that I used to manually build the multipart form data: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2

Categories : Scala

Sending a post request in spray
Here is an example. There is going to be a small amount of akka code but as I mentioned in my comment, it's necessary for spray: import spray.httpx.RequestBuilding._ import spray.http._ import HttpMethods._ import HttpHeaders._ import MediaTypes._ import spray.json._ import DefaultJsonProtocol._ import spray.httpx.SprayJsonSupport._ import akka.actor.ActorSystem import spray.io.IOExtension import akka.actor.Props import spray.can.client.HttpClient import spray.client.HttpConduit import scala.concurrent.Future import scala.util.Failure import scala.util.Success case class MyObj(str:String, i:Int) object SprayExample { implicit val myObjFormat = jsonFormat2(MyObj) def main(args: Array[String]) { import concurrent.ExecutionContext.Implicits._ val obj = MyObj("hello", 1)

Categories : Json

spray-json and list marshalling
You also need to import the format you defined on the route scope: import JollyJsonProtocol._ get { complete { List(new ElementResponse(...), new ElementResponse(...)) } }

Categories : Scala

Scala parameters pattern (Spray routing example)
Why don't you look into source? As for me, it could be implemented as follows method path takes arbitrary type parameter, some pattern-object of that type and a function from that type: def path[T](pattern:Pattern[T])(function:Function[T, `some other type like unit or any`]) the pattern is constructed with two tricks. The String is either "pimped" to have method / or has an implicit convertion to Pattern[Nothing] the Pattern[T] has method / that constructs another pattern with some new type. The method takes single argument (some ancestor of Segment). I guess — Pattern[T2]: trait Pattern[T] { /// def `/`[T2](otherPattern:Pattern[T2]):Pattern[(T,T2)] } So the first argument of path allows to determine the constructed type of pattern as being the pair. Thus we get prop

Categories : Scala

How do I turn all rejections into custom json in spray?
If you just want to turn all of the rejections into your custom json format, you can create a rejection handler. For example, I'll put this in my ServiceActor and do the following: class ApiServiceActor extends Actor with HttpServiceActor with ApiServices { def jsonify(response: HttpResponse): HttpResponse = { response.withEntity(HttpBody(ContentType.`application/json`, JSONObject(Map( "details" -> response.entity.asString.toJson, "errorType" -> ApiErrorType.Unknown.toJson )).toString())) } implicit val apiRejectionHandler = RejectionHandler { case rejections => mapHttpResponse(jsonify) { RejectionHandler.Default(rejections) } } def receive = runRoute { yourRoute ~ yourOtherRoute ~ someOtherRoute } }

Categories : Json

Spray HttpClient Synchronous/Blocking Call
Doesn't the spray HTTP Client just return a scala Future? If so, then you should be able to just do: import scala.concurrent._ import duration._ val fut = ... //call spray here val result = Await.result(fut, 5 seconds) This will block on the future for up to 5 seconds waiting for it to be completed. If it times out, an exception will be thrown instead of getting a result.

Categories : Scala

Spray io - unable to resolve an error about dependencies in sbt
There is no version 1.0 of spray yet, according to the docs (and browsing the repo): see spray - Current Versions. The latest seems to be either 1.0-M7 for scala 2.9.2 or 1.1-M7 for scala 2.10.0-RC5.

Categories : Scala

How do I make sure the path in a Scala Spray URI does not have a trailing slash?
There are two directives in Spray-Routing toolkit in FileAndResourceDirectives module: stripLeadingSlash and withTrailingSlash, both returns boolean. Example from my project: lazy val staticPath = staticPrefixes & cache(simpleRouteCache) & encodeResponse(Gzip) & extract(ctx => !withTrailingSlash(ctx.request.uri.path))

Categories : Scala

sbt publish spray example apps to local maven repository
In the build publishing is purposely disabled for examples in this line (same file): lazy val exampleSettings = basicSettings ++ noPublishing Try removing ++ noPublishing.

Categories : Scala

spray.io http server inside Play2 application context
I can say that Spray actually is the fastest JVM-based toolkit for web-based development, you can check out the latest benchmarks on the official blog. As for the question. If you want to write your own implementation for a little HTTP server then you should check spray-can http based api, spray-io is just a layer between Akka IO and Java NIO. I'm not very good at Play, but as a way i would sugest to create a multi-build sbt config or separate project with Spray http server and connect them through REST api. Architecture would be pretty simple cause it's based on Akka actors in the simplest case would look like a bunch of cases in the receive method: def receive = { case HttpRequest(GET, Uri.Path("/ping"), _, _, _) => sender ! HttpResponse(entity = "PONG") } On the Play side

Categories : Scala

Spray client marshalling of custom case class to JSON
Ok, I figured this out. I needed to add this import to support json marshalling: import spray.httpx.SprayJsonSupport._ After that marshalling function would be: implicit def StartObjMarshaller[T](implicit writer: RootJsonWriter[T], printer: JsonPrinter = PrettyPrinter) = Marshaller.delegate[T, String](ContentTypes.`application/json`) { value ⇒ val json = writer.write(value) printer(json) }

Categories : Json

spray-json cannot marshal Map[String,String]
Someone on the spray mailing list pointed out that the Map being created was a mutable one, spray-json won't marshal that. I changed it to be scala.collection.immutable.Map and also added the following imports: import spray.httpx.SprayJsonSupport._ import spray.json.DefaultJsonProtocol._ And now everything works great.

Categories : Scala

Understanding 'try' : C++
Here's the workflow of your program in pseudocode: { //outer try create e(5); { //inner try create e(7); failed create e(-8);//exception here throw; delete e(7);//-> 7# } { //catch in inner try; cout &&&;//-> 2&&&5 throw e; // throw sliced copy of original exception } delete e(5);//-> 5# } { //catch in outer try cout ^^^^;//-> 3^^^^^ St9exception (the last thrown is pure std::exception) throw e; // throw another copy, no more slicing as it's already exception } program termination because of uncaught exception; //-> std::exception: St9exception //-> Aborted. //return 0; was never reached

Categories : C++

Need help understanding better RNG
Say you want to generate random integer in the range [a, b). This can be accomplished by generating random integer in the range [0, b - a) and adding a: random_integer = a + rand(0, b - a) We can generate random integers in the range [0, RAND_MAX] using the ordinary rand(). Now, we need to scale this interval to fit [0, r), r = b - a. Since RAND_MAX is the maximal value returned by rand(), rand() / (MAX_RAND + 1.0) is in [0, 1). So, r * rand() / (MAX_RAND + 1.0) is in [0, r).

Categories : C++

CTE understanding
It sounds like you just want a conditional SUM(), which doesn't require an extra JOIN to the cte: SELECT psp.Id, p.Firstname + ' '+ p.Surname, rt.Description, psp.JoinSprintDate, psp.LeaveSprintDate, psp.AssignedProductiveHours, psp.AssignedHours, SUM(cteTotal.AssignedProductiveHours) AS ProdHrs SUM(CASE WHEN DateValue >= GetUTCDate() THEN cteTotal.AssignedProductiveHours ELSE 0 END) AS RemainingProductiveHours

Categories : SQL

Understanding web.xml
Have you written a JSP or a servlet? I am a little bit confused If you are using a JSP, then the servlet tag should be like <servlet> <description></description> <display-name>WelcomePage</display-name> <servlet-name>WelcomePage</servlet-name> <jsp-file>/WelcomePage.jsp</jsp-file> </servlet> If you are using servlet , then your tag is fine. In case of url-pattern, are you sure you have not written any annotation for the WelcomPage servlet class? If you are using Tomcat 7 or any java EE 6 container, then creating a new servlet through eclipse will create a default @WebServlet annotation and add to the servlet as follows. @WebServlet("/WelcomePage") public class WelcomePage extends HttpServlet {} This means that your url p

Categories : Jsp

Understanding ... RewriteCond foo#%{ENV:bar} ^([^#]+)#1$
The clever bit here is that 1 lets you reference a capture group from earlier in your regex. ^ - from the beginning of the string you are checking (in this case foo#%{ENV:bar}) ( - start capture group [^#]+ - 1 or more characters that are not a # ) - end capture group # - the character # 1 - the capture group from line 2-3 $ - the end of the string. Update The issue is that the CondPattern part of RewriteCond does not evaluate environment variables, and it must be a perl compatible regular expression, or a string.

Categories : Htaccess

Understanding this 16-bit PRNG
The variables x and y are not truly "local" to the function in the sense that you imply. They are declared as static which means while their scope is local to the function (they cannot be accessed by name from outside), their lifetime is that of the entire program. So they will retain their values between calls, which means two things: x and y are in fact the PRNG state. The function is not thread-safe.

Categories : C

Understanding Asp.net MVC Architecture
AFAIK, in MVC architecture, Model is an Object which will be used to pass data between controller to view and vice-versa. Hence, if a Model is changed by controller then, the view when it is to be rendered to user gets the data from Model.

Categories : Asp Net

understanding setTimeout()
Make it easier for yourself and define your functions ahead of time and in a way that saves you the trouble of scope and closure var next = function () {return c.next();}, prev = function () {return c.prev();}, noop = function () {}; this.timer = window.setTimeout( (a === 0.5 ? next : a === 0.6 ? prev : noop), 500 ); Now If you want to debug a function, you can debug it separately to setTimeout. It's clear which function is being passed into setTimeout. Edit Also note how I'm not invoking the functions as they're passed as the argument; when one uses setTimeout it is because they want something invoked later, not immediately.

Categories : Javascript

Understanding UpdatePanels
The issue actually isn't with the UpdatePanel, but with ASP.NET. ASP.NET web forms uses a control hierarchy for the entire page, and you are adding the controls to the hierarchy "dynamically". Since you are doing it that way, ASP.NET requires you add the control back into the control hierarchy on every postback to the server. The UpdatePanel is a way to post back to the server, and therefore you must re-add the old user controls and new ones to that hierarchy. Essentially the UpdatePanel was added to make AJAX easy, but you still have to work within the rules of ASP.NET.

Categories : Asp Net

Understanding AngularJS ng-src
Put the whole path inside the $scope variable. That way ng-src will wait until you provide it with the fully resolved path to the image: <div ng-controller="MyCtrl"> <img ng-src="{{ path }}" /> </div> function MyCtrl($scope, $timeout) { var path = 'https://si0.twimg.com/profile_images/'; $timeout(function () { $scope.path = path + '2149314222/square.png'; }, 1000); }; FIDDLE

Categories : Angularjs

Understanding classes?
You're using static variables with an instance. there is only ever 1 static variable. So you should either use it statically like so Report.KwotaZ[Report.IlOperacji] = 213.3; or define them as instance variables like so(without the static keyword) public double[] KwotaZ = new double[10]; public int IlOperacji = 0;

Categories : C#

Need help understanding C code
The stage 2 example is very interesting because it is an extra level of indirection with a self replicating program. What he means is that since this compiler code is written in C it is completely portable because it detects the presence of a literal and returns the character code for without ever knowing what that actual character code is since the compiler was written in C and compiled for the system. The paper goes on to show you very interesting trojan horse with the compiler. If you use this same technique to make the compiler insert a bug into any program, then remove move the bug from the source code, the compiler will compile the bug into the supposedly bug free compiler. It is a bit confusing but essentially it is about multiple levels of indirection.

Categories : C

Understanding pipes
The last child process (i == N - 1) reads cev[N - 1][0] which is past the end of cev. Similarly process N - 2 writes to cev[N - 1][1] which is also past the end. You need to offset all of the pipe indices by -1: if(i>0) { read(cev[i-1][READ],&a,sizeof(int)); a = f(a); // calculate next element } printf("%d ",a); fflush(stdout); if(i!=N-1) write(cev[i][WRITE],&a,sizeof(int));

Categories : C

Understanding Utl_file
Answers on your questions: 1) Following code creates link from Oracle internally defined directory (can see them by selecting data from DBA_DIRECTORIES) to file system directory. CREATE OR REPLACE DIRECTORY NEWFILE_DIRECTORY AS '/xxx/xxx/xxx' If path '/xxx/xxx/xxx' already exists in file system, then this will be correct way. 2) If I understand you correctly, then you must check that in NEWFILE_DIRECTORY exists file with current date in it's name. It can be done with following function: FUNCTION check_if_file_exists (p_file_name IN VARCHAR2 ,p_file_dir IN VARCHAR2) RETURN BOOLEAN IS v_file utl_file.file_type; BEGIN v_file := utl_file.fopen(p_file_dir, p_file_name, 'R'); IF utl_file.is_open(v_file) THEN RETURN TRUE; ELSE RETURN FALSE; END IF; EXCEPTION WHEN

Categories : SQL

Understanding .ear packaging
You can remove all maven meta-data from META-INF directory (like pom.xml and pom.properties). The main file in *.EAR (Enterprise archive) is application.xml (application server uses this file during deployment). Maven generates appication.xml file with maven-ear-plugin. So, all required data in *.EAR/META-INF: /META-INF/application.xml /META-INF/MANIFEST.MF all other data you can remove

Categories : Maven

need help understanding the C++ code
In fact, it does compile. You can also call one of these functions, e.g. the following prints +: template<int I> void f(int (&)[24/(4-I)]) { std::cout << "-" << std::endl; } template<int I> void f(int (&)[24/(4+I)]) { std::cout << "+" << std::endl; } int main() { int a[3]; f <4>(a); } Anyhow, both template functions f expect a reference to an int array, whose length depends on template parameter I. For instance, I picked a[3] because 24/(4+I) = 24/8 = 3 for I=4. The function is not called by &f<4>, but only instantiated by taking its address (which actually issues a warning for the unused result). I guess the book assumes the code won't compile due to the division by zero caused by attempting to instantiate the first

Categories : C++

Understanding CMIS
CMIS aims at becoming the standard API for B2B content integration. As such, it describes an interface that a CMS must expose, as a REST or SOAP set of endpoints, to be compliant to the spec. This also means that implementing a repository is completely out of scope for CMIS itself, since it's meant to hide all implementation details behind a standard interface. The easiest way to get started with a CMIS compliant server would be to use the Java SPIs provided by the Chemistry project, which basically implement the protocol itself and ask you to provide concrete implementations for the persistency and business logic layers. I'm not into .NET and can't advise you there. Bottom line is, you can choose every single detail you want when implementing your CMS, and find the proper mapping to CMI

Categories : Misc

Understanding ASP.NET C# libraries
Just to clarify: Windows Phone 8 does not require Portable Class Libraries - you can build a class library that targets the Windows Phone platform directly. Portable Class Libraries are useful when you want to build a library that targets multiple platforms, for example: The second of the links provided by @SLaks points to the Json.NET library which is now available as a Portable Class Library - most conveniently as a Nuget package in the latest build: http://james.newtonking.com/archive/2012/10/07/json-net-4-5-release-10-portable-class-library-on-nuget.aspx. If you build your own Portable Class Library, you can reference the Json.NET Portable Class Library to enable Json Serialization and Deserialization.

Categories : C#

Understanding ConditionalWeakTable
One advantage to the first approach is that you can cache the instances of OtherClass. For example, class ClassA { static readonly ConditionalWeakTable<ClassA, OtherClass> OtherClassTable = new ConditionalWeakTable<ClassA, OtherClass>(); public void Attach(OtherClass otherClass) { OtherClassTable.Add(this, otherClass); } public bool Get(out OtherClass otherClass) { return OtherClassTable.TryGetValue(this, out otherClass); } } Then, you can attach an instance of OtherClass to an instance of ClassA. The instance of OtherClass will be kept in memory as long as the instance of ClassA to which it is attached is kept alive.

Categories : Dotnet

Understanding MVC design in iOS
Let me clarify all your doubts one by one Question : Let's say i have a simple class which contains an NSMutableArray of NSString* so this is my MODEL. Yes? Answer : Yes it is model class because it will be serving only a single purpose in the world that is "handling data" Question : Let's say i wanted to write a method which sorted these names alphabetically. Should this method be a method in the model, or done separately in a data controller class? To me, it would make more sense to have this method in the model. So the model does the actual sorting, and the controller is the place where the sorting is initialised? Answer : This method should be in view, because it is just sorting the data according to your needs, someday in future you might need this data sorted in some other way.

Categories : IOS

Understanding unsigned 0 in C
In: void show_unsigned(short x) { show_bytes((byte_pointer) &x, sizeof(unsigned)); } You declared the argument short x which is smaller than int x so you ignored some of the 00 and your print function is displaying adjacent garbage.

Categories : C

Need help understanding while loops
Your code : #include <stdio.h> #include<ctype.h> int main() { int c;//getchar() returns integer int x; printf("Num here: "); x=0; //As @Jonathan Leffler suggested , //usage of while loop like this is very helpful the moment you press Enter loop breaks. while (isdigit(c = getchar())) //isdigit is a function from ctype.h checks for Entered character is digit or not x = x*10 + c - 48; //here '0'==48 printf("%d",x); } when you enter 42 loop rotates two times for c==4 and c==2 c==4 x=0*10+'4'-48 //here '4'==52 ==> x=0+52-48 ==>x=4 c==2 x=4*10+'2'-48 //here '2'==50 ==> x=40+50-48 ==>x=42 to add ones digits to tens and then hundreds ... if you want to add digits in input number use this below whi

Categories : C

Understanding of MVC ViewModel
When you have dozens of distinct values to pass to a view, the same flexibility that allows you to quickly add a new entry, or rename an existing one, becomes your worst enemy .You are left on your own to track item names and values; you get no help from Microsoft IntelliSense and compilers . The only proven way to deal with complexity in software is through appropriate design. So defining an object model for each view helps you track what that view really needs. I suggest you define a view-model class for each view you add to the application. -- "Programming Microsoft ASP.NET MVC" by Dino Esposito A simple ViewModel might be something like this public class FooViewModel { [Required] public SelectList BarLov1 { get; set; } public SelectList BarLov2 { get; se

Categories : Asp Net Mvc

Understanding the dlm package in r
To the first question: I think dlmModSeas(12) is correct for monthly data. And if you execute in R the command: dlmModPoly() + dlmModSeas(12) and look at the matrix W you see, that still only the second and the third diagonal elements are different from zero. I suppose the diag(W(dlmGas))[2] refers to the system noise variance of the trend component (dlmModPoly()) and diag(W(dlmGas))[3] to the system noise variance of the seasonal component (dlmModSeas(12)) So, as I understand it, increasing the number of seasons does not increase the diagonal elements of W to be estimated.

Categories : R



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.