_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d8001
train
Not that I'm aware of. You could always make it a ThreadLocal<Lazy<T>>, and set it to a new Lazy<T> whenever you wanted to reset it. If this is something you use more than once, you might want to consider encapsulating it as a ResettableThreadLocal<T> or something like that.
unknown
d8002
train
The problem is that params[:id] is not truthy, and therefore the @favor ||= Favor.find(params[:id]) if params[:id] statement is evaluating to nil
unknown
d8003
train
The Dockerfile has Windows \r\n line endings. Each \r that is printed causes the cursor to jump back to the beginning of the line and overwrite the previous setting. Debugging tip: Use declare -p var to see exactly what's in a variable.
unknown
d8004
train
You can use the dirname filter: {{ inventory_dir | dirname }} For reference, see Managing file names and path names in the docs. A: You can use {{playbook_dir}} for the absolute path to your current playbook run. For me thats the best way, because you normally know where your playbook is located. A: OK, a workaround is to use a separate task just for this: tasks: - name: Get source code absolute path shell: dirname '{{inventory_dir}}' register: dirname - name: Run docker containers include: tasks/dockerup.yml src_code={{dirname.stdout}} Thanks to udondan for hinting me on inventory_dir.
unknown
d8005
train
The complexity of LCA is O(h) where h is the height of the tree. The upper bound of the tree height is O(n), where n denotes the number of vertices/nodes in the tree. If your tree is balanced, (see AVL, red black tree) the height is order of log(n), consequently the total complexity of the algorithm is O(log(n)). A: The worst case for this algorithm would be if the nodes are sibling leave nodes. Node *LCA(Node *root, Node *p, Node *q) { for root call countMatchesPQ; for(root->left_or_right_child) call countMatchesPQ; /* Recursive call */ for(root->left_or_right_child->left_or_right_child) call countMatchesPQ; ... for(parent of leave nodes of p and q) call countMatchesPQ; } countMatchesPQ is called for height of tree times - 1. Lets call height of tree as h. Now check the complexity of helper function int countMatchesPQ(Node *root, Node *p, Node *q) { Search p and q in left sub tree recursively Search p and q in right sub tree recursively } So this is an extensive search and the final complexity is N where N is the number of nodes in the tree. Adding both observations, total complexity of the algorithm is O(h * N) If tree is balanced, h = log N (RB tree, treap etc) If tree is unbalanced, in worse case h may be up to N So complexity in terms of N can be given as For balanced binary tree: O(N logN) To be more precise, it is actual h(N + N/2 + N/4...) for balanced tree and hence should come 2hN For unbalanced binary tree: O(N2) To be more precise, it is actual h(N + N-1 + N-2...) for balanced tree and hence should come h x N x (N+1) / 2 So the worse case complexity is N2 Your algorithm doesn't use any memory. By using some memory to save path, you can improve your algorithm drastically.
unknown
d8006
train
* *Which SilverStripe version? *Is there anything in the logs (both nginx and PHP)? My slightly tuned nginx configuration for SilverStripe 3 looks like this: https://gist.github.com/xeraa/eab6bc9914e4b75009b8 — this might get you started
unknown
d8007
train
The Better option is that when you clicked on UITextField at that time also hide your UITextField so your UITextField is not mixup with your UITableView and when You remove/hide your UITableView at that time your hidden UITextField again unHide( give hidden = NO). Other wise there are many ways for solve your problem, i like this option so i suggest you. Other Option is. Take your UITableView in UIView, i hope that you have already know that UITableView have its own ScrollView so you not need to put in/over any scrollView. And when you click on UITextFiled that are in UIScrollView at that time you also put restriction that user can not do with UIScrollView and UITextField also (give userInteraction = NO). so also give (give userInteraction = YES) when your UITableView is hide. A: UserInteraction is right for but You know when we write this [self.view addsubview:Table_AdviseDoctor] then ....when we scroll already and then click on text field then my table open long below from required position then we write code UserInteraction.enable=No; then scroll not work this right but first scroll and then click on text filed then ..problem occur not right position .....
unknown
d8008
train
As mentioned in the FAQ it is possible to get access to the request object but it should be avoided because transport specific processing should be kept outside of services (for example, when using Feathers via websockets, there won't be a content type at all). Service call parameters (params) for HTTP calls can be set by using a custom Express middleware so you can add a params.contentType to every service call like this (or use it as a service specific middleware): app.use(function(req, res, next) { req.feathers.contentType = req.headers['content-type']; next(); });
unknown
d8009
train
Yes, all you need to do is just download your artifacts from JCenter. On a related note, I'd suggest doing it the other way around - publish to JCenter and sync to Central. It should be easier for you. I am with JFrog, the company behind Bintray and [artifactory], see my profile for details and links.
unknown
d8010
train
According to the documentation for isEditing Use the setEditing(_:animated:) method as an action method to animate the transition of this state if the view is already displayed. And from setEditing(_:animated:) Subclasses that use an edit-done button must override this method to change their view to an editable state if isEditing is true and a non-editable state if it is false. This method should invoke super’s implementation before updating its view. TL;DR You'll want to override setEditing(_:animated:) instead. A: It's for those who can't find any example how setEditing works. SWIFT 5 : override func setEditing(_ editing: Bool, animated: Bool) { if yourTableView.isEditing == true { yourTableView.isEditing = false //change back } else { yourTableView.isEditing = true // activate editing editButtonItem.isSelected = true // select edit button } }
unknown
d8011
train
This is one way to solve your problem: * *Wrap the property whose validation you want to extend in your viewmodel public string Epc { get { return _epc; } set { Animal.Epc = value; Set(() => Epc, ref _epc, value, false); } } *Add two custom validation rules to that property [CustomValidation(typeof(ViewModel), "AnimalEpcValidate")] [CustomValidation(typeof(ViewModel), "ExtendedEpcValidate")] *Add your extended validation code, that is not done by Animal itself, to ExtendedEpcValidate *Call the Animal.Epc validation and add the results to the Epc validation results in your viewmodel public static ValidationResult AnimalEpcValidate(object obj, ValidationContext context) { var aevm = context.ObjectInstance as ViewModel; // get errors from Animal validation var animalErrors = aevm.Animal.GetErrors("Epc")?.Cast<string>(); // add errors from Animal validation to your Epc validation results var error = animalErrors?.Aggregate(string.Empty, (current, animalError) => current + animalError); // return aggregated errors of Epc property return string.IsNullOrEmpty(error) ? ValidationResult.Success : new ValidationResult(error, new List<string> { "Epc" }); }
unknown
d8012
train
pseudocode: bool forwardsEqualBackwards(array a, int length, int indexToLookAt=0) { if (indexToLookAt >= length-indexToLookAt-1) return true; //reached end of recursion if (a[indexToLookAt] == a[length-indexToLookAt-1]) return forwardsEqualBackwards(a,length, indexToLookAt+1); //normal recursion here else return false; } forwardsEqualBackwards("",0); //returns true forwardsEqualBackwards("a",1); //returns true forwardsEqualBackwards("otto",4); //returns true forwardsEqualBackwards("otsto",5); //returns true forwardsEqualBackwards("otstou",5); //returns false A: bool method(int start, int end) { if(start<=end) { if(Array[start]!=array[end]) return false; return method(start+1, end-1) } return true; }
unknown
d8013
train
Your link could be like this person.php?id=1243 Where person.php is the page where you display the information about the Person with id = 1243 You can retrieve the id by using $id = $_GET['id'] and then use it on a mysql query: SELECT * from Person WHERE id = $id; // Don't forget to handle SQL injection And you're done. EDIT: For multiple fields The link person.php?id1=1243&id2=5678 Retrieve the value $id1 = $_GET['id1'] and $id2 = $_GET['id2'] MySQL: SELECT * from Person WHERE id IN($id1, $id2); EDIT2 : For a range of users The link person.php?startId=1&endId=5000 Retrieve the value $startId = $_GET['startId'] and $endId = $_GET['endId'] MySQL: SELECT * from Person WHERE id BETWEEN $startID AND $endId; ALTERNATIVE suggested by @PierreGranger Your link could be like this person.php?id[]=1243&id[]=5678 Where person.php is the page where you display the information about the Person with id = 1243 and id = 5678 You can retrieve the id by using $id = $_GET['id'][0] and then use it on a mysql query: if ( isset($_GET['id']) && is_array($_GET['id']) ) // Check if parameter is set { $ids = $_GET['id'] ; foreach ( $ids as $k => $v ) if ( ! preg_match('#^[0-9]+$#',$v) ) unset($ids[$k]) ; // Remove if parameters are not identifiers if ( sizeof($ids) > 0 ) // If there is still at least 1 id, do your job { $sql = ' SELECT * from Person WHERE id in (".implode('","',$ids).") ' ; $rq = mysql_query($sql) or die('SQL error') ; while ( $d = mysql_fetch_assoc($rq) ) { // Do your SQL request and build your table } } } Wich will result in : SELECT * from Person WHERE id in ("1234","5678") ; And you're done. A: Based on Akram response you can try this one. There is 2 cases : if you only have 4 or 5 particular ids, you can do this : page.php?id[]=1&id[]=2&id[]=9 And if you want to reach a range (id from 1 to 1000) : page.php?from=1&to=1000 unset($sql) ; if ( isset($_GET['id']) && is_array($_GET['id']) ) // Check if parameter is set { $ids = $_GET['id'] ; foreach ( $ids as $k => $v ) if ( ! preg_match('#^[0-9]+$#',$v) ) unset($ids[$k]) ; // Remove if parameters are not identifiers if ( sizeof($ids) > 0 ) // If there is still at least 1 id, do your job { $sql = ' SELECT * from Person WHERE id in ("'.implode('","',$ids).'") ' ; } } elseif ( isset($_GET['from']) && isset($_GET['to']) ) { if ( preg_match('#^[0-9]+$#',$_GET['from']) && preg_match('#^[0-9]+$#',$_GET['to']) ) { $sql = ' SELECT * from Person WHERE id between "'.$_GET['from'].'" and "'.$_GET['to'].'"' ; } } if ( isset($sql) ) { $rq = mysql_query($sql) or die('SQL error') ; while ( $d = mysql_fetch_assoc($rq) ) { // Do your SQL request and build your table } }
unknown
d8014
train
This is what I do when a user logged out. public function logout() { Auth::user()->tokens->each(function($token, $key) { $token->delete(); }); return response()->json('Successfully logged out'); } This code will remove each token the user generated. A: I think something like this can revoke the token: $this->user->token()->revoke() Based on this link. A: Laravel Sanctum documentation stated 3 different ways to revoke tokens. you can find it here. but for most cases we just revoke all user's tokens via: // Revoke all tokens... auth()->user()->tokens()->delete(); note: for some reason intelephense gives an error saying tokens() method not defined but the code works fine. Hirotaka Miyata found a workaround here. so the over all logout method can be something like this: public function logout() { //the comment below just to ignore intelephense(1013) annoying error. /** @var \App\Models\User $user **/ $user = Auth::user(); $user->tokens()->delete(); return [ 'message' => 'logged out' ]; } A: the best working solution is this public function logout(LogoutRequest $request): \Illuminate\Http\JsonResponse { if(!$user = User::where('uuid',$request->uuid)->first()) return $this->failResponse("User not found!", 401); try { $this->revokeTokens($user->tokens); return $this->successResponse([ ], HTTP_OK, 'Successfully Logout'); }catch (\Exception $exception) { ExceptionLog::exception($exception); return $this->failResponse($exception->getMessage()); } } public function revokeTokens($userTokens) { foreach($userTokens as $token) { $token->revoke(); } } A: public function __invoke(Request $request) { $request->user() ->tokens ->each(function ($token, $key) { $this->revokeAccessAndRefreshTokens($token->id); }); return response()->json('Logged out successfully', 200); } protected function revokeAccessAndRefreshTokens($tokenId) { $tokenRepository = app('Laravel\Passport\TokenRepository'); $refreshTokenRepository = app('Laravel\Passport\RefreshTokenRepository'); $tokenRepository->revokeAccessToken($tokenId); $refreshTokenRepository->revokeRefreshTokensByAccessTokenId($tokenId); }
unknown
d8015
train
I agree with you. The open-source OAuth support classes available for .NET apps are hard to understand, overly complicated (how many methods are exposed by DotNetOpenAuth?), poorly designed (look at the methods with 10 string parameters in the OAuthBase.cs module from that google link you provided - there's no state management at all), or otherwise unsatisfactory. It doesn't need to be this complicated. I'm not an expert on OAuth, but I have produced an OAuth client-side manager class, that I use successfully with Twitter and TwitPic. It's relatively simple to use. It's open source and available here: Oauth.cs For review, in OAuth 1.0a...kinda funny, there's a special name and it looks like a "standard" but as far as I know the only service that implements "OAuth 1.0a" is Twitter. I guess that's standard enough. ok, anyway in OAuth 1.0a, the way it works for desktop apps is this: * *You, the developer of the app, register the app and get a "consumer key" and "consumer secret". On Arstechnica, there's a well written analysis of why this model isn't the best, but as they say, it is what it is. *Your app runs. The first time it runs, it needs to get the user to explicitly grant approval for the app to make oauth-authenticated REST requests to Twitter and its sister services (like TwitPic). To do this you must go through an approval process, involving explicit approval by the user. This happens only the first time the app runs. Like this: * *request a "request token". Aka temporary token. *pop a web page, passing that request token as a query param. This web page presents UI to the user, asking "do you want to grant access to this app?" *the user logs in to the twitter web page, and grants or denies access. *the response html page appears. If the user has granted access, there's a PIN displayed in a 48-pt font *the user now needs to cut/paste that pin into a windows form box, and click "Next" or something similar. *the desktop app then does an oauth-authenticated request for an "Access token". Another REST request. *the desktop app receives the "access token" and "access secret". After the approval dance, the desktop app can just use the user-specific "access token" and "access secret" (along with the app-specific "consumer key" and "consumer secret") to do authenticated requests on behalf of the user to Twitter. These don't expire, although if the user de-authorizes the app, or if Twitter for some reason de-authorizes your app, or if you lose your access token and/or secret, you'd need to do the approval dance again. If you're not clever, the UI flow can sort of mirror the multi-step OAuth message flow. There is a better way. Use a WebBrowser control, and open the authorize web page within the desktop app. When the user clicks "Allow", grab the response text from that WebBrowser control, extract the PIN automatically, then get the access tokens. You send 5 or 6 HTTP requests but the user needs to see only a single Allow/Deny dialog. Simple. Like this: If you've got the UI sorted, the only challenge that remains is to produce oauth-signed requests. This trips up lots of people because the oauth signing requirements are sort of particular. That's what the simplified OAuth Manager class does. Example code to request a token: var oauth = new OAuth.Manager(); // the URL to obtain a temporary "request token" var rtUrl = "https://api.twitter.com/oauth/request_token"; oauth["consumer_key"] = MY_APP_SPECIFIC_KEY; oauth["consumer_secret"] = MY_APP_SPECIFIC_SECRET; oauth.AcquireRequestToken(rtUrl, "POST"); THAT'S IT. Simple. As you can see from the code, the way to get to oauth parameters is via a string-based indexer, something like a dictionary. The AcquireRequestToken method sends an oauth-signed request to the URL of the service that grants request tokens, aka temporary tokens. For Twitter, this URL is "https://api.twitter.com/oauth/request_token". The oauth spec says you need to pack up the set of oauth parameters (token, token_secret, nonce, timestamp, consumer_key, version, and callback), in a certain way (url-encoded and joined by ampersands), and in a lexicographically-sorted order, generate a signature on that result, then pack up those same parameters along with the signature, stored in the new oauth_signature parameter, in a different way (joined by commas). The OAuth manager class does this for you automatically. It generates nonces and timestamps and versions and signatures automatically - your app doesn't need to care or be aware of that stuff. Just set the oauth parameter values and make a simple method call. the manager class sends out the request and parses the response for you. Ok, then what? Once you get the request token, you pop the web browser UI in which the user will explicitly grant approval. If you do it right, you'll pop this in an embedded browser. For Twitter, the URL for this is "https://api.twitter.com/oauth/authorize?oauth_token=" with the oauth_token appended. Do this in code like so: var url = SERVICE_SPECIFIC_AUTHORIZE_URL_STUB + oauth["token"]; webBrowser1.Url = new Uri(url); (If you were doing this in an external browser you'd use System.Diagnostics.Process.Start(url).) Setting the Url property causes the WebBrowser control to navigate to that page automatically. When the user clicks the "Allow" button a new page will be loaded. It's an HTML form and it works the same as in a full browser. In your code, register a handler for the DocumentedCompleted event of the WebBrowser control, and in that handler, grab the pin: var divMarker = "<div id=\"oauth_pin\">"; // the div for twitter's oauth pin var index = webBrowser1.DocumentText.LastIndexOf(divMarker) + divMarker.Length; var snip = web1.DocumentText.Substring(index); var pin = RE.Regex.Replace(snip,"(?s)[^0-9]*([0-9]+).*", "$1").Trim(); That's a bit of HTML screen scraping. After grabbing the pin, you don't need the web browser any more, so: webBrowser1.Visible = false; // all done with the web UI ...and you might want to call Dispose() on it as well. The next step is getting the access token, by sending another HTTP message along with that pin. This is another signed oauth call, constructed with the oauth ordering and formatting I described above. But once again this is really simple with the OAuth.Manager class: oauth.AcquireAccessToken(URL_ACCESS_TOKEN, "POST", pin); For Twitter, that URL is "https://api.twitter.com/oauth/access_token". Now you have access tokens, and you can use them in signed HTTP requests. Like this: var authzHeader = oauth.GenerateAuthzHeader(url, "POST"); ...where url is the resource endpoint. To update the user's status, it would be "http://api.twitter.com/1/statuses/update.xml?status=Hello". Then set that string into the HTTP Header named Authorization. To interact with third-party services, like TwitPic, you need to construct a slightly different OAuth header, like this: var authzHeader = oauth.GenerateCredsHeader(URL_VERIFY_CREDS, "GET", AUTHENTICATION_REALM); For Twitter, the values for the verify creds url and realm are "https://api.twitter.com/1/account/verify_credentials.json", and "http://api.twitter.com/" respectively. ...and put that authorization string in an HTTP header called X-Verify-Credentials-Authorization. Then send that to your service, like TwitPic, along with whatever request you're sending. That's it. All together, the code to update twitter status might be something like this: // the URL to obtain a temporary "request token" var rtUrl = "https://api.twitter.com/oauth/request_token"; var oauth = new OAuth.Manager(); // The consumer_{key,secret} are obtained via registration oauth["consumer_key"] = "~~~CONSUMER_KEY~~~~"; oauth["consumer_secret"] = "~~~CONSUMER_SECRET~~~"; oauth.AcquireRequestToken(rtUrl, "POST"); var authzUrl = "https://api.twitter.com/oauth/authorize?oauth_token=" + oauth["token"]; // here, should use a WebBrowser control. System.Diagnostics.Process.Start(authzUrl); // example only! // instruct the user to type in the PIN from that browser window var pin = "..."; var atUrl = "https://api.twitter.com/oauth/access_token"; oauth.AcquireAccessToken(atUrl, "POST", pin); // now, update twitter status using that access token var appUrl = "http://api.twitter.com/1/statuses/update.xml?status=Hello"; var authzHeader = oauth.GenerateAuthzHeader(appUrl, "POST"); var request = (HttpWebRequest)WebRequest.Create(appUrl); request.Method = "POST"; request.PreAuthenticate = true; request.AllowWriteStreamBuffering = true; request.Headers.Add("Authorization", authzHeader); using (var response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode != HttpStatusCode.OK) MessageBox.Show("There's been a problem trying to tweet:" + Environment.NewLine + response.StatusDescription); } OAuth 1.0a is sort of complicated under the covers, but using it doesn't need to be. The OAuth.Manager handles the generation of outgoing oauth requests, and the receiving and processing of oauth content in the responses. When the Request_token request gives you an oauth_token, your app doesn't need to store it. The Oauth.Manager is smart enough to do that automatically. Likewise when the access_token request gets back an access token and secret, you don't need to explicitly store those. The OAuth.Manager handles that state for you. In subsequent runs, when you already have the access token and secret, you can instantiate the OAuth.Manager like this: var oauth = new OAuth.Manager(); oauth["consumer_key"] = CONSUMER_KEY; oauth["consumer_secret"] = CONSUMER_SECRET; oauth["token"] = your_stored_access_token; oauth["token_secret"] = your_stored_access_secret; ...and then generate authorization headers as above. // now, update twitter status using that access token var appUrl = "http://api.twitter.com/1/statuses/update.xml?status=Hello"; var authzHeader = oauth.GenerateAuthzHeader(appUrl, "POST"); var request = (HttpWebRequest)WebRequest.Create(appUrl); request.Method = "POST"; request.PreAuthenticate = true; request.AllowWriteStreamBuffering = true; request.Headers.Add("Authorization", authzHeader); using (var response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode != HttpStatusCode.OK) MessageBox.Show("There's been a problem trying to tweet:" + Environment.NewLine + response.StatusDescription); } You can download a DLL containing the OAuth.Manager class here. There is also a helpfile in that download. Or you can view the helpfile online. See an example of a Windows Form that uses this manager here. WORKING EXAMPLE Download a working example of a command-line tool that uses the class and technique described here:
unknown
d8016
train
You have to register ItemSelected event handler for you ListView. ListView listViewJson = new ListView(); listViewJson.HasUnevenRows = true; listViewJson.ItemSelected += listViewJson_ItemSelected; In Event Handler, you can get selected item. private void listViewJson_ItemSelected(object sender, SelectedItemChangedEventArgs e) { var item = e.SelectedItem; // Navigate to new page Navigation.PushAsync(new YOUR_PAGE(item)); } And you can develop UI as you want in you new page for displaying a joke. UPDATE You detail page should be like this. I prepared this very roughly. Please make necessary changes. namespace JokesListView { public class JokeDetail : ContentPage { private Joke jk; public JokeDetail(Joke j) { jk = j; Display(); } public void Display() { try { Label lblJoke = new Label(); lblJoke.LineBreakMode = LineBreakMode.WordWrap; lblJoke.Text = jk.joke; Content = lblJoke; } catch (Exception e) { throw e; } } }
unknown
d8017
train
I found it, added a onDialogOKPressed method to my MainActivity and put this inside the onClick of my dialog ((MainActivity)(MyAlertDialogFragment.this.getActivity())).onDialogOKPressed(); so now it looks like this MyDialogFragment ... @Override public Dialog onCreateDialog(Bundle savedInstanceState) { String title = getArguments().getString("title"); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity()); alertDialogBuilder.setTitle(title); alertDialogBuilder.setMessage("Are you sure?"); alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // on success ((MainActivity)(MyAlertDialogFragment.this.getActivity())).onDialogOKPressed(); } }); alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { getTargetFragment().onActivityResult(getTargetRequestCode(), 1, getActivity().getIntent()); dialog.dismiss(); } }); return alertDialogBuilder.create(); } MainActivity ... public void onDialogOKPressed () { // Stuff to do, dependent on requestCode and resultCode Toast.makeText(MainActivity.this, "OK pressed", Toast.LENGTH_SHORT).show(); }
unknown
d8018
train
I figured it out. My initial code was correct but because there was an issue when the backing array of the data table was being updated via push. I had to create a separate array with the empty objects and assign it to the backing array.
unknown
d8019
train
Look at this link, under the section "The ST monad": http://book.realworldhaskell.org/read/advanced-library-design-building-a-bloom-filter.html Back in the section called “Modifying array elements”, we mentioned that modifying an immutable array is prohibitively expensive, as it requires copying the entire array. Using a UArray does not change this, so what can we do to reduce the cost to bearable levels? In an imperative language, we would simply modify the elements of the array in place; this will be our approach in Haskell, too. Haskell provides a special monad, named ST, which lets us work safely with mutable state. Compared to the State monad, it has some powerful added capabilities. We can thaw an immutable array to give a mutable array; modify the mutable array in place; and freeze a new immutable array when we are done. ... The IO monad also provides these capabilities. The major difference between the two is that the ST monad is intentionally designed so that we can escape from it back into pure Haskell code. So should be possible to modify in-place, and it won't defeat the purpose of using Haskell after all. A: Yes, you would probably want to use the IO monad for mutable data. I don't believe the ST monad is a good fit for this problem space because the data updates are interleaved with actual IO actions (reading input streams). As you would need to perform the IO within ST by using unsafeIOToST, I find it preferable to just use IO directly. The other approach with ST is to continually thaw and freeze an array; this is messy because you need to guarantee that old copies of the data are never used. Although evidence shows that a pure solution (in the form of Data.Sequence.Seq) is often faster than using mutable data, given your requirement that data be pushed out to OpenGL, you'll possible get better performance from working with the array directly. I would use the functions from Data.Vector.Storable.Mutable (from the vector package), as then you have access to the ForeignPtr for export. You can look at arrows (Yampa) for one very common approach to event-driven code. Another area is Functional Reactivity (FRP). There are starting to be some reasonably mature libraries in this domain, such as Netwire or reactive-banana. I don't know if they'd provide adequate performance for your requirements though; I've mostly used them for gui-type programming.
unknown
d8020
train
You need INDIRECT: =SUMIF(INDIRECT("'"&E2&"'!G22:G70");'2018'!$B4;INDIRECT("'"&E2&"'!J22:J70")) Note that since the ranges are literal text strings, you don't need to make them absolute since they won't adjust if you copy/fill anyway.
unknown
d8021
train
Have you tried simply removing it? Map.MapElements.Remove(_line);
unknown
d8022
train
Use simply: if($.cookie("language")){} A: To see what the plugin is returning, do a console.log() call: console.log($.cookie("language")); This should tell you what is being returned from the plugin if you monitor your Inspector / Firebug console. I think you can get away with just doing if($.cookie("language")) but you'll have to test that. A: Line #90 in the source looks like that SHOULD be the result you want. Check for any errors and test what happens if the cookie is set. https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js
unknown
d8023
train
Can try with hook_file_presave(); https://drupal.stackexchange.com/questions/9744/how-do-i-change-the-uploaded-file-name-after-the-node-has-been-saved
unknown
d8024
train
To answer your question: This answer should help you. You should (!?) be able to use ./sql_exporter & to run the process in the background (when not using --stdin --tty). If that doesn't work, you can try nohup as described by the same answer. To recommend a better approach: Using kubectl exec is not a good way to program a Kubernetes cluster. kubectl exec is best used for debugging rather than deploying solutions to a cluster. I assume someone has created a Kubernetes Deployment (or similar) for Microsoft SQL Server. You now want to complement that Deployment with the exporter. You have options: * *Augment the existing Deployment and add the sql_exporter as a sidecar (another container) in the Pod that includes the Microsoft SQL Server container. The exporter accesses the SQL Server via localhost. This is a common pattern when deploying functionality that complements an application (e.g. logging, monitoring) *Create a new Deployment (or similar) for the sql_exporter and run it as a standalone Service. Configure it scrape one|more Microsoft SQL Server instances. Both these approaches: * *take more work but they're "more Kubernetes" solutions and provide better repeatability|auditability etc. *require that you create a container for sql_exporter (although I assume the exporter's authors already provide this).
unknown
d8025
train
try this one var db = await Db.create(MONGO_CONN_STRING); await db.open(); var coll = db.collection('reports'); await coll.insertOne({ "username": "Tom", "action": "test", "dateTime": "today", }).toList(); A: Are you using the latest version of the package? I think your problem is related to this issue in the GitHub Repo of the package but it is closed at Jul 25, 2015. A: The error is arising because you declared variables db and (collection name) outside the static connect() async function; declare them inside the function. var db = await Db.create(MONGO_CONN_STRING); await db.open(); var coll = db.collection('reports'); await coll.insertOne({ "username": "Tom", "action": "test", "dateTime": "today", }); static connect() async { var db = await Db.create(MONGO_CONN_STRING); await db.open(); var coll = db.collection('reports'); await coll.insertOne({ "username": "Tom", "action": "test", "dateTime": "today", }); }
unknown
d8026
train
This answer has been outdated by substantial changes in OP question I am quite sure there is no such feature in NHibernate, or any other ORM. By the way, what should yield updating Id 3 to Cat after having updated it to Dog? Id | Animal 1 | 2 | 3 | Cat If that means that Id 1&2 now have the empty string value, that will be an unique constraint violation too. If they have the null value, it depends then on the db engine being ANSI null compliant or not (null not considered equal to null). This is not the case of SQL Server, any version I know of, at least for the case of unique indexes. (I have not tested the unique constraint case.) Anyway, this kind of logic, updating a row resulting in an additional update on some other rows, has to be handled explicitly. You have many options for that: * *Before each assignment to the Animal property, query the db for finding if another one has that name and take appropriate action on that another one. Take care of flushing right after having handling this other one, for ensuring it get handled prior to the actual update of the first one. *Or inject an event or an interceptor in NHibernate for catching any update on any entities, and add there your check for duplicates. Stack Overflow has examples of NHibernate events or interceptors, like this one. But your case will probably bit a bit tough, since flushing some other changes while already flushing a session will probably cause troubles. You may have to directly tinker with the sql statement with IInterceptor.OnPrepareStatement by example, for injecting your other update first in it. *Or handle that with some trigger in DB. *Or detect a failed flush due to an unique constraint, analyze it and take appropriate action. The third option is very likely easier and more robust than the others.
unknown
d8027
train
Every widget can only have one parent. So you have to create as many widgets as you have cells, like this: Label l1=new Label("USER") ; tweetFlexTable.setWidget(0,0,l1); Label l2=new Label("dunno") ; tweetFlexTable.setWidget(0,1,l2);
unknown
d8028
train
If you look at what you can apply an attribute to, you'll notice you can only apply it to Assembly, Class, Constructor, Delegate, Enum, Event, Field, GenericParameter, Interface, Method, Module, Parameter, Property, ReturnValue, or Struct (source). You can't apply attributes to individual values so you will have to store additional data, you could make a small class, something like: public class Operation { public string Description {get;set;} public Func<int, int, int> Func {get;set;} } And then use it in your dictionary like: dict.Add("SUM", new Operation() { Description = "Adds numbers", Func = (a,b) => {return a+b;} });
unknown
d8029
train
I think you are trying to access hudson.model.build, but I believe that is a class and not an object. It is also not a property of the current object - WorkflowScript. So it simply does not exist. In a pipeline script you should have access to "currentBuild". Go to your.jenkins.server.url/pipeline-syntax/globals to see what global variables scripts run via that server can access. That same page should also show that you have access to a variable called "params" Perhaps what you are looking for is there? From your question, it is unclear what your end goal is. You already have access to VERSION as demonstrated by the echo statement. So why are you trying to get at it from a build object? You may get more help if you update to explain what the end goal is.
unknown
d8030
train
EDIT This is the second attempt. Earlier I understood you wanted to copy and paste the HTML as text but after your comments and edits to the question I now understand that you have some text that you format using HTML and you want to paste that text while retaining the formatting. More or less as shown below. This also illustrates how to wire it up in storyboard. Here is the code. #import "ViewController.h" #import <MobileCoreServices/UTCoreTypes.h> #import <WebKit/WebKit.h> @interface ViewController () @property (weak, nonatomic) IBOutlet UILabel * statusLabel; @property (weak, nonatomic) IBOutlet WKWebView * webView; @property (weak, nonatomic) IBOutlet UITextView * textView; @end @implementation ViewController #pragma mark - #pragma mark Actions - (IBAction)reloadButtonAction:(id)sender { [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.webfx.com/blog/images/assets/cdn.sixrevisions.com/0435-01_html5_download_attribute_demo/samp/htmldoc.html"]]]; } - (IBAction)copyButtonAction:(id)sender { if ( self.webView.loading ) { self.statusLabel.text = @"Loading"; } else { self.statusLabel.text = @"Copying ..."; [self.webView evaluateJavaScript:@"document.documentElement.outerHTML.toString()" completionHandler: ^ ( id content, NSError * error ) { if ( error ) { self.statusLabel.text = @"Error"; } else if ( [content isKindOfClass:NSString.class] ) { [UIPasteboard.generalPasteboard setData:[( NSString * ) content dataUsingEncoding:NSUTF8StringEncoding] forPasteboardType:( NSString * ) kUTTypeHTML]; self.statusLabel.text = @"Copied HTML"; } else { self.statusLabel.text = @"Unknown type"; } }]; } } - (IBAction)pasteButtonAction:(id)sender { if ( [UIPasteboard.generalPasteboard containsPasteboardTypes:@[( NSString * ) kUTTypeHTML]] ) { // Convert to attributed string NSError * cvtErr; NSData * data = [UIPasteboard.generalPasteboard dataForPasteboardType:( NSString * ) kUTTypeHTML]; NSAttributedString * attr = [[NSAttributedString alloc] initWithData:data options:@{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType } documentAttributes:NULL error: & cvtErr]; if ( cvtErr ) { self.statusLabel.text = @"Convert error"; } else if ( attr ) { self.statusLabel.text = @"Attributed"; self.textView.attributedText = attr; } else { self.statusLabel.text = @"Unable to decode"; } } else { NSString * content = UIPasteboard.generalPasteboard.string; if ( content ) { // Paste plain text self.textView.text = content; self.statusLabel.text = @"Pasted"; } else { self.statusLabel.text = @"No string content"; } } } @end The code is very similar to before. The problem is that HTML = plain text so to copy HTML and retain the style or formatting also depends on the destination app into which you paste it. That destination app needs to handle the HTML correctly for what you want to achieve. Anyhow, here are the changes from earlier. On the copy side: the text is now copied as HTML and not as a string. There is very little difference there except that now, unlike before, the string is converted to data and the type is marked as kUTTypeHTML. On the paste side: the real difference is here. If the pasteboard contains HTML then it is retrieved and formatted using an attributed string. It also works fine if you e.g. paste into Notes BTW. This illustrates the problem you are dealing with here. I could just as well have used the code I used earlier and everything would work but in stead of formatted HTML I would get the unformatted / source HTML. Here I assume that you are interested in fairly simple but formatted text. You did not mention text specifically and if you e.g. wanted to copy an HTML formatted table then my example is not adequate as I use a UITextView as destination. For more complex HTML I'd use a WKWebView as destination as well and set its HTML string to the pasted in HTML, but again, this shows how the destination app also needs to cooperate in handling the HTML correctly. Finally, looking at the updated answer and your code it is difficult to spot a difference, so I suspect your problem could be earlier with content itself in RCT_EXPORT_METHOD(setString:(NSString *)content) UPDATE I also looked at the git repository you mention. There I found the following RCT_EXPORT_METHOD(hasString:(RCTPromiseResolveBlock)resolve reject:(__unused RCTPromiseRejectBlock)reject) { BOOL stringPresent = YES; UIPasteboard *clipboard = [UIPasteboard generalPasteboard]; if (@available(iOS 10, *)) { stringPresent = clipboard.hasStrings; } else { NSString* stringInPasteboard = clipboard.string; stringPresent = [stringInPasteboard length] == 0; } resolve([NSNumber numberWithBool: stringPresent]); } It looks wrong, I think that one line should be stringPresent = [stringInPasteboard length] != 0; HTH A: I found the answer here: http://www.andrewhoyer.com/converting-html-to-nsattributedstring-copy-to-clipboard/ The string needed to be converted to RTF before it was put in the clipboard. RCT_EXPORT_METHOD(setString:(NSString *)content) { // Source: http://www.andrewhoyer.com/converting-html-to-nsattributedstring-copy-to-clipboard/ UIPasteboard *clipboard = [UIPasteboard generalPasteboard]; // Sets up the attributes for creating Rich Text. NSDictionary *documentAttributes = [NSDictionary dictionaryWithObjectsAndKeys: NSRTFTextDocumentType, NSDocumentTypeDocumentAttribute, NSCharacterEncodingDocumentAttribute, [NSNumber numberWithInt:NSUTF8StringEncoding], nil]; // Create the attributed string using options to indicate HTML text and UTF8 string as the source. NSAttributedString *atr = [[NSAttributedString alloc] initWithData: [content dataUsingEncoding:NSUTF8StringEncoding] options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding) } documentAttributes:nil error:nil]; // Generate the Rich Text data using the attributed string and the previously created attributes. NSData *rtf = [atr dataFromRange:NSMakeRange(0, [atr length]) documentAttributes:documentAttributes error:nil]; // Set the Rich Text to the clipboard using an RTF Type // Note that this requires <MobileCoreServices/MobileCoreServices.h> to be imported [clipboard setData:rtf forPasteboardType:(NSString*)kUTTypeRTF]; }
unknown
d8031
train
Aside from a typo (you duplicated select, and you didn't terminate the RETURN statement with a semicolon), I think you were quite close - just needed to disambiguate the table columns within the query by qualifying them with the table name. Try this (reformatted hopefully to improve readability): CREATE OR REPLACE FUNCTION test_proc4(sr_num bigint) RETURNS TABLE(sr_number bigint, product_serial_number varchar(35)) AS $$ BEGIN RETURN QUERY SELECT temp_table.sr_number, temp_table.product_serial_number from temp_table where temp_table.sr_number=sr_num; END; $$ LANGUAGE 'plpgsql' VOLATILE; Caveat: I only tested this in PG 9.4, so haven't tested it in your version yet (which is no longer supported, I might add). In case there are issues regarding PLPGSQL implementation between your version and 9.4, you can try this form as an alternative: CREATE OR REPLACE FUNCTION test_proc4(sr_num bigint) RETURNS TABLE(sr_number bigint, product_serial_number varchar(35)) AS $$ BEGIN FOR sr_number, product_serial_number IN SELECT temp_table.sr_number, temp_table.product_serial_number from temp_table where temp_table.sr_number=sr_num LOOP RETURN NEXT; END LOOP; RETURN; END; $$ LANGUAGE 'plpgsql' VOLATILE; A small sanity check using a table I populated with dummy data: postgres=# select * from temp_table; sr_number | product_serial_number -----------+----------------------- 1 | product 1 2 | product 2 2 | another product 2 (3 rows) postgres=# select * from test_proc4(1); sr_number | product_serial_number -----------+----------------------- 1 | product 1 (1 row) postgres=# select * from test_proc4(2); sr_number | product_serial_number -----------+----------------------- 2 | product 2 2 | another product 2 (2 rows)
unknown
d8032
train
1.) At least you need to fix: public void changeNumOne(int NewNumOne){ firstNum = NewNumOne; } // Error: Same name as above public void changeNumOne(int NewNumTwo){ // Error: Capital SecondName SecondNum = NewNumTwo; } To: public void changeNumOne(int firstNum){ this.firstNum = firstNum; } public void changeNumTwo(int secondNum){ this.secondNum = secondNum; } 2.) And here you would like to print result, but your class does not have such a variable (also check, if your function calculateNums makes sense): public void showResults(){ System.out.println(firstNum + " " + operation + " " + secondNum + " = " + result); } 3.) This should also fail: public Calculator(int firstNum, int secondNum, int NumOperation){ NumOne = firstNum; NumTwo = secondNum; NumOperation = operation; } Should be: public Calculator(int firstNum, int secondNum, string operation){ this.firstNum = firstNum; this.secondNum = secondNum; this.operation = operation; } 4.) Here you do not assign the values: public Calculator(){ int firstNum = 0; int secondNum = 0; operation = "Addition"; } Should be: public Calculator(){ this.firstNum = 0; this.secondNum = 0; this.operation = "Addition"; } Overall: There might be other errors. You need to check all your variables names. They are quite inconsistent. Though, read your error messages carefully and try to understand them for the future. A: There are many errors. I solved with this code, acting with Calculator class. I commented on the code where there were errors. class Calculator { // instance variables - first number, second number, operation private int firstNum; private int secondNum; private int result; //I declare the result variable so I can print it private String operation; // static field to keep track of number of Calculator objects public static int Calculatorobjects = 0; // default constructor public Calculator(){ this.firstNum = 0; //useless because uninitialized int are already 0 this.secondNum = 0; //same this.operation = "Addition"; } // initializing constructor public Calculator(int firstNum, int secondNum, String NumOperation){ //NumOperation is a String, not an int this.firstNum = firstNum; //I'm setting the global variables as the local variables that you pass to the constructor this.secondNum = secondNum; this.operation = NumOperation; } // getters for all 3 instance variables public int one(){ return firstNum; } public int two(){ return secondNum; } public String three(){ return operation; } // setters to be able to change any of the 3 instance variables after creating them public void changeNumOne(int NewNumOne){ firstNum = NewNumOne; } public void changeNumTwo(int NewNumTwo){. //changed method name secondNum = NewNumTwo; } public void changeNumOne(String NewNumOperation){ operation = NewNumOperation; } // instance method to perform operation public void calculateNums(){ if(operation.equals("Addition")){ //equals is used to compare strings result = firstNum + secondNum; } if(operation.equals("Subtraction")){ result = firstNum - secondNum; } } // instance method to display results public void showResults(){ System.out.println(firstNum + " " + operation + " " + secondNum + " = " + result); }
unknown
d8033
train
JavaScript events bubble up the DOM by default, so events triggered on a children will be triggered on the parent. To prevent this, you need to stop the propagation of the event. This is done by: event.stopPropagation(); Note that event is usually passed as a parameter to your callback functions. (Meaning, don't use onclick="" attributes so you get function callback) Full documentation: https://developer.mozilla.org/en-US/docs/Web/API/event.stopPropagation (IE < 8 fallback: Prototype Event.StopPropagation for IE >= 8)
unknown
d8034
train
One way to solve this problem is to project each Animal to a Task that contains more information than either a naked name or a naked error. For example you could project it to a Task<ValueTuple<Animal, string, Exception>> that contains three pieces of information: the animal, the animal's scientific name from the zooApi, and the error that may have happened while invoking the zooApi.GetScientificNameAsync method. The easiest way to do this projection is the LINQ Select operator: List<Task<(Animal, string, Exception)>> tasks = animals.Select(async animal => { try { return (animal, await this.zooApi.GetScientificNameAsync(animal), (Exception)null); } catch (Exception ex) { return (animal, null, ex); } }).ToList(); (Animal, string, Exception)[] results = await Task.WhenAll(tasks); foreach (var (animal, scientificName, error) in results) { if (error != null) this.logger.LogError(error, $"The {animal.Name} from {animal.Country} was not found"); } A: You have almost nailed it. :) Rather than having a List<Task<string>> you need a Dictionary<Task<string>, string> structure: static async Task Main() { var taskInputMapping = new Dictionary<Task<string>, string>(); var inputs = new[] { "input", "fault", "error", "test"}; foreach (var input in inputs) { taskInputMapping.Add(DelayEcho(input), input); } try { await Task.WhenAll(taskInputMapping.Keys); } catch { foreach (var pair in taskInputMapping.Where(t => t.Key.IsFaulted)) { Console.WriteLine($"{pair.Value}: {pair.Key.Exception?.GetType().Name}"); } } } static readonly ImmutableArray<string> wrongInputs = ImmutableArray.Create("error", "fault"); static async Task<string> DelayEcho(string input) { if (wrongInputs.Contains(input)) throw new ArgumentException(); await Task.Delay(10); return input; } * *taskInputMapping.Add(DelayEcho(input), input): Stores the input next to the Task itself *taskInputMapping.Where(t => t.Key.IsFaulted): Iterates through the faulted tasks *$"{pair.Value}: {pair.Key.Exception?.GetType().Name}": Retrieves the input + the related error A: I combined the answers and came up with this: var tasks = animals.Select(async animal => { try { return await this.zooApi.GetNameAsync(animal); } catch (Exception ex) { this.logger.LogError(error, $"The {animal.Name} from {animal.Country} was not found"); return null; } }); var results = await Task.WhenAll(tasks); foreach (var name in results.Where(x => x != null))...
unknown
d8035
train
You seem to be asking two different questions. In the first paragraph you're asking about bundles that are bound to you, which I interpret to mean bundles that import your exported packaged. In the second you're asking about consumers of your services; these are orthogonal issues. For the first question, you can use the BundleWiring API: BundleWiring myWiring = myBundle.adapt(BundleWiring.class); List<BundleWire> exports = myWiring.getProvidedWires(PackageNamespace.PACKAGE_NAMESPACE); for (BundleWire export : exports) { Bundle importer = export.getRequirerWiring().getBundle() } For services, you can use the ServiceFactory pattern. By registering your service as an instance of ServiceFactory rather than directly as an instance of the service interface you can keep track of the bundles that consume your service. Here is a skeleton of a service implementation using this pattern: public class MyServiceFactory implements ServiceFactory<MyServiceImpl> { public MyServiceImpl getService(Bundle bundle, ServiceRegistration reg) { // create an instance of the service, customised for the consumer bundle return new MyServiceImpl(bundle); } public void ungetService(Bundle bundle, ServiceRegistration reg, MyServiceImpl svc) { // release the resources used by the service impl svc.releaseResources(); } } UPDATE: Since you are implementing your service with DS, things are a bit easier. DS manages the creation of the instance for you... the only slightly tricky thing is working out which bundle is your consumer: @Component(servicefactory = true) public class MyComponent { @Activate public void activate(ComponentContext context) { Bundle consumer = context.getUsingBundle(); // ... } } In many cases you don't even need to get the ComponentContext and the consuming bundle. If you are assigning resources for each consumer bundle, then you can just save those into instance fields of the component, and remember to clean them up in your deactivate method. DS will create an instance of the component class for each consumer bundle.
unknown
d8036
train
Try this: logger.debug ["This is", "an", "Array"].inspect This also works for all other kinds of objects: Hashes, Classes and so on. A: you could try the .inspect method.... logger.debug array.inspect I agree with Andrew that there is nothing wrong with... puts YAML::dump(object) A: When you do that, to_s is automatically called on the array, and that's how to outputs. Calling to_yaml is by no means verbose. You could also look at using join or inspect.
unknown
d8037
train
you can create user.py and import mysql and app users.py from app import mysql import app from flask import Blueprint, render_template, abort users_bp = Blueprint('users_bp', __name__) @users_bp.route('/register', methods=["GET", "POST"]) def register(): # USE BD sQuery = "INSERT INTO user (mail, password, name) VALUES (%s, %s, %s)" cur = mysql.connection.cursor() cur.execute(sQuery, (mail, password, name)) mysql.connection.commit() register blueprint in main app :- from users import users_bp app.register_blueprint(users_bp, url_prefix='/users')
unknown
d8038
train
The simplest solution would probably be mindist = minimum(distanceBetweenCities,2) where the ,2 denotes the dimension over which the minimum is searched.
unknown
d8039
train
The only way that I know, is to use a computed subform. if the doc has the flag, show subform with field that have the property "Look up names as each character is entered". if the doc has not the flag, show subform with field that not have the property "Look up names as each character is entered". A: Using a subform as stated by adminfd is one possibility. But it has some disadvantages: * *you don't see the content of a computed subform in designer and cannot double click (inconvenient for developers). *using a lot of subforms can make loading the form very slow I usually do things like that with additional fields. I make the field itself hidden and computed with the formula: @If( YourCondition; FieldNameWithLookup; FieldNameWithoutLookup ); Then I create two fields above the hidden field, name them FieldNameWithLookup and FieldNameWithoutLookup and hide them using the same condition as in the Value- Formula of the field. Yes, it produces some overhead as there are two additional fields, that are not necessary, but I simply like this approach more. If you have existing documents, then you need the formula FieldName in the two new fields as default values and probably some code, if the Condition value for displaying one or the other field changes during different states of the document...
unknown
d8040
train
You might want to have a look at Bringing your Java Application to Mac OS X and (more importantly) Bringing your Java Application to Mac OS X Part 2 and Bringing your Java Application to Mac OS X Part 3 You might Java System Property Reference for Mac of use You may want to take a look at Apple's Java 6 Extensions API, from my brief reading, it would appear that you basically want to use the default instance if com.apple.eawt.Application and supply the handlers you need (such as setAboutHandler). You may also want to read through The Java on Mac OS X About, Quit and Preferences menu items and events article, which should provide some more additional hints.
unknown
d8041
train
Yes, this code is almost correct, with a slight exception. Your call to getData should look like: getData(temp_array, sizeof(T)); You should not be passing the address of array into your getValue function. Other than that, it is good, and it doesn't suffer from quite common strict aliasing violation. You are also avoiding any issues of alignment, and the code is as optimal as can be give the API. A: A problem I see is that because you are only templating the returned value, you will need to explicitly specify the type to use your template method, i.e. auto val = getValue<uint32_t>(); isDataGood(val); // Should be! Without using auto, this is prone to mismatch errors, not all of which will be reported: uint32_t val = getValue<uint16_t>(); isDataGood(val); // perhaps not! It depends how heavy-handed you want to be to protect against this, but one way is to make the returned value a parameter, which allows template type deduction: uint32_t val; getValue(val); isDataGood(val); // Must be! Another is to not use raw integers, but always a struct containing the value as a member of the right size. You can't trivially switch between structs like you can between integer sizes. Another is to have getValue return a wrapper that for a given type knows how to cast to it, and for other types, fails to cast at compile time: struct FailIntBase { operator uint8_t()const = delete; operator uint16_t()const = delete; operator uint32_t()const = delete; operator uint64_t()const = delete; // etc }; template <class Castable> struct SafeInt: FailIntBase { Castable val; SafeInt(Castable val): val(val) {} operator Castable()const { return val; } }; template <typename T> SafeInt<T> getValue() { //... // Testing: auto X = getValue<uint16_t>(); uint16_t Y = getValue<uint16_t>(); uint32_t Z = getValue<uint16_t>(); //error: use of deleted function 'FailIntBase::operator uint32_t() const' If you need to cover more types including signed types, you can get away with a much smaller implementation of FailIntBase if you can live with the less informative error message: conversion from 'SafeInt<short unsigned int>' to 'uint32_t' {aka 'unsigned int'} is ambiguous note: candidate: 'SafeInt<Castable>::operator Castable() const [with Castable = short unsigned int]' note: candidate: 'FailIntBase::operator uint64_t() const' <deleted>
unknown
d8042
train
Since you're calling index() without arguments, it returns the index of each element relative to its siblings. Therefore, that index will "reset" when going from one <map> element to another. You can use the index argument provided by each() instead: $(".fancybox").each(function(index) { $(this).attr("title", mapDetails[index]); }); That way, the index will keep incrementing for each element and will not reset between maps. A: You should use the index of each() $('.fancybox').each(function(index, el) { $(this).attr('title', mapDetails[index]); })
unknown
d8043
train
If you have the Apache service monitor in your system tray, you can just open that (right click, I think?) and click "restart Apache". If it's not in your system tray, you can find it in the /bin folder of the Apache installation (called ApacheMonitor.exe). I'd recommend making a shortcut to it in the "Startup" folder. A: Copy apache_start.bat and rename it to apache_restart.bat. Change the line apache\bin\httpd.exe to apache\bin\httpd.exe -k restart Voila, there you go with your restart script. and you can also give it a shortcut. A: For me, with the version 3.2.2 the first answer didn't work. I've put together a script from the two apache_start.bat and apache_stop.bat files. @echo off cd /D %~dp0 echo Apache 2 is stopping... apache\bin\pv -f -k httpd.exe -q if not exist apache\logs\httpd.pid GOTO exit del apache\logs\httpd.pid echo Apache 2 is re-starting ... apache\bin\httpd.exe if errorlevel 255 goto finish if errorlevel 1 goto error goto finish :error echo. echo Apache konnte nicht gestartet werden echo Apache could not be started pause :finish A: @adrianthedev's version didn't work for (XAMPP v3.2.4) me but helped me find a solution. It's a lot less sophisticated as I don't know much about scripting but here it is and it worked for me: @echo off C:/xampp/apache/bin/httpd -k stop C:/xampp/apache/bin/httpd -k start Note: apache\logs\httpd.pid doesn't need to be deleted as it's done already by the httpd -k stop command.
unknown
d8044
train
Try value_counts df["Month"].value_counts()
unknown
d8045
train
Use process.env.port in server.js to listen const port = process.env.port || 5000; app.listen(port);
unknown
d8046
train
since iOS(13.0, *) AppDelegate handles its own UIWindow via SceneDelegate's and so the method @implementation AppDelegate -(void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler { // here shortcut evaluation below ios(13.0) } @end is only invoked on iPhones or iPads with iOS lower Version 13.0 So to make it work in iOS(13.0,*) and above you need to implement it in SceneDelegate with a slightly different name, see below.. (matt was right!) @implementation SceneDelegate -(void)windowScene:(UIWindowScene *)windowScene performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler { // here shortcut evaluation starting with ios(13.0) NSLog(@"shortcutItem=%@ type=%@",shortcutItem.localizedTitle, shortcutItem.type); } @end PS: The Apple Example Code for Quick Actions in swift is bogus when you assume you can use it as is in iOS(13.0,*) because it is written for versions earlier iOS < 13.0 EDIT: as asked, here in full beauty for iOS >= 13.0 @interface SceneDelegate : UIResponder <UIWindowSceneDelegate> @property (strong, nonatomic) UIWindow * window; @end and -(void)windowScene:(UIWindowScene *)windowScene performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler { /* //go to Info.plist open as Source Code, paste in your items with folling scheme <key>UIApplicationShortcutItems</key> <array> <dict> <key>UIApplicationShortcutItemIconType</key> <string>UIApplicationShortcutIconTypePlay</string> <key>UIApplicationShortcutItemTitle</key> <string>Play</string> <key>UIApplicationShortcutItemSubtitle</key> <string>Start playback</string> <key>UIApplicationShortcutItemType</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER).Start</string> </dict> <dict> <key>UIApplicationShortcutItemIconType</key> <string>UIApplicationShortcutIconTypePlay</string> <key>UIApplicationShortcutItemTitle</key> <string>STOP</string> <key>UIApplicationShortcutItemSubtitle</key> <string>Stop playback</string> <key>UIApplicationShortcutItemType</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER).Stop</string> </dict> </array> */ // may look complex but this is 100% unique // which i would place $(PRODUCT_BUNDLE_IDENTIFIER). in front of types in Info.plist NSString *devIdent = [NSString stringWithFormat:@"%@.",NSBundle.mainBundle.bundleIdentifier]; if ([shortcutItem.type isEqualToString:[devIdent stringByAppendingString:@"Start"]]) { completionHandler([self windowScene:windowScene byStoryBoardIdentifier:@"startview"]); } else if ([shortcutItem.type isEqualToString:[devIdent stringByAppendingString:@"Stop"]]) { completionHandler([self windowScene:windowScene byStoryBoardIdentifier:@"stopview"]); } else { NSLog(@"Arrgh! unrecognized shortcut '%@'", shortcutItem.type); } //completionHandler(YES); } -(BOOL)windowScene:(UIWindowScene *)windowScene byStoryBoardIdentifier:(NSString *)identifier { // idear is to return NO if build up fails, so we can startup normal if needed. UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; if (story!=nil) { UIViewController *vc = [story instantiateViewControllerWithIdentifier:identifier]; if (vc!=nil) { if (_window==nil) _window = [[UIWindow alloc] initWithWindowScene:windowScene]; _window.rootViewController = vc; // .. OR following code.. //[_window.rootViewController presentViewController:vc animated:YES completion:^{ }]; //[_window makeKeyAndVisible]; // should be success here.. return YES; } } // no success here.. return NO; } You can do also other things than instantiate a ViewController from Storyboard. In example you could switch a property or something similar. A: Sorry being too late. Further research about home quick actions showed me the following conclusions after discussing with major developers . The following points which needed to be followed while integrating HomeQuickActions are : * *Most Important point for every developer: Home quick actions(short cut items on clicking app icon) are definitely OS and hardware based (supported only from iOS 13). Apple documents. It means before iOS 13 no device will show app short cut items even if they have Haptic Touch / 3D Touch. iOS 13 and above is a mandatory requirement.(Checked in Simulator for all iPhone, need to test in real device with older phones) Both 3D touch enable and non-3D touch enabled devices support this feature through force-touch or long-press depending on device capabilities if they are capable of running iOS 13 or above. *So for App short cuts to work the iOS devices must be having iOS 13 for sure and the hardware compatibility is also required which means the devices must be having iOS 13 and above for App short cuts to work. For iPhone 5S, iPhone 6 owners: iOS 13 won't be compatible anymore. *Since Apple has replaced 3D Touch hardware with Haptic Touch , the newer iPhones from iPhone XR will have only Haptic Touch . Old devices after SE(1 st generation, iPhone 6 series till iPhone X ) have 3D Touch hardware. Haptic Touch is a software OS dependent which uses finger pressed area and 3D Touch is a hardware dependent which uses a specific sensor between screen.
unknown
d8047
train
Since we're working with a Voronoi tessellation, we can simplify the current algorithm. Given a grid point p, it belongs to the cell of some site q. Take the minimum over each neighboring site r of the distance from p to the plane that is the perpendicular bisector of qr. We don't need to worry whether the closest point s on the plane belongs to the face between q and r; if not, the segment ps intersects some other face of the cell, which is necessarily closer. Actually it doesn't even matter if we loop r over some sites that are not neighbors. So if you don't have access to a point location subroutine, or it's slow, we can use a fast nearest neighbors algorithm. Given the grid point p, we know that q is the closest site. Find the second closest site r and compute the distance d(p, bisector(qr)) as above. Now we can prune the sites that are too far away from q (for every other site s, we have d(p, bisector(qs)) ≥ d(q, s)/2 − d(p, q), so we can prune s unless d(q, s) ≤ 2 (d(p, bisector(qr)) + d(p, q))) and keep going until we have either considered or pruned every other site. To do pruning in the best possible way requires access to the guts of the nearest neighbor algorithm; I know that it slots right into the best-first depth-first search of a kd-tree or a cover tree.
unknown
d8048
train
In theory, you'll want to set the context of your ajax request to the element containing the text you want. Then on success, you would increase the number in that context. $.ajax({ /* everything else as before */ context: $('selector for element containing number to increase'), success: function(result) { $(this).html(parseInt($(this).html(), 10) + 1); } }); This assumes that the content of the context element will always be a single integer If you need to select a cell by it's column and row, you could do the following: var column = 1; var row = 1; var $cell = $('table tr:eq(' + row + ') td:eq(' + column + ')'); $cell.html(parseInt($cell.html(), 10) + 1); See fiddle: http://jsfiddle.net/xixionia/4HLp9/ Although, you would need to change "table" to a table's id, otherwise you'll end up selecting all of the cells from every table at that row in and column. Note: Having seen your html, we would be able to provide a much more detailed description of how to select the desired cell. A: How many rows do you have? It might make sense just to re-generate the table from the AJAX call and reload the html on it's way back.
unknown
d8049
train
The accuracy quantized SSD model is slightly lowered than the float model, you can probably try the efficient-det model: https://www.tensorflow.org/lite/api_docs/python/tflite_model_maker/object_detector A: It looks that the newest update of Coral compiler and RaspberryPI runtime solved the issue. RPI runtime after update: 2.5.0.post1 Edge CPU compiler after update: 16.0.384591198 Some example detections (class, score): Coral: [(0, 0), (1, 0.7210485935211182), (0, 0), (1, 0.6919153332710266), (1, 0.7428985834121704), (1, 0.8485066890716553), (24, 0.6919153332710266)] TF Lite - CPU: [(0, 0), (1, 0.7210485935211182), (0, 0), (1, 0.6919153332710266), (1, 0.7356152534484863), (1, 0.8412233591079712), (24, 0.7028403282165527)] TF CPU: [(0, 0), (1, 0.75359964), (0, 0), (1, 0.7409908), (1, 0.7797077), (1, 0.8114069), (24, 0.750371)]
unknown
d8050
train
To get the values of Client ID and Client secret, you need to create one Google application as mentioned in below reference. I tried to reproduce the same in my environment and got below results: I created one Google application by following same steps in that document and got the values of Client ID and Client secret like this: Go to Google Developers Console -> Your Project -> Credentials -> Select your Web application I configured Google as an identity provider by entering above client ID and secret in my Azure AD B2C tenant like below: Make sure to add Google as Identity provider in your Sign up and sign in user flow as below: When I ran the user flow, I got the login screen with Google like below: After selecting Google, I got consent screen as below: I logged in successfully with Google account like below: Reference: Set up sign-up and sign-in with a Google account - Azure AD B2C
unknown
d8051
train
I'm not entirely sure I understand what you're looking for here, since it should be as easy as copying the menu code: <ul id="nav"> <li> <a href="#">Music</a> <ul> <li><a href="#">New Tracks</a></li> <li><a href="#">Old Tunes</a></li> <li><a href="#">Downloads</a></li> <li><a href="#">Upcoming</a></li> </ul> </li> </ul> and pasting it into the head container: http://jsfiddle.net/LH5TC/
unknown
d8052
train
It looks like spring won't be helpful here, but you still can do that. This @Valid annotation processing implementation is basically in integration with project Hibernate Validator (Don't get confused with the name, it has nothing to do with Hibernate ORM ;) ) So you could create the engine and validate "manually". An example of using the validation engine: ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); validator = factory.getValidator(); User user = ... Set<ConstraintViolation<User>> constraintViolations = validator.validate( user ); As you see, the Result of the validation in hibernate validator is not an exception (this is something that spring has added on top to better integrate with web mvc flow) but rather a set of "validation constraint violations". So basically is this set is not empty, there is at least one validation error so that you could filter it out. I believe wrapping the this logic into filter is not that interesting once you're familiar with the foundations...
unknown
d8053
train
I managed to do this by manually concatenating the state into a single tensor. I'm not sure if this is wise, since this is how tensorflow used to handle states, but is now deprecating that and switching to tuple states. Instead of setting state_is_tuple=False and risking my code being obsolete soon, I've added extra ops to manually stack and unstack the states to and from a single tensor. Saying that, it works fine both in python and C++. The key code is: # setting up zero_state = cell.zero_state(batch_size, tf.float32) state_in = tf.identity(zero_state, name='state_in') # based on https://medium.com/@erikhallstrm/using-the-tensorflow-multilayered-lstm-api-f6e7da7bbe40#.zhg4zwteg state_per_layer_list = tf.unstack(state_in, axis=0) state_in_tuple = tuple( # TODO make this not hard-coded to LSTM [tf.contrib.rnn.LSTMStateTuple(state_per_layer_list[idx][0], state_per_layer_list[idx][1]) for idx in range(num_layers)] ) outputs, state_out_tuple = legacy_seq2seq.rnn_decoder(inputs, state_in_tuple, cell, loop_function=loop if infer else None) state_out = tf.identity(state_out_tuple, name='state_out') # running (training or inference) state = sess.run('state_in:0') # zero state loop: feed = {'data_in:0': x, 'state_in:0': state} [y, state] = sess.run(['data_out:0', 'state_out:0'], feed) Here is the full code if anyone needs it https://github.com/memo/char-rnn-tensorflow
unknown
d8054
train
In react some things (almost everything) needs the same start and end tag to be valid, take a return for example, this is valid: export default observer(() => { return ( <div> <h1>Hello</h1> </div> ) }) This will reslut in a error export default observer(() => { return ( <h1>Hello</h1> <div> </div> ) }) So what you can do is to use the <React.Fragment>tag around all code in your loop, or simply use a loop foreach block. This is valid export default observer(() => { return ( <React.Fragment> <h1>Hello</h1> <div> </div> </React.Fragment> ) }) Your code with fragment return( <div className="container"> <Table> <TableHead> <TableRow> {this.props.headers.map((el, i) => <TableCell key={i+3}>{el}</TableCell> )} </TableRow> </TableHead> <TableBody> {this.props.data.map((element, j) => <React.Fragment> <TableRow key={j+j+j+j+j}> <TableCell key={element["Nr"]+j}>{element["Nr"]}</TableCell> <TableCell key={element["Description"]+j}>{element["Description"]}</TableCell> <TableCell key={element["Reference"]+j}>{element["Reference"]}</TableCell> <TableCell key={element["Parameters"]+j}><FontAwesomeIcon data-index={j} className="font-awesome-icon info-icon" onMouseLeave={this.hideToolTip} onMouseEnter={this.showToolTip} icon={faInfoCircle} /> {toolTip[j]} </TableCell> </TableRow> <TableRow> !!REACT WILL ACCEPT THIS SECOND TABLEROW!! </TableRow> </React.Fragment> )} </TableBody> </Table> </div> )
unknown
d8055
train
Could you modify autoload/poshcomplete.vim in your vimfiles directory like this? let res = webapi#http#post("http://localhost:" . g:PoshComplete_Port . "/poshcomplete/", \ {"text": buffer_text}, {}, s:noproxy_option) + echo 'Response: ' . res.content return webapi#json#decode(res.content) Press <C-X><C-O> with this code, show response from server.
unknown
d8056
train
public synchronized void put(K k, V o) { a.put(k, o); new Thread(() -> { try { TimeUnit.SECONDS.sleep(delay); lock.lock(); a.remove(k, o); removed.signalAll(); lock.unlock(); } catch (InterruptedException e){ e.printStackTrace(); } }).start(); } Try this maybe. You re locking the lock and unlocking the lock in different threads. The thread that call theput method is the one using lock.lock() so it is the only one that can unlock it. The code inside the new Thread(....) belong to another thread so calling lock.unlock() there will not work. Also in the current code I don't see any use of the lock and condition, you can just remove all this (unless you plan on using it somewhere else we don't see), you can put and remove from a concurrent map with worrying about managing the access yourself. A: In order to wait or notify (await and signal if using Condition) the thread, which performs an action, must own the lock it's trying to wait or notify on. From your example: you put a lock in the main thread (lock.put()), then start a new thread. The new thread does not own the lock (it's still held by the main thread), but despite that you try to invoke signalAll() and get IllegalMonitorStateException. In order to fix the problem you should: 1. Release the lock the main thread holds when it's ready (you never release it at the moment). 2. Lock in the new thread first and only then call signalAll() 3. Release the lock in the new thread when you're ready. Do it in the finally clause of the try-catch block to guarantee that the lock gets released in case of an exception. Also a few moments: - in order to be notified a thread must be waiting for notification. - synchronization on the put() method is redundant, since you're already using a ReentrantLock inside. A: We have a few things to look at here: * *lock *removed which is a condition created using lock Your main thread acquires a lock on lock in the put method. However it never releases the lock; instead it creates a new Thread that calls removed.signalAll(). However this new thread does not hold a lock lock which would be required to do this. I think what you need to do is to make sure that every thread that locks lock also unlocks it and that every thread calling signalAll also has a lock. public synchronized void put(K k, V o) { a.put(k, o); new Thread(() -> { try { TimeUnit.SECONDS.sleep(delay); lock.lock(); // get control over lock here a.remove(k, o); removed.signalAll(); lock.unlock(); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); }
unknown
d8057
train
2 changes needed in app.components.ts * *Ensure googleanalytics.startTrackerWithId("UA-XXXXXXXXX-1"); is always the first line to be executed before any other analytics code. *Remove googleanalytics.debugMode();
unknown
d8058
train
Change cancelBtn.click(function () { $(elem).attr("checked", "true"); }); To cancelBtn.click(function () { $(elem).prop("checked", true); }); A: try this: $(elem).attr("checked", true);
unknown
d8059
train
I've just tried this: <cfset fileLocation = "\\192.168.8.20\websites"> <cfdirectory action = "list" directory = "#fileLocation#" name = "pass_fail_files" > <cfdump var="#pass_fail_files#" expand="yes" label="files in pass-fail" > On CF7, CF8 and Railo, and works everytime. Notice I updated your code so it uses the directory attribute as directory = "#fileLocation#" as opposed to directory = fileLocation. Trying your code, I never got results, but didn't get errors either. Changing it to use double-quotes and hashes did the trick, as it stopped using it as a variable. Hope it helps you. A: My first question would be, does the ColdFusion Service User have read access on folder? Actually, I think your code should be <cfdirectory action = "list" directory = "#fileLocation#" name = "pass_fail_files" > I think right now, you're telling it to look in a directory named "fileLocation". A: Assuming you've done all the latest CF7 updates/patches/hotfixes..
unknown
d8060
train
"-lm -lcrypt" specifies to link with the math and cryptography libraries - useful if you're going to use the functions defined in math.h and crypt.h. "-pipe" just means it won't create intermediate files but will use pipes instead. "-DONLINE_JUDGE" defines a macro called "ONLINE_JUDGE", just as if you'd put a "#define" in your code. I guess that's so you can put something specific to the judging in your code in an "#ifdef"/"#endif" block.
unknown
d8061
train
With all the questions you're asking I believe you're an absolute beginner regarding ROR. Perhaps you should visit some tutorials to learn rails. I don't know what your genre model describes, but I think it will have a name. Basic steps for a basic genre model: * *Delete the table for your genres if created manually (with SQL code) DROP TABLE genres; *generate a complete scaffolding for genres: $ ruby script/generate genre name:string $ rake db:migrate *Now you have a complete controller for all CRUD actions for a simple genre model If I were you I would read some tutorial about RoR, because you make the impression that you don't understand RoR or the MVC principle behind it. A good start would be: http://storecrowd.com/blog/top-50-ruby-on-rails-tutorials/ A: You need to generate a controller to handle the index action when your browse your application on localhost ruby script/generate controller genres index run that from your console within your application and it will generate the GenresController with the action index (it will be an empty action but you shouldn't see an error when browsing http://localhost:3000/genres/) A: file C:/Users/Will/Desktop/INSTAN~1/rails_apps/talewiki/app/controllers/genres_controller.rb must be present
unknown
d8062
train
I found out that ingress and cert manager is setup correctly there was issue in my backend. Since LetsEncrypt root cert is expired and I am calling axios which is giving invalid cert hence no response was returned to nginx ingress. Solution: Upgrade openssl version to 1.1.0 or later.
unknown
d8063
train
Short Answer : Add a class to the images for rating, say a class "rating" and then replace $("img") with $("img.rating") Long Answer : Ok, the jquery selector you are using is this $("img") which says select all images from the page. Hence the problem. Now what you should do, As you want to have the jquery run only for the 5 Rating images, you can have all the images have a common class like as shown below.. <img class="Rating" src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="1" /> <img class="Rating" src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="2" /> <img class="Rating" src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="3" /> <img class="Rating" src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="4" /> <img class="Rating" src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="5" /> and Now you can use your code like this... <script language="javascript" type="text/javascript"> $(function () { $("img.rating").mouseover(function () { giveRating($(this), "FilledStar.png"); $(this).css("cursor", "pointer"); }); $("img.rating").mouseout(function () { giveRating($(this), "EmptyStar.png"); }); $("img.rating").click(function () { $("img.rating").unbind("mouseout mouseover click"); // call ajax methods to update database var url = "/Rating/PostRating?rating=" + parseInt($(this).attr("id")); $.post(url, null, function (data) { $("#result").text(data); }); }); }); function giveRating(img, image) { img.attr("src", "/Content/Images/" + image) .prevAll("img").attr("src", "/Content/Images/" + image); } </script> A: Brilliant..... Thanks a lot Yasser... Code required a bit fixes but thanks to u now its working. Bellow I have given the working code.. its almost the same code u hv corrected for me but with capital letters in necessary places. <script> $(function () { $("img.Rating").mouseover(function () { giveRating($(this), "FilledStar.png"); $(this).css("cursor", "pointer"); }); $("img.Rating").mouseout(function () { giveRating($(this), "EmptyStar.png"); }); $("img.Rating").click(function () { $("img.Rating").unbind("mouseout mouseover click"); // call ajax methods to update database var url = "/Rating/PostRating?rating=" + parseInt($(this).attr("id")); $.post(url, null, function (data) { $("#result").text(data); }); }); }); function giveRating(img, image) { img.attr("src", "/Content/Images/" + image) .prevAll("img.Rating").attr("src", "/Content/Images/" + image); } </script> <p> <img class="Rating" src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="1" /> <img class="Rating" src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="2" /> <img class="Rating" src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="3" /> <img class="Rating" src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="4" /> <img class="Rating" src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="5" /> </p> <div id="result"></div> Yahooo .. Thanks a lot
unknown
d8064
train
As taskList is a List<Callable<String>>, executor.invokeAll(taskList) returns a List<Future<String>> containing a Future<String> corresponding to each task in taskList. You need to save that List<Future<String>> so that you can later get at the results of your tasks. Something like this: List<Future<String>> futureList = executor.invokeAll(tasklist); String result = futureList.get(0).get() + futureList.get(1).get() + futureList.get(2).get(); In addition to InterruptedException, Future.get() can also throw CancellationException and ExecutionException so you need to be prepared to deal with these in your try block. A: As you have very few number of task, you can create 3 CompletableFutures and stream over it and join it. CompletableFuture<String> task1 = CompletableFuture.supplyAsync(() -> method1()); CompletableFuture<String> task2 = CompletableFuture.supplyAsync(() -> method2()); CompletableFuture<String> task3 = CompletableFuture.supplyAsync(() -> method3()); String concate = Stream.of(task1, task2, task3) .map(CompletableFuture::join) .reduce("", (s1, s2) -> s1 + s2); System.out.println(concate); A: Adding on top of @Govinda answer - You can create Stream of CompletableFutures by using the supplyAsync factory method and complete them by calling CompletableFuture::join and concat by calling Collectors.joining(). CompletableFuture<String> task1 = CompletableFuture.supplyAsync(Test::method1); CompletableFuture<String> task2 = CompletableFuture.supplyAsync(Test::method2); CompletableFuture<String> task3 = CompletableFuture.supplyAsync(Test::method3); String concat = Stream.of(task1, task2, task3).map(CompletableFuture::join).collect(Collectors.joining()); System.out.println(concat);
unknown
d8065
train
Aren't these answers putting too much emphasis on IO? If you want to intersperse newlines the standard Prelude formula is : > unlines (map show [1..10]) "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n" This is the thing you want written - newlines are characters not actions, after all. Once you have an expression for it, you can apply putStrLn or writeFile "Numbers.txt" directly to that. So the complete operation you want is something like this composition: putStrLn . unlines . map show In ghci you'd have > (putStrLn . unlines . map show) [1,2,3] 1 2 3 A: Try this: mapM_ (putStrLn . show) [1..10] A: Here is my personal favourite monad command called sequence: sequence :: Monad m => [m a] -> m [a] Therefore you could totally try: sequence_ . map (putStrLn . show) $ [1..10] Which is more wordy but it leads upto a function I find very nice (though not related to your question): sequence_ . intersperse (putStrLn "") Maybe an ugly way to do that but I thought it was cool.
unknown
d8066
train
Your class, PagedCollection, doesn't implement INotifyPropertyChanged. public class PagedCollection<TEntity> where TEntity : class, INotifyPropertyChanged What this says is that TEntity must be a class and implement INotifyPropertyChanged. Try this instead: public class PagedCollection<TEntity> : INotifyPropertyChanged where TEntity : class, INotifyPropertyChanged A: You can't call PagedCollection.Get(); like that you have to instantiate something. A: A change in a property of an object within a regular ObservableCollection does not trigger the CollectionChanged event. Maybe you could use the TrulyObservableCollection class, derived from the former: ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged) A: One thing is the ObservableCollection property itself. When you run the program, it is get once when the view is loaded, and it is set once when you first initialize that property. After that, when you populate the list, it's not the PropertyChanged event that is fired, since it would be fired only if you assign the whole OC property to another value (usually via Items = new ObservableCollection<TEntity>()); Thus, the event you should be watching is CollectionChanged, which is fired every time you add, remove, swap or replace elements.
unknown
d8067
train
Oracle does not automatically shrink datafiles, which is what a tablespace is made of. Oracle simply marked the space which had been used by user XYZ's segments (tables, indexes, and the like) as free for some other user's segments to use. SELECT * FROM DBA_OBJECTS WHERE OWNER = 'XYZ'; should demonstrate that user XYZ no longer owns any physical (tables, indexes, clusters) or logical (sequences, procedures, packages, triggers, types) objects in the database. A: You can shrink datafile, under certain circumstances, with following command: ALTER DATABASE DATAFILE 'filename2' RESIZE new_size; Datafile size can be reduced if there is no data at the end of file. See "Managing Tablespaces" for detailed information.
unknown
d8068
train
I am recommending carrierwave gem over paperclip. Easier to parse from link. Carrierwave
unknown
d8069
train
Yes, you can place HTML elements in a SVG with a foreignObject. Example w/ d3
unknown
d8070
train
Check your SourceTree Git settings, and make sure your are using the System Git, not the embedded one. Otherwise, your local Git installation (which does connect to GitHub) would be ignored.
unknown
d8071
train
It depends on which environment you work, but lets assume that this is single-threaded environment. Next, first thought was to create instance attribute to manually assign and retrieve anything. It is will work fine when Player instance is the same for all places. If not, I suggest to introduce class variable, some sort of cache, that will hold Player#id => <some_obj> reference, and with helper accessors, like Player#some_obj which will query Player for object by self.id. That way you will be ensured that for all Player with the same Id, some_obj will be the same. Also, you will need to deside, when to empty that class-cache. For Rails, i suppose after_filter is good enough.
unknown
d8072
train
You can convert them to Byte, like this: var States : TUpdateStatusSet; // Can be any set, I took this one from DB.pas unit SetAsAInteger: Integer; dbs: Pointer; // Here's the trick begin States := [usModified, usInserted]; // Putting some content in that set dbs := @States; SetAsAInteger := PByte(dbs)^; //Once you got it, SetAsAInteger is just another ordinary integer variable. //Use it the way you like. end; To recover from anywhere: var MSG: string; Inserted, Modified: string; States: TUpdateStatusSet; MySet: Byte; begin while not ClientDataSet.Eof do begin //That's the part that interest us //Convert that integer you stored in the database or whatever //place to a Byte and, in the sequence, to your set type. iSet := Byte(ClientDatasetMyIntegerField);// Sets are one byte, so they // fit on a byte variable States := TUpdateStatusSet(iSet); //Conversion finished, below is just interface stuff if usInserted in States then Inserted := 'Yes'; if usModified in States then Modified := 'Yes'; MSG := Format('Register Num: %d. Inserted: %s. Modified:%s', [ClientDataSet.RecNo, Inserted, Alterted]); ShowMessage( MSG ); ClientDataset.Next; end; end; A: You could use a TBytesField or a TBlobField ClientDataSet1MySet: TBytesField, Size=32 var MySet: set of Byte; Bytes: array of Byte; begin MySet := [1, 2, 4, 8, 16]; // Write Assert(ClientDataSet1MySet.DataSize >= SizeOf(MySet), 'Data field is too small'); SetLength(Bytes, ClientDataSet1MySet.DataSize); Move(MySet, Bytes[0], SizeOf(MySet)); ClientDataSet1.Edit; ClientDataSet1MySet.SetData(@Bytes[0]); ClientDataSet1.Post; // Read SetLength(Bytes, ClientDataSet1MySet.DataSize); if ClientDataSet1MySet.GetData(@Bytes[0]) then Move(Bytes[0], MySet, SizeOf(MySet)) else MySet := []; // NULL end; A: Based on the example of Andreas, but made somewhat simpler and clearer IMHO. Tested on XE2 You could use a TBytesField or a TBlobField ClientDataSet1MySet: TBytesField, Size=32 1) Writing var MySet: set of Byte; Bytes: TBytes; begin MySet := [0]; // Write Assert(ClientDataSet1Test.DataSize >= SizeOf(MySet), 'Data field is too small'); SetLength(Bytes, ClientDataSet1Test.DataSize); Move(MySet, Bytes[0], SizeOf(MySet)); ClientDataSet1.Edit; ClientDataSet1Test.AsBytes := Bytes; ClientDataSet1.Post; end; 2) Reading var MyResultSet: set of Byte; begin Move(ClientDataSet1Test.AsBytes[0], MyResultSet, ClientDataSet1Test.DataSize); end;
unknown
d8073
train
Use DataFrame.groupby per years and months or month periods and use custom lambda function with DataFrame.sample: df1 = (df.groupby([df['daate'].dt.year, df['daate'].dt.month], group_keys=False) .apply(lambda x: x.sample(n=10))) Or: df1 = (df.groupby(df['daate'].dt.to_period('m'), group_keys=False) .apply(lambda x: x.sample(n=10))) Sample: data = {'daate':pd.date_range('2019-01-01', '2020-01-22'), 'tweets':np.random.choice(["aaa", "bbb", "ccc", "ddd"], 387) } df = pd.DataFrame(data) df1 = (df.groupby([df['daate'].dt.year, df['daate'].dt.month], group_keys=False) .apply(lambda x: x.sample(n=10))) print (df1) date tweets daate 9 2019-01-10 bbb 2019-01-10 29 2019-01-30 ddd 2019-01-30 17 2019-01-18 ccc 2019-01-18 12 2019-01-13 ccc 2019-01-13 20 2019-01-21 ddd 2019-01-21 .. ... ... ... 381 2020-01-17 bbb 2020-01-17 375 2020-01-11 aaa 2020-01-11 373 2020-01-09 bbb 2020-01-09 368 2020-01-04 aaa 2020-01-04 382 2020-01-18 bbb 2020-01-18 [130 rows x 3 columns] A: import pandas as pd data = {"date": ["2019-01-01", "2019-01-02", "2020-01-01", "2020-02-02"], "tweets": ["aaa", "bbb", "ccc", "ddd"]} df = pd.DataFrame(data) df["daate"] = pd.to_datetime(df["date"], infer_datetime_format=True) # Just duplicating row df = df.loc[df.index.repeat(100)] # The actual code available_dates = df["daate"].unique() sampled_df = pd.DataFrame() for each_date in available_dates: rows_with_that_date = df.loc[df["daate"] == each_date] sampled_rows_with_that_date = rows_with_that_date.sample(5) # 5 samples sampled_df = sampled_df.append(sampled_rows_with_that_date) print(len(sampled_df))
unknown
d8074
train
Since you can get the dates in any format, get them in YYYYMMDDHHmmss format. Then get those timestamps in an array. There's not enough information about your system in your question to explain how to do this but just loop through the files pulling out the timestamps and pushing them into an array. Basically you should have an array like this when you're done: dates = ['20130719114030', '20130720114030', '20130721114030', '20130722114030', '20130723114030', '20130724114030', '20130725114030', '20130726114030', '20130727114030', '20130728114030']; Once done, simply sort the array: dates.sort(); Dates will be in alphanumeric order, which also happens to be chronological order because of our date format. The oldest date will be the first one in the array, so dates[0] // '20130719114030' Again, there's not enough information about your system to explain how to delete the file, but perhaps you could loop through the files again to find a matching timestamp, then delete the file. A: I'm not experienced with Javascript, but my logical progression would be: Out of the 11 files, find the lowest year If the same Out of the 11 files, find the lowest month [...] all the way down to second A: Convert them all to date objects and then compare them. You would only have to do two pass throughs of the list to find the smallest date (one to convert and one to compare)... instead of extracting each snippet and going through the list multiple times. http://www.w3schools.com/js/js_obj_date.asp
unknown
d8075
train
I've encountered the same problem you did last week. Unfortunately right now Azure Functions (even 2.x) don't support polymorphism for durable functions. The durable context serializes your object to JSON, but there's no way to pass JSON serialization settings as described here on GitHub. There's also another issue about this specific problem. In my case I have an abstract base class, but you can use the same approach for your derived types. You can create a custom JSON converter that will deal with picking the correct type during deserialization. So for example if you have this sort of inheritance: [JsonConverter(typeof(DerivedTypeConverter))] public abstract class Base { [JsonProperty("$type")] public abstract string Type { get; } } public class Child : Base { public override string Type => nameof(Child); } public class Child2 : Base { public override string Type => nameof(Child2); } Then you can have your а JSON Converter: public class BaseDerivedTypeConverter : DefaultContractResolver { // You need this to protect yourself against circular dependencies protected override JsonConverter ResolveContractConverter(Type objectType) { return typeof(Base).IsAssignableFrom(objectType) && !objectType.IsAbstract ? null : base.ResolveContractConverter(objectType); } } public class DerivedTypeConverter : JsonConverter { private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings() { ContractResolver = new BaseDerivedTypeConverter() }; public override bool CanConvert(Type objectType) => (objectType == typeof(Base)); public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject jsonObject = JObject.Load(reader); // Make checks if jsonObject["$type"].Value<string>() has a supported type // You can have a static dictionary or a const array of supported types // You can leverage the array or dictionary to get the type you want again var type = Type.GetType("Full namespace to the type you want", false); // the false flag means that the method call won't throw an exception on error if (type != null) { return JsonConvert.DeserializeObject(jsonObject.ToString(), type, Settings); } else { throw new ValidationException("No valid $type has been specified!"); } } public override bool CanWrite => false; public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException(); } In my usage when I call context.GetInput<Base>() I can get either Child or Child1 because Base is abstract. In your case it can be Book or Student depending on what's the actual value. This also applies for other durable function operations like like var foobar = await context.CallActivityAsync<Base>("FuncName", context.GetInput<int>()); The converter will deal with that and you'll get the object you want inside foobar. A: Per my understanding, the class Textbook extends Book, so "Book" is parent class and "Textbook" is subclass. In your context, you want to turn the child class(Textbook) to the parent class(Book). After that, "book" will just have the attribute "title" which is their common attribute but doesn't have the specific attribute "classfor". You can refer to the code below: A: Tracked the updates to pass in Json serialization to Azure Functions here showing that it will be in v2.1!
unknown
d8076
train
Both are approaches are similar but there is a big difference between Usability * *Class OnCompleteListenerImpl is reuseable, you need not override the same object multiple places *You need to be careful while initializing OnCompleteListenerImpl object, as you can initialize in multiple ways, you have to be careful with its scope. *You need not create a new implementation class if you are going with an anonymous approach. In summary, there are different use cases for both the approaches it is up to you which one you want to follow. For clean code and reusability, we go with implementation class but in case of secure and single instance use, you can go with anonymous class approach.
unknown
d8077
train
After little chat, on official IRC: By default, meaning in builtin.vcl, cache lookup is bypassed for POST requests -- return(pass) from vcl_recv so it doesn't change anything in the cache, it just doesn't look in the cache, and the backend response is marked as uncacheable.
unknown
d8078
train
As you have mentioned in the comment, deleting the data and logs directory will solve the problem, but it will reset the sandbox. CDAP sandbox is running on a single java process so it does not have High Availability (HA). When the process is killed suddenly, it may end up in a corrupted state. A: I'had the same isue. To solve the problem you have to delete or rename the tx.snapshot directory in the directory called data. It's ok for me without any reset.
unknown
d8079
train
call_user_func($_POST['fn']); See http://php.net/call_user_func. But in fact $_POST['fn']() will work in all non-ancient PHP versions as well (5.3+ if I remember correctly). But you absolutely need to whitelist the value first, so users can't invoke arbitrary code on your system: $allowed = ['giveme_lb', ...]; if (!in_array($_POST['fn'], $allowed)) { throw new Exception("Not allowed to execute $_POST[fn]"); }
unknown
d8080
train
The number of reads in Firestore is always equal to the number of documents that are returned from the server by a query. Let's say you have a collection of 1 million documents, but your query only returns 10 documents, then you'll have to pay only 10 document reads. If your query yields no results, according to the official documentation regarding Firestore pricing, it said that: Minimum charge for queries There is a minimum charge of one document read for each query that you perform, even if the query returns no results. Those unexpected reads most likely come from the fact that you are using the Firebase console. All operations that you perform in the console are counted towards the total quota. So please remember to not keeping your Firebase console open, as it is considered another Firestore client that reads data. So you'll be also billed for the reads that are coming from the console.
unknown
d8081
train
Yes it's embedded in the framework, look at load on connections settings. You have 3 options : * *maxHeapUsedBytes - maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). *maxRssBytes - maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). *maxEventLoopDelay - maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). ` And you must not forget to set a sample interval (time between 2 checks) on server.load config: * *sampleInterval - the frequency of sampling in milliseconds. Defaults to 0 (no sampling). Example : server configuration : { "load": { "sampleInterval": 1000 } } connection configuration : { "load": { "maxHeapUsedBytes": 1073741824, "maxRssBytes": 1610612736, "maxEventLoopDelay": 5000 } }
unknown
d8082
train
Worksheet objects and Workbook objects both have a CodeName property which will match the VBCmp.Name property, so you can compare the two for a match. Sub Tester() Dim vbcmp For Each vbcmp In ActiveWorkbook.VBProject.VBComponents Debug.Print vbcmp.Name, vbcmp.Type, _ IIf(vbcmp.Name = ActiveWorkbook.CodeName, "Workbook", "") Next vbcmp End Sub A: This is the Function I'm using to deal with exported code (VBComponent's method) where I add a preffix to the name of the resulting file. I'm working on an application that will rewrite, among other statements, API Declares, from 32 to 64 bits. I'm planning to abandon XL 32 bits definitely. After exportation I know from where did the codes came from, so I'll rewrite them and put back on the Workbook. Function fnGetDocumentTypePreffix(ByRef oVBComp As VBIDE.VBComponent) As String '[email protected] Dim strWB_Date1904 As String Dim strWS_EnableCalculation As String Dim strChrt_PlotBy As String Dim strFRM_Cycle As String On Error Resume Next strWB_Date1904 = oVBComp.Properties("Date1904") strWS_EnableCalculation = oVBComp.Properties("EnableCalculation") strChrt_PlotBy = oVBComp.Properties("PlotBy") strFRM_Cycle = oVBComp.Properties("Cycle") If strWB_Date1904 <> "" Then fnGetDocumentTypePreffix = "WB_" ElseIf strWS_EnableCalculation <> "" Then fnGetDocumentTypePreffix = "WS_" ElseIf strChrt_PlotBy <> "" Then fnGetDocumentTypePreffix = "CH_" ElseIf strFRM_Cycle <> "" Then fnGetDocumentTypePreffix = "FR_" Else Stop 'This isn't expected to happen... End If End Function
unknown
d8083
train
Style it as a table row, set width to 100% for both the table and the “active” cell, and prevent line breaks inside cells. Demo: http://jsfiddle.net/yucca42/jyTCw/1/ This won’t work on older versions of IE. To cover them as well, use an HTML table and style it similarly. A: If you are fine with css3, you could use box-flex property. box-flex property specifies how a box grows to fill the box that contains it. Try this, #menu { width: 100%; padding: 0; list-style: none; display: -moz-box; /* Mozilla */ -moz-box-orient: horizontal; /* Mozilla */ display: -webkit-box; /* WebKit */ -webkit-box-orient: horizontal; /* WebKit */ display: box; box-orient: horizontal; } .active { -moz-box-flex: 1; /* Mozilla */ -webkit-box-flex: 1; /* WebKit */ box-flex: 1; } A: No. You have to add some JS that will monitor window size changes and adjusts your element accordingly. A: Instead of giving widths in px, set the widths in percentages. So you could have the non-active each be 10%, and the active will be give a width of 70%
unknown
d8084
train
You'll need to use a loop: for file in files: assert Path(file).exists(), f"{file} does not exist!" In Python 3.8+, you can do it in one line by using the walrus operator: assert not (missing_files := [n for n in files if not Path(n).exists()]), f"files missing: {missing_files}" A: n from comprehension isn't in scope where you do f'{n}' You can show all not exists files not_exists = [f for f in files if not Path(f).exists()] assert not not_exists, f'Files {not_exists} not exist' Or, only the first one for f in files: assert Path(f).exists(), f'{f} not exists' A: As already pointed out in comments, assert is strictly a development tool. You should use an exception which cannot be turned off for any proper run-time checks; maybe create your own exception for this. (Assertions will be turned off in production code under some circumstances.) Secondly, the requirement to do this in a single line of code is dubious. Code legibility should trump the number of lines everywhere, except possibly in time-critical code, where execution time trumps both. class MissingFilesException(Exception): pass missing = {x for x in files if not Path(x).exists()} if missing: raise MissingFilesException( 'Missing files: {}'.format(", ".join(missing))
unknown
d8085
train
You can declare custom object array in your app.component.ts file like this import { Component } from '@angular/core'; import { FormsModule } from '@angular/forms'; @Component({ selector: 'app-root', template: ` <div class="container"> <table class="table table-responsive table-striped"> <tr> <th>id</th> <th>name</th> <th>year</th> </tr> <tr *ngFor="let row of rows"> <td>{{row.id}}</td> <td>{{row.name}}</td> <td>{{row.year}}</td> </tr> </table> <div> <hr /> <input type="text" [(ngModel)]="id" placeholder="id" /> <input type="text" [(ngModel)]="name" placeholder="name" /> <input type="text" [(ngModel)]="year" placeholder="year" /> <button (click)="buttonClicked()">Click to Insert New Row</button> `, styles: [] }) export class AppComponent { title = 'app'; public id: number; public name: string; public year: number; public rows: Array<{id: number, name: string, year: number}> = []; buttonClicked() { this.rows.push( {id: this.id, name: this.name, year: this.year } ); //if you want to clear input this.id = null; this.name = null; this.year = null; } } A: // html data// <table border="1"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Batters</th> <th>Toppings</th> </tr> </thead> <tbody> <tr *ngFor="let data of Newjson;"> <td > {{data.type}} </td> <td> {{data.name}} </td> <td> <ul *ngFor="let item of data.batters.batter;" [ngClass]="{'devils-find':item.type==='Devil\'s Food'}"> <li [ngClass]="item.type"> {{item.type}} </li> </ul> </td> <td> <ul *ngFor="let y of data.topping;"> <li> {{y.type}} </li> </ul> </td> </tr> </tbody> </table> //component.ts file// export class AppComponent { public newtext:any; public rows:any=[]; public url:any=["../assets/images/image.jpeg","../assets/images/danger.jpeg","../assets/images/crab.jpeg", "../assets/images/aws.png","../assets/images/error404.jpg","../assets/images/night.jpg"]; public displayimage:any=["../assets/images/image.jpeg"]; public setimage:boolean=true; public i:any=1; Newjson=[ { "id": "0001", "type": "donut", "name": "Cake", "ppu": 0.55, "batters": { "batter": [ { "id": "1001", "type": "Regular"}, { "id": "1002", "type": "Chocolate"}, { "id": "1003", "type": "Blueberry"}, { "id": "1004", "type": "Devil's Food"} ] }, "topping": [ { "id": "5001", "type": "None" }, { "id": "5002", "type": "Glazed" }, { "id": "5005", "type": "Sugar" }, { "id": "5007", "type": "Powdered Sugar" }, { "id": "5006", "type": "Chocolate with Sprinkles" }, { "id": "5003", "type": "Chocolate"}, { "id": "5004", "type": "Maple" } ] }, { "id": "0002", "type": "donut", "name": "Raised", "ppu": 0.55, "batters": { "batter": [ { "id": "1001", "type": "Regular"} ] }, "topping": [ { "id": "5001", "type": "None" }, { "id": "5002", "type": "Glazed" }, { "id": "5005", "type": "Sugar" }, { "id": "5003", "type": "Chocolate"}, { "id": "5004", "type": "Maple" } ] }, { "id": "0003", "type": "donut", "name": "Old Fashioned", "ppu": 0.55, "batters": { "batter": [ { "id": "1001", "type": "Regular"}, { "id": "1002", "type": "Chocolate"} ] }, "topping": [ { "id": "5001", "type": "None" }, { "id": "5002", "type": "Glazed" }, { "id": "5003", "type": "Chocolate"}, { "id": "5004", "type": "Maple" } ] } ] }
unknown
d8086
train
According to the documentation, the type of table row data can only be object. You can convert raw data, for example, like this: // We should know the columns order var columns = ['id', 'name', 'username', 'email']; var data = rawData.map(function(item) { return item.reduce( function(result, item, columnIndex) { result[columns[columnIndex]] = item; return result; }, {} ); }); https://jsfiddle.net/jLwmhbwv/
unknown
d8087
train
You could use counter_cache. The :counter_cache option can be used to make finding the number of belonging objects more efficient. From here belongs_to :user, counter_cache: true Then create the migration: def self.up add_column :users, :properties_count, :integer, :default => 0 User.reset_column_information User.find(:all).each do |u| User.update_counters u.id, :properties_count => u.properties.length end end Then you can fetch user which have max properties_count User.maximum("properties_count") Here is an awesome RailsCast about counter_cache A: To find the user with min properties you can simply do, User.joins(:properties).group("properties.user_id").order("count(properties.user_id) desc").last And to find the user with max properties, User.joins(:properties).group("properties.user_id").order("count(properties.user_id) desc").first Note: Because its a join operation with properties, so user with no properties will not appear in this query. A: I think you can do like this by scopes class User has_many :properties scope :max_properties, select("users.id, count(properties.id) AS properties_count"). joins(:properties). group("properties.id"). order("properties_count DESC"). limit(1) scope :min_properties, select("users.id, count(properties.id) AS properties_count"). joins(:properties). group("properties.id"). order("properties_count ASC"). limit(1) And just call User.max_properties and User.min_properties UPDATED: It will aslo work like BoraMa suggeted class User has_many :properties scope :max_properties, select("users.*, count(properties.id) AS properties_count"). joins(:properties). group("users.id"). order("properties_count DESC"). limit(1) scope :min_properties, select("users.*, count(properties.id) AS properties_count"). joins(:properties). group("users.id"). order("properties_count ASC"). limit(1)
unknown
d8088
train
The graphConnection.addRequest is an asynchronous function and you are trying to synchronously return the array of strings back. This won't work because the graphConnection.addRequest is done in the background to avoid blocking the main thread. So instead of returning the data directly make a completion handler. Your function would then become this: func fbGraphCall(completion: ([String]) -> Void, errorHandler errorHandler: ((NSError) -> Void)?) { if (FBSDKAccessToken.currentAccessToken() != nil) { // get fb info var userProfileRequestParams = [ "fields" : "id, name, email, about, age_range, address, gender, timezone"] let userProfileRequest = FBSDKGraphRequest(graphPath: "me", parameters: userProfileRequestParams) let graphConnection = FBSDKGraphRequestConnection() graphConnection.addRequest(userProfileRequest, completionHandler: { (connection: FBSDKGraphRequestConnection!, result: AnyObject!, error: NSError!) -> Void in if(error != nil) { println(error) errorHandler?(error!) } else { var fbData = [String]() // Notice how I removed the empty string you were putting in here. // DEBUG println(result) let fbEmail = result.objectForKey("email") as! String // DEBUG println(fbEmail) fbData.append("\(fbEmail)") let fbID = result.objectForKey("id") as! String if(fbEmail != "") { PFUser.currentUser()?.username = fbEmail PFUser.currentUser()?.saveEventually(nil) } println("Email: \(fbEmail)") println("FBUserId: \(fbID)") completion(fbData) } }) graphConnection.start() } } I added the completion handler and the error handler blocks that get executed according to what's needed. Now at the call site you can do something like this: fbGraphCall( { println($0) // $0 refers to the array of Strings retrieved }, errorHandler: { println($0) // TODO: Error handling }) // Optionally you can pass `nil` for the error block too incase you don't want to do any error handling but this is not recommended. Edit: In order to use the variables you would do something like this at the call site fbGraphCall( { array in dispatch_async(dispatch_get_main_queue(), { // Get the main queue because UI updates must always happen on the main queue. self.fbIDLabel.text = array.first // array is the array we received from the function so make sure you check the bounds and use the right index to get the right values. self.fbEmailLabel.text = array.last }) }, errorHandler: { println($0) // TODO: Error handling })
unknown
d8089
train
You can generate the select form: <?php $req = $pdo->query('SELECT * FROM table'); $rep = $req->fetchAll(); ?> <select> foreach($rep as $row) { ?> <option value="<?= $row['country'] ?>"><?= $row['country'] ?></option> <? } ?> </select> <?php foreach($rep as $row) { <input style="display:none" id="<?= $row['country'] ?>" value="<?= $row['capital'] ?>" /> <?php } ?> So you will have the select with all country, and an input for each Capital with their Country as id, so you can display it with javascript: (jQuery example) <script> $('select').change(function() { $('input:visible').toggle(); $('input[id='+$(this).val()+']').toggle(); }); </script> A: You can fetch the countries and ther capitals from the database using the following code in php //This is where you put the fetched data $entries = Array(); //Make new connection $connection = new mysqli("127.0.0.1", "username", "password", "databasename"); //Create prepared statement $statement = $connection->prepare("SELECT `country`, `capital` FROM `table`"); $statement->bind_result($country, $capital); //Put the fetched data in the result array while($statement->fetch()) { $entry = Array(); $entry['country'] = $country; $entry['capital'] = $capital; $entries[] = $entry; } //Close the statement and connection $statement->close(); $connection->close(); Next, you make the HTML select objects. It's important that the order of countries remains the same as the order of the capitals. <!-- Country selection --> <select id="select-country"> <?php $i = 0; foreach ($entries as $c) { ?> <option data-country="<?php echo $i++; ?>"><?php echo $c['country'] ?></option> <?php } ?> </select> <!-- Capitals select --> <select id="select-capital"> <?php $i = 0; foreach ($entries as $c) { ?> <option data-capital="<?php echo $i++ ?>"><?php echo $c['capital'] ?></option> <?php } ?> </select> Finally, you add an event listener to the select with the id of select-country where you listen for the change event. Once called, you change the selected index of the second select to that of the first. That's why it's important that the order remains the same. <script> document.getElementById('select-country').addEventListener('change', function () { document.getElementById('select-capital').getElementsByTagName('option')[this.selectedIndex].selected = true; }); </script>
unknown
d8090
train
Method 1. Use React debounce input, simple method https://www.npmjs.com/package/react-debounce-input Method 2 Create timer and call API based on that, no external library needed. and i always suggest this let timer = null const handleChange = (e) => { setInputValue(e.target.value) if(timer) { clearTimeout(timer) } timer = setTimeout(()=>yourApiCall(e.target.value), 700) } const yourApiCall = (val) => { //call API here } <form> <TextField onChange={handleChange} onBlur={clearInput} value={inputValue} placeholder="Do an api request" /> </form> a working example https://codesandbox.io/s/beautiful-goldberg-vyo2u?file=/src/App.js Method 3 Use loadash debounce check the answers from this link Lodash debounce with React Input
unknown
d8091
train
If something else is stopping the text box from receiving the enter key you could try overriding ProcessCmdKey of the UserControl instead. It might work, but it all depends on where in the event chain that the parent intercepts the message. Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, keyData As System.Windows.Forms.Keys) As Boolean If keyData = Keys.Return AndAlso tbOccurrenceElevation.Focused = True Then 'Do your stuff here. Return True 'We've handled the key press. End If Return MyBase.ProcessCmdKey(msg, keyData) End Function A: Try this: Private Sub tbOccurrenceElevation_KeyDown(sender As Object, e As KeyEventArgs) Handles tbOccurrenceElevation.KeyDown ' Check if the enter key is pressed If e.KeyCode = Keys.Enter or e.KeyCode = Keys.Return Then OccurrenceElevation_Changed() End If End Sub You have to remember most of the keyboards have both Enter and Return. The code for those is different so you have to include them both
unknown
d8092
train
[request setHTTPShouldHandleCookies:NO]; A: I don't know if you can disable automatic addition of cookies but you can delete cookies anytime you want using the following code NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; for (NSHTTPCookie *cookie in storage.cookies) { [storage deleteCookie:cookie]; } A: Here you go, this is a method to do this, this method sets a cookie after implementing your own cookie info, and the category below this method powers this method, this will work by sniping the EXSISTING cookie right after you make the cookie methos above and then you mutate the cookie to whatever data you want, you will still have a cookie, but it won't be useful unless you are replacing the cookie info with real info. You can just immediatley look through the array of cookies and delete them. Either way, you can make cookies NOT work and get rid of them: - (void)manipulateCookie { NSArray* cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]; for (NSHTTPCookie* cookie in cookies) { NSString *alipaySetCookieString = @"CAKEPHP=nil; path=#; domain=#; expires=Wed, 30-Nov-2001 01:01:01 GMT"; NSHTTPCookie * clok = [alipaySetCookieString cookie]; [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:clok]; } } category: NSString+Cookie.h @interface NSString(Cookie) - (NSHTTPCookie *)cookie; @end NSString+Cookie.m #import "NSString+Cookie.h" @implementation NSString(Cookie) - (NSDictionary *)cookieMap { NSMutableDictionary *cookieMap = [NSMutableDictionary dictionary]; NSArray *cookieKeyValueStrings = [self componentsSeparatedByString:@";"]; for (NSString *cookieKeyValueString in cookieKeyValueStrings) { NSRange separatorRange = [cookieKeyValueString rangeOfString:@"="]; if (separatorRange.location != NSNotFound && separatorRange.location > 0 && separatorRange.location < ([cookieKeyValueString length] - 1)) { NSRange keyRange = NSMakeRange(0, separatorRange.location); NSString *key = [cookieKeyValueString substringWithRange:keyRange]; NSString *value = [cookieKeyValueString substringFromIndex:separatorRange.location + separatorRange.length]; key = [key stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; [cookieMap setObject:value forKey:key]; } } return cookieMap; } - (NSDictionary *)cookieProperties { NSDictionary *cookieMap = [self cookieMap]; NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary]; for (NSString *key in [cookieMap allKeys]) { NSString *value = [cookieMap objectForKey:key]; NSString *uppercaseKey = [key uppercaseString]; if ([uppercaseKey isEqualToString:@"DOMAIN"]) { if (![value hasPrefix:@"."] && ![value hasPrefix:@"www"]) { value = [NSString stringWithFormat:@".%@",value]; } [cookieProperties setObject:value forKey:NSHTTPCookieDomain]; }else if ([uppercaseKey isEqualToString:@"VERSION"]) { [cookieProperties setObject:value forKey:NSHTTPCookieVersion]; }else if ([uppercaseKey isEqualToString:@"MAX-AGE"]||[uppercaseKey isEqualToString:@"MAXAGE"]) { [cookieProperties setObject:value forKey:NSHTTPCookieMaximumAge]; }else if ([uppercaseKey isEqualToString:@"PATH"]) { [cookieProperties setObject:value forKey:NSHTTPCookiePath]; }else if([uppercaseKey isEqualToString:@"ORIGINURL"]){ [cookieProperties setObject:value forKey:NSHTTPCookieOriginURL]; }else if([uppercaseKey isEqualToString:@"PORT"]){ [cookieProperties setObject:value forKey:NSHTTPCookiePort]; }else if([uppercaseKey isEqualToString:@"SECURE"]||[uppercaseKey isEqualToString:@"ISSECURE"]){ [cookieProperties setObject:value forKey:NSHTTPCookieSecure]; }else if([uppercaseKey isEqualToString:@"COMMENT"]){ [cookieProperties setObject:value forKey:NSHTTPCookieComment]; }else if([uppercaseKey isEqualToString:@"COMMENTURL"]){ [cookieProperties setObject:value forKey:NSHTTPCookieCommentURL]; }else if([uppercaseKey isEqualToString:@"EXPIRES"]){ NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]]; dateFormatter.dateFormat = @"EEE, dd-MMM-yyyy HH:mm:ss zzz"; [cookieProperties setObject:[dateFormatter dateFromString:value] forKey:NSHTTPCookieExpires]; }else if([uppercaseKey isEqualToString:@"DISCART"]){ [cookieProperties setObject:value forKey:NSHTTPCookieDiscard]; }else if([uppercaseKey isEqualToString:@"NAME"]){ [cookieProperties setObject:value forKey:NSHTTPCookieName]; }else if([uppercaseKey isEqualToString:@"VALUE"]){ [cookieProperties setObject:value forKey:NSHTTPCookieValue]; }else{ [cookieProperties setObject:key forKey:NSHTTPCookieName]; [cookieProperties setObject:value forKey:NSHTTPCookieValue]; } } if (![cookieProperties objectForKey:NSHTTPCookiePath]) { [cookieProperties setObject:@"/" forKey:NSHTTPCookiePath]; } return cookieProperties; } - (NSHTTPCookie *)cookie { NSDictionary *cookieProperties = [self cookieProperties]; NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties]; return cookie; } @end
unknown
d8093
train
You can use a subquery that picks out the orders with that category and use to filter out those orders: select OrderNum from T1 as t where not exists( select * from T1 inner join T2 on T2.Ordernum = T1.Ordernum inner join T3 on T3.Orderitem = T2.Orderitem and T3.Catid = 100 where T1.Ordernum = t.Ordernum ) A: You can to use EXISTS clause: SELECT T1.OrderNum FROM T1 WHERE NOT EXISTS (SELECT * FROM T2 INNER JOIN T3 ON T2.Orderitem = T3.Orderitem WHERE T1.OrderNum = T2.OrderNum AND T3.Catid != 100) A: you need to select all and then exclude them on where statement. I think this will work. SELECT a1.OrderNum FROM T1 a1 INNER JOIN T2 a2 ON a1.OrderNum = a2.OrderNum INNER JOIN T3 a3 ON a2.Orderitem = a3.Orderitem WHERE not a1.OrderNum in (select ordernum from T2 where orderitem in (select Orderitem from T3 where T2.OrderItem = OrderItem and Catid = 100)) or maybe with subjoin is better: WHERE not a1.OrderNum in (select sa2.ordernum from T2 sa2 where sa2.orderitem in (select sa3.Orderitem INNER JOIN T3 sa3 on sa2.OrderItem = sa3.OrderItem and sa3.Catid = 100)) A: here it is ; select * from T1 where ordernum not in (select ordernum from t2,t3 where t2.Orderitem=t3.Orderitem and t3.catid=100)
unknown
d8094
train
It's a multithreading issue. At some point you're trying to change the datasource of your datagrid at the exact same time it's painting itself on screen. dgvComputers1.DataSource = dt; Try replacing that by: this.Invoke(delegate(DataTable table) { dgvComputers1.DataSource = table; }, dt); A: Have you tried this? dr[1] = IPAddress ?? "(unknown)"; A: Try putting a breakpoint in (if you are using Visual Studio) and checking each line and see where the error occurs. Then, after getting to the line, check in the watch window to see what is null. Then go: if(nullThing == null) return; before the line where the error occurs, of course, you shouldn't always do this, but find out WHY it is null, and sort it out. That should do the job. A: Check this out: `private void backgroundWorker2_Dowork(object sender, DoWorkEventArgs e) Delete that ` It should be: private void backgroundWorker2_Dowork(object sender, DoWorkEventArgs e)
unknown
d8095
train
It's easier not to use (just) regex. Split the string on quotes (-1 to keep any trailing empty parts): String[] parts = str.split("\"", -1); Trim the odd-numbered elements: for (int i = 1; i < parts.length; i += 2) { parts[i] = parts[i].trim(); } Join the parts again: String newStr = String.join("\"", parts);
unknown
d8096
train
Try this, you were not using the correct id: import React, { useState, useEffect } from 'react' import axios from 'axios' function Renderreview() { const [renderReview, setRenderReview] = useState([]) useEffect(() => { axios.get('/reviews') .then(res => { console.log(res) setRenderReview(res.data) }) .catch(err => { console.log(err) }) }, []) function handleDelete(id) { axios.delete(`/reviews/${id}`,) } return ( <div className='card1'> <h2>reviews</h2> {renderReview.map((renderReview) => { return ( <div className='renderedreviews'>{renderReview.review} <button onClick={() => { handleDelete(renderReview.id); }} key={renderReview.review}> Delete </button> </div> ) })} </div> ) } export default Renderreview
unknown
d8097
train
I've ran into the same problem a few times; you can, but you'll have to index each by itself (not all in one hash like you've done). But you could through the whole thing in the value for emit. It can be fairly inefficient, but gets the job done. (See this link: View Snippets) I.e.: function(doc) { if (doc.type=="Employee") { emit(["EID",doc.values.EID], doc.values); emit(["FirstName", doc.fName], doc.values); emit(["LastName", doc.lName], doc.values); emit(["Designation", doc.designation], doc.values); emit(["Department", doc.department], doc.values); emit(["ReportingTo", doc.reportingTo], doc.values); emit(["Active", doc.isActive], doc.values); } } This puts all "EID" things in the same part of the tree, etc., I'm not sure if that is good or bad for you. If you start needing a lot of functionality with [field name:]value searches, its probably worth it to move towards a Lucene-CouchDB setup. Several exist, but are a little immature.
unknown
d8098
train
Same instance would mean any call (from anywhere) to getBean() from ApplicationContext or BeanFactory will land you with the same instance, i.e. constructor is called just once when Spring is being initialized (per Spring container). However, there are scenarios when you would want different object instances to work with. For example, if you have a Point object as a member variable in a Triangle class, in case of Singleton, when the Triangle class is being instantiated, the Point object also is instantiated as it is dependent. If you require a different instance of Point to work with elsewhere, then you will need to define the Point as a prototype, else it carries the same state. Googling would surely help you find answers and examples demonstrating the use case. Hope this helps. A: In case if the same instance is injected everywhere as Singleton, you can use it's shared state for containing any kind of data. In case if new instance is created any time bean is being injected - it's state is not shared. By default all beans are Singletons. Prototype scope stands for cases when bean's inner data should be unique for each place you inject bean into. Example: you have the bean which represents REST client. Different parts of application use different REST services, each requires some specific request headers - for security purposes, for example. You can inject the same REST client in all these beans to have it's own REST client bean with some specific headers. At the same time you can configure client's politics in common for the whole application - request timeouts, etc. See also: When to use Spring prototype scope? A: It helps in designing a software, refer java design patterns you fill find much useful information, In case of singleton you will be able to create only object, it will helps cases like 1.saving time in creating a very complex object (we can reuse the same object) 2.Some times we need to use the same object throughout the application E.g if you want count the total number of active users in the application, you can use singleton object to store it, because there will be only one object so you can easily update and retrieve data. In case of Prototype it will always give you different object, it is necessary in some cases like some access token, you should always get the new /valid token to proceed further, so prototype pattern /Bean is useful. A: My understanding for Singleton is more likely used in the situation like return single Utility instance. //SomeUtil is Singleton var util = SomeUtil.getInstance(); print(util.doTask1()); print(util.doTask2()); If another thread goes into these code, SomeUtil.getInstance() just return the SomeUtil instance other than creating a new one (which might cost much to create a new one). As to Prototype, I just found this situation using Prototype: Lets understand this pattern using an example. I am creating an entertainment application that will require instances of Movie, Album and Show classes very frequently. I do not want to create their instances everytime as it is costly. So, I will create their prototype instances, and everytime when i will need a new instance, I will just clone the prototype. Example code locates https://github.com/keenkit/DesignPattern/tree/master/src/PrototypePattern
unknown
d8099
train
Many of the people face this problem this is just a permission Issue Follow Below Step 1)Open Ftp by filezilla or any ftp client 2)Right Click on Wp_contnet Folder 3) Change Permissions From 755 TO 777(Please Make Sure That 777 permission to all in side folder's under wp_content) 4) Than Try to Upload File Agin and its'done A: If you checked the permission then try this solution : Please login to the wordpress dashboard ( http://www.domainname.com/wp-admin ) and access the Miscellaneous settings. Find the uploads path specified, it will most likely be specified as: "/wp-content/uploads/ Change it to read "wp-content/uploads/ A: change your wp-content folder's writing permission Step 1: Open your File Manager and navigate to the file or folder that you need to change. Step 2: Click on the name of the file or folder. Step 3: Click on the Change Permissions link in the top menu of the File Manager page. Step 4: Click on as many check boxes as you require to create the right permission. The permission numbers underneath the check boxes will update automatically. Step 5: Click on the Change Permissions button when you are ready. The new permission level is saved and the display updated to show the modified file. A: Some time when you upload image so this issue arise just try to change permission level to 744 but select only for directories and try to change the permission level to 644 this time for files hope this will works for you .
unknown
d8100
train
I remapped F12 to redo my syntax highlighting in case it gets messed up: nnoremap <F12> :syntax sync fromstart<cr> Maybe you can just run it as an autocmd event in your vimrc based on reading a new buffer? autocmd BufReadPost * :syntax sync fromstart
unknown