_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d2601
train
Your property names (some of them) are invalid identifiers. You can quote it to fix the problem: rules: { "form-nocivique": { //Chrome complains here required: true, digits: true }, You can't use - in an identifier in JavaScript; it's a token (the "minus" operator).
unknown
d2602
train
You usually pass data between threads by writing the data into some shared data structure, like a queue that one thread is writing to and another thread is reading from. There are other explicit ways, however. For example, if you are trying to get data from a background thread to the UI thread, so you can invoke UI API's with that data, then there are techniques to execute bits of code on other thread contexts. For example, you can use the Task class from System.Threading.Tasks to start a task on the UI thread if you know the TaskScheduler associated with the UI thread. You can get that from TaskScheduler.FromCurrentSynchronizationContext() when your code is executing on the UI thread, and save it in a static variable to use later.
unknown
d2603
train
ok i solved..the problem was what i thought...thaks to a comment by @Joachim Pileborg i've tried with this (NULL)... so thanks to you all `int p=0; int count=0; while(p!=-1){ if (tokens[count] != NULL){ printf("\nprinto: %s",tokens[count]); count++; } else p=-1; }` A: the segmentation fault occures when the process execute strlen(tokens[count]) inside the IF at the last iteration..the return value would be 0(no string?) but instead seg fault... probably in that location there isn't a string so this occures...how can i solve the problem? anyway this is str_split,it is the same(more or less) posted on this site somewhere,it works char** str_split(char* a_str, char a_delim) { char** result = 0; size_t count = 0; char* tmp = a_str; char* last_comma = 0; char delim[2]; delim[0] = a_delim; delim[1] = 0; /* Count how many elements will be extracted. */ while (*tmp) { if (a_delim == *tmp) { count++; last_comma = tmp; } tmp++; } /* Add space for trailing token. */ count += last_comma < (a_str + strlen(a_str) - 1); /* Add space for terminating null string so caller knows where the list of returned strings ends. */ count++; result = malloc(sizeof (char*) * count); if (result) { size_t idx = 0; char* token = strtok(a_str, delim); while (token) { assert(idx < count); *(result + idx++) = strdup(token); token = strtok(0, delim); } assert(idx == count - 1); *(result + idx) = 0; } return result; }
unknown
d2604
train
You forgot to add the ANE to your package. Project > Properties > Flex Build Packaging > (Your OS) > Native Extentions... Add...
unknown
d2605
train
Java was designed around the idea that finalizers could be used as the primary cleanup mechanism for objects that go out of scope. Such an approach may have been almost workable when the total number of objects was small enough that the overhead of an "always scan everything" garbage collector would have been acceptable, but there are relatively few cases where finalization would be appropriate cleanup measure in a system with a generational garbage collector (which nearly all JVM implementations are going to have, because it offers a huge speed boost compared to always scanning everything). Using Closable along with a try-with-resources constructs is a vastly superior approach whenever it's workable. There is no guarantee that finalize methods will get called with any degree of timeliness, and there are many situations where patterns of interrelated objects may prevent them from getting called at all. While finalize can be useful for some purposes, such as identifying objects which got improperly abandoned while holding resources, there are relatively few purposes for which it would be the proper tool. If you do need to use finalizers, you should understand an important principle: contrary to popular belief, finalizers do not trigger when an object is actually garbage collected"--they fire when an object would have been garbage collected but for the existence of a finalizer somewhere [including, but not limited to, the object's own finalizer]. No object can actually be garbage collected while any reference to it exists in any local variable, in any other object to which any reference exists, or any object with a finalizer that hasn't run to completion. Further, to avoid having to examine all objects on every garbage-collection cycle, objects which have been alive for awhile will be given a "free pass" on most GC cycles. Thus, if an object with a finalizer is alive for awhile before it is abandoned, it may take quite awhile for its finalizer to run, and it will keep objects to which it holds references around long enough that they're likely to also earn a "free pass". I would thus suggest that to the extent possible, even when it's necessary to use finalizer, you should limit their use to privately-held objects which in turn avoid holding strong references to anything which isn't explicitly needed for their cleanup task. A: Phantom references is an alternative to finalizers available in Java. Phantom references allow you to better control resource reclamation process. * *you can combine explicit resource disposal (e.g. try with resources construct) with GC base disposal *you can employ multiple threads for postmortem housekeeping Using phantom references is complicated tough. In this article you can find a minimal example of phantom reference base resource housekeeping. In modern Java there are also Cleaner class which is based on phantom reference too, but provides infrastructure (reference queue, worker threads etc) for ease of use.
unknown
d2606
train
Regular expressions, the way they are defined in mathematics, are actually string generators, not search patterns. They are used as a convenient notation for a certain class of sets of strings. (Those sets can contain an infinite number of strings, so enumerating all elements is not practical.) In a programming context, regexes are usually used as flexible search patterns. In mathematical terms we're saying, "find a substring of the target string S that is an element of the set generated by regex R". This substring search is not part of the regex proper; it's like there's a loop around the actual regex engine that tries to match every possible substring against the regex (and stops when it finds a match). In fundamental regex terms, it's like there's an implicit .* added before and after your pattern. When you look at it this way, ^ and $ simply prevent .* from being added at the beginning/end of the regex. As an aside, regexes (as commonly used in programming) are not actually "regular" in the mathematical sense; i.e. there are many constructs that cannot be translated to the fundamental operations listed above. These include backreferences (\1, \2, ...), word boundaries (\b, \<, \>), look-ahead/look-behind assertions ((?= ), (?! ), (?<= ), (?<! )), and others. As for ε: It has no character code because the empty string is a string, not a character. Specifically, a string is a sequence of characters, and the empty string contains no characters. A: ^AB can be expressed as (εAB) ie an empty string followed by AB and AB$ can be expressed as (ABε) that's AB followed by an empty string. The empty string is actually defined as '', that's a string of 0 length, so has no value in the ASCII table. However the C programming language terminates all strings with the ASCII NULL character, although this is not counted in the length of the string it still must be accounted for when allocating memory. EDIT As @melpomene pointed out in their comment εAB is equivalent to AB which makes the above invalid. Having talked to a work college I'm no longer sure how to do this or even if it's possible. Hopefully someone can come up with an answer.
unknown
d2607
train
A derives directly from Object class and neither A or Object overload == operator, so why doesn't next code cause an error? As with your other question, you seem to have some strange belief that whether an overloaded operator exists has any bearing on whether an operator can be meaningfully chosen. It does not. Again, to resolve this situation overload resolution first attempts to determine if there is a user-defined operator defined on either of the operands. As you note, there is not. Overload resolution then falls back on the built-in operators. As I mentioned in your other question, the built-in operators are the equality operators on int, uint, long, ulong, bool, char, float, double, decimal, object, string, all delegate types and all enum types, plus the lifted-to-nullable versions of all the value types. Given those operators we must now determine the applicable ones. There is no implicit conversion from "A" to any of the value types, to any of the nullable value types, to string, or to any delegate type. The only remaining applicable candidate is object. If overload resolution chooses the equality operator that compares two objects, additional constraints must be met. In particular, both operands must either be null or a reference type, or a type parameter not constrained to be a value type. That constraint is met. Also, if the two sides have types then the operand types must have some sort of compatibility relationship; you can't do "myString == myException" because there is no relationship between string and Exception. There is a relationship between "A" and "A", namely, they are identical. Therefore the reference equality operator is chosen, and the == means "compare these two object expressions by reference". I am mystified as to why you believe having a user-defined == operator has anything to do with this, either in this question or your other question. The absence of such a method does not prevent the compiler from generating whatever code it likes for this expression. Can you explain? A: Because by default, the == operator compares the references (memory locations) of the objects a1 and a2. And because they're different instances of class A, the expression a1 == a2 always evaluates to false in your example. A: Objects have a default implementation of the == operator that checks if they refer to the same object (reference comparison). So there's no reason for it to be an error. The operator does have a meaning. A: Because Object has a default implementation comparing references. A: The base's == operator is called that why its not giving any error. A: By default, the operator == tests for reference equality by determining if two references indicate the same object, so reference types do not need to implement operator == in order to gain this functionality. From: http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx The important bit concerning your question being: reference types do not need to implement operator == in order to gain this functionality
unknown
d2608
train
If i read well, you use gmp_div_q for rounding only? Then, you should check round(). The only case, that round() cannot cover is GMP_ROUND_ZERO, but you don't use that (and you could cover it with a simple if).
unknown
d2609
train
[ {name: Jhon1} {name: Jhon2} {name: Jhon3} ] B: [ {lastName: Pom1} {lastName: Pom2} {lastName: Pom3} ] Expected Result after merge : A: [ {name: Jhon1, lastName: Pom1} {name: Jhon2, lastName: Pom2} {name: Jhon3, lastName: Pom3} ] Concat method just merges the whole array in to one like this : A: [ {name: Jhon1} {name: Jhon2} {name: Jhon3} {lastName: Pom1} {lastName: Pom2} {lastName: Pom3} ] My own function that I am trying. Below there is two arrays: this.prices and this.search.favoriteItems, I want to merge then the same way as I described before : showProducts(){ for(let i of this.localStorageArray){ let id = localStorage.getItem(i); this.search.getProductsById(id).subscribe ((data: any) => { this.prices.push(data.lowestPrices.Amazon); this.search.favoriteItems.push(data); //something here to merge this.prices and this.search }); } } A: You can use .map() with Object destrcuturing: let arr1 = [{name: 'Jhon1'}, {name: 'Jhon2'}, {name: 'Jhon3'}], arr2 = [{lastName: 'Pom1'}, {lastName: 'Pom2'}, {lastName: 'Pom3'}]; let zip = (a1, a2) => a1.map((o, i) => ({...o, ...a2[i]})); console.log(zip(arr1, arr2)); .as-console-wrapper { max-height: 100% !important; top: 0; }
unknown
d2610
train
If you're upgrading a .NET 3.5 project that uses contracts to .NET 4.0, make sure you remove your reference to the Microsoft.Contracts assembly. The Microsoft.Contracts assembly provides code contracts for use in .NET 2.0 or 3.5 projects, but is provided by default with .NET 4.0 in mscorlib, so you don't need it. They both share the System.Diagnostics.Contracts namespace, so by having references to both at the same time, the compiler isn't able to figure out which one you're trying to use. A: I solved it by first installing it, thou that did not actually solve it. Then removed the references and then I changed the project versions to 4.5 and after that, it worked.
unknown
d2611
train
You need to match complete input by using .* on either side of your search pattern to be able to replace full line with just the captured group's back-reference. This sed should work: s='"version": "1.0.0",' sed 's/.*: "\([^"]*\)",.*/\1/' <<< "$s" 1.0.0 Or even this one: sed 's/.*: "\(.*\)",.*/\1/' <<< "$s" 1.0.0 A: Another approach, using grep with lookahead/lookbehind: $ grep -oP '(?<=: ")[^"]*(?=")' <<< '"version": "1.0.0",' 1.0.0 or shorter, using \K to exclude : " from the matched string: $ grep -oP ': "\K[^"]+' <<< '"version": "1.0.0",' 1.0.0
unknown
d2612
train
In your {{action...}} you should pass a real model, not a promise. To get a model from a promise you need to do something like this: var myMstore; that.store.find('mstore', mstoreId).then(function(mstore) { myMstore = mstore; });
unknown
d2613
train
Have you tried putting the super call in an else block so it is only called if the key is not KEYCODE_BACK ? /* Prevent app from being killed on back */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Back? if (keyCode == KeyEvent.KEYCODE_BACK) { // Back moveTaskToBack(true); return true; } else { // Return return super.onKeyDown(keyCode, event); } } That should work for now! Feel free to comment if you have any problems. A: try this: @Override public void onBackPressed() { FragmentManager fm = getSupportFragmentManager(); int count = fm.getBackStackEntryCount(); if(count == 0) { // Do you want to close app? showDialog(); } } public void showDialog() { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Do you want to close the app"); alert.setPositiveButton("Confirm", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { finish(); //or super.onBackPressed(); } }); alert.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); alert.show(); } A: Override activity's onBackPressed with the following in case you have for instance made changes in some values and forgot to update those afterwards, but in stead pressed the back button : @Override public void onBackPressed() { if( <condition>) { AlertDialog.Builder ad = new AlertDialog.Builder( this); ad.setTitle("Changes were made. Do you want to exit without update?"); ad.setPositiveButton( "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { backPress(); } } ); ad.setNegativeButton( "Update the changes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { <Update the changes>; Toast.makeText(getApplicationContext(), "Changes were updated", Toast.LENGTH_SHORT).show(); backPress(); } } ); ad.setCancelable( false); ad.show(); } else { backPress(); } } private void backPress() { super.onBackPressed(); }
unknown
d2614
train
var app = angular.module("exApp",["ngSanitize"]); app.controller('ctrl', function($scope, $sce){ $scope.image = $sce.trustAsHtml('<img src="http://i67.tinypic.com/s6rmeo.jpg" style="width:200px;height:200px">'); }); <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-sanitize.min.js"></script> <body ng-app="exApp"> <div ng-controller="ctrl"> <span ng-bind-html="image"></span> </div> </body>
unknown
d2615
train
ERR_NAME_RESOLUTION_FAILED is a DNS failure error. If you have recently changed the DNS of your domain, it should take a while to become available in all regions. If you've already changed for quite a time, check if the computer where you are trying to access is having any other DNS errors / change DNS servers to known public service (Google/Cloudflare/OpenDNS). As you can see here, your DNS is failing in several regions: https://www.whatsmydns.net/#A/www.scaleitusa.com
unknown
d2616
train
You'll want to use the Request.QueryString collection to get your rid parameter out: sdm.UpdateParameters["rid"].DefaultValue = Request.QueryString["rid"]; Using an indexer with Request will get you values out of the QueryString, Form, Cookies or ServerVariables collections, using Request.QueryString directly makes your intentions that little bit clearer. A: Shouldn't the query string be ?replyid=a instead of ?rid=a?. It seems that Request["replyid"] returns null, and then ToString() throws the exception.
unknown
d2617
train
You don't really need to target your shipping methods, but instead customer shipping country: add_filter( 'woocommerce_cart_shipping_method_full_label', 'cart_shipping_method_full_label_filter', 10, 2 ); function cart_shipping_method_full_label_filter( $label, $method ) { // The targeted country code $targeted_country_code = 'DE'; if( WC()->customer->get_shipping_country() !== $targeted_country_code ){ $days_range = '5-7'; // International } else { $days_range = '3-5'; // Germany } return $label . '<br /><small class="subtotal-tax">' . sprintf( __("Lieferzeit %s Werktage"), $days_range ) . '</small>'; } Code goes on function.php file of your active child theme (or active theme). Tested and works.
unknown
d2618
train
So all of your input's name is record[], that will make the record[] value to be something like: ['name', 'ttl', 'type', 'prio', 'content','name', 'ttl', 'type', 'prio', 'content','name', 'ttl', 'type', 'prio', 'content'] Then you could try this: var final = []; var value = []; var i = 1; $("input[name='record[]']").each(function() { value.push($(this).val()); if(i % 5 == 0) { final.push(value); value = []; } i++; }); It will iterate over all of the record[], creating the new variable for each grouped input. It will be: [["name", "ttl", "type", "prio", "content"], ["name", "ttl", "type", "prio", "content"], ["name", "ttl", "type", "prio", "content"]] A: Here is a solution to my problem: var final = []; var value = []; var i = 1; $("input[name='record[]']").each(function() { value.push($(this).val()); if(i % 5 == 0) { final.push(value); value = []; } i++; }); var data = { records: value, zone_id: $(this).find("input[name='zone_id']").val(), action: $(this).find("input[name='action']").val(), csrf: $(this).find("#csrf").val(), } request = $.ajax({ cache: false, url: 'ajax/dns_zone.php', type: "post", dataType: "json", data: $(this).serialize(data) }); Here is HTML part: <form id="records-table"> {$csrf} <input type="hidden" name="action" value="edit_records" /> <input type="hidden" name="zone_id" value="{$zone.id}" /> {counter assign=i start=1 print=false} {foreach $dns_records as $record} <tr> <td class="text-center align-middle"> <a href="javascript:void(0);" class="text-danger delete-record" title="Delete record"><i class="fas fa-times-circle"></i></a> </td> <td> <input type="text" name="record[{$i}][name]" id="name" class="form-control" value="{$record.name|escape:html}" /> </td> <td> <select class="form-select" name="record[{$i}][ttl]" id="ttl" {if !$record.ttl}disabled{/if}> <option value="">-</option> {if $record.ttl} {foreach from=$dns_allowed_ttl item=ttl key=key} <option value="{$ttl}" {if $ttl eq $record.ttl}selected{/if}>{$ttl} min.</option> {/foreach} {/if} </select> </td> <td> <select class="form-select" name="record[{$i}][type]" id="type"> <option value="">-</option> {foreach from=$dns_record_types item=type key=key} <option value="{$type}" {if $type eq $record.type}selected{/if}>{$type}</option> {/foreach} </select> </td> <td style="width: 10%"> <input type="text" name="record[{$i}][prio]" id="prio" class="form-control" value="{if $record.priority}{$record.priority|escape:html}{else}-{/if}" {if $record.type neq 'MX'}disabled{/if}/> </td> <td> <input type="text" name="record[{$i}][content]" id="content" class="form-control" value="{$record.content|escape:html}"/> </td> </tr> {counter} {foreachelse} <tr>No records found.</tr> {/foreach} </form> Take a note at counter. It iterates array. It is important!
unknown
d2619
train
if the image loading failed, the callback will never call. but imported_image.sourceImg referent to the real img element, may be this will help. you can use it to detect the image load state. ex: imported_image.sourceImg.complete ;imported_image.sourceImg.onerror; A: Actually, the best way I've found to do this is checking the loaded property of the image in the draw loop. So: void draw() { if(imported_image != null ) { if(imported_image.loaded) { image(imported_image,0,0,500,500); } } } Not a callback, but same end result. Had more luck with that property than @DouO's sourceImg.complete.
unknown
d2620
train
var arrays = new List<float[]>(); //....your filling the arrays var averages = arrays.Select(floats => floats.Average()).ToArray(); //float[] var counts = arrays.Select(floats => floats.Count()).ToArray(); //int[] A: Not sure I understood the question. Do you mean something like foreach (string line in File.ReadAllLines("fileName.txt") { ... } A: Is it ok for you to use Linq? You might need to add using System.Linq; at the top. float floatTester = 0; List<float[]> result = File.ReadLines(@"Data.txt") .Where(l => !string.IsNullOrWhiteSpace(l)) .Select(l => new {Line = l, Fields = l.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) }) .Select(x => x.Fields .Where(f => Single.TryParse(f, out floatTester)) .Select(f => floatTester).ToArray()) .ToList(); // now get your totals int numberOfLinesWithData = result.Count; int numberOfAllFloats = result.Sum(fa => fa.Length); Explanation: * *File.ReadLines reads the lines of a file (not all at once but straming) *Where returns only elements for which the given predicate is true(f.e. the line must contain more than empty text) *new { creates an anonymous type with the given properties(f.e. the fields separated by comma) *Then i try to parse each field to float *All that can be parsed will be added to an float[] with ToArray() *All together will be added to a List<float[]> with ToList() A: Found an efficient way to do this. Thanks for your input everybody! private void ReadFile() { var lines = File.ReadLines("Data.csv"); var numbers = new List<List<double>>(); var separators = new[] { ',', ' ' }; /*System.Threading.Tasks.*/ Parallel.ForEach(lines, line => { var list = new List<double>(); foreach (var s in line.Split(separators, StringSplitOptions.RemoveEmptyEntries)) { double i; if (double.TryParse(s, out i)) { list.Add(i); } } lock (numbers) { numbers.Add(list); } }); var rowTotal = new double[numbers.Count]; var rowMean = new double[numbers.Count]; var totalInRow = new int[numbers.Count()]; for (var row = 0; row < numbers.Count; row++) { var values = numbers[row].ToArray(); rowTotal[row] = values.Sum(); rowMean[row] = rowTotal[row] / values.Length; totalInRow[row] += values.Length; }
unknown
d2621
train
The spring Roo 1.x version provides the "Database Reverse Engineering" functionality. This add-on allows you to create an application tier of JPA 2.0 entities based on the tables in your database. DBRE will also incrementally maintain your application tier if you add or remove tables and columns. After generate the entities, you could execute the necessary web mvc commands to generate the complete application. However, remember that the Spring Roo 1.x is not beeing maintained, because uses old technologies. See more about the DBRE process here: http://docs.spring.io/spring-roo/reference/html/base-dbre.html Hope it helps, A: There's a JHipster module that is being developed for this purpose: https://github.com/bastienmichaux/generator-jhipster-db-helper It is probably not ready yet but could be a good start.
unknown
d2622
train
It is actually not related to arrays at all. This is a string problem. In PHP you can access and modify characters of a string with array notation. Consider this string: $a = 'foo'; $a[0] gives you the first character (f), $a[1] the second and so forth. Assigning a string this way will replace the existing character with the first character of the new string, thus: $a[0] = 'b'; results in $a being 'boo'. Now what you do is passing a character 'x' as index. PHP resolves to the index 0 (passing a number in a string, like '1', would work as expected though (i.e. accessing the second character)). In your case the string only consists of one character (c). So calling $array['a']['b']['x'] = 'y'; is the same as $array['a']['b'][0] = 'y'; which just changes the character from c to y. If you had a longer string, like 'foo', $array['a']['b']['x'] = 'y'; would result in the value of $array['a']['b'] being 'yoo'. You cannot assign a new value to $array['a']['b'] without overwriting it. A variable can only store one value. What you can do is to assign an array to $array['a']['b'] and capture the previous value. E.g. you could do: $array['a']['b'] = array($array['a']['b'], 'x' => 'xyz'); which will result in: $array = array( 'a' => array( 'b' => array( 0 => 'c', 'x' => 'xyz' ) ) ); Further reading: * *Arrays *Strings
unknown
d2623
train
One possible solution you could think of is to use localStorage For every user, who has already rate, you then store a boolean to the local storage. Then next time, it will be validated first Something like this: export default function App() { const [value, setValue] = React.useState(0); const hasRated = localStorage.getItem("hasRated"); const handleRate = (e) => { setValue(e.target.value); localStorage.setItem("hasRated", true); }; return ( <div> <Box component="fieldset" mb={3} borderColor="transparent"> <Typography component="legend">Rate</Typography> <Rating disabled={hasRated} name="pristine" value={value} onClick={handleRate} /> </Box> </div> ); } Please note, that this is only a demonstrated example, so it supposes that you will need to have some improvement based on your needs Sanbox Example:
unknown
d2624
train
you can do it with jquery but if you want to use pure css you can do something like this: [type=radio]:checked ~ .[CLASS_OF_THE_IMAGE] { outline: 2px solid #f00; }
unknown
d2625
train
Your ngIf is not referencing your service. I think you have a typo :) *ngIf="!userSettings.uberSettings?.uberActivated" instead of *ngIf="!uberSettings?.uberActivated"
unknown
d2626
train
#inside-cntr { overflow:hidden; zoom:1; } Explanation: http://work.arounds.org/clearing-floats/
unknown
d2627
train
So I figured this out, This code block need to be var posTex = new Veldrid.ImageSharp.ImageSharpTexture(posPath, false, true); var normalTex = new Veldrid.ImageSharp.ImageSharpTexture(normalPath, false, true); var posDeviceTex = posTex.CreateDeviceTexture(gd, gd.ResourceFactory); var normalDeviceTex = normalTex.CreateDeviceTexture(gd, gd.ResourceFactory); var posViewDesc = new TextureViewDescription(posDeviceTex, PixelFormat.R8_G8_B8_A8_UNorm); var normalViewDesc = new TextureViewDescription(normalDeviceTex, PixelFormat.R8_G8_B8_A8_UNorm); positionTexture = gd.ResourceFactory.CreateTextureView(posViewDesc); normalTexture = gd.ResourceFactory.CreateTextureView(normalViewDesc); Instead. While fixing this someone also mentioned I needed to declare my TextureViews before my sampler if I wanted to use the same sampler for both textureViews. as far as gl_VertexIndex goes I'm looking into how to map the data into a spare uv channel instead as this should always be available in any game engine.
unknown
d2628
train
You definitely can specify the width of the slider by using initWithFrame or changing the bounds of it. There has to be something else going on here that's preventing it from working.
unknown
d2629
train
Try: input:required:-moz-ui-invalid {box-shadow: 1px 2px 9px yellow}; See https://developer.mozilla.org/en/CSS/:invalid
unknown
d2630
train
You are running an asyncronous operation and still expecting it to block your call and wait for the response, this is one workaround that i have seen in the past, you hide your submit button and create another button that calls your ajax request, in the success of this request you click you hidden button, something like this : <asp:Button ID="btn_upload_dummy" runat="server" CssClass="btnEffects" Text="Upload" OnClientClick="Validate();" /> <asp:Button ID="btn_upload" runat="server" CssClass="btnEffects" style='display:none;' Text="Upload" onclick="btn_upload_Click" /> <script language="javascript"> function Validate() { var filename = $get('<%=txt_filename.ClientID %>').value; PageMethods.IsValidFile(filename,OnSuccess, OnFailure); // IsValidFile is a Page Method of bool return type } function OnSuccess(result) { if ( !result) { alert('File '+ $get('<%=txt_filename.ClientID %>').value + ' does not exist'); return false; } else { var btn = $get('<%btn_upload.ClientID'); var clicker = btn.click ? btn.click : btn.onclick; clicker(); } } </script>
unknown
d2631
train
Your code: <h1><xsl:value-of select="h1"/></h1> is OK, but you wrote it in a wrong place. You should use it in a template matching the parent tag (containg h1 tags) and add an empty template for h1, to prevent rendition of original h1 elements by the identity template. Look at the following script: <?xml version="1.0" encoding="UTF-8" ?> <xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"> <xsl:output method="xml" encoding="UTF-8" indent="yes" /> <xsl:strip-space elements="*"/> <xsl:template match="main"> <xsl:copy> <h1><xsl:value-of select="h1"/></h1> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="h1"/> <xsl:template match="@*|node()"> <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy> </xsl:template> </xsl:transform> For the input given below: <main> <h1>aaa</h1> <h1>bbb</h1> <h1>ccc</h1> <h2>xxx</h2> </main> It prints: <main> <h1>aaa bbb ccc</h1> <h2>xxx</h2> </main>
unknown
d2632
train
Late, late answer. You're totally fine. That's the proper way to do it, actually. See my blog post: http://touchlabblog.tumblr.com/post/24474750219/single-sqlite-connection/. Dig through my profile here. Lots of examples of this. ContentProvdier is just a lot of overhead and not needed unless you're sharing data outside of your app. Transactions are good to speed things up and (obviously) improve consistency, but not needed. Just use one SqliteOpenHelper in your app and you're safe. A: My bet: it isn't safe. To be in safer position you should use SQL transactions. Begin with beginTransaction() or beginTransactionNonExclusive() and finish with endTransaction(). Like shown here A: This is my solution I created a class and a private static object to syncronize all db access public class DBFunctions { // ... private static Object lockdb = new Object(); /** * Do something using DB */ public boolean doInsertRecord(final RecordBean beanRecord) { // ... boolean success = false; synchronized (lockdb) { // ... // // here ... the access to db is in exclusive way // // ... final SQLiteStatement statement = db.compileStatement(sqlQuery); try { // execute ... statement.execute(); statement.close(); // ok success = true; } catch (Exception e) { // error success = false; } } return success; } } I tryed using ASYNC task and it works fine . I hope is the right way to solve the problem. Any other suggestions ??? A: Good question. My first thought is it wouldn't be safe. However, according to the SQLite docs, SQLite can be used in 3 modes. The default mode is "serialized" mode: Serialized. In serialized mode, SQLite can be safely used by multiple threads with no restriction So I assume this it's compiled in serialized mode on Android. A: Just saw this while I was looking for something else. This problem looks like it would be efficiently solved by using a ContentProvider. That way both the Activity as well as the Service can use the content provider and that will take care of the Db contention issues.
unknown
d2633
train
Try using MultiCell with some cell width combination, like this: public function Footer() { // Make more space in footer for additional text $this->SetY(-25); $this->SetFont('helvetica', 'I', 8); // Page number $this->Cell(0, 10, 'Seite '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M'); // New line in footer $this->Ln(8); // First line of 3x "sometext" $this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M'); $this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M'); $this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M'); // New line for next 3 elements $this->Ln(4); // Second line of 3x "sometext" $this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M'); $this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M'); $this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M'); // and so on... } You can see more examples of how to use MultiCell function in TCPDF official examples: https://tcpdf.org/examples/example_005/
unknown
d2634
train
When comparing floating point values, instead of doing this : if (log != -0.1) You should allow a little delta/tolerance on the value to account for floating point precision and the eventual value "change" you may get from passing it as a varying. So you should do something like : if (abs(log - (-0.1)) >= 0.0001) Here the 0.0001 I chosen is a bit arbitrary ... It has to be a small value ... Another example with == Instead of : if (log == 0.7) do if (abs(log - 0.7) <= 0.0001) However here you probably also have another issue: * *The vertex shader executes for each 3 vertex of all your triangles (or quads) *So for a specific triangle, you may set different values (-0.1 or 0.7) for log for each vertex *Now the problem is that in the fragment shader the GPU will interpolate between the 3 log values depending on which pixel it is rendering ... so in the end you can get any value in [-0.1,0.7] interval displayed on screen :-( To avoid this kind of issue, I personally use #ifdefs in my shaders to be able to switch them between normal and debug mode, and can switch between the two with a keypress. I never try to mix normal and debug displays based on if tests, especially when the test is based on a vertex position. So in your case I would first create a specific debug version of the shader, and then use 0.0 and 1.0 as values for log, like this what you will see are red gradients, the more red the color is, the closer you are to the case you want to test.
unknown
d2635
train
It should be $(this.element).
unknown
d2636
train
I had some good results reusing the Parse class from Fit/Fitnesse for getting data out of html tables.
unknown
d2637
train
Yes. You're going to want to use AbstractUser instead of AbstractBaseUser. Details are provided here: https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#extending-django-s-default-user It creates a different table in the database (not auth_user), but still fully extends into the Django Admin quite elegantly.
unknown
d2638
train
As you mentioned in your question I review the website and find this code, after that I tested it on my android device and I figure out this is the answer. First, add this code to your page to show the file picker user interface <z-place inside="Body"> <FilePicker Id="MyFilePicker"></FilePicker> </z-place> Then, add below code to the page code behind to set the control just for picking the photos. public override async Task OnInitializing() { await base.OnInitializing(); await InitializeComponents(); MyFilePicker.Set(x => x.AllowOnly(MediaSource.PickPhoto, MediaSource.TakePhoto)); }
unknown
d2639
train
First of all, that looks like Pivotal's tc Server rather than Apache Tomcat. tc Server is based on Apache Tomcat but they are not exactlt the same and it always helps to provide the most accurrate information you can. There is something seriously wrong with your dependencies. Tomcat is detecting the following class heirarchy: org.bouncycastle.asn1.ASN1EncodableVector ->org.bouncycastle.asn1.DEREncodableVector ->org.bouncycastle.asn1.ASN1EncodableVector This is a cyclic dependency. In Java it is illegal for A to extend B if B extends A. Cleaning out your dependencies and ensuring you are using only using one version of the bouncy castle JAR should fix this. If the problem persists and can be reproduced on a clean install of the latest stable Tomcat 7 release then please do open a bug against Apache Tomcat and provide the web application that demonstrates the issue.
unknown
d2640
train
To solve this, just modify the properties of .carousel-control-prev and .carousel-control-prev in the CSS. .carousel-control-prev, .carousel-control-next { height: 25%; top: 37.5%; }; <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> <body> <div class="container"> <div class="row"> <div class="col"> <div id="carouselExampleIndicators" class="carousel slide my-4" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> </ol> <div class="carousel-inner" role="listbox"> <div class="carousel-item active"> <img class="d-block img-fluid" src="http://placehold.it/900x350" alt="First slide"> </div> <div class="carousel-item"> <img class="d-block img-fluid" src="http://placehold.it/900x350" alt="Second slide"> </div> <div class="carousel-item"> <img class="d-block img-fluid" src="http://placehold.it/900x350" alt="Third slide"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> </div> </div> </body> I have no idea why the top property could not override in the demo. But it works in my project.
unknown
d2641
train
You can do something like : public boolean collide(HasBounds a, HasBounds b){... With the interface : public interface HasBounds{ Rectangle getBounds(); } That you should define on your objects Arrow,Enemy etc... (you may already have an object hierarchy suitable for that). A: what do you think of this.. public boolean collide(Rectangle a1, Rectangle b1) { return a1.intersects(b1); } or may be Create an interface public interface CanCollide { Rectangle getBounds(); } and use it in the method... public boolean collide(CanCollide a, CanCollide b) { Rectangle a1 = a.getBounds(); Rectangle b1 = b.getBounds(); if(a1.intersects(b1)) return true; else return false; } Hope you find it usefull. Thanks! @leo. A: Just make abstract class GameObject with method: Rectangle2D getShape(). This method could look like: abstract class GameObject { private Image image; GameObject(String path) { try { image = ImageIO.read(new File(path)); } catch (IOException ex) {} } Rectangle2D getShape() { return new Rectangle2D.Float(0, 0, (int)image.getWidth(), (int)image.getHeight()); } } Player, Enemy, Arrow, Wall would be subclasses of GameObject class
unknown
d2642
train
I would do this using the default attribute in serializer fields. class PersonCommentSerialiser(serializers.HyperlinkedModelSerializer): author = serializers.PrimaryKeyRelatedField(read_only=True, default=CurrentUserDefault()) class Meta: model = PersonComment fields = ('url', 'body', 'person', 'author') CurrentUserDefault is a class predefined in Django REST framework for exactly this purpose. This way you don't have to overwrite create in your own serializer. I was not sure what is the difference between person and author. But you should be able to do something similar I suppose.
unknown
d2643
train
The first solution is quite complex, you are not actually scaling the rectangle, but rather the projection matrix. The projection matrix is the series of mathematical operations that are applied before something is drawn to the screen. You can think of it as a camera, but it is far more complex than that. I actually put the code side by side and didn't notice that much difference in the smoothness. I also added a few tweaks, so that may have helped :) float r = 1; float s = 0.0; void setup() { size(200,200); rectMode(CENTER); frameRate(30); smooth(); } void draw(){ rect(width/4, height/2, r, r); r += 1.4; translate(width/2, height/2); scale(s); translate(-width/2, -height/2); rect(width/2, height/2, 50, 50); s += 0.04; } The main change that I made was to turn on smooth. I think that because you didn't have it on, the top square drawing was jumping to each pixel, but with the tranlation / scale operation, it would smooth those over. The other thing I did, was to translate back to the top left after doing the scale operation. This is important to do so that things draw where you expect them to. You will notice that the scaling rect now scale out from the center.
unknown
d2644
train
Instead of set, you would use the splice array method, which will invoke the update.
unknown
d2645
train
You have several options. Read here: https://developer.android.com/guide/topics/data/data-storage.html In your case perhaps you can simply use SharedPreferences, here: https://developer.android.com/guide/topics/data/data-storage.html#pref SharedPreferences sharedPreferences = context.getSharedPreferences("FILE_NAME", Context.MODE_PRIVATE); To put the value: (.commit() instead of .apply() if you care whether or not putString was successful) SharedPreferences sharedPreferences = context.getSharedPreferences(COOKIE_SP_FILE_NAME, Context.MODE_PRIVATE); if (sharedPreferences != null) { sharedPreferences.edit().putString("KEY", "VALUE").apply(); } To retrieve the value: SharedPreferences sharedPreferences = context.getSharedPreferences("FILE_NAME", Context.MODE_PRIVATE); if (sharedPreferences != null) { String theString = sharedPreferences.getString("KEY", "DEFAULT_VALUE"); } Where "DEFAULT_VALUE" is what you would get if no value with "KEY" as key was found.
unknown
d2646
train
() => void, B: string } I use those to build the following class methods: declare class MyClass { myFunction(option: 'A', value: OptionsValueType['A']) myFunction(option: 'B', value: OptionsValueType['B']) myFunction(option: Exclude<Options, SpecificOptions>, value: number) } This works great: And I also have some code that calls myFunction inside a loop, using Function.prototype.apply, it looks something like this: const calls = [ ['A', 1], ['B', 1], ['C', 1], ] for (const call of calls) { a.myFunction.apply(undefined, call) } But the code above does not shows any type error. I cannot use as const on the calls array because it's built dynamically (and even if I could, it does not seems to work either). How to type the code above to make sure the .apply is correctly typed? Or is that currently not possible with Typescript? Above code is available on this Typescript playground A: If calls is built dynamically then no, there is no way to get a compile time error based on its value. You can check the values at runtime and throw an error of your own. Otherwise, JS will pass them in as function arguments regardless of their type. If you wanted to check the types yourself you could do: for (const call of calls) { if (typeof call[0] !== 'string' || typeof call[1] !== 'string') { throw new Error('Both arguments to myFunction must be strings'); } a.myFunction.apply(undefined, call) }
unknown
d2647
train
Not a good idea in general but you can find discussion here : Blocking device rotation on mobile web pages How do I lock the orientation to portrait mode in a iPhone Web Application? a solution could be to rotate the content using CSS3 on orientation change event.
unknown
d2648
train
I hava the same problem。this is my solution。 first stop etcd service using systemctl systemctl stop etcd.service and then, check port is occupied lsof -i:2380 if occupied kill the pid kill -9 xxx last,start etcd service systemctl start etcd.service
unknown
d2649
train
Why are you against giving the UnitController a reference to its Map? public UnitController { private final Map map; public UnitController(Map map) { this.map = map; } } Now your UnitController has a reference to the Map. And this makes sense, if you think about it. What units can be controlled without a map? Shouldn't all UnitControllers have a Map on which they are controlling units? It makes sense as a property, does it not? You certainly don't want to make Map a singleton, as you suggest, as this sort of breaks the elegant object-orientedness of your model. The whole point is to be able to have multiple Maps, on which multiple UnitControllers can be acting. Restricting this to one run at a time, one Map at a time, makes the code much more procedural than object-oriented. No matter what you do, the Map and the UnitController will have to have something in common in order to share data, even if you don't want them to have direct references to each other. As far as "towers which attack the nearest unit" being a reason not to use this model, it doesn't make sense; a Tower ought to simply request the nearest unit from the Map object (i.e., map.getNearestUnit(int x, int y)). No need for any more convoluted references, as long as everything can push and pull information from the Map. For a more complicated example of the threaded Tower you're concerned with: public class Tower extends Unit implements ActionListener { private final Timer fireTimer; private final Map map; private int damage; private int range; public Tower(Map map, int damage, int range, int fireRate) { this.map = map; this.damage = damage; this.range = range; fireTimer = new Timer(fireRate, this); fireTimer.start(); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == fireTimer) { map.damageNearestUnit(this, range, damage); } } } ... where the signature for map.damageNearestUnit is something like damageNearestUnit(Unit unit, int range, int damage). This should essentially take the passed in Unit, get its coordinates, and find the nearest unit in the int range. If one exists in range, deal the int damage to that other unit. Then if the damaged Unit has less than 1 health, it should be removed from the Map, trigger a UI change, etc. Actually, if I had simple getters and setters in my Tower and had my damageNearestUnit method assume that one unit was damaging another, I could simply have its signature be damageNearestUnit(Unit attacker). I hope this shows how the Map is the fabric that binds everything else together and controls that which exists on it.
unknown
d2650
train
If you move to storyboards and autolayout you don't need to localize your UI, you just need to provide the localised strings files. A: Is localizing XIB files good because it is not possible/easy to use localized strings as titles for the controls in the interface builder? The backside is, when you need to show a message to the user sometimes needed the label localized text without colon. The xib provides name with colon and without. Sometimes hard to keep in evidence what / where is in localized xib. You can make an utility software to make easier the localisation of strings and editing those inline with many languages. That why I prefer strings localized over xib.
unknown
d2651
train
try this SELECT round(convert(float,17)/26,2) A: For whatever it's worth, when I'm doing something like this with an actual hard-coded value I just add a decimal place to one of the elements. A CAST() is better for a database field, but if you're typing something in just use a decimal ... SELECT 17/26, 17/26.0, 17.0/26 A: try force engine to manage floats (multiplying with float number '1.0') like this... SELECT (1.0*17/26) as x; also to round... you can write it like SELECT round((1.0*17/26),2) as x; (tried on PostgreSQL and worked)
unknown
d2652
train
You have the seconds, so just do something like SELECT secondsField / 3600 as 'hours' FROM tableName A: Here is an example of finding the difference between two timestamps in days. //Get current timestamp. $current_time = time(); //Convert user's create time to timestamp. $create_time = strtotime('2011-09-01 22:12:55'); echo "Current Date \t".date('Y-m-d H:i:s', $current_time)."\n"; echo "Create Date \t".date('Y-m-d H:i:s', $create_time)."\n"; echo "Current Time \t ".$current_time." \n"; echo "Create Time \t ".$create_time." \n"; $time_diff = $current_time - $create_time; $day_diff = $time_diff / (3600 * 24); echo "Difference \t ".($day_diff)."\n"; echo "Quote Index \t ".intval(floor($day_diff))."\n"; echo "Func Calc \t ".get_passed_days($create_time)."\n"; function get_passed_days($create_time) { return intval(floor((time() - $create_time) / 86400)); } To convert to hours, instead of 86400 put 3600 instead. Hope this helps.
unknown
d2653
train
The proper way is using an interface, it doesn't generate extra code when compiled to javascript and it offers you static typing capabilities: https://www.typescriptlang.org/docs/handbook/interfaces.html A: Here is an easy and naive implementation of what you're asking for: interface IDataNode { id: number; title: string; node: Array<IDataNode>; } If you want to instantiate said nodes from code: class DataNode implements IDataNode { id: number; title: string; node: Array<IDataNode>; constructor(id: number, title: string, node?: Array<IDataNode>) { this.id = id; this.title = title; this.node = node || []; } addNode(node: IDataNode): void { this.node.push(node); } } Using this to hardcode your structure: let data: Array<IDataNode> = [ new DataNode(1, 'something', [ new DataNode(2, 'something inner'), new DataNode(3, 'something more') ]), new DataNode(4, 'sibling 1'), new DataNode(5, 'sibling 2', [ new DataNode(6, 'child'), new DataNode(7, 'another child', [ new DataNode(8, 'even deeper nested') ]) ]) ]; A: Update: 7/26/2021 I revisited the discussion noted in the original answer, and there is now an update with an improved implementation. type JSONValue = | string | number | boolean | null | JSONValue[] | {[key: string]: JSONValue} interface JSONObject { [k: string]: JSONValue } interface JSONArray extends Array<JSONValue> {} This has been working very well for me. Discussion reference: https://github.com/microsoft/TypeScript/issues/1897#issuecomment-822032151 Original answer: Sep 29 '20 I realize this is an old question, but I just found a solution that worked very well for me. Declare the following type JsonPrimitive = string | number | boolean | null interface JsonMap extends Record<string, JsonPrimitive | JsonArray | JsonMap> {} interface JsonArray extends Array<JsonPrimitive | JsonArray | JsonMap> {} type Json = JsonPrimitive | JsonMap | JsonArray then any of the following (including the OP's version slightly modified for syntax errors) will work let a: Json = {}; a[1] = 5; a["abc"] = "abc"; a = { a: { a: 2, }, b: [1, 2, 3], c: true, }; a = [ { "id": 1, "title": "something", "node": [ { "id": 1, "title": "something", "node": [], }, ], }, { "id": 2, "title": "something", "node": [ { "id": 1, "title": "something", "node": [], }, ], }, ]; This answer should be credited to Andrew Kaiser who made the suggestion on the discussion about making Json a basic type in Typescript: https://github.com/microsoft/TypeScript/issues/1897#issuecomment-648484759
unknown
d2654
train
Yes, the height is 568. If you want to remove "letterboxing", please see this post: iPhone 5 letterboxing / screen resize
unknown
d2655
train
MailChimp's docs state that support for custom fonts in emails is limited. Elements to Avoid > Custom Fonts MailChimp’s Drag and Drop Editor provides web-safe fonts only. Most email clients don’t support CSS properties like @font-face, @import, and that import custom fonts into web pages. For consistent display, use web-safe fonts. Or use images to display custom-font headlines, and include the body content as text. Without this balance of text and images, spam filters can flag your campaign. from Limitations of HTML Email Perhaps they are trying to protect you from seeing a preview different than what most of your users will see. However it does seem you can override this default with a custom template: Note If you’re comfortable with coding or if you have access to a developer, you can design custom coded templates that contain HTML elements with limited email client support, but we don’t always recommend it. Keep in mind that MailChimp support agents won’t be able to help you troubleshoot issues with your custom code. Update: In the custom template docs (see Experimenting with Web Fonts), they do discourage use, but claim <link>, @import, @font-face, etc will work as expected in mail clients whose browsers do support custom fonts. A: well, I think is more matter of what email client (or browser) you are using on mobile device, unfortunately it's highly possible that on older devices etc, you won't be able to get your font, especially in old mail mobile clients, here is something what I consider as a quite ok solution ( yep, not the best one probably ), but if your mail looks good in Outlook 2010 on your desktop, then it should be ok in most of the other clients/browsers, Outlook 2010 is could be such a pain, that if you make things work in it, that should cover the other environments
unknown
d2656
train
If you don't mind a little Win32, you can use SHGetSpecialFolderPath. [DllImport("shell32.dll")] static extern bool SHGetSpecialFolderPath(IntPtr hwndOwner, StringBuilder lpszPath, CSIDL nFolder, bool fCreate); enum CSIDL { COMMON_STARTMENU = 0x0016, COMMON_PROGRAMS = 0x0017 } static void Main(string[] args) { StringBuilder allUsersStartMenu = new StringBuilder(255); SHGetSpecialFolderPath(IntPtr.Zero, allUsersStartMenu, CSIDL.COMMON_PROGRAMS, false); Console.WriteLine("All Users' Start Menu is in {0}", allUsersStartMenu.ToString()); } A: Use Environment.SpecialFolder.CommonStartMenu instead of StartMenu. A: Thanks guys, I found the answer: private void RemoveShortCutFolder(string folder) { folder = folder.Replace("\" ", ""); folder = Path.Combine(Path.Combine(Path.Combine(Environment.GetEnvironmentVariable("ALLUSERSPROFILE"), "Start Menu"), "Programs"), folder); try { if (System.IO.Directory.Exists(folder)) { System.IO.Directory.Delete(folder, true); } else { } } catch (Exception) { } }
unknown
d2657
train
If you make a new structure that might look like this: Public Structure Version Public ID As String Public TIME As String Public releaseTime As String Public type As String End Structure And then, maybe on a button click, write this Dim allVersions = New List(Of Version) Using wc = New WebClient() With {.Proxy = Nothing} Dim JSON = Await wc.DownloadStringTaskAsync("https://s3.amazonaws.com/Minecraft.Download/versions/versions.json") 'Downloads the JSON file Dim values = JsonConvert.DeserializeObject(Of JObject)(JSON) 'Converts it to JObject For Each i In values("versions").Children() 'Gets the versions YOUR_LISTBOX.Items.Add(i.ToObject(Of Version).ID) Next End Using
unknown
d2658
train
I have tried your example as such: import unittest class A(unittest.TestCase): def test_a(self): self.assertEqual(1, 1) class B(A): def test_b(self): self.assertEqual(2, 3) if __name__ == '__main__': unittest.main() and it worked, this is test result: test_a (__main__.A) ... ok test_a (__main__.B) ... ok test_b (__main__.B) ... FAIL
unknown
d2659
train
This is a bcrypt issue. Verify that you have uncommented bcrypt in your Gemfile, run bundle install, and then restarted the server. See: undefined method `key?' for nil:NilClass with bcrypt-ruby and has_secure_password
unknown
d2660
train
Why don't you try Picasso? It's as simple as this: Picasso .with(context) .load("https://pbs.twimg.com/profile_banners/169252109/1422362966") .into(imgView); And, you can also transform the Bitmap, applying tint, resizing to prevent memory issues, all that stuff.
unknown
d2661
train
Something like this is one way /* * Example of deleting X rows of data at a time from a table to avoid e.g. transaction log full on row organized talbes * */ BEGIN DECLARE DONE BOOLEAN DEFAULT FALSE; -- DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' BEGIN SET DONE = TRUE; END; -- WHILE NOT DONE DO DELETE FROM (SELECT * FROM MY_TABLE WHERE COL1 = 'A' FETCH FIRST 20000 ROWS ONLY) COMMIT; END WHILE; END You could also consider using MDC tables to allow "rollout" deletion, or other physical design optimizations
unknown
d2662
train
I have found the issue myself: * *Binding between server side and client side must be the same, hence I change both to basicHttpBinding *Service name is case sensitive, I changed "WcfClient.XXXService" to "wcfClient.XXXService" and it works now. Hope this can help others with the same difficulties =)
unknown
d2663
train
Using this code you can retrieve the PropertyInfos for the Something and for the Else property: Foo myObject = new Foo { bar = new Bar() }; // the FieldInfo for Foo.bar var barField = myObject.GetType().GetFields().First(); // the Bar instance, i.e. myObject.bar var barValue = barField.GetValue(myObject); var somethingProperty = barField.FieldType.GetProperty("Something", BindingFlags.Instance | BindingFlags.Public); var elseProperty = barField.FieldType.GetProperty("Else", BindingFlags.Instance | BindingFlags.Public); as PsiHamster noted, you can then use GetValue and SetValue to retrieve and set the values of somethingProperty and elseProperty like this: // get the value var somethingValue = somethingProperty.GetValue(barValue); // set the value somethingProperty.SetValue(barValue, new List<int>()); A: //Get Bar FieldInfo var barFieldInfo = myObject.GetType().GetFields().First(); // Get all public instance properties info var barProps = barFieldInfo.FieldType.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); // Get Something and Else properties info var smthPropInfo = barProps.First(prop => prop.Name == nameof(Bar.Something)); var elsePropInfo = barProps.First(prop => prop.Name == nameof(Bar.Else)); // Get values var bar = barFieldInfo.GetValue(myObject); var smth = smthPropInfo.GetValue(bar); var else = elsePropInfo.GetValue(bar);
unknown
d2664
train
Your form is not submitting to the right route. Use form builder instead: <%= form_for @welcome do |f| %> <%= f.label :kind %> <%= f.text_field :kind %> <%= f.submit %> <% end %> This will put right route for form submission into your HTML
unknown
d2665
train
If you want that the avg values will be a tuple element (I don't see any reason to do so but maybe I don't have enough context), try: results={k: (sum(v)/len(v),) for k,v in students.items()} A: I was trying this but realized we had a problem summing a tuple of length 1. So you can do it this way. results = {} for k, v in students.items(): print(v) if (isinstance(v, int)): results[k] = v else: results[k] = sum(v) / len(v) A: I'd do: result = {} for k, v in students.items(): if type(v) in [float, int]: result[k] = v else: result[k] = sum(v) / len(v) A: A pythonic solution would be to use dictionary comprehension to create the results dictionary. def avg(l): return sum([l]) / len(l) results = {key: (avg(val)) for (key, val) in students.items()} You need brackets around the l in sum so the tuple is treated as a list. I would further change the data structure to a list instead of tuple.
unknown
d2666
train
Note: I haven't done this myself, so all the info below is purely from reading the documentation: The NSMetadataItem class has, among others, an attribute key called NSMetadataUbiquitousItemIsUploadedKey. Knowing this, you should be able to set up an NSMetadataQuery that notifies you once the item has been uploaded. A: You can check with NSUURL getResourceValue:forKey:error: method NSURLUbiquitousItemIsUploadedKey—Indicates that locally made changes were successfully uploaded to the iCloud server. NSURLUbiquitousItemIsUploadingKey—Indicates that locally made changes are being uploaded to the iCloud server now. NSURLUbiquitousItemPercentUploadedKey—For an item being uploaded, indicates what percentage of the changes have already been uploaded to the server. For details: https://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/iCloud/iCloud.html#//apple_ref/doc/uid/TP40007072-CH5-SW1
unknown
d2667
train
The code is poorly written regardless of which version of SQL you're using, because NULL is never "equal" to anything (even itself). It's "unknown", so whether or not it's equal (or greater than, or less than, etc.) another value is also "unknown". One thing that can affect this behavior is the setting of ANSI_NULLS. If your 2005 server (or that connection at least) has ANSI_NULLS set to "OFF" then you'll see the behavior that you have. For a stored procedure the setting is dependent at the time that the stored procedure was created. Try recreating the stored procedure with the following before it: SET ANSI_NULLS ON GO and you'll likely see the same results as in 2008. You should correct the code to properly handle NULL values using something like: WHERE X = @X OR (X IS NULL AND @X IS NULL) or WHERE X = COALESCE(@X, X) The specifics will depend on your business requirements. A: That might be due to your ansi_null settings in two servers. When SET ANSI_NULLS is ON, a SELECT statement that uses WHERE column_name = NULL returns zero rows even if there are null values in column_name. A SELECT statement that uses WHERE column_name <> NULL returns zero rows even if there are nonnull values in column_name. When SET ANSI_NULLS is OFF, the Equals (=) and Not Equal To (<>) comparison operators do not follow the SQL-92 standard. A SELECT statement that uses WHERE column_name = NULL returns the rows that have null values in column_name. A SELECT statement that uses WHERE column_name <> NULL returns the rows that have nonnull values in the column. Also, a SELECT statement that uses WHERE column_name <> XYZ_value returns all rows that are not XYZ_value and that are not NULL. You can find detailed information here: https://msdn.microsoft.com/en-us/library/ms188048(v=sql.90).aspx A: Try this: select A, B, C from TABLE where X IS NULL The reason why your original query did not return the expected result is explained here A: SET ANSI_NULLS OFF GO ^^That made the stored procs work the way I expected.
unknown
d2668
train
The reason is this.props is not defined in a functional component. They receive the props as an argument. Change your TextField to take argument props and use props.title const TextField = (props) => { return ( <Text> {props.title} </Text> ) }
unknown
d2669
train
Notifications created by SL4A do nothing; they have no callback and can only alert users. Unfortunately there isn't really any way around this: BeanShell, JRuby and Rhino can make Java API calls (eg., to add the 'open my app when clicked' part) but can't use Contexts (which notifications require), and you could make your own version of the API facade, but then users would be required to install your specific version of x (eg., Python) for Android. Otherwise all I could think of would be to get tricky with Intents or something and include an activity in the /src of your app to show the notification, though that would likely require learning Java / Android programming meaning you may as well follow through and write the entire app natively. Sorry, but there really isn't an easy way to do this A: You stated you wanted to publish it so I am assuming you were implying that in the long run you will be compiling it into a standalone apk? If so, which package are/will you be using? py4a's method, python27, kivy? From my experiences when you compile to an apk with python27, there is no notification window at the top at all but if you were to compile it using py4a's method it should create a workable notification item for you. Please see the following link for further information: http://code.google.com/p/android-scripting/wiki/SharingScripts Otherwise ProfSmiles answer is correct but it appears to be a much more complex solution then using the py4a method. You can also see the python27 project if you would like a more embedded approach, although as mentioned previously it does not have a notification setup by default like py4a. Kivy's implementation also looks promising but I am unfamiliar with it, it might also be worth looking at further: https://github.com/kivy/python-for-android A: Well It seems that you can see the notifications started by SL4A "como.googlecode.android_scripting" package with the following command: This is more like a hack. dumpsys statusbar | grep "pkg=com.googlecode.android_scripting" Every notification initiated by SL4A will have an "id". For example the "id=1" is the notification started by SL4A when the server is running. The one you click to stop the server. With this in mind you can can actually list every notification started by your package and block until the id of your notification disappear. If so then your next notifications should have an id with 2 or above. Note that this can change if SL4A is stopped or crash. The next time you may get the "id=2" for the (RPC) server notification and then "id=3" and over for your app notifications until you restart your device and so the RPC server notification goes back to "id=1". Knowing this means that you need to keep searchig for new notifications within a loop. For example in bash and using adb: while read Info; do echo "$Info" | grep 'pkg=com.googlecode.android_scripting'; done < <(adb shell dumpsys statusbar) You'll get something like this: 1: StatusBarNotification(pkg=com.googlecode.android_scripting id=2 tag=null score=0 notn=Notification(pri=0 contentView=com.googlecode.android_scripting/0x109008f vibrate=null sound=null defaults=0x0 flags=0x62 kind=[null]) user=UserHandle{0}) # SL4A RPC Notification 7: StatusBarNotification(pkg=com.googlecode.android_scripting id=3 tag=null score=0 notn=Notification(pri=0 contentView=com.googlecode.android_scripting/0x109008f vibrate=null sound=null defaults=0x0 flags=0x10 kind=[null]) user=UserHandle{0}) # My Notification Let's play with this! Running: while read Info; do echo "$Info" | grep "pkg=com.googlecode.android_scripting" | awk '{print $3}' | cut -s -d '=' -f2 ; done < <(adb shell dumpsys statusbar) Will get you for example: # Without Using Cut id=2 # SL4A Notificaion id=3 # My Notification Or: # Using Cut 2 # SL4A Notification 3 # My Notification Let's get to the action! (An ugly solution) # Start ADB USB Serial Connection adb devices # Activate Wireless ADB (Needs Root) - Not Needed # adb shell setprop service.adb.tcp.port 5555 # stop adbd # start adbd Or: # Start ADB Wireless adb connect 192.168.1.3 NotifyCount=0 NotifyList=() while read Notify; do DumpNotify=`echo "$Notify" | grep "pkg=com.googlecode.android_scripting" | awk '{print $3}' | cut -s -d '=' -f2` if [ ! -z "$DumpNotify" ] ; then NotifyList[$NotifyCount]="$DumpNotify" ((NotifyCount++)) fi done < <(adb shell dumpsys statusbar) SL4ARPCNotification="2" MyScriptNotification="3" if [[ ${NotifyList[*]} != *"$MyScriptNotification"* ]] ; then adb shell am start -a android.intent.action.MUSIC_PLAYER fi This should be better in 2 functions with arguments for MyNotification and SL4ARPCNotification variables. That way you can verify from anywhere in the code and divide the job: FunctionX for listing the notifications and FunctionY for comparing the results. This can easily be done in Pyhon or other interpreters. You need to remember that there's always a notification from SL4A itself. By using Threading in python you can continuously search for new or old notifications without the need to block your program waiting for a change and thus you can continue runninig your script normally.
unknown
d2670
train
The Dataflow SDK 2.x for Java and the Dataflow SDK for Python are based on Apache Beam. Make sure you are following the documentation as a reference when you update. Quotas can be an issue for slow running pipeline and lack of output but you mentioned those are fine. It seems there is a need to look at the job. I recommend to open an issue on the PIT here and we’ll take a look. Make sure to provide your project id, job id and all the necessary details.
unknown
d2671
train
Considering the IntelliJ-git integration requires a git, make sure you have the latest (1.8.3+) installed. Otherwise, you should be able to use the same working tree/repo as the one used by Eclipse Egit. No special migration should be required.
unknown
d2672
train
A MAC address is nothing more than a number represented by 6 bytes written in hexdecimal form. So, converting the lower and upper limit of the MAC address could give you a manageable range of values to check with a single IF Sub Main Dim lowRange = "78:A1:83:24:40:00" Dim upRange = "78:A1:83:24:40:FF" Dim startVal = GetValue(lowRange) Dim endVal = GetValue(upRange) Console.WriteLine(startVal) ' 132635085258752 Console.WriteLine(endVal) ' 132635085259007 Dim macToCheck = "78:A1:83:24:40:B0" Dim checkVal = GetValue(macToCheck) Console.WriteLine(checkVal) ' 132635085258928 if checkVal >= startVal AndAlso checkVal <= endVal Then ' VP-1 Console.WriteLine("In range") End If End SUb Function GetValue(mac as String ) as Long Dim clearText = mac.Replace(":", "") Dim result Long.TryParse(clearText, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, result) return result End Function Now, as an example to avoid a long list of IF you could use a Dictionary filled with your ranges and then apply a simple For Each logic to find your ranges Sub Main Dim dc as New Dictionary(Of String, MacRange)() dc.Add("VP-1", new MacRange() with { .Lower = "78:A1:83:24:40:00", .Upper = "78:A1:83:24:40:FF" }) dc.Add("VP-2", new MacRange() with { .Lower = "78:A1:83:24:41:00", .Upper = "78:A1:83:24:41:FF" }) dc.Add("VP-3", new MacRange() with { .Lower = "78:A1:83:24:42:00", .Upper = "78:A1:83:24:42:FF" }) Dim result = "" Dim macToCheck = "78:A1:83:24:42:B0" Dim checkVal = GetValue(macToCheck) 'For Each k in dc ' Dim lower = GetValue(k.Value.Lower) ' Dim upper = GetValue(k.Value.Upper) ' if checkVal >= lower AndAlso checkVal <= upper Then ' result = k.Key ' Exit For ' End If 'Next 'Console.WriteLine(result) ' VP-3 ' The loop above could be replaced by this LINQ expression Dim m = dc.FirstOrDefault(Function(x) checkVal >= GetValue(x.Value.Lower) AndAlso _ checkVal <= GetValue(x.Value.Upper)) If m IsNot Nothing Then Console.WriteLine(m.Key) ' VP-3 Else Console.WriteLine("Range not found") End If End Sub Class MacRange Public Lower as String Public Upper as String End Class Function GetValue(mac as String ) as Long Dim clearText = mac.Replace(":", "") Dim result Long.TryParse(clearText, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, result) return result End Function A: There aren't existing functions that provide such utility. You could just split each string and create your ranges manually. A: I'd use some sort of regex (Regular Expression) validation for various ranges. http://regexlib.com/Search.aspx?k=mac%20address&AspxAutoDetectCookieSupport=1 will give you a good starting point.
unknown
d2673
train
Your data events are guaranteed to be emitted in order. See this answer for some additional details and some snippets from node's source code, which shows that indeed you will get your data events in order. The problem appears when you add asynchronous code in your data callback (setTimeout is an example of async code). In this situation, your data callbacks are not guaranteed to finish processing in the order they were called. What you need to do is ensure that by the time your data callback returns, you have fully processed your data. In other words your callback code needs to be sync code. fs.createReadStream(filePath, { encoding: 'ascii' }) .pipe(streamToEntry) .on('data', (chunk) => { // only synchronous code here console.log(chunk); }); To make the question code work, async/await can be used: fs.createReadStream(filePath, { encoding: 'ascii' }) .pipe(streamToEntry) .on('data', async (chunk) => { // only synchronous code here await setTimeout(() => console.log(chunk), Math.random() * 1000); });
unknown
d2674
train
The problem is that when a transformed variable is hardcoded, the marginaleffects package does not know that it should manipulate both the transformed and the original at the same time to compute the slope. One solution is to de-mean inside the formula with I(). You should be aware that this may make the model fitting less efficient. Here’s an example where I pre-compute the within-group means using data.table, but you could achieve the same result with dplyr::group_by(): library(lme4) library(data.table) library(modelsummary) library(marginaleffects) dt <- data.table(lme4::sleepstudy) dt[, `:=`(Days_mean = mean(Days), Days_within = Days - mean(Days)), by = "Subject"] re_poly <- lmer( Reaction ~ poly(Days_within, 2, raw = TRUE) + (1 | Subject), data = dt, REML = FALSE) re_poly_2 <- lmer( Reaction ~ poly(I(Days - Days_mean), 2, raw = TRUE) + (1 | Subject), data = dt, REML = FALSE) models <- list(re_poly, re_poly_2) modelsummary(models, output = "markdown") Model 1 Model 2 (Intercept) 295.727 295.727 (9.173) (9.173) poly(Days_within, 2, raw = TRUE)1 10.467 (0.799) poly(Days_within, 2, raw = TRUE)2 0.337 (0.316) poly(I(Days - Days_mean), 2, raw = TRUE)1 10.467 (0.799) poly(I(Days - Days_mean), 2, raw = TRUE)2 0.337 (0.316) SD (Intercept Subject) 36.021 36.021 SD (Observations) 30.787 30.787 Num.Obs. 180 180 R2 Marg. 0.290 0.290 R2 Cond. 0.700 0.700 AIC 1795.8 1795.8 BIC 1811.8 1811.8 ICC 0.6 0.6 RMSE 29.32 29.32 The estimated average marginal effects are – as expected – different: marginaleffects(re_poly) |> summary() #> Term Effect Std. Error z value Pr(>|z|) 2.5 % 97.5 % #> 1 Days_within 10.47 0.7989 13.1 < 2.22e-16 8.902 12.03 #> #> Model type: lmerMod #> Prediction type: response marginaleffects(re_poly_2) |> summary() #> Term Effect Std. Error z value Pr(>|z|) 2.5 % 97.5 % #> 1 Days 10.47 0.7989 13.1 < 2.22e-16 8.902 12.03 #> #> Model type: lmerMod #> Prediction type: response A: The following answer is not exactly what I asked for in the question. But at least it is a decent workaround for anyone having similar problems. library(lme4) library(data.table) library(fixest) library(marginaleffects) dt <- data.table(lme4::sleepstudy) dt[, `:=`(Days_mean = mean(Days), Days_within = Days - mean(Days), Days2 = Days^2, Days2_within = Days^2 - mean(Days^2)), by = "Subject"] fe_poly <- fixest::feols( Reaction ~ poly(Days, 2, raw = TRUE) | Subject, data = dt) re_poly_fixed <- lme4::lmer( Reaction ~ Days_within + Days2_within + (1 | Subject), data = dt, REML = FALSE) modelsummary(list(fe_poly, re_poly_fixed), output = "markdown") We start with the two models previously described. We can manually calculate the AME or marginal effects at other values and get confidence intervals using multcomp::glht(). The approach is relatively similar to that of lincom in STATA. I have written a wrapper that returns the values in a data.table: lincom <- function(model, linhyp) { t <- summary(multcomp::glht(model, linfct = c(linhyp))) ci <- confint(t) dt <- data.table::data.table( "estimate" = t[["test"]]$coefficients, "se" = t[["test"]]$sigma, "ll" = ci[["confint"]][2], "ul" = ci[["confint"]][3], "t" = t[["test"]]$tstat, "p" = t[["test"]]$pvalues, "id" = rownames(t[["linfct"]])[1]) return(dt) } This can likely be improved or adapted to other similar needs. We can calculate the AME by taking the partial derivative. For the present case we do this with the following equation: days + 2 * days^2 * mean(days). marginaleffects(fe_poly) |> summary() Term Effect Std. Error z value Pr(>|z|) 2.5 % 97.5 % 1 Days 10.47 1.554 6.734 1.6532e-11 7.421 13.51 Model type: fixest Prediction type: response By adding this formula to the lincom function, we get similar results: names(fe_poly$coefficients) <- c("Days", "Days2") mean(dt$Days) # Mean = 4.5 lincom(fe_poly, "Days + 2 * Days2 * 4.5 = 0") estimate se ll ul t p id 1: 10.46729 1.554498 7.397306 13.53727 6.733549 2.817051e-10 Days + 2 * Days2 * 4.5 lincom(re_poly_fixed, "Days_within + 2 * Days2_within * 4.5 = 0") estimate se ll ul t p id 1: 10.46729 0.798932 8.901408 12.03316 13.1016 0 Days_within + 2 * Days2_within * 4.5 It is possible to check other ranges of values and to add other variables from the model using the formula. This can be done using lapply or a loop and the output can then be combined using a simple rbind. This should make it relatively easy to present/plot results. EDIT Like Vincent pointed out below there is also marginaleffects::deltamethod. This looks to be a better more robust option, that provide similar results (with the same syntax): mfx1 <- marginaleffects::deltamethod( fe_poly, "Days + 2 * Days2 * 4.5 = 0") mfx2 <- marginaleffects::deltamethod( re_poly_fixed, "Days_within + 2 * Days2_within * 4.5 = 0") rbind(mfx1, mfx2) term estimate std.error statistic p.value conf.low conf.high 1 Days + 2 * Days2 * 4.5 = 0 10.46729 1.554498 6.733549 1.655739e-11 7.420527 13.51405 2 Days_within + 2 * Days2_within * 4.5 = 0 10.46729 0.798932 13.101597 3.224003e-39 8.901408 12.03316
unknown
d2675
train
Below mysql function removes special characters from a string: DROP FUNCTION IF EXISTS replacespecialchars; DELIMITER | CREATE FUNCTION replacespecialchars( str CHAR(255) ) RETURNS CHAR(255) DETERMINISTIC BEGIN DECLARE i, len SMALLINT DEFAULT 1; DECLARE ret CHAR(255) DEFAULT ''; DECLARE c CHAR(1); SET len = CHAR_LENGTH( str ); REPEAT BEGIN SET c = MID( str, i, 1 ); IF c REGEXP '[[:alnum:]]' THEN SET ret=CONCAT(ret,c); END IF; SET i = i + 1; END; UNTIL i > len END REPEAT; RETURN ret; END | DELIMITER ;
unknown
d2676
train
node will have to send a response object with the flagCount property if you want to use it in the frontend. If the flagCount is just getting saved in a database you do not need to use a get request for it. You could use a post request instead. A post request is useful to change database info. Node can respond with the flagCount if you need it on the frontend. If you do need the flagCount then check the node response object to see if it is sending it. If the flagCount is used in the browser than you could also save it and retrieve it in an angular service.
unknown
d2677
train
There are lots of ways you could mean this. If you just want to panic, use .map(|x| x.unwrap()). If you want all results or a single error, collect into a Result<X<T>>: let results: Result<Vec<i32>, _> = result_i32_iter.collect(); If you want everything except the errors, use .filter_map(|x| x.ok()) or .flat_map(|x| x). If you want everything up to the first error, use .scan((), |_, x| x.ok()). let results: Vec<i32> = result_i32_iter.scan((), |_, x| x.ok()); Note that these operations can be combined with earlier operations in many cases. A: filter_map can be used to reduce simple cases of mapping then filtering. In your example there is some logic to the filter so I don't think it simplifies things. I don't see any useful functions in the documentation for Result either unfortunately. I think your example is as idiomatic as it could get, but here are some small improvements: let things = vec![...]; // e.g. Vec<String> things.iter().map(|thing| { // The ? operator can be used in place of try! in the nightly version of Rust let a = do_stuff(thing)?; Ok(other_stuff(a)) // The closure braces can be removed if the code is a single expression }).filter(|thing_result| match *thing_result { Err(e) => true, Ok(a) => check(a), } ).map(|thing_result| { let a = thing_result?; // do stuff b }) The ? operator can be less readable in some cases, so you might not want to use it. If you are able to change the check function to return Some(x) instead of true, and None instead of false, you can use filter_map: let bar = things.iter().filter_map(|thing| { match do_stuff(thing) { Err(e) => Some(Err(e)), Ok(a) => { let x = other_stuff(a); if check_2(x) { Some(Ok(x)) } else { None } } } }).map(|thing_result| { let a = try!(thing_result); // do stuff b }).collect::<Result<Vec<_>, _>>(); You can get rid of the let a = try!(thing); by using a match in some cases as well. However, using filter_map here doesn't seem to help. A: Since Rust 1.27, Iterator::try_for_each could be of interest: An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. This can also be thought of as the fallible form of for_each() or as the stateless version of try_fold(). A: You can implement these iterators yourself. See how filter and map are implemented in the standard library. map_ok implementation: #[derive(Clone)] pub struct MapOkIterator<I, F> { iter: I, f: F, } impl<A, B, E, I, F> Iterator for MapOkIterator<I, F> where F: FnMut(A) -> B, I: Iterator<Item = Result<A, E>>, { type Item = Result<B, E>; #[inline] fn next(&mut self) -> Option<Self::Item> { self.iter.next().map(|x| x.map(&mut self.f)) } } pub trait MapOkTrait { fn map_ok<F, A, B, E>(self, func: F) -> MapOkIterator<Self, F> where Self: Sized + Iterator<Item = Result<A, E>>, F: FnMut(A) -> B, { MapOkIterator { iter: self, f: func, } } } impl<I, T, E> MapOkTrait for I where I: Sized + Iterator<Item = Result<T, E>>, { } filter_ok is almost the same: #[derive(Clone)] pub struct FilterOkIterator<I, P> { iter: I, predicate: P, } impl<I, P, A, E> Iterator for FilterOkIterator<I, P> where P: FnMut(&A) -> bool, I: Iterator<Item = Result<A, E>>, { type Item = Result<A, E>; #[inline] fn next(&mut self) -> Option<Result<A, E>> { for x in self.iter.by_ref() { match x { Ok(xx) => if (self.predicate)(&xx) { return Some(Ok(xx)); }, Err(_) => return Some(x), } } None } } pub trait FilterOkTrait { fn filter_ok<P, A, E>(self, predicate: P) -> FilterOkIterator<Self, P> where Self: Sized + Iterator<Item = Result<A, E>>, P: FnMut(&A) -> bool, { FilterOkIterator { iter: self, predicate: predicate, } } } impl<I, T, E> FilterOkTrait for I where I: Sized + Iterator<Item = Result<T, E>>, { } Your code may look like this: ["1", "2", "3", "4"] .iter() .map(|x| x.parse::<u16>().map(|a| a + 10)) .filter_ok(|x| x % 2 == 0) .map_ok(|x| x + 100) .collect::<Result<Vec<_>, std::num::ParseIntError>>() playground
unknown
d2678
train
The trick for finding the day with the most entries is to group by day, then sort the groups by the number of entries in each group, then grab the first one. Dim query = Projects.GroupBy(Function(e) e.Name, Function(name, groupedEntries) New With { _ .Name = name, _ .TopDay = groupedEntries.GroupBy(Function(e) e.[Date].DayOfWeek).OrderByDescending(Function(g) g.Count()).First().Key, _ .TotalHours = groupedEntries.Sum(Function(e) e.Hours) _ })
unknown
d2679
train
You are trying to save d in csv which is not assigned anywhere. You are assigning d here only which will not be available outside here. Or you want to save c in csv but mistakenly you wrote d. Edit according to comment: with open('simplejson2.json', 'r') as f: str1=f.read() data_csv= csv.reader(f, delimiter=',') You can read f only inside with. If you are trying to read f outside with then the file is already closed you give you that error. A: no idea what you are trying to achieve (or why you need a counter instead of just using len), but this is a working version of your code: import csv import json from collections import Counter with open('result.csv', 'w') as output: with open('simplejson2.json', 'r') as f: str1=f.read() output_data=csv.writer(output, delimiter=',') data_csv= csv.reader(f, delimiter=',') data=json.loads(str1) status_fields = [k[:] for d in data for k, v in d.items() if k.startswith('sta') and v] c = Counter(status_fields) output_data.writerow(status_fields) print("there are total", c['status'], "test case") status_fields_failed = [k[:] for d in data for k, v in d.items() if k.startswith('status') and v.startswith('failed')] c = Counter(status_fields_failed) output_data.writerow(status_fields_failed) if c['status'] > 0: print("There are", c['status'], "failed cases") else: print("there are", c['status'], "sucessfully pass") content of generated file result.csv status,status,status status,status changes made: * *indentation *fixed for-loop expression (d undefined, iterable required by Counter constructor)
unknown
d2680
train
According to the article, the FAQ section refers to the following known issue: * *After installing all the prerequisites I still do not see the Windows Phone Unit Test template. Workaround: install the prerequisites in order on the system drive. VS 2012 Windows Phone SDK 8.0 VS 2012 Update 2 CTP2 A: With the latest update your issue should go away
unknown
d2681
train
Having php script run for an "infinite" amount of time is almost never appropriate. You can: * *set the page to reload using html (<meta http-equiv="refresh" content="5">) *set it to run and display via a cron script *reload the page regularly using javascript *something else I haven't thought of All of these ways of approaching the problem would save you the type of headaches you're experiencing now. A: Here is what you can do, Have your script write the parameters to the javascript, so you can reload your page every 2 seconds with new parameters. example: <script type='text/javascript'> setTimeout(function() { location.href="http://www.example.com/?jobid=<?php echo $nextJobId ?>"; },2000); </script> so if you need to do a Db offset on each sql query, you can pass that parameter in the url. Having an infinite loop might seem like a good idea, but maybe you should reevalute your code and see if you really need it, or if you can implement it this way
unknown
d2682
train
Explaining the workflow of your program. I tried your program & got this C:\Users\LENOVO\Desktop\so>python try.py Welcome to Treasure Island! Its your mission to find the treasure. You begin at a cross roads, do you go left or right? left You ran into enemies, attack? no You ran to the lake You found a long river, it leads somewhere. Swim or wait? right C:\Users\LENOVO\Desktop\so>python try.py Welcome to Treasure Island! Its your mission to find the treasure. You begin at a cross roads, do you go left or right? right Traceback (most recent call last): File "try.py", line 11, in <module> river1 NameError: name 'river1' is not defined The reason river1 is not defined and you getting that error is because when I entered "right" the program goes to the 2nd if thus since crossroads == "left" will be False. When it executes the code on the second if there is REALLY NO variable or object named river1. Why is there no river1 variable where you created or put it on the first if? Well that is because the first if does not even get executed (when I enter "right") thus NOT creating your river1 variable. You might think once you put it there it will be created but it will only be created when that part of code is executed. So if you would like to have a variable river1 globally you can create it a top and initialize it let's say None or an empty string , your call. river1 = '' print("Welcome to Treasure Island! \nIts your mission to find the treasure.") crossroads = input("You begin at a cross roads, do you go left or right? ").lower() if crossroads == "left": enemies = input("You ran into enemies, attack? ").lower() if enemies == "no": print("You ran to the lake") river1 = input("You found a long river, it leads somewhere. Swim or wait? ").lower() else: print("You were overpowered and died, game over") if crossroads == "right": river1 if river1 == "swim": print("You swam and drowned, Game over") else: print("You found a boat") A: For variables that may only be defined under certain circumstances, you have a couple of options. First, you can declare them all beforehand: print("Welcome to Treasure Island! \nIts your mission to find the treasure.") crossroads = input("You begin at a cross roads, do you go left or right? ").lower() enemies = None river1 = None if crossroads == "left": ... Or, you can test to see if they exist: if crossroads == "right": if river1 and river1 == "swim": ... A: I believe that what you are looking for is how to reuse your code. Use functions. def river1_func(): choice = input("You found a long river, it leads somewhere. Swim or wait? ").lower() if choice == "swim": print("You swam and drowned, Game over") else: print("You found a boat") if __name__ == "__main__": print("Welcome to Treasure Island! \nIts your mission to find the treasure.") crossroads = input("You begin at a cross roads, do you go left or right? ").lower() if crossroads == "left": enemies = input("You ran into enemies, attack? ").lower() if enemies == "no": print("You ran to the lake") river1_func() else: print("You were overpowered and died, game over") if crossroads == "right": river1_func()
unknown
d2683
train
I received an email today that you now have visibility to active subscriptions. Log into iTunes connect, Go to "Sales and Trends" then select "Subscriptions" from the report chooser. Report Chooser
unknown
d2684
train
Following the clockwise/spiral rule, fun is a pointer to an array of two pointers to void. A: OK, basically, this is how typedef works: first imagine that the typedef isn't there. What remains should declare one or more variables. What the typedef does is to make it so that if you would declare a variable x of type T, instead it declares x to be an alias for the type T. So consider: void*(*fun)[2]; This declares a pointer to an array of void* of size 2. Therefore, typedef void*(*fun)[2]; declares fun to be the type "pointer to array of void* of size 2". And fun new_array declares new_array to be of this type.
unknown
d2685
train
The user will care about the message, because he wanted to do some modification, and the modifications have not been made. He will thus refresh the page to see the new state of the data, and will redo his modifications, or decide they should not be made anymore given the new state. Is it a problem if two users modify an entity concurrently, and if the last modification wins, whatever the modification is? If it is a problem, then use optimistic locking, and inform your user when there is a problem. There's no way around it. If it's not a problem, then don't use optimistic locking. The last modification, if it doesn't break constraints in your database, will always win. But having concurrent users modifying the same data will always lead to exceptions (for example, because some user might delete an entity before some other user submits a modification to the same entity). Retrying is not an option: * *either it will fail again, because it's just not possible to do the modifications *or it will succeed, but will defeat the point of having optimistic locking in the first place. Your problem could be explained with a car analogy. Suppose you choose to buy a car with a speed limiter, in order to make sure you don't break the speed limit. And now you ask: but I don't care about the speed limits. Shouldn't I always disable the speed limiter? You can, but then don't be surprised if you get caught by the police.
unknown
d2686
train
Issue here is I closed the session. After removing it, everything works fine
unknown
d2687
train
You could use two nested iterations and build an new array for choosing as random result. function getNonConsecutives(array) { return array.reduce((r, a, i, aa) => r.concat(aa.slice(i + 2).map(b => [a, b])), []); } console.log(getNonConsecutives([ 0, 1, 2, 4 ])); .as-console-wrapper { max-height: 100% !important; top: 0; } According to Bee157's answer, you could use a random choice with a constraint, like length for the first index and add the needed space for the second index. The problem is, due to the nature of choosing the first number first, the distribution of the result is not equal. function getNonConsecutives(array) { var i = Math.floor(Math.random() * (array.length - 2)); return [ array[i], array[Math.floor(Math.random() * (array.length - 2 - i)) + 2 + i] ]; } console.log(getNonConsecutives([ 0, 1, 2, 4 ])); A: since you state that the array ellemnts are all unique, and that they are sorted. It should suffice to take an random element var index1=Math.floor(Math.random()*arr.length) now any other element (except maybe the elemnts on position (index1 +/- 1) are not consecutive So a new random element can be chosen excluding the first index. var index2=Math.floor(Math.random()*arr.length); if(index2==index1){ index2+=((index2<arr.length-1)?1:-1); } if(Math.abs(arr[index1]-arr[index2])<=1){ if(index2==0 && arr.length<4){ //set index2 to arr.length-1 and do check again, if not ok=> no result if(!(arr[index1]-arr[arr.length-1]>=-1)){ return [arr[arr.length-1],arr[index1]]; } } else if(index2==arr.length-1 && arr.length<4){ //set index2 to 0 and do check again, if not ok=> no result if(!(arr[index1]-arr[0]<=1)){ return [arr[0],arr[index1]]; } } else{ //if index2>index1 index2++ //else index2-- //always OK so no further check needed index2+=(index2>index1?1:-1); return [arr[index1],arr[index2]]; } } else{ //ok return [arr[index1,arr[index2]]; } return false; if speed is not important, you can use a filter on the array to calculate a new array with all elements differing more then 1 unit of arr[index1]. and randomly select a new number from this new array. Other attempt function getNonConsecutive(arr){ var index1,index2,arr2; index1=Math.floor(Math.random()*arr.length); arr2=[].concat(arr); arr2.splice((index1!==0?index1-1:index1),(index!==0?3:2)); if(arr2.length){ index2=Math.floor(Math.random()*arr2.length); return [arr[index1],arr2[index2]]; } else{ //original array has length 3 or less arr2=[].concat(arr); arr2.splice(index1),1); for (var j=0,len=arr.length;j<len;j++){ if(Math.abs(arr1[index1]-arr2[j])>1){ return [arr[index1],arr2[j]]; } } } return false } A: Something like this should do it: const pick = nums => { // Pick a random number const val = nums[Math.floor(Math.random() * nums.length) + 0]; // Filter out any numbers that are numerically consecutive const pool = nums.filter(n => Math.abs(n - val) > 1); // Pick another random number from the remainer const other = pool[Math.floor(Math.random() * pool.length) + 0]; // Sort + return them return [val, other].sort(); }; console.log(pick([0, 1, 2, 4])); A: demoFn(array) { var i,j, y =[]; for (i=0; i<=array.length;i++) { for (j = i + 1; j <= array.length; j++) { if (array[j] && array[i]) { if (array[j] !== array[i] + 1) { y.push([array[i], array[j]]); } } } } } Take a random array and check it. A: You can create a function using recursion that will pick random number in each iteration and loop all other elements and if condition is met add to array. function findN(data) { data = data.slice(); var r = [] function repeat(data) { if (data.length < 2) return r; var n = parseInt(Math.random() * data.length); data.forEach(function(e, i) { if (i != n) { var a = data[n]; if (Math.abs(a - e) != 1 && r.length < 2) r.push(n < i ? [a, e] : [e, a]) } }) data.splice(n, 1); repeat(data) return r; } return repeat(data) } console.log(findN([1, 2, 3])) console.log(findN([0, 1, 2, 4])) console.log(findN([0, 3, 4]))
unknown
d2688
train
You really are declaring an array of type Object and trying to cast it, which doesn't work. Instead, in your constructor, do: S = new Entry[capacity]; A: Why do you do a cast in S = (Entry[]) new Object[capacity]; and not just S = new Entry[capacity]; That would probably solve the problem. A: Your error appears to be attempting to mix generics with something that can't handle this use of generics - namely, arrays. Changing the definition of S to List<Entry<E>>, and the instantiation to new ArrayList<Entry<E>>(capacity) allows your program to run (given the limited sample). Some other random notes, given your sample: * *You've named your array-to-sort S. Please follow the standard naming conventions (other people will expect you to), and give it a meaningful name. It doesn't help that it may look similar to 5 (depends on font, I'll admit). *capacity is an instance variable used for initialization for every instance of the class (and nowhere else). Change this to a final static variable and/or change the name of the variable to reference why this is the case *You define size - Likely, you should be returning S.size() regardless, unless you have some (unstated) specific need. *Your use of the terms key and value suggests you are attempting to use (or maybe implement) a HashMap.
unknown
d2689
train
You can use NSNotificationCenter to send notification to enable/ disable the CLLocationManager's autopause attribute in another View Controller. Other approaches can be: * *Use class method, it is explained very well in this SO Answer *Use Delegates A: idk what' your problem with CLLocationManager, do you mean the way to pass object to another view controller? there are several way to do this.See this question:Passing Data between View Controllers I'm pretty sure that you can pass the CLLocationManager object to settingViewController by setting a property of that CLLocationManager,because passing the object means pass the reference the object,you can change the object in settingViewController life cycle,and it affects the CLLocationManager object which created by ViewController.
unknown
d2690
train
When you receive a canonical registration ID in the response from Google, the message was accepted by the GCM server and the GCM server would attempt to deliver it to the device. Whether it is actually sent to the device depends on whether the device is available (i.e. connected to the internet). So if your server sends a GCM message to both the old ID and the new ID, the device will probably get two messages. Canonical IDs On the server side, as long as the application is behaving well, everything should work normally. However, if a bug in the application triggers multiple registrations for the same device, it can be hard to reconcile state and you might end up with duplicate messages. GCM provides a facility called "canonical registration IDs" to easily recover from these situations. A canonical registration ID is defined to be the ID of the last registration requested by your application. This is the ID that the server should use when sending messages to the device. If later on you try to send a message using a different registration ID, GCM will process the request as usual, but it will include the canonical registration ID in the registration_id field of the response. Make sure to replace the registration ID stored in your server with this canonical ID, as eventually the ID you're using will stop working. (Source) You can overcome this problem by assigning a unique identifier to each instance of your application. If you store that identifier in the device's external storage, it won't be deleted when the app is uninstalled. Then you can recover it when the app is installed again. If you send this identifier to your server along with the registration ID, you can check if your server has an old registration ID for this identifier, and delete it. A: @Eran We have two option either to remove older registration ids or update with Key and position of canonical id. I prefer to update... You can view working code of mine i have answered here Steps to Update Canonical Ids
unknown
d2691
train
It turned out to be a problem with my project not being located in the root.
unknown
d2692
train
It works with Jetty 9 and the jetty-maven-plugin: <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>${jetty.version}</version> <dependencies> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-access</artifactId> <version>${logback.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> </dependencies> <configuration> <scanIntervalSeconds>10</scanIntervalSeconds> <webAppSourceDirectory>src/main/resources/htdocs</webAppSourceDirectory> <webApp> <descriptor>src/main/webapp/WEB-INF/web.xml</descriptor> </webApp> <systemProperties> <systemProperty> <name>org.eclipse.jetty.util.log.Log</name> <value>org.eclipse.jetty.util.log.Slf4jLog</value> </systemProperty> <systemProperty> <name>logback.configurationFile</name> <value>src/main/resources/logback.xml</value> </systemProperty> </systemProperties> </configuration> </plugin> A: Using the older maven-jetty-plugin rather than the jetty-maven-plugin works for me: <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>maven-jetty-plugin</artifactId> <version>6.1.26</version> <configuration> <systemProperties> <systemProperty> <name>logback.configurationFile</name> <value>${project.build.outputDirectory}/jetty-logback.xml</value> </systemProperty> </systemProperties> </configuration> <dependencies> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.4</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.0.0</version> </dependency> </dependencies> </plugin> A: you can use the Properties-Maven-Plugin: <project> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>properties-maven-plugin</artifactId> <version>1.0-alpha-2</version> <executions> <execution> <goals> <goal>set-system-properties</goal> </goals> <configuration> <properties> <property> <name>logback.configurationFile</name> <value>src/test/resources/logback.xml</value> </property> </properties> </configuration> </execution> </executions> </plugin> </plugins> </build> </project> Documentation: http://mojo.codehaus.org/properties-maven-plugin/usage.html It's not perfect, but it should work. A: I've encountered this same problem. As a workaround, I used slf4j-simple in place of logback. The slf4j-simple has a default configuration set to INFO level, but is not very configurable otherwise, so it may or may not meet your needs. In the plugin configuration, replace logback-classic with: <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.6.4</version> </dependency>
unknown
d2693
train
Use .classname to select based on any of the element's classed. When you use an attribute selector, it matches the entire attribute (unless you use modifiers like *=, but they're not appropriate here, either). $("coral-checkbox.natural").hide(); A: Use the class the selector instead of the attribute selector: $("coral-checkbox.natural").hide();
unknown
d2694
train
You want to implement protected void onPostExecute (Result result) on your AsyncTask implementation. The result parameter will be whatever you return from the doInBackground method. Since this runs in the UI thread you can modify the UI how you want at that time. A: If you want to look at the value, then you need to save the return value of the method in a local variable if(user1 !=null && user1.length() > 0 && pass1 !=null && pass1.length() > 0) { boolean comLogin = ComHelper.SendLogin(user1, pass1); if(comLogin) { //do something } }
unknown
d2695
train
You are right: the easiest way is to tell Mercurial to forget the files (by using hg forget). However Mercurial is not tracking directories, only files. You cannot add a directory and thus cannot forget it either. You probably have files under bin and res that have been added to the list of tracked files: those are the ones you need to forget.
unknown
d2696
train
Infinispan allows you to chain cache stores together (by defining multiple stores within the persistence XML section), and each can be configured to either be synchronous or asynchronous (see here). However, transactional persistence stores are not supported (see here)
unknown
d2697
train
For matrix multiplication, the number of columns in the first matrix must be equal to the number of rows in the second matrix. If you want to check the no of rows of 1st matrix and the no. of columns of the 2nd matrix then change the if A_cols != B_rows to if A_rows != B_cols With your current code, it will print NOT POSSIBLE when A_cols != B_rows which is right. Ex. Enter number of rows of 1st matrix: 2 Enter number of columns of 1st matrix: 3 Enter number of rows of 2nd matrix: 2 Enter number of columns of 2nd matrix: 3 Enter the elements of the 1st matrix: A[0][0]: 1 A[0][1]: 2 A[0][2]: 3 A[1][0]: 4 A[1][1]: 5 A[1][2]: 6 Enter the elements of the 2nd matrix: B[0][0]:1 B[0][1]:2 B[0][2]:3 B[1][0]:4 B[1][1]:5 B[1][2]:6 First Matrix : 1 2 3 4 5 6 Second Matrix : 1 2 3 4 5 6 NOT POSSIBLE Another mistake in the code is when you are initialize the Matrices.You are doing A = [[0 for i in range(B_cols)] for j in range(A_rows)] B = [[0 for i in range(B_cols)] for j in range(A_rows)] If the B_cols are smaller than the A_cols when you adding elements in A it will raise IndexError The same if the B_cols are greater than A_cols when you are adding elements to B will raise IndexError. Change it to A = [[0 for i in range(A_cols)] for j in range(A_rows)] B = [[0 for i in range(B_cols)] for j in range(B_rows)]
unknown
d2698
train
$array = array( 'first_name' => 'John', 'last_name' => 'Duei', 'product' => array( 'title' => 'Product #1', 'price' => '90', 'product' => array( 'title' => 'Product #2', 'price' => '90', 'product' => array( 'title' => 'Product #3', 'price' => '90', ), ), ), 'misc' => array( 'country' => 'United States', array( 'product' => array( 'title' => 'Product #4', 'price' => '90', ), ) ), array( 'title' => 'Product #5', 'price' => '90', ) ); function array_walk_recursive_full($array, $callback) { if (!is_array($array)) return; foreach ($array as $key => $value) { $callback($value, $key); array_walk_recursive_full($value, $callback); } } $result = []; array_walk_recursive_full( $array, function ($value, $key) use (&$result) { if (isset($value['price'])) { $result[] = [ 'title' => $value['title'], 'price' => $value['price'], ]; } } ); print_r($result); working code example here
unknown
d2699
train
So simple! -(void) searchBarCancelButtonClicked:(UISearchBar *)searchBar{ [self.searchDisplayController setActive:NO animated:YES]; self.navigationController popToViewController:UIViewControllerA animated:YES; } A: Create a CGPoint based on the scrollview's original center. In viewDidLoad() : self.originalCenter = scrollView.center; And when your user closes the searchbar: - (void)hideSearchBar scrollView.center = self.originalCenter; Where scrollView is whatever you've called your UIScrollView. A: So finally instead of dragging a searchBar control into the storyboard. I'm creating and destroying the searchBarControl on the fly. -(void)initialiseSearch { //Start searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; searchBar.delegate = self; searchBar.showsCancelButton = YES; searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self]; searchDisplayController.delegate = self; searchDisplayController.searchResultsDataSource = self; searchDisplayController.searchResultsDelegate = self; [self.view addSubview:searchBar]; searchBar.hidden = YES; [searchDisplayController setActive:NO animated:NO]; // [self.searchDisplayController.searchResultsTableView registerNib:[UINib nibWithNibName:@"CustomSearch" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"search"]; //End } The method is called in the view did load.
unknown
d2700
train
First, you're not using "num" at the function, so it can be like this: function enlargeDisc(e) { let t = e.target if (t.classList.contains(styles.active)) { t.classList.remove(styles.active) discRender() } else { t.classList.add(styles.active) discRender() } } Now that you only have the event has parameter, you could just put the onClick like: {discs.map((item) => ( <div className ={styles.disc} key={item.id} style=. {{top: item.top + 'px'}} onClick={enlargeDisc}> </div> Test what is reciving "enlargeDisc" event with a console.log inside the function, if there is the e.target, you could handle better using const clsList = e.target.classList, so you just need if(classList."property"). Also, you can instead using ReactDOM.render(), make a component Disc and use a State to handle when the class property gonna change or remove.
unknown