id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_5200
Thank you. A: Solution: Add constraints to center the Image View Horizontaly/Vertical and for Bottom/Top space.
doc_5201
Thank you for your answers. A: Oh, I solved it myself! :D I have set 'lib_ldf_mode' to 'deep' on platformio.ini. It's now acts exactly as I need. It starts in 'src/' folder and then recursively compiles imports and imports of imports and so on.
doc_5202
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, test_size=0.3, random_state=42) X_test, X_val, y_test, y_val = train_test_split(X_test, y_test, test_size=0.5, random_state=42) The problem is that my dataset is really unbalanced. Some classes have 500 samples while some have 70 for example. Is this splitting method accurate in this situation? Is the sampling random or does sklearn use seome methods to keep the distribution of the data same in all sets? A: You should use the stratify option (see the docs): X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, test_size=0.3, random_state=42, stratify=y_data) X_test, X_val, y_test, y_val = train_test_split(X_test, y_test, test_size=0.5, random_state=42, stratify=y_test)
doc_5203
A: I suggest you avoid giving them prefixed names, and create an actual array using something like the following; <input type="checkbox" name="question[{{ $question->id }}]" ...> Now in your controller method you can just do; $questions = $request->input('questions'); And your validator rules can look like the following; $request->validate([ 'questions.*' => ['required', 'string'] ]); Laravel lets you validate arrays in many way, check out the documentation. A: You could look at building a custom validation rule if you really want to use prefixes. But I agree with ollieread, you should probably just handle all the questions as array elements. To extend on that answer a little bit, here's what those rules would look like: $rules = [ 'questions' => 'array', 'questions.*.text' => 'required_with:questions|string', 'questions.*.score' => 'required_with:questions|integer|min:1|max:10' ]; A: You can use php and laravel to handle this. Suppose you get all the question Ids with a query in array. $questionIds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; Than create an empty array to create the rules. $validatedQuestionIds = []; Now add the rules foreach the question Ids foreach($questionIds as $key => $questionId){ $validatedQuestionIds = [ 'q_'.$questionId = 'required|string'; ]; } And now validate the array using the laravel validate function. $request->validate($validatedQuestionIds);
doc_5204
Thank you in advance! A: Add this code in you function.php file function action_woocommerce_customer_save_address( $user_id, $load_address ) { wp_safe_redirect(wc_get_page_permalink('myaccount')); exit; }; add_action( 'woocommerce_customer_save_address', 'action_woocommerce_customer_save_address', 99, 2 );
doc_5205
An array seq containing the sequence in which the data objects are to be displayed is also provided. It is an array of key[1] values. I want to step through the sequence array, each time getting the record from the data-object array with the matching key[1] value.; but there is no direct map. For example, the sequence array could be [10,4,7,1,3,5,9] and the data array will be [ { 'key' : [n,1], ...}, { ['key' : [n,3],...}, { 'key' : [n,4],...}, { 'key' : [n,5],...}, { 'key' : [n,7],...}, { 'key' : [n,9],...}, { 'key' : [n,10],...} ]. Thus, when the third object to be displayed is that of key[1] = 7, I need to know that it is the fifth element in the data array. I have been using an object to map, such as: k = new Object(); data.forEach( ( v, i ) => { k[ v.key[1] ] = i; } ); And using it to reference as: seq.forEach( (v, i ) => { e = data[ k[ v ] ]; } ); or for ( i = 0; i < seq.length; i++ ) { e = data[ k[ seq[i] ] ]; }; Is there a better way? Thank you. Update after thinking a bit and realizing how stupid I can be at times. Sometimes I can be so stupid. I thought I got off track in looking at this simple issue as a task of coming up with some sort of index mapping between the seq and data arrays; and thought all that is required is to sort data by key[1] according to the sequence order provided in the seq array of key[1] values. In a sense that is correct. Thus, object k would not be needed and data could be sorted in place, so to speak. I thought k was a copy of array data with property names equal to the desired index, and that the approach was not efficient. However, as @barmar points out below, k does not contain a copy of the objects in data but only their references. And bulding an object of references should be more efficient than sorting the array in place and actually 'moving' the data. I assume it is similar to using pointers. I included the snippet of the sort below just for illustration, even though it is likely not as efficient, because it was interesting to someone at my lower level to build a sort function based off of an object property. The snippet illustrates how to take the example I provided to ask this question and sort it in place based on sequence order in seq. It's nothing new or novel. You'll see that data is in key[1] order as in seq and the property p are in increasing numerical order from 1 to 7 indicating their desired positions just for illustration. Thank you. var seq = [10,4,7,1,3,5,9], data = [ { 'key' : [5,1], 'p' : 4 }, { 'key' : [5,3], 'p' : 5 }, { 'key' : [5,4], 'p' : 2 }, { 'key' : [5,5], 'p' : 6 }, { 'key' : [5,7], 'p' : 3 }, { 'key' : [5,9], 'p' : 7 }, { 'key' : [5,10], 'p' : 1 } ]; data.sort( ( a, b ) => { return seq.indexOf( a.key[1] ) - seq.indexOf( b.key[1] ); } ); console.log( data ); A: Don't put the index in k, put the object itself. data.forEach(v => k[v.key[1]] = v);
doc_5206
Is that possible to do so?If so how can I modify my code: This is how I'm trying to upload Images and adding them to div(thumbs): <script type="text/javascript"> $(function () { $("#<%=uploader.ClientId%>").plupload({ runtimes: 'gears,flash,silverlight,browserplus,html5', url: 'Editor.aspx', max_file_size: '10mb', max_file_count: 21, chunk_size: '1mb', unique_names: true, rename: true, dragdrop:true, filters: [ { title: "Image files", extensions: "jpg,gif,png" }, { title: "Zip files", extensions: "zip" } ], flash_swf_url: 'js/plupload.flash.swf', silverlight_xap_url: 'js/plupload.silverlight.xap' }); $('form').submit(function (e) { var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader'); if (uploader.files.length > 0) { uploader.bind('StateChanged', function () { if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) { $('form')[0].submit(); } }); uploader.start(); } else //alert('You must at least upload one file.'); return false; }); var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader'); uploader.bind('FilesAdded', function (up, files) { var i = up.files.length, maxCountError = false; plupload.each(files, function (file) { setTimeout(function () { up.start(); }, 100); if (uploader.settings.max_file_count && i >= uploader.settings.max_file_count) { $.msgBox({ title: "Info", content: "Uuh! Please don't put me any more files.<br>Maximum Upload limit is only 20 Images.<br>Rest of the Images will be removed.", type: "info", showButtons: true, opacity: 0.1, autoClose: false }); uploader.removeFile(up.files[i - 1]); } else { } }); }); var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader'); uploader.bind('FileUploaded', function (up, file, res) { $('#<%=thumbs.ClientId%>').append("<div id=" + file.id + "><a href='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "' rel='group1'><img class='clickImage' src='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "' width='75' height='50' data-full='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "'/></div>"); if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) { showStickySuccessToast(); } }); }); function randomString(length) { var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split(''); if (!length) { length = Math.floor(Math.random() * chars.length); } var str = ''; for (var i = 0; i < length; i++) { str += chars[Math.floor(Math.random() * chars.length)]; } return str; } </script> After editing operation which I am doing it in my codebehind I have saved all those Images to one folder where users can save them.So Now What I want to do Is add all those existed Images on my server folder to be displayed it in the same div(thumbs)where I am adding Images using the uploader at the beginning. A: To access a control in code behind, the control must have runat="server". However, it is simpler to use a Panel control instead of a div. A Panel control renders as a div so any client JavaScript will continue to work. Image NewImage = new Image(); NewImage.ImageUrl= MapPath(@"~\Images\april.jpg"); Panel1.Controls.Add(NewImage);
doc_5207
public static void printStuff(Object[] stuffs, Function<?, String> func) { for(Object stuff : stuffs) { String stringStuff = func.apply(stuff); System.out.println(stringStuff); // or whatever, what is done with that String is not relevant } // ... This method is to be called with arrays of different types, and corresponding func value, for example: printStuff(arrayOfClasses, (Class<?> c) -> c.getSimpleName()); printStuff(arrayOfStrings, (String s) -> '"' + s + '"'); printStuff(arrayOfObjects, o -> o.toString()); so I definitely need my stuffs to be Object[], because it is the first common superclass of the different types amongst the method's calls. And on compilation, I get: MyClass.java:6: error: incompatible types: Object cannot be converted to CAP#1 String stringStuff = func.apply(stuff); ^ where CAP#1 is a fresh type-variable: CAP#1 extends Object from capture of ? My guess is that javac rants for the parameter I give to the Function<?, String> call, whose type, Object, does not extend Object. So my question is, how can I pass an Object parameter to a Function<?, String>? I can change the interface types to <Object, String>, but it breaks my others calls (with Class[], String[], etc) and it would imply losing pretty much the whole point of genericity, wouldn't it? Unless there is some way to change my stuffs type to something like <? extends Object>[], or a generic type, and I'm pretty sure it's not possible. Thanks in advance, folks. EDIT: if I change my method to a generic one, i.e.: public static <U> void printStuff(Object[] stuffs, Function<U, String> func) { I still get a compilation error : MyClass.java:6: error: method apply in interface Function<T,R> cannot be applied to given types; String stringStuff = func.apply(stuff); ^ required: U found: Object reason: argument mismatch; Object cannot be converted to U A: One solution would be to use: public static <T> void printStuff(T[] stuffs, Function<T, String> func) { for(T stuff : stuffs) { // .... A: As for the first code: public static void printStuff(Object[] stuffs, Function<?, String> func) { for(Object stuff : stuffs) { String stringStuff = func.apply(stuff); System.out.println(stringStuff); // or whatever, what is done with that String is not relevant } } You are getting this error MyClass.java:6: error: incompatible types: Object cannot be converted to CAP#1 You get that error because the ? could be any more specific class, e.g. you could also pass an argument func of type Function<String, String>. You could fix that by declaring the signature like public static void printStuff(Object[] stuffs, Function<Object, String> func) or in a generic way: public static <U> void printStuff(U[] stuffs, Function<? super U, String> func) { for(U stuff : stuffs) { String stringStuff = func.apply(stuff); System.out.println(stringStuff); // or whatever, what is done with that String is not relevant } } It is essential that the type of the array is equal to (or a subclass of) the first type parameter of the Function.
doc_5208
Bu I have a problem with the StopStoryboard. Whenever the exit trigger occurs, I get: Name cannot be found in the name scope of 'System.Windows.Style'. This is the code I'm using: private static void InjectStorybord(Hourglass originator) { Storyboard sb = GetStoryboard(originator); originator.Resources["MainStory"] = sb; Binding runningBinding = GetBinding(originator); DataTrigger trigger = new DataTrigger() { Binding = runningBinding, Value = true }; BeginStoryboard begineStory = new BeginStoryboard() { Storyboard = sb, Name = BEGIN_MAIN_NAME }; begineStory.SetValue(FrameworkElement.NameProperty, BEGIN_MAIN_NAME);//Trying this to achive x:Name not helping eithre trigger.EnterActions.Add(begineStory); trigger.ExitActions.Add(new StopStoryboard() { BeginStoryboardName = begineStory.Name }); Style beginStoryStyle = new Style(typeof(Grid)); beginStoryStyle.Triggers.Add(trigger); originator.layoutRoot.Style = beginStoryStyle; } A: Try to register the name with the style using the RegisterName method Style beginStoryStyle = new Style(typeof(Grid)); beginStoryStyle.RegisterName(BEGIN_MAIN_NAME, begineStory); beginStoryStyle.Triggers.Add(trigger);
doc_5209
my object looks like below: function Person(name, age, weight) { this._name = name; this._weight = weight; this._age = age; this.Anatomy = { Weight: this._weight, Height: function () { //calculate height from age and weight return this._age * this._weight; //yeah this is stupid calculation but just a demonstration //not to be intended and here this return the Anatomy object //but i was expecting Person Object. Could someone correct the //code. btw i don't like creating instance and referencing it //globally like in the linked post } } } A: this.Anatomy = { //'this' here will point to Person this.f = function() { // 'this' here will point to Anatomy. } } Inside functions this generally points at the next thing up a level. The most consistent way to solve this would be this.Anatomy = { _person: this, Weight: this._weight, Height: function () { //calculate height from age and weight return _person._age * _person._weight; } } Alternatively you can do this function Person(name, age, weight) { this.Anatomy = { weight: weight, height: function() { return age*weight; } }; }
doc_5210
I want to design the pipeline in a way that: * *Additional functions can be insert in the pipeline *Functions already in the pipeline can be popped out. Here is what I came up with: import asyncio @asyncio.coroutine def add(x): return x + 1 @asyncio.coroutine def prod(x): return x * 2 @asyncio.coroutine def power(x): return x ** 3 def connect(funcs): def wrapper(*args, **kwargs): data_out = yield from funcs[0](*args, **kwargs) for func in funcs[1:]: data_out = yield from func(data_out) return data_out return wrapper pipeline = connect([add, prod, power]) input = 1 output = asyncio.get_event_loop().run_until_complete(pipeline(input)) print(output) This works, of course, but the problem is that if I want to add another function into (or pop out a function from) this pipeline, I have to disassemble and reconnect every function again. I would like to know if there is a better scheme or design pattern to create such a pipeline? A: I've done something similar before, using just the multiprocessing library. It's a bit more manual, but it gives you the ability to easily create and modify your pipeline, as you've requested in your question. The idea is to create functions that can live in a multiprocessing pool, and their only arguments are an input queue and an output queue. You tie the stages together by passing them different queues. Each stage receives some work on its input queue, does some more work, and passes the result out to the next stage through its output queue. The workers spin on trying to get something from their queues, and when they get something, they do their work and pass the result to the next stage. All of the work ends by passing a "poison pill" through the pipeline, causing all stages to exit: This example just builds a string in multiple work stages: import multiprocessing as mp POISON_PILL = "STOP" def stage1(q_in, q_out): while True: # get either work or a poison pill from the previous stage (or main) val = q_in.get() # check to see if we got the poison pill - pass it along if we did if val == POISON_PILL: q_out.put(val) return # do stage 1 work val = val + "Stage 1 did some work.\n" # pass the result to the next stage q_out.put(val) def stage2(q_in, q_out): while True: val = q_in.get() if val == POISON_PILL: q_out.put(val) return val = val + "Stage 2 did some work.\n" q_out.put(val) def main(): pool = mp.Pool() manager = mp.Manager() # create managed queues q_main_to_s1 = manager.Queue() q_s1_to_s2 = manager.Queue() q_s2_to_main = manager.Queue() # launch workers, passing them the queues they need results_s1 = pool.apply_async(stage1, (q_main_to_s1, q_s1_to_s2)) results_s2 = pool.apply_async(stage2, (q_s1_to_s2, q_s2_to_main)) # Send a message into the pipeline q_main_to_s1.put("Main started the job.\n") # Wait for work to complete print(q_s2_to_main.get()+"Main finished the job.") q_main_to_s1.put(POISON_PILL) pool.close() pool.join() return if __name__ == "__main__": main() The code produces this output: Main started the job. Stage 1 did some work. Stage 2 did some work. Main finished the job. You can easily put more stages in the pipeline or rearrange them just by changing which functions get which queues. I'm not very familiar with the asyncio module, so I can't speak to what capabilities you would be losing by using the multiprocessing library instead, but this approach is very straightforward to implement and understand, so I like its simplicity. A: I don't know if it is the best way to do it but here is my solution. While I think it's possible to control a pipeline using a list or a dictionary I found easier and more efficent to use a generator. Consider the following generator: def controller(): old = value = None while True: new = (yield value) value = old old = new This is basically a one-element queue, it stores the value that you send it and releases it at the next call of send (or next). Example: >>> c = controller() >>> next(c) # prime the generator >>> c.send(8) # send a value >>> next(c) # pull the value from the generator 8 By associating every coroutine in the pipeline with its controller we will have an external handle that we can use to push the target of each one. We just need to define our coroutines in a way that they will pull the new target from our controller every cycle. Now consider the following coroutines: def source(controller): while True: target = next(controller) print("source sending to", target.__name__) yield (yield from target) def add(): return (yield) + 1 def prod(): return (yield) * 2 The source is a coroutine that does not return so that it will not terminate itself after the first cycle. The other coroutines are "sinks" and does not need a controller. You can use these coroutines in a pipeline as in the following example. We initially set up a route source --> add and after receiving the first result we change the route to source --> prod. # create a controller for the source and prime it cont_source = controller() next(cont_source) # create three coroutines # associate the source with its controller coro_source = source(cont_source) coro_add = add() coro_prod = prod() # create a pipeline cont_source.send(coro_add) # prime the source and send a value to it coro_source.send(None) print("add =", coro_source.send(4)) # change target of the source cont_source.send(coro_prod) # reset the source, send another value coro_source.send(None) print("prod =", coro_source.send(8)) Output: source sending to add add = 5 source sending to prod prod = 16
doc_5211
<?php $data = mysql_query("SELECT COUNT(*) FROM pins ORDER BY user_id ASC LIMIT 5") or die(mysql_error()); while($info = mysql_fetch_array( $data )) { Print "<table><tr><td>"; Print "".$info['user_id'].""; Print "</td></tr></table>"; } ?> This is a code I have adapted which works for individual users with a WHERE user_id='999' clause. But how do I change it to get the top 5? A: Use GROUP BY: SELECT user_id FROM pins GROUP BY user_id ORDER BY COUNT(*) DESC LIMIT 5
doc_5212
Traceback (most recent call last): File "/Users/<path>/file.py", line 1, in <module> from coinmarketcap import Market File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/coinmarketcap/__init__.py", line 10, in <module> from .core import Market File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/coinmarketcap/core.py", line 8, in <module> import requests_cache File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/requests_cache/__init__.py", line 28, in <module> from .core import( File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/requests_cache/core.py", line 14, in <module> from requests import Session as OriginalSession ImportError: cannot import name 'Session' It seems to be generated from the very first line where the import and code is the following: from coinmarketcap import Market cmc = Market() coins = cmc.ticker(limit=15) # assumes Dash in top 15. print(coins) A: Not sure if it helps but I had similar issue with import - turned out I have created requests.py file and imported stuff from there. It caused namespace clash as other libraries I used in the project were dependent on built-in requests module.
doc_5213
The product field is a varchar field, and is typically something like "300x250" and not that string of hex-values: Editing the first record gives me this screen which displays the value properly: This problem started when I upgraded to 4.1.7 locally, and so I downgraded back to 4.0.6 and everything was normal again. However, these tables are copied over from another production database. I export from production using phpMyAdmin, then drop my local tables, and re-import them into my local. All varchar fields display as strings of two-digit hex values now, but only in those tables that I have dropped and imported. Tables that haven't been touched in a while still display the correct varchar values. I never saw this problem before the upgrade, but now it's started happening on 4.0.6. The production server is using 3.4.10.1, but it hasn't been updated recently, so I don't think that's the issue as I used to do this process regularly and never had any issues. Edit: So after further reading, I realized that the issue was that the varchar fields were set to utf8_bin and needed to be changed to utf8_general_ci. What I don't understand is that the fields in the production database are set to utf8_bin, and they display correctly at all times, and why this wasn't an issue until recently. A: Edit ./config.inc.php and change line $cfg['Servers'][$i]['extension'] = 'mysql'; to $cfg['Servers'][$i]['extension'] = 'mysqli';
doc_5214
I've tried: <appendAssemblyId>false</appendAssemblyId> in the <configuration> block of the plugin, but that only excludes the id from being appended to the final name (the output file), it doesn't affect the context root. Is there a way to stop the maven-assembly-plugin from appending the ID to the war's context root parameters? Edit: The assembly file is used to build a portlet version of the webapp. In the assembly XML file, there is this line: <id>portlet</id> The context root of the non-portlet webapp is portal, so the context root of the portlet built from the assembly ends up being portal-portlet. I need the context root of the two builds to be the same because I am building a flex swf that relies on that context root in the MessageBroker. I know I could do this by compiling two separate swfs, but that would lead to pom changes I don't want to make for various reasons.
doc_5215
Remarks: * *I don't want to use more than the table name in order to locate it (I don't want all the div\div\table\div\tbody\td\tr[r]\td[c] in the code). *I'm using Selenium within PHPUnit. Hence, I can use PHP logic for the task, though I don't want any complex logic for such a simple task. Clarification: If the element in the cell is just plain text, then I can retrieve that text like this: $this->getText("xpath=//table[@name='tableName']//tr[".$r."]//td[".$c."]"); (PHP) But what if the cell has an element which is not just plain text? What if the element is a link (link=anchor) or a button (//button[@type='button']) or an image or something more complex? I need to assert that an element specified by a locator of that element resides in a given cell. A: You could try Selenium's getXpathCount $this->("xpath=//table[@name='tableName']//tr[".$r."]//td[".$c."]//TAG"); This will return the number of matches the xpath gets. in your case, zero would mean a fail. A: Sounds like you want isElementPresent(...locator of element...). For example: $cell = "//table[@name='tableName']//tr[".$r."]/td[".$c."]"; $foundLink = $this->isElementPresent("xpath=".$cell."/a[.='".linktext."']"); $foundButton = $this->isElementPresent("xpath=".$cell."/button[@type='button']"); $foundImage = $this->isElementPresent("xpath=".$cell."/img[ends-with(@src='pretty-pony.gif')]"); isElementPresent() returns true if so, false if not.
doc_5216
hub2['time'] = pd.to_datetime(hub2.timestamp) works, but when I write hub2 >> mutate(time=pd.to_datetime(X.timestamp)) with https://github.com/kieferk/dfply I get the error Traceback (most recent call last): File "<input>", line 1, in <module> File "[...]/lib/python2.7/site-packages/pandas/util/decorators.py", line 91, in wrapper return func(*args, **kwargs) File "[...]/lib/python2.7/site-packages/pandas/tseries/tools.py", line 419, in to_datetime elif isinstance(arg, ABCSeries): File "[...]/lib/python2.7/site-packages/pandas/types/generic.py", line 9, in _check return getattr(inst, attr, '_typ') in comp TypeError: __nonzero__ should return bool or int, returned Call Why is that?
doc_5217
Product table has a field called "CategoryID" and the Category table has a field called "CategoryName", ID, DateCreated, and a few others. I want to use LINQ to SQL to query all the Product rows as well as JUST the Category.CategoryName. This query will be used in a datasource and be bound to a ListView. I know I can use the LoadWith option with the DataContext and a join. But the problem is that I end up with all the rows from Product and Category. What I really want is all rows from Product and just the Category.CategoryName The perfect solution would be if the LoadWith option would let you specify the fields to return but as answered here, that's not possible. I did find one way to do it, create a custom class which has the same exact fields that I want returned. So for example public class ProductInfo { public string ProdName { get; set; } public int ProdID { get; set; } public int CategoryID { get; set; } public string CategoryName { get; set; } } but the problem is that the select statement ends up really long. for example... var products = from p in db.Products join c in db.Categories on p.CategoryID = c.ID select new ProductInfo { ProdName = p.ProdName, ProdID = p.ID, CategoryID = p.CategoryID, CategoryName = c.CategoryName } this becomes really error prone. So my question - is there a better way to accomplish this? Edit/Clarification: i should have mentioned that the REASON i need the intermediary class is because i need to be able to return the result set as a specific type, in this case ProductInfo A: I think you're pretty much on the right track, but I wouldn't really worry about the intermediery class: var products = from p in db.Products join c in db.Categories on p.CategoryID = c.ID select new { p.ProdName, ProdId = p.ID, p.CategoryID, CategoryName = c.CategoryName } You can then wire this up in the Selecting event of the LinqDataSource. Scott Guthrie talks about in the section "Performing Custom Query Projections with the Selecting Event" in his post "Using a Custom Linq Expression with the asp:LinqDataSource" control". A: oh gosh, i should have mentioned that the REASON i need the intermediary class is because i need to be able to return the result set as a specific type, in this case ProductInfo A: List<ProductInfo> products = (from p in db.Products join c in db.Categories on p.CategoryID = c.ID select new ProductInfo { ProdName = p.ProdName, ProdID = p.ID, CategoryID = p.CategoryID, CategoryName = c.CategoryName }).ToList<ProductInfo>();
doc_5218
There are ideally 15 - 20 different filters, and I am managing them using Intercept Design Pattern. before applying filters List could be empty, so should I use NullValueFilter in the filter chain? after applying some filters list again can be empty, to check that also should I inject the same null or empty check strategy using the strategy design pattern? I usually think more on designing perspective to manage such cases. I want to know if I am thinking in the right direction or maybe I am overengineering on that part. Some pseudo code to illustrate the scenario - Class NullValueFilter : IFilter { Execute(List<CampaignList> campaignList) { if(campaignList != null && campaignList.Count == 0) { return false; } return true; } } Class PlatformFilter : IFilter { Execute(List<CampaignList> campaignList) { if(campaignList != null && campaignList.Count == 0) { return false; } campaignList = campaignList.Where( x => x.Platform == 'Mobile'); return true } } Class CampaignRunningFilter : IFilter { Execute(List<CampaignList> campaignList) { if(campaignList != null && campaignList.Count == 0) { return false; } // first Fetch campaign start date and end date campaignList = campaignList.Where( x => x.startdate <= curr_date && x.enddate >= curr_date); return true } } I can think of two options here - * *create a filterbase class that can manage null and empty check for list. *inject null value filter instance in each filter using constructor injection and call that null and empty check method. A: For 15 up to 20 filters, I would simply not do any checks for the empty list, that makes things more complicated than necessary without any noteable benefit. Each filter behaves perfectly consistent when it passes an empty list just through, so I don't see any compelling reason why this premature optimization of "breaking the chain" is necessary. The most cleanest design is IMHO the one where we have thrown any unneccesary waste over board, so this is what I would start with. However, if you really notice measureable, relevant performance improvement by stopping the processing at the empty list, I would not let the filters test for this case. Instead, let the caller test it directly, instead of checking a boolean return code. I would recommend to make the Execute method return the filtered list, and do implement it along the lines of this snippet: List<Campaign> campaignList = ...; // init this here foreach(IFilter filter in GetActiveFilters) { if(campaignList==null || campaignList.Count == 0) break; campaignList = filter.Execute(campaignList); } This way, there is only one place in the code where the empty-list test needs to be implemented, and you don't have to repeat this in the filters over and over again. A: can we create an abstract class that will expose a public method Execute that will be responsible for calling another protected abstract method lets say ExecuteFilter and call it conditionally and all filters will implement this abstract class eg: Class AbstractBaseFilterClass : IFilter { public Execute(List<CampaignList> campaignList) { if(campaignList != null && campaignList.Count == 0) { return false; } ExecuteFilter(campaignList); } protected abstract boolean ExecuteFilter(List<CampaignList> campaignList); } Class PlatformFilter : AbstractBaseFilterClass { ExecuteFilter(List<CampaignList> campaignList) { if(campaignList != null && campaignList.Count == 0) { return false; } campaignList = campaignList.Where( x => x.Platform == 'Mobile'); return true } } Class CampaignRunningFilter : AbstractBaseFilterClass { ExecuteFilter(List<CampaignList> campaignList) { if(campaignList != null && campaignList.Count == 0) { return false; } // first Fetch campaign start date and end date campaignList = campaignList.Where( x => x.startdate <= curr_date && x.enddate >= curr_date); return true } } // client can call it simply List<Campaign> campaigns = ...; foreach(IFilter filter in Filters) { filter.Execute(campaignList); }
doc_5219
After this validation the pop up window closes and I need to start a MySQL transaction to modify the accessories picked for the rented equipment. I need it to be a transaction because the user can cancel the rent at any moment and I need to "return" everything to the way it was before the rent. Is it possible to handle MySQL transactions using several PHP files with AJAX? A: No, you can't do it with mysql transactions because you will not be able to serialize a reference to the transaction or connection, and the transaction will either be rolled back or committed (not sure which, but I think it gets committed) when the script execution stops. This means that it will not work across multiple requests. Instead of using transactions, a possible solution would be to update your schema to add a flag for "picked" accessories. When the customer selects them, set this flag. If they cancel, unset it.
doc_5220
I have tried .Except() method like below but it does not work for me. dt1.AsEnumerable().Except(dt2.AsEnumerable()).CopyToDataTable(); I think i have mistake in using this method but i could not find that? A: You can create your own Comparer using IEquailtyComparer public class CustomDataRowComparer : IEqualityComparer<DataRow> { public bool Equals(DataRow x, DataRow y) { for (int i = 0; i < x.Table.Columns.Count; i++) { if (x[i].ToString() != y[i].ToString()) { return false; } } return true; } public int GetHashCode(DataRow obj) { return obj.ToString().GetHashCode(); } } Later you can call it like: CustomDataRowComparer myDRComparer = new CustomDataRowComparer(); var result2 = dt1.AsEnumerable().Except(dt2.AsEnumerable(),myDRComparer).CopyToDataTable(); A: Except will not work because the references are different. Each "copy" of a data row in memory is a different object, thus the equality comparison being made in Except will always return false. You need to compare with something comparable, like row IDs. A couple ideas how to do this: var rowsInFirstNotInSecond = dt1.Rows.Where(r1=>!dt2.Rows.Any(r2=>r1.ID == r2.ID)); Or: var rowsInFirstNotInSecond = dt1.Rows.Where(r1=>dt2.FindById(r1.ID) == null); A: I have used the following code to subtract two datatables from each other : var query = from row1 in dt1 where !(from row2 in dt2 select row2.ID) .Contains(row1.ID) select row1; this code returns exactly what i want... A: This Code works for sure: var rows =dtFirst.AsEnumerable().Except(dtSecond.AsEnumerable(), DataRowComparer.Default); DataTable result = null; if (rows.Count() != 0) result = rows.CopyToDataTable();
doc_5221
The problem is, when I try to set stickyHeaderDates, which should fix the calendar header toolbar at the top when scrolling down the page. It is actually working, however calendar header toolbar only sticks to the top of the page, which is behind the bootstrap navigation bar, so it is not visible. So my question is, how to stick calendar header to the top of parent element, for example parent div, instead to top of the page? Here is my current code: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>TEST</title> <!-- Bootstrap core CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <!-- fullcalendar scheduler 5.4.0 https://www.jsdelivr.com/package/npm/fullcalendar-scheduler --> <link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/fullcalendar-scheduler@5.4.0/main.min.css' /> <style> body { padding-top: 54px; } #calendar { max-width: 1100px; margin: 40px auto; } </style> </head> <body> <nav id="mynav" class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top" style="height:80px; z-index:-10;"> <div class="container text-white"> This is my fiexd header, I would like to stick fullcalendar dates toolbar beneeth it. </div> </nav> <!-- Page Content --> <div class="container content"> <div id='calendar'></div> </div> <!-- fullcalendar scheduler 5.4.0 https://www.jsdelivr.com/package/npm/fullcalendar-scheduler --> <script type="text/javascript" src='https://cdn.jsdelivr.net/npm/fullcalendar-scheduler@5.4.0/main.min.js'></script> <script> document.addEventListener('DOMContentLoaded', function() { var calendarEl = document.getElementById('calendar'); var calendar = new FullCalendar.Calendar(calendarEl, { schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source', timeZone: 'UTC', initialView: 'resourceTimeGridWeek', headerToolbar: { left: 'prev,next today', center: 'title', right: 'resourceTimeGridWeek,resourceTimeGridDay' }, resources: 'https://fullcalendar.io/demo-resources.json?max=4', events: 'https://fullcalendar.io/demo-events.json?with-resources=2&single-day', editable: true, selectable: true, height: 'auto', // will activate stickyHeaderDates automatically! slotDuration: '00:05:00', // very small slots will make the calendar really tall dayMinWidth: 150, // will cause horizontal scrollbars }); calendar.render(); }); </script> </body> </html> A: .fc .fc-scrollgrid-section-header.fc-scrollgrid-section-sticky>* { top: 80px; } You can add .fc .fc-scrollgrid-section-header.fc-scrollgrid-section-sticky>* to the css file and it should go fine see fixed version on https://codepen.io/igolus/pen/rNYLOVo
doc_5222
For example the word "home" written in uisearchbar, be sent to query: SELECT * FROM table1 WHERE content MATCH '…..' // here '….' to be sent "home" -(NSArray *)titles{ NSMutableArray * retval = [[[NSMutableArray alloc] init] autorelease]; NSString * query = @"SELECT * FROM table 1 WHERE content MATCH '…..' "; sqlite3_stmt * statement; if (sqlite3_prepare_v2(_database, query.UTF8String, -1, &statement, nil) == SQLITE_OK) { while (sqlite3_step(statement) == SQLITE_ROW) {………..}}}; I want to know if this is possible ,and a link with an example. Thank you. A: please refer to this post: text search too slow on sqlite db on tableview on iphone A: You have to make sure your view controller implements the UISearchBarDelegate protocol then add the following method - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText { [self titles:searchText]; } Modify your titles method to accept a string as parameter: -(NSArray *)titles:(NSString *)toMatch { NSMutableArray * retval = [[[NSMutableArray alloc] init] autorelease]; NSString * query = [NSString stringWithFormat:@"SELECT * FROM table 1 WHERE content MATCH '%@'", toMatch]; sqlite3_stmt * statement; if (sqlite3_prepare_v2(_database, query.UTF8String, -1, &statement, nil) == SQLITE_OK) { while (sqlite3_step(statement) == SQLITE_ROW) {………..}}}; Make sure your viewcontroller is the delegate for the UISearchBar.
doc_5223
Here's my jsx: <View style={styles.aboutSection}> <SvgUri width="150" height="150" source={require('../../assets/images/logo_blue.svg')} /> </View> and my SVG file: <?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <svg version="1.1" id="Calque_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="-574 823.3 20 14" style="enable-background:new -574 823.3 20 14;" xml:space="preserve"> <style type="text/css"> .st0{fill:#2A327B;} </style> <g> <g transform="translate(-320.000000, -1983.000000)"> <g transform="translate(40.000000, 1680.000000)"> <path class="st0" d="M-284,1140.3c-7.4,0-10-7-10-7s3.4-7,10-7c6.7,0,10,7,10,7S-277.3,1140.3-284,1140.3L-284,1140.3z M-284,1129.3c-2.2,0-4,1.8-4,4s1.8,4,4,4s4-1.8,4-4S-281.8,1129.3-284,1129.3L-284,1129.3z M-284,1135.3c-1.1,0-2-0.9-2-2 s0.9-2,2-2s2,0.9,2,2S-282.9,1135.3-284,1135.3L-284,1135.3z"/> </g> </g> </g> </svg> And is not showing when I debug, what I am missing and is there a better way to show images from SVG files? Is converting them to jsx using SVGR is a better approach or there are other ways to do so. A: Since the package seems to be no more maintained, after a good time of searching around, I’ve eventually ended up with using custom web fonts with the help of react-native-icons: * *(Optional) Minimizing the size of SVG, I used for this purpose SVG minizer *Convert fonts using icomoon *Add generated font to assets/fonts folder in your root (or any other path) *Add a linker in your packages.json "rnpm": { "assets": [ "./assets/fonts/" ] } *And link it using react-native link *To create a custom icon component I’ve used react-native-icons, it has a createIconSetFromIcoMoon function to render font generated from IcoMoon, and also a one generated from Fontello In my custom component MyIcon.js, I also add the selection.json generated. import { createIconSetFromIcoMoon } from 'react-native-vector-icons'; import MyIconConfig from '../../../selection.json'; const MyIcon = createIconSetFromIcoMoon(MyIconConfig, 'MyIcon-icons', 'MyIcon-icons.ttf'); //name of font I used in the website to generate font and name of ttf files generated export default MyIcon; I use it in my component, I the names of icons I've found them in demo.html: <MyIcon style={styles.customStyle} name="previous" size={18} color=’red’ /> Note: Make sure you use version >6.3.0 of react-native-icons, and link your assets by running: react-native link ./assets/fonts/
doc_5224
here's my popover code: <button type="button" class="btn btn-lg btn-danger" data-toggle="popover" title="Popover title" data-content="And here's some amazing content. It's very engaging. Right?">Click to toggle popover</button> and here's my js: <script type="text/javascript"> $(function () { $('.example-popover').popover({ container: 'body' }) }) </script> A: add example-popover class name in your button it will works $('.example-popover').popover({ container: 'body' }) <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> <button type="button" class="btn btn-lg btn-danger example-popover" data-toggle="popover" title="Popover title" data-content="And here's some amazing content. It's very engaging. Right?">Click to toggle popover</button>
doc_5225
const fixedHeader = $('.header'); const headerWrapper = $('.header__wrapper'); const scrolledItems = $('.items-wrapper'); let shift = 0; const scrollArea = (scrollItem) => { scrollItem.on('DOMMouseScroll mousewheel', function (e) { if(e.originalEvent.detail > 0 || e.originalEvent.wheelDeltaX < 0) { shift = shift - 20; scrolledItems.css('transform', `translateX(${shift}px`); headerWrapper.css('transform', `translateX(${shift}px`); } else { shift = shift + 20; scrolledItems.css('transform', `translateX(${shift}px`); headerWrapper.css('transform', `translateX(${shift}px`); //scroll left } return false; }); } scrollArea(headerWrapper); scrollArea(scrolledItems); .container { border: 4px solid red; width: 500px; height: 300px; overflow-x: scroll; padding: 20px; } .header { display: flex; background-color: green; width: 500px; height: 50px; overflow-x: auto; padding: 10px; margin-bottom: 20px; position: fixed; top: 0; left: 20px; right:0; } .header__wrapper { display: flex; width: 100%; } .header > .item { background-color: yellow; } .wrapper { display: flex; flex-direction: row; height: 200px; overflow-x: auto; } .items-wrapper { display: flex; margin-top: 50px; } .item { background-color: blue; width: 20px; height: 20px; margin-right: 20px; flex-shrink: 0; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <div class="wrapper"> <header class="header"> <div class="header__wrapper"> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> </header> <div class="items-wrapper"> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> </div> </div> A: Hmmm you can try this in you JS Code: $('.header').scroll(function(){ $('.wrapper').scrollLeft($(this).scrollLeft()); if ($('.header').scrollLeft() >= 270) { $('.wrapper').scrollLeft($('.wrapper').scrollLeft() + 50); } }) $('.wrapper').scroll(function(){ $('.header').scrollLeft($(this).scrollLeft()); }) UPDATE 2: This update both cotainers (header and wrapper) have the same width and the horizontal scroll have the same height, then the condition in the header event scroll for determinate the scroll's end is not necesary: CSS: .container { border: 4px solid red; width: 500px; height: 300px; overflow-x: scroll; padding: 20px; } .header { display: flex; background-color: green; width: 500px; height: 50px; overflow-x: auto; padding: 10px; margin-bottom: 20px; position: fixed; top: 0; left: 20px; right:0; } .header__wrapper { display: flex; width: 100%; } .header > .item { background-color: yellow; } .wrapper { display: block; flex-direction: row; width: 500px; height: 200px; overflow-x: auto; overflow-y: hidden; padding: 10px; position: fixed; left: 20px; top: 90px; } .items-wrapper { display: flex; margin-right: 0px; } .item { background-color: blue; width: 20px; height: 20px; margin-right: 20px; flex-shrink: 0; } JS Code: $('.header').scroll(function(){ $('.wrapper').scrollLeft($(this).scrollLeft()); }) $('.wrapper').scroll(function(){ $('.header').scrollLeft($(this).scrollLeft()); })
doc_5226
I'm trying to build a workspace with dependencies between each module via build tasks. I've tried to set dependsOn parameter for a task, but it yields a following error: Couldn't resolve dependent task 'build FOO' in workspace folder 'BAR' (here BAR build task depends on FOO) Is there a better/correct/any way to achieve my goal? A: Check if the new VSCode 1.42 User level Tasks can help share a task. tasks.json is now supported at a user settings level. You can run the the Tasks: Open User Tasks command to create a user level tasks. These tasks will be available across all folders and workspaces. Only shell and process task types are supported here. A: You can have a tasks section in your .code-workspace file. There you can create a task like "Build all" and define dependsOn tasks. However, there you also cannot reference build tasks from the workspace folders (to me this sounds like a reasonable feature and I believe they should implement it at some time). My workaround is to copy the relevant build task from the sub-tasks files into the .code-workspace file and reference them in my "Build all" task. Example .code-workspace: { "folders": [ { "path": "proj-A" }, { "path": "proj-B" } ], "tasks": { "version": "2.0.0", "tasks": [ { "type": "shell", "label": "Build A", "command": "make", "args": ["-j4"], "options": { "cwd": "${workspaceFolder}/../proj-A", }, "problemMatcher": [ "$gcc" ], "group": "build", }, { "type": "shell", "label": "Build B", "command": "make", "args": ["-j4"], "options": { "cwd": "${workspaceFolder}/../proj-B", }, "problemMatcher": [ "$gcc" ], "group": "build", }, { "type": "shell", "label": "Build all", "command": "echo", "args": ["Building everything"], "options": {}, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "dependsOrder":"sequence", "dependsOn": ["Build A", "Build B"] }, ] } } Note the cwd option in the individual build tasks. ${workspaceFolder} seems to be set to the first path in the "folders" section. You could also set cwd to absolute paths. This is a bit hacky and the fact that one has to copy the build tasks is not beautiful, but it works for now and it can be easily adapted once it is possible to reference tasks of sub-tasks files. A: The documentation for Multi-Folder workspace shows how to do this, instead of just adding strings with the task name, add an object like this: { "name": "foo", "folder": "bar" }
doc_5227
Where is my error? class _NewTest extends State<NewTest> { static String mmobileNumber = ''; List<SimCard> _simCard = <SimCard>[]; var list; String text = "Mobilnumber is empty"; @override void initState() { super.initState(); Future.delayed(Duration(seconds: 3), () { Navigator.pushAndRemoveUntil( context, MaterialPageRoute(builder: (context) => Carrier_Info()), (_) => false); }); MobileNumber.listenPhonePermission((isPermissionGranted) { if (isPermissionGranted) { initMobileNumberState(); } else {} }); initMobileNumberState(); } // Platform messages are asynchronous, so we initialize in an async method. Future<void> initMobileNumberState() async { if (!await MobileNumber.hasPhonePermission) { await MobileNumber.requestPhonePermission; return; } String mobileNumber = ''; // Platform messages may fail, so we use a try/catch PlatformException. try { mobileNumber = await MobileNumber.mobileNumber; _simCard = await MobileNumber.getSimCards; } on PlatformException catch (e) { debugPrint("Failed to get mobile number because of '${e.message}'"); } if (!mounted) return; setState(() async { var re = RegExp(r'\+[^]*'); mmobileNumber = mobileNumber.replaceRange(0, 3, ''.replaceAll(re, '+')); print('Hier ist die mobilnummer'); print(mmobileNumber); }); } Widget fillCards() { List<Widget> widgets = _simCard .map((SimCard sim) => Text( 'Sim Card Number: (${sim.countryPhonePrefix}) - ${sim.number}\nCarrier Name: ${sim.carrierName}\nCountry Iso: ${sim.countryIso}\nDisplay Name: ${sim.displayName}\nSim Slot Index: ${sim.slotIndex}\n\n')) .toList(); return Column(children: widgets); } bool _loading = true; @override Widget build(BuildContext context) { if (mmobileNumber == null) { return MaterialApp( title: 'Fetch Data Example', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( backgroundColor: Color.fromRGBO(35, 31, 32, 1), title: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Image.asset( 'assets/images/test.png', fit: BoxFit.contain, height: 55, ) ], ), ), body: Center( child: _loading ? Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ CircularProgressIndicator( valueColor: AlwaysStoppedAnimation<Color>( Color.fromRGBO(35, 31, 32, 1), ), backgroundColor: Colors.grey[200], strokeWidth: 5, ), Text(" "), Text("Data is loaded and MobileNumber is not empty.", style: TextStyle(fontSize: 20)), Text(mmobileNumber), ], ) : Text("Press button to download"), ), )); } else { return MaterialApp( title: 'Fetch Data Example', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( backgroundColor: Color.fromRGBO(35, 31, 32, 1), title: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Image.asset( 'assets/images/autokontor.png', fit: BoxFit.contain, height: 55, ) ], ), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text(" "), Text("MobileNumber is empty.", style: TextStyle(fontSize: 20)), ], )), )); } } } A: Thanks for your help I have found a solution: @override void initState() { super.initState(); Future.delayed(Duration(seconds: 1), () { if (mmobileNumber.length < 1) { print("is empty"); Navigator.pushAndRemoveUntil( context, MaterialPageRoute(builder: (context) => NoMobileNumber()), (_) => false); } else if (list == null) { Navigator.pushAndRemoveUntil( context, MaterialPageRoute(builder: (context) => NoInternet()), (_) => false); } else { print(_loadHtml3(String)); Navigator.pushAndRemoveUntil( context, MaterialPageRoute( builder: (context) => Test(mmobileNumber, mmobileNumber, list[1][0], _loadHtml2(String), _loadHtml3(String))), (_) => false); } }); MobileNumber.listenPhonePermission((isPermissionGranted) { if (isPermissionGranted) { initMobileNumberState(); } else {} }); futureAlbum = fetchAlbum(); initMobileNumberState(); } I just made the IF else statments in the init. Might not be the smartest solution but it works for me. A: Yes, instead of conditionally return MaterialApp widget you can conditionally render widget in the child. See bellow example : Container( child : if(mobileNumber) Text() else Container(), color: Colors.red ); Perhaps, using a state management approach will be better solution on conditional rendering, see Flutter State Management Approach A: You can use the ternary operator for this. phoneNumber? Container(): Text("Not Present")
doc_5228
Generally speaking, What causes the build function to run and how to restructure a program that prevents the entire screen from repainting even if the build is triggered? class TestPad extends StatefulWidget { _TestPadSate createState() => new _TestPadSate(); final Bloc _bloc = new Bloc(); } class _TestPadSate extends State<TestPad>{ static final txtAreaController = TextEditingController(); @override void initState() { super.initState(); widget._bloc.fetchVal(); } @override Widget build(BuildContext context) { return Material( child: Scaffold( appBar: new AppBar(), body: StreamBuilder( stream: widget._bloc.getVal, builder: (context, snapshot) { if(snapshot.connectionState == ConnectionState.waiting){ return buildProgressIndicator(true, width: 50, height: 50); } return Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Expanded( child: new Container( margin: EdgeInsets.only( ), //height: MediaQuery.of(context).size.height - 210, decoration: BoxDecoration( color: Colors.white, border: Border(top: BorderSide(color: Colors.grey))), child: ListView( reverse: true, shrinkWrap: true, children: List(), ), ) ), Container( margin: EdgeInsets.only( top: 2.0, ), decoration: new BoxDecoration( color: Colors.white, ), height: 72, child: new Column( children: <Widget>[ textAreaSection(context), ], )), ], ); } ) ) ); } Widget _postBtn() { return IconButton( icon: Icon(Icons.send, size: 22,), ); } Widget textAreaSection(context) { return Row( mainAxisSize: MainAxisSize.min, //mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Expanded( child: textFormFieldScroller(), ), _postBtn() ], ); } Widget textFormFieldScroller() { return SingleChildScrollView( physics: ClampingScrollPhysics(), child: Form( child: TextFormField( controller: txtAreaController, keyboardType: TextInputType.text, style: new TextStyle( //height: 0.5, color: Colors.grey), autofocus: false, //initialValue: "What's on your mind?", // maxLines: null, decoration: new InputDecoration( contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0), hintText: "What's on your mind?", hintStyle: new TextStyle( color: Colors.grey[600], ), fillColor: Colors.white, filled: true, border: InputBorder.none, ), ) ), ); } Widget buildProgressIndicator(showIndicator,{double width, double height}) { return new Padding( padding: const EdgeInsets.all(8.0), child: new Center( child: new Opacity( opacity: showIndicator ? 1.0 : 0.0, child: Container( width: width??10.0, height: height??10.0, child: new CircularProgressIndicator( )), ), ), ); } } class Bloc { final _fetcher = BehaviorSubject<String>(); Observable<String> get getVal => _fetcher.stream; fetchVal() async{ await Future.delayed(Duration(seconds: 2), (){ _fetcher.sink.add("test"); }); } dispose() { _fetcher.close(); } } A: setState() causes a rebuild. I believe that the Flutter team don't consider rebuilding the screen a problem because it is very fast. However, the thing to do is to separate the collection of data (eg. Select) from the rebuild. IE. Structure your program so that if a re-select of data is done, then it is separate from the build. If and when a re-Select of data is required and the screen needs to be repainted then do a setState().
doc_5229
The ViewController is creating a Ntwk object and calling the PostData function in it and returns immediately. So now how does the ViewController get the data from the call? This must be a solved problem and obj-c probably already provides a way to do this but I am completely lost. I am learning this as I go, so I am looking for help. I see two ways to solve this - * *Have the didReceiveData delegate somehow be defined and called in the ViewController. This will be awesome. *Pass either a block or a function pointer to the Ntwk object from the ViewController and have it called from inside the didReceiveData delegate inside the Ntwk object. Is it possible to do either one of these? What is the correct way to do this? A: The approaches you mentioned are pretty much right but if you declare the DidReceiveData method in same class then we can not achieve the MVC and as you created the Network class for the functionality you can use either Block callback reference or you can use Delegate-Protocol methodology, for this you need to set the delegate with self as the reference of the calling class, then when your task gets finished just call the method from Protocol from this delegate reference. This might solve your problem.
doc_5230
SET @sql = CONCAT('SELECT TraineeID, ', @sql, ' from tbl_submit_coursefee c where c.BatchID='BID' group by c.TraineeID'); in where clause '' quotes do not allow and without quotes query return empty but if I put the parameter value in where clause straight then it works. I'm really stack with this. Here is my prepared statement (working fine): SET @sql = NULL; SELECT GROUP_CONCAT(DISTINCT CONCAT ('MAX(IF(BillNo = ''', BillNo, ''', CRA, NULL)) AS `Inv.', BillNo, '`') ) INTO @sql FROM tbl_submit_coursefee WHERE BatchID="ID-Welding/FMMTTC-01M/R8/01"; SET @sql = CONCAT('SELECT TraineeID, ', @sql, ' from tbl_submit_coursefee c where c.BatchID="ID-Welding/FMMTTC-01M/R8/01" group by c.TraineeID'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; when put this statement in a stored procedure (not working): DELIMITER @@ DROP PROCEDURE GetRetainment @@ CREATE PROCEDURE vtproject.GetRetainment (IN `BID` VARCHAR(100)) BEGIN SET @sql = NULL; SELECT GROUP_CONCAT(DISTINCT CONCAT ('MAX(IF(BillNo = '', BillNo, '', CRA, NULL)) AS `Inv.', BillNo, '`') ) INTO @sql FROM tbl_submit_coursefee WHERE BatchID=BID; SET @sql = CONCAT('SELECT TraineeID, ', @sql, ' from tbl_submit_coursefee c where c.BatchID='BID' group by c.TraineeID'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; END @@ DELIMITER ; If I select @sql before prepare stmt FROM @sql then output as below: SELECT TraineeID, MAX(IF(BillNo = 1, CRA, NULL)) AS `Inv.1`,MAX(IF(BillNo = 2, CRA, NULL)) AS `Inv.2`,MAX(IF(BillNo = 3, CRA, NULL)) AS `Inv.3`,MAX(IF(BillNo = 4, CRA, NULL)) AS `Inv.4`,MAX(IF(BillNo = 5, CRA, NULL)) AS `Inv.5`,MAX(IF(BillNo = 6, CRA, NULL)) AS `Inv.6`,MAX(IF(BillNo = 7, CRA, NULL)) AS `Inv.7` from tbl_submit_coursefee c where c.BatchID=BID group by c.TraineeID A: you need to escape the quotes, like this : SET @sql = CONCAT('SELECT TraineeID, ', @sql, ' from tbl_submit_coursefee c where c.BatchID=''',BID,''' group by c.TraineeID'); according with doc : http://dev.mysql.com/doc/refman/5.7/en/string-literals.html A: I found the solution in another way myself. BEGIN SET @sql = NULL; SET @bid=BID; SELECT GROUP_CONCAT(DISTINCT CONCAT ('MAX(IF(BillNo = ', BillNo, ', CRA, NULL)) AS `Inv.', BillNo, '`') ) INTO @sql FROM tbl_submit_coursefee WHERE BatchID=@bid; SET @sql = CONCAT('SELECT TraineeID, ', @sql, ' from tbl_submit_coursefee c where c.BatchID=@bid group by c.TraineeID'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; END
doc_5231
Is it possible to write a function or write an MDX expression such as: =IIf(Parameters!userPercent.Value <= 100 And Parameters!userPercent.Value >= 1, true, false) and obtain a user-friendly error message? I tried inserting the above expression in the default value tab for the parameter, but when previewing the report, the field turned out to be disabled A: You can achieve this by using a custom code.
doc_5232
So I started using it (I'm using the System.IO namespace) and it tells me that 'System.IO.Directory' does not contain a definition for 'GetFiles'. Indeed, if I use the intellisense, there is no such method. MSDN tells me that there is though, and I know I've used it before, and I'm 99% sure it was System.IO.Directory. I do have System.IO.Directory... it just doesn't have that method. It has methods like 'GetCreationTime', 'GetDirectoryRoot', 'GetLastAccessTime', 'SetCurrentDirectory' and so on, but no 'GetFiles'. Can anyone offer any help? A: How are you making the call? That will tell us a lot about why the compiler might be complaining. There are 3 Overloads for GetFiles on System.IO.Directory Could you be looking for DirectoryInfo.GetFiles Indeed, if I use the intellisense, there is no such method The only 2 logical things I can think of that might cause this: * *Visual Studio, or your solution are in a corrupted state (Restart VS / Reboot) *Your Project is targeting a version of .Net lower than 2.0 (GetFiles was introduced in 2.0) A: If you focus this issue using the framework of Silverlight 4 just change the use of .Getfiles(string directory) into .EnumerateFiles(string directory) instead
doc_5233
Have to solve this situation in a development of a desktop application whit Visual Studio and C#. A confirmation closing message is repeating twice when the user desire exit the application. I made a Form base and inherit the closing advice(for the X button top right corner and the logout button option 2) to the others. Forms are linked on to another but when I try to close the others forms and select Yes to close, the advice ask me again. enter image description here Here are the codes I put. For Inherit from Form Base: public partial class SelectUsuario : FormBase Code of the Form Base for the close confirmation: public void button1_Click(object sender, System.EventArgs e) { { Application.Exit(); } } public void FormBase_FormClosing(object sender, FormClosingEventArgs e) { if (MessageBox.Show("¿Seguro(a) que desea salir del sistema?", "Consulta", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No) { e.Cancel = true; //Cancela el cerrado del formulario } And the code to link forms: private void pbxUsuarioOps_Click(object sender, System.EventArgs e) { this.Hide(); IG_UsuOPs irUsuarioOPs = new IG_UsuOPs(); irUsuarioOPs.Show(); }
doc_5234
* *When my laptop is off at 11PM, launchd does not run the command srd exec. *If Launchd runs the command when I get started the next day, it should run srd exec -y instead. Explanation: I have a Launchd configured with Lingon to run Sifttter Redux on my OSX 10.10 laptop at 11PM every day. Quite often, the laptop is off at that time, otherwise the command does run successfully with expected results. It will also run as expected on demand from Terminal. Given that this application's purpose is essentially a logger, finding activity from specific date ranges in a text file and aggregating it into Day One entries for those days, the command should only be run once for every day or else duplicate entries are created. When I input srd exec, today's information is found and added to today's entry. When I input srd exec -y, yesterday's info is found and added to yesterday's entries. There are also parameters for date ranges. A: Try establishing a log file, and append the date to that file every time the agent successfully launches. Create an 11:00 AM agent that checks the log, and if yesterday's date is not present, launch the -y version, and you are done. A: I have solved this issue by creating a bash script which checks the time and executes srd with respective parameters: #!/bin/bash NOW=$(date +"%H") echo $(date); if [[ $NOW == 23 ]] then /usr/bin/srd exec --verbose echo "Sifttter grabbed today's events."; else /usr/bin/srd exec -y --verbose echo "Sifttter caught up on yesterday's events."; fi The task ran properly when run directly from terminal, but when run through launchd the stdout showed it cutting off halfway through and the sifttter proper log is showed invalid byte sequence in US-ASCII. This issue was fixed by adding the following character declaration to the launchd plist: <key>EnvironmentVariables</key> <dict> <key>LANG</key> <string>en_US.UTF-8</string> </dict>
doc_5235
grep "DROP TABLE" * above statement gives all the lines in all the files in directory having DROP TABLE statement. But it will not give if there are multiple spaces between DROP and TABLE. I want a command to fetch only those lines that have DROP table statement but not IF EXITS clause ignoring multiple spaces in between DROP TABLE TABLE1 IF EXISTS; ## command should not display above line DROP TABLE TABLE1 IF EXISTS; ## command should not display above line DROP TABLE TABLE1 ; ### command should display above line DROP TABLE table1; ### command should display above line Appreciate response :-) A: By default grep uses basic regular expressions. You can express your criteria like this: grep "DROP \+TABLE" * | grep -v "IF \+EXISTS" The -v inverts the match. Using the -v "word regex" mode would perhaps be safer (but a proper parser would be best if your input file could contain arbitrarily complex SQL statements): grep -w "DROP \+TABLE" * | grep -vw "IF \+EXISTS" If your file contained a line like: NODROP TABLE FOO The first version would include it in the output but the second wouldn't. DROP TABLE FOO IF ISEXISTSWHATERVER Would be included by the first version but filtered out by the one with the -w. Thanks to hek2mgl for the -w suggestion. A: Use awk: awk '/\yDROP[[:blank:]]+TABLE\y/ && !/\yIF[[:blank:]]+EXISTS\y/' file Explanation: Basically the command looks like this: awk '/DROP TABLE/ && !/IF EXISTS/' file which prints lines with DROP TABLE in it but which do not contain IF EXISTS. Then we allow multiple spaces or tabs in between awk '/DROP[[:blank:]]+TABLE/ && !/IF[[:blank:]]+EXISTS/' file At the end we align them on word boundaries to make sure DROP wouldn't match somethink like XYDROP awk '/\yDROP[[:blank:]]+TABLE\y/ && !/\yIF[[:blank:]]+EXISTS\y/' file A: can you try tr -s ''. This would remove multiple spaces in between echo "DROP TABLE" | tr -s ' ' | grep "DROP TABLE" A: If your grep supports Perl regex (most likely): grep -P 'DROP\s+TABLE\s+\w+\s*(?!IF\s+EXISTS)\s*;' * Check the explantion
doc_5236
$start_time = time(); while ((time() - $start_time) < 30) { if ($db->getNewStuff()->rows > 0) { $response = "new stuff!"; break; } usleep(1000000); } echo $response; How do you evaluate, how "long" you "poll"? In this example, I chose 30 seconds, because... well, I can't even tell why. What are the impacts when using even longer polls, several minutes or alike? Will Apache crash? Will my application get laggy / stuck / decrease performance? Furthermore: How long should the process usleep? A: Your PHP script may not live that long, depending on the time limit. So, be sure to (re)set the time limit. Otherwise I don't see any problem increasing the times. As for how long the usleep should be, that is something that you need to benchmark for yourself. Shorter microsleeps will increase the server load, but find results faster. What is appropriate is determined very much by the rest of your application and your resources. You may even want to vary the microsleep time according to the server load (i.e. make it sleep longer when server load is high). A: You can easy saturate the available apache process/workwer. For instance if the apache is configured as show below: StartServers 2 MinSpareServers 4 MaxSpareServers 8 ServerLimit 11 MaxClients 11 MaxRequestsPerChild 4000 You can just serve 11 request ad your site will be unreachable for at last 30 seconds. If you are looking for just a proof of concept, it's ok to play with apache and PHP but on a real server you really avoid a PHP-->Apache long polling. You need to use something likas a comet environment for a scalable solution A: When usleep() is called php does nothing until the sleep expires. Generally the default maximum script execution time is 30 seconds, but sleep() and usleep() will go on for longer because technically PHP does not have control during the sleep operation. Have never tried any more than a few mins - and never had any issues. Potentially if it's something busy and get lots of threads going to sleep - you could run out of threads to process other requests... A: What long polling is The code you presented isn't long polling. Long polling is when you allow clients to wait for something, and allows your user interface to respond instantly to events on the server. The client makes a regular ajax request. Your server code might wait, or might respond immediately. If there is nothing to return (yet), it simply makes the response take longer to respond. If and when some waited-for event occurs, it sends a response immediately. The client polls your ajax request, which doesn't respond until some event occurs, but when that event occurs, it responds instantly. The client is expected to turn around and do another long poll request, right away. Preventing missed events For this reason, you usually use a sequence number in your long poll protocol. Each event is assigned a sequence number, and newer events have higher sequence numbers than older events. If you can arrange for that, then you can make the long poll be a "get events since id" request. If there are events they missed, it will return them instantly. If they gave you the latest sequence number, then there is nothing to return, so don't return any response, just make it take longer. If multiple events sneak in between long polls, your poll will return multiple event records. This requires some way for your code that notifies an event to notify the code that is waiting to send a response. You can implement that as a reasonable-rate poll of a key-value store, some sort of interprocess communication, or something suitably lightweight for repeated use. Your options are somewhat limited in PHP, due to its process model. In nodejs or another single-process server architecture, you could use a simple array of responses awaiting results, and call them all, respecting each one's "since" parameter, when a new event occurs. Classic example A chat client is the classic example of this. All of the people on the chat page have a long poll sitting there taking long to get a response. The page working fine, just a network request taking time in the background. When someone types a message, they post it to the server, and the handler for that inserts a message with the next id. All of the long polls will notice the new record is greater than the "since" value they are looking for, and they will immediately send a response for all records with an id greater than the "since" parameter. Essentially notifying all of the other chat participants within a short time, without making them constantly check for new messages themselves. A: You should really look into using Node and Socket.io. :) A: Having a total response interval of 20+ seconds will make your application prone to browser timeouts. Keep it at, or below 20 seconds -- just to be on the safe side.
doc_5237
a:1 a:1 123 b:2 345 c:3 456 d:4 d:4 456 .. .. I am interested in the output to be a:1 123 d:4 456 i.e lines which have the preceding field to have just one field. A: Try this: { if (NF == 1) { getline; print; next; } }
doc_5238
import Data.Array data UnitDir = Xp | Xm | Yp | Ym | Zp | Zm deriving (Show, Eq, Ord, Enum, Bounded, Ix) type Neighborhood a = Array UnitDir (Tree a) data Tree a = Empty | Leaf a | Internal a (Neighborhood a) deriving (Eq, Show) Clearly, Tree can be defined as an instance of Functor as follows: instance Functor Tree where fmap _ Empty = Empty fmap f (Leaf x) = Leaf (f x) fmap f (Internal x ts) = Internal (f x) $ fmap (fmap f) ts I would like to define a function that traverses an instance of Tree by permuting the indices of the Array UnitDir (Tree a) (so it's a permutation on the 6 possible values of UnitDir). A possible implementation would be this one: type Permutation = Array UnitDir UnitDir applyPermutation :: Permutation -> Tree a -> Tree a applyPermutation _ Empty = Empty applyPermutation _ (Leaf x) = Leaf x applyPermutation f (Internal x ts) = Internal x (applyPermutation' ts) where applyPermutation' ts = ixmap (Xp, Zm) (f !) (applyPermutation f <$> ts) My question is the following: Is there a natural Haskell construction to "traverse" the tree while reindexing the children? Functor does not work, since I use it to change the content of the tree, not its indexing scheme. It seems I would need two instances of Functor, one to change the content and the other to change the array indices. I thought that Traversable would be the right choice, but none of the signatures of the provided functions matches that of applyPermutation. Thanks in advance for any help. A: Functor does not work, since I use it to change the content of the tree, not its indexing scheme. It seems I would need two instances of Functor, one to change the content and the other to change the array indices. Your intuition here is spot on: a functor that acted on the Neighborhood a field would do what you need, and it is correct to call such a thing "functor". Here is one possible refactoring of applyPermutation: {-# LANGUAGE LambdaCase #-} -- I prefer case syntax for this sort of definition; with it, there is less stuff -- that needs to be repeated. LambdaCase is the icing on the cake: it frees me -- me from naming the Tree a argument -- without it I would be forced to write -- mapOverNeighborhoods f t = case t of {- etc. -} mapOverNeighborhoods :: (Neighborhood a -> Neighborhood a) -> Tree a -> Tree a mapOverNeighborhoods f = \case Empty -> Empty Leaf x -> Leaf x Internal x ts -> Internal x (f (mapOverNeighborhoods f <$> ts)) applyPermutation :: Permutation -> Tree a -> Tree a applyPermutation perm = mapOverNeighborhoods applyPermutation' where applyPermutation' = ixmap (Xp, Zm) (perm !) (You might prefer to go even further and use a mapping that takes UnitDirection -> UnitDirection directly, rather than Neighborhood a -> Neighborhood a. I didn't do that primarily to make it mirror the rest of this answer more closely, but also because it arguably makes for a more honest interface -- rearranging indices in an Array is not quite as straightforward as applying an arbitrary function to the indices.) There are two limitations of this attempt to define another functor: * *We already have a Functor instance, as you point out. It wouldn't be sensible to replace just for this use case, and defining a newtype for it would be too annoying. *Even if that wasn't the case, mapOverNeighborhoods can't be made into a Functor instance, as fmap takes arbitrary a -> b functions, and changing the type of the neighborhoods is not an option. These two concerns are addressed by optics libraries such as lens (if you end up using optics for just this one thing in your code base, though, you might prefer microlens for a smaller dependency footprint). {-# LANGUAGE TemplateHaskell #-} -- makeLenses needs this. {-# LANGUAGE DeriveFunctor #-} -- For the sake of convenience. {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveTraversable #-} -- Record fields on sum types are nasty; these, however, are only here for the -- sake of automatically generating optics with makeLenses, so it's okay. data Tree a = Empty | Leaf { _value :: a } | Internal { _value :: a, _neighborhood :: Neighborhood a } deriving (Eq, Show, Functor, Foldable, Traversable) makeLenses ''Tree applyPermutation :: Permutation -> Tree a -> Tree a applyPermutation perm = over neighborhood applyPermutation' where applyPermutation' = ixmap (Xp, Zm) (perm !) over (infix spelling: %~) is literally an fmap which allows choosing the targets. We do that by passing it an appropriate optic (in this case, neighborhood, which is a Traversal that targets all neighborhoods in a tree -- over neighborhood can be read as "map over all neighborhoods"). Note that the fact that we can't change the type of the neighborhood is not a problem (and also, in other circumstances, it would be possible to have type-changing optics). On a final note, the type of neighborhoods is Traversal' (Tree a) (Neighborhood a). If we expand the Traversal' type synonym, we get: GHCi> :t neighborhood neighborhood :: Applicative f => (Neighborhood a -> f (Neighborhood a)) -> Tree a -> f (Tree a) While going into the reasons why it is like that would make this answer too long, it is worth noting that this is a lot like the signature of traverse for Tree... GHCi> :set -XTypeApplications GHCi> :t traverse @Tree traverse @Tree :: Applicative f => (a -> f b) -> Tree a -> f (Tree b) ... except that it acts on the neighborhoods rather than on the values (cf. the parallel between fmap and mapOverNeighborhoods). In fact, if you were to adequately implement the traverse analogue with that type, you would be able to use it instead of the one automatically generated by makeLenses. A: For completeness, I coded a small variant based on catamorphisms, exploiting recursion-schemes. {-# LANGUAGE LambdaCase, DeriveFunctor, KindSignatures, TypeFamilies, DeriveFoldable, DeriveTraversable, TemplateHaskell #-} import Data.Functor.Foldable import Data.Functor.Foldable.TH import Data.Array data UnitDir = Xp | Xm | Yp | Ym | Zp | Zm deriving (Show, Eq, Ord, Enum, Bounded, Ix) type Neighborhood a = Array UnitDir (Tree a) data Tree a = Empty | Leaf a | Internal a (Neighborhood a) deriving (Eq, Show, Functor) -- Use TH to automatically define a base functor for Tree, -- enabling recursion-schemes makeBaseFunctor ''Tree The wanted mapping function is then: mapOverNeighborhoods :: (Neighborhood a -> Neighborhood a) -> Tree a -> Tree a mapOverNeighborhoods f = cata $ \case EmptyF -> Empty LeafF x -> Leaf x InternalF x nb -> Internal x (f nb) Roughly, cata does all the recursion for us. It provides to its function argument (\case ..., above) a value of type TreeF a (Tree a) which is essentially the same as a plain Tree a except that the very first "layer" uses different constructors, ending with an extra F. All such constructors have their inner trees already pre-processed by cata: above, we can assume that all the trees inside the nb array already had f applied recursively. What we need to do is to handle the first "layer", transforming the F constructors into the regular ones, and applying f to this first "layer" as well.
doc_5239
As we know each interval new thread is created to handle the OnTimedEvent. I am looking for way to force the system to wait creating a new thread if the previous thread is still running. My OnTimedEvent execute some method and I would like to wait until the method is finished Any idea how to do that? A: You are mistaken in the sense that no new thread will be created when the Elapsed event is fired. The event will be raised on the the .NET threadpool, so an arbitrary thread will process it. One way to do what you want is to Stop the timer at the start of your event handler and to Start it again once it is finished. Like this: var timer = new System.Timers.Timer(1000); timer.Elapsed += HandleTimerElapsed; timer.Start(); ... private void HandleTimerElapsed(object s, ElapsedEventArgs e) { var t = (System.Timers.Timer)s; t.Stop(); try { ... do some processing } finally { // make sure to enable timer again t.Start(); } } The other option is to set the AutoReset property of the timer to false. This way the timer will only be raised once. Then you can call Start when you want it to start again. So the above code would change to include a timer.AutoReset = false; at the beginning and then you don't need to call Stop inside the handler. This is a bit safer as the above method probably has a race condition in the sense that if the system is under load your handler might not be guaranteed to execute before the timer elapses again.
doc_5240
how can i achieve it using BIRT RPT. because if i use Apache POI the formating of text is missing. A: You can't do that with BIRT, because BIRT is not meant to be a template processor.
doc_5241
let user = ["Player", "Computer"]; let pScore = 0; let cScore = 0; let gameIsOver = false; // Some other functions in here... // End Game if (pScore === 10) { isGameOver = true; winner.textContent = `${user[0]} Wins the Game!`; return; } else if (cScore === 10) { isGameOver = true; winner.textContent = `${user[1]} Wins the Game!`; return; } else { isGameOver = false; } // Some other functions here... A: You need to check the conditions every time the score changes. To do that, put your if-statements in a separate function and call it from the function which is triggered when someone scores. I create small functions because, in my opinion, it's the best practice, but not necessary for such a small operation. let pScore = 0; let cScore = 0; let user = ["Player", "Computer"]; let isGameOver = (score) => { if (pScore === 10 || cScore === 10) { return true; } return false; } function gameOver() { let winner = pScore === 10 ? user[0] : user[1]; console.log(winner); } function theFunctionThatChangesTheScores() { // after the code that changes the score if ( isGameOver() ) { // you can code in this block, but ideally. // create another function and call it: return gameOver(); } return console.log("game is still on"); } theFunctionThatChangesTheScores();
doc_5242
The point of the project is to create a query of sorts, where the user searches for a report using a GUI interface and the app spits out all related data. Ex: report all where quality > 3 I use a StringTokenizer object to break the String down and evaluate each token. The first token MUST be report, the second token MUST be all, third token MUST be where, the fourth token MUST be either quality, basePrice or numInStock, the fifth token MUST be a relational operator(> < <= >= ==). We were instructed to throw custom checked exceptions if any of the tokens do not match what they should be. So far I have evaluated each token, and throw an Exception if the expected token is not what it should be. Now once I reach the relational operator, i'm supposed to dump it into a new String called optok. The problem is, I can't seem to get my program to do this and i'm having a hard time figuring out how to do so. I've tried many different things and nothing seems to work. The final goal is, once all the tokens have been evaluated and checked, to call a method to print the correct query and all data that goes along with said query. If one of the tokens doesn't match, an Exception is thrown. Here is my code for evaluating each token, to check that it is in the correct format: public void detectUserInput(String input) throws MissingInputException { if (input.equals("")) { System.out.println("Null input"); throw new MissingInputException(); } else { System.out.println("Input is not null"); } }//end detectUserInput public void countTokens(String input) throws IncorrectFormatException { StringTokenizer tokenLength = new StringTokenizer(input, " ,"); if (tokenLength.countTokens() < 6) { throw new IncorrectFormatException(); } }//end countTokens public void evaluateTokens(String input) throws IllegalStartOfQueryException, InvalidSelectorException, InvalidQualifierException, InvalidLValueException, InvalidOperatorException { StringTokenizer testTokens = new StringTokenizer(input, " ,"); if (!testTokens.nextToken().equalsIgnoreCase("report")) { throw new IllegalStartOfQueryException(); } else if (!testTokens.nextToken().equalsIgnoreCase("all")) { throw new InvalidSelectorException(); } else if (!testTokens.nextToken().equalsIgnoreCase("where")) { throw new InvalidQualifierException(); } else if (!testTokens.nextToken().matches("quality|numInStock|basePrice")) { throw new InvalidLValueException(); } else if (!testTokens.nextToken().matches(">|<|>=|<=|==")) { throw new InvalidOperatorException(); } //here is where I try to take the relational operator //and dump it into optok, after all the previous input //has been validated, but it doesnt work :( while (testTokens.hasMoreTokens()) { tok = testTokens.nextToken(); if (tok.matches("<|>|>=|<=|==")) { optok = tok; } } }//end evaluateTokens And here is the actionPerformed() of my program that reacts when the user types their query into the TextField and presses the GO! JButton : private class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent ev) { if (ev.getSource() == goBtn) { input = queryFld.getText(); try { detectUserInput(input); countTokens(input); evaluateTokens(input); } catch (MissingInputException mie) { errorFld.setText("Enter an expression"); queryFld.setText(""); System.err.println(mie); mie.printStackTrace(); } catch (IncorrectFormatException ife) { errorFld.setText("Too few terms"); queryFld.setText(""); System.err.println(ife); ife.printStackTrace(); } catch (IllegalStartOfQueryException isqe) { errorFld.setText("Word REPORT expected"); queryFld.setText(""); System.err.println(isqe); isqe.printStackTrace(); } catch (InvalidSelectorException ise) { errorFld.setText("Selector must be ALL"); queryFld.setText(""); System.err.println(ise); ise.printStackTrace(); } catch (InvalidQualifierException iqe) { errorFld.setText("Qualifier error - keyword WHERE missing"); queryFld.setText(""); System.err.println(iqe); iqe.printStackTrace(); } catch (InvalidLValueException ilve) { errorFld.setText("Invalid query. quality, numInStock, " + "or basePrice expected"); queryFld.setText(""); System.err.println(ilve); ilve.printStackTrace(); } catch (InvalidOperatorException ioe) { errorFld.setText("InvalidOperatorException. < <= > >= == expected"); queryFld.setText(""); System.err.println(ioe); ioe.printStackTrace(); } } }//end actionPerformed }//end ButtonHandler I apologize if this seems trivial, but i'm having a really hard time figuring it out for some reason. I appreciate any input or suggestions. If i'm missing any info needed please let me know and i'll add it asap. Also, here are the instructions for this segment: 11) Now, focus on the evaluateAll method. Get the next token. It should be any one of 3 words: “basePrice” or “quality” or “numInStock” . If it is not, place the message “Invalid query, quality, numInStock or basePrice expected. If is one of those 3 words, you expect a relational operator, so get the next token, but save it in a new String, call it optok. If it is not a correct operator, place the message “invalid query, You now have two Strings: token which is either “basePrice” or “quality” or “numInStock” and an optok which is one of the 5 relational operators listed above. Thanks in advance :) A: You didn't post a stacktrace, so I'm guessing you're not having an exception, and reading from your code I'm trying to understand what could be happening .. so I might be wrong. It seems to me that you are using a tokenizer. A tokenizer is like a stream, once you call nextToken() it returns the token, and unless you save it somewhere the next call to nextToken() will make the previous one not accessible. So, where you make : else if (!testTokens.nextToken().matches("quality|numInStock|basePrice")) { throw new InvalidLValueException(); } else if (!testTokens.nextToken().matches(">|<|>=|<=|==")) { throw new InvalidOperatorException(); } You are consuming the tokens. As a result, when you get to the while : while (testTokens.hasMoreTokens()) { All the tokens are consumed, so it will not iterate here. You should instead save your tokens in variables, so that you can both check and the use them : StringTokenizer testTokens = new StringTokenizer(input, " ,"); if (!testTokens.nextToken().equalsIgnoreCase("report")) { throw new IllegalStartOfQueryException(); } else if (!testTokens.nextToken().equalsIgnoreCase("all")) { throw new InvalidSelectorException(); } else if (!testTokens.nextToken().equalsIgnoreCase("where")) { throw new InvalidQualifierException(); } // TODO here i use local variables, since you need to use these outside this method, // maybe use class fields or whatever else String subject = testTokens.nextToken(); String opttok = testTokens.nextToken(); if (!subject.matches("quality|numInStock|basePrice")) { throw new InvalidLValueException(); } else if (!opttok.matches(">|<|>=|<=|==")) { throw new InvalidOperatorException(); } // done, now you have opttok and subject
doc_5243
this.HasMany(t => t.Users) .WithMany(t => t.Roles) .Map(m => { m.ToTable("UsersToRoles"); m.MapLeftKey("RoleId"); m.MapRightKey("UserId"); }); However, whereas I do want the User (class) to have a collection of Roles, I don't want the Role (class) to have a collection of users as, typically, there might be very many Users in each role - and I don't want the risk that accessing a Role instance might cause all those Users to be loaded. So two questions: * *Am I right to be concerned? (I have memories problems back in the early days of .edmx where spurious bi-directional relationships caused huge performance issues until removed)? *If so, how can I specify the many-to-many relationship if there isn't a collection on both classes? Thanks A: Am I right to be concerned? (I have memories problems back in the early days of .edmx where spurious bi-directional relationships caused huge performance issues until removed)? The risk might be there if you allow lazy loading. You could remove the virtual modifier from the Role.Users collection to be sure that this collection can never be loaded lazily, only on explicit request using Include(r => r.Users) for example. The "spurious bi-directional relationships" you mean with EF 4.0 were probably with POCOs that contained autogenerated relationship fixup code which indeed sometimes caused unwished side effects (but also mainly due to lazy loading). If so, how can I specify the many-to-many relationship if there isn't a collection on both classes? You must configure the many-to-many relationship from the User side and then use WithMany() without lambda parameter: this.HasMany(t => t.Roles) .WithMany() .Map(m => { m.ToTable("UsersToRoles"); m.MapLeftKey("UserId"); m.MapRightKey("RoleId"); }); this is an EntityTypeConfiguration<User> in this case. Also note the reversal of "Left" and "Right" in the mapping.
doc_5244
function shot() { document.getElementById('power').play(); for (var i=140; i<400; i++) { document.getElementById('shot').style.visibility='visible'; imgShot.style.left = parseInt(imgObj.style.left) - 130 + 'px'; imgShot.style.top = parseInt(imgObj.style.top) - i + 'px'; setInterval('',500); } } A: The only way to block sequential execution in JavaScript is to create a busy loop (or use a blocking function like alert): but you do not want to do this as it will freeze the user interface - including updating the UI display of the elements movement! Instead, structure the code such that it uses asynchronous callbacks - this model allows the browser event loop to continue uninterrupted so that it can react to user input and update the display from the DOM changes. document.getElementById('power').play(); document.getElementById('shot').style.visibility='visible'; var i = 140; function moveIt() { imgShot.style.left = parseInt(imgObj.style.left) - 130 + 'px'; imgShot.style.top = parseInt(imgObj.style.top) - i + 'px'; i++; if (i < 400) { // If have more, schedule again in .5s // Remember that setTimeout *returns immediately* because it // is an asynchronous operation. setTimeout(moveIt, 500); } else { // This will be executed when animation finishes. } } moveIt(); // This will be executed after first movement which is well before // the animation finishes. We could also use setTimeout(moveIt, ..) here, // depending on what is desired. Or, better, use something like jQuery.animate which takes care of much of the repetitive stuff. (You may have to write a custom easing for this case, because the movement is accelerating linearly from a non-0 initial value along the y-axis.) setInterval can also be used (just cancel it when done, instead of starting a new timeout), but I find the setTimeout approach slightly easier to show conceptually. The difference is that setInterval will try to always run at time=iteration*timeout, which can - in degenerate cases - be noticeably more consistent than multiple setTimeout calls or, as pointed out Alnitak, it can stack/cascade harmfully. A: If you want to run the "shot" function every 500ms, function shot() { document.getElementById('power').play(); for (var i=140; i<400; i++) { document.getElementById('shot').style.visibility='visible'; imgShot.style.left = parseInt(imgObj.style.left) - 130 + 'px'; imgShot.style.top = parseInt(imgObj.style.top) - i + 'px'; } } setInterval(shot,500); Otherwise if you want to delay each iteration of the for loop, take look at this question that's almost a duplicate: How to pause a FOR loop in Javascript in a function?
doc_5245
I've 2 tables Entry and Category connected by a many-to-many relationship via an EntryCategory table. I set isCrossRef on true in schema.xml. Everything works fine : I'm able to filter entry by category like this : EntryQuery::create()->filterByCategory($cat) BUT I'm not able to filter entries with no category. I tried EntryQuery::create()->filterByCategory(null, Criteria::EQUAL) or EntryQuery::create()->filterByCategory(null, Criteria::ISNULL) but, it gives me 'filterByCategory() only accepts arguments of type \Category or Collection' I also tried EntryQuery::create()->where('Category IS NULL') but, i've got this error Unknown column 'Category' in 'where clause' So, I need some help ... EDIT : Extract of my schema.xml : <?xml version="1.0" encoding="utf-8"?> <database package="core" name="bank" identifierQuoting="true" defaultIdMethod="native" defaultPhpNamingMethod="underscore"> <table name="category" idMethod="native" phpName="Category"> <column name="id" phpName="Id" type="INTEGER" size="5" primaryKey="true" autoIncrement="true" required="true"/> <column name="name" phpName="Name" type="VARCHAR" size="50" required="true"/> <column name="parent_id" phpName="ParentId" type="INTEGER" size="5"/> <foreign-key foreignTable="category" phpName="Parent"> <reference local="parent_id" foreign="id"/> </foreign-key> <index name="parent_id"> <index-column name="parent_id" size="5"/> </index> <vendor type="mysql"> <parameter name="Engine" value="InnoDB"/> </vendor> </table> <table name="entry" idMethod="native" phpName="Entry"> <column name="id" phpName="Id" type="INTEGER" primaryKey="true" autoIncrement="true" required="true"/> <column name="account_id" phpName="AccountId" type="INTEGER" required="true"/> <column name="date" phpName="Date" type="DATE" required="true"/> <column name="entry" phpName="Entry" type="VARCHAR" size="255" required="true"/> <column name="type" phpName="Type" type="INTEGER" size="2"/> <column name="amount" phpName="Amount" type="DECIMAL" size="12" scale="2" required="true"/> <index name="account"> <index-column name="account_id"/> </index> <index name="md5"> <index-column name="md5" size="32"/> </index> <index name="md5_2"> <index-column name="md5" size="32"/> <index-column name="account_id"/> </index> <foreign-key foreignTable="account"> <reference local="account_id" foreign="id"/> </foreign-key> <vendor type="mysql"> <parameter name="Engine" value="InnoDB"/> </vendor> </table> <table name="entry_category" idMethod="native" phpName="EntryCategory" isCrossRef="true"> <column name="entry_id" phpName="EntryId" type="INTEGER" primaryKey="true" required="true"/> <column name="category_id" phpName="CategoryId" type="INTEGER" size="5" primaryKey="true" required="true"/> <foreign-key foreignTable="entry" name="entry_category_ibfk_1"> <reference local="entry_id" foreign="id"/> </foreign-key> <foreign-key foreignTable="category" name="entry_category_ibfk_2"> <reference local="category_id" foreign="id"/> </foreign-key> <index name="category_id"> <index-column name="category_id" size="5"/> </index> <vendor type="mysql"> <parameter name="Engine" value="InnoDB"/> </vendor> </table> </database> A: You need to use the Id or Name or whatever the column name is. ->filterByCategory expects a propel object of the category type. ->filterByCategoryId() or whatever the name for the actual column is. (having your schema would be beneficial) Not passing anything sets it up to look for null. Anything else is handled as a string literal. where column = 'null' Use either ->filterByCategory() (if that is the name of your column and NOT a foreign key reference) or ->filterByCategoryId() if 'CategoryId' is the 'phpName' of the column. A: Ok i found 2 solutions (yes, 5 years after ;) ) EntryQuery::create()->leftJoinCategory->where('Category.CategoryId IS NULL') Or EntryQuery::create()->useCategoryQuery(null, Criteria::LEFT_JOIN)->filterByCategoryId(null, Criteria::ISNOTNULL)->endUse();
doc_5246
But when I have several icons displayed as background images of different sizes, and I want to display all icons, say, 70% their original sizes, I can't just set a background-size: 70% because that would mean 70% of the square, whereas what I want is 70% of the background image own size. Any way to achieve that in CSS ? A: Transform the block instead of background image. transform: scale(.7); A: If I understand correctly what you are asking for (70% of the background image itself) then I don't think that's possible with CSS. You could achieve it with JS though. Get the dimensions of the image, calculate what is 70% of those (width * 0.7 and height) and use that to set this as the dimensions of the background-size:40px 40px;
doc_5247
At the moment I have about 5 servers (some dedicated, some EC2's). I need to transfer files between them. I have one server running an SFTP server which I use as a 'middle-man' but this means I'm double-handling data (upload to SFTP, then download from other server). How do others manage this sort of thing? Should I run an SFTP server on each server? Or is there a simpler SSH-based method? A: Instead of an SFTP server as your 'middle-man', use Amazon S3. Create pick up/drop locations on Amazon S3 that your servers can push and pull from. It's cheap, extremely reliable and scalable. File transfers can be scripted via command line or done via GUI (just like FTP).
doc_5248
However, i want this to rerun every time there is a change to the document folder. So i am using Jenkins with Folder Watcher trigger (FSTrigger) which calls the POST to re-index like this :- /opt/solr/bin/solr delete -c resumes sudo -u solr /opt/solr/bin/solr create -c resumes -d /opt/solr/example/files/conf /opt/solr/bin/post -c resumes /home/chak/Documents Is there a folder watcher in Solr itself, so i can avoid using Jenkins ? A: No, Solr does not have any watch capabilities - seeing as it's also meant to be running as a cluster on multiple server, I'm pretty sure that's functionality that would be considered to be external to Solr (possibly integrated into the post tool if any). That being said, you don't have to use something as complex as Jenkins to implement that. Using inotifywait you could implement the same functionality with a couple of lines of bash.
doc_5249
What I'm expecting is something like this: and this is the code, import plotly.graph_objects as go layout = dict( paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)' ) header = ['LVL', 'Base ATK', 'ATK'] cells = [['1', '46', '10.8%'], ['10', '86', '14.7%'], ['20', '153', '19.1%'], ['30', '194', '23.4%'], ['40', '266', '27.8%'], ['50', '340', '32.2%'], ['60', '414', '36.5%'], ['70', '488', '40.9%'], ['80', '563', '45.3%'], ['90', '608', '49.6%']] def format_list(items): level = [] baseatk = [] value = [] for item in items: level.append(item[0]) baseatk.append(item[1]) value.append(item[2]) return [level, baseatk, value] fig = go.Figure(layout=layout, data=[go.Table( header=dict( values=header, line_color='black', fill_color='rgba(0,0,0,0)', align='center' ), cells=dict( values=format_list(cells), line_color='black', fill_color='rgba(0,0,0,0)', align='center', height=30), ) ]) fig.update_layout( width=250, font=dict(color='black', size=12), margin={"l": 1, "r": 1, "t": 1, "b": 1} ) As you can see, I already set the bottom margin to 0, and did not set the height size. Is there a way for it to automatically set the height depending on the table size, or without having to set the height value?
doc_5250
Basically, I have an app in the AppStore which is a soundboard. It works great and we've shifted a few copies. My client now wants to include random sounds when the character's face is clicked on TouchDown. I've got that working fine, using an array. However, he now wants the button to return, let's say, 10 sounds BEFORE playing random sounds from another batch of 10. So, in theory, you'd have to hit the button at least 10 times to hear the other sounds. I was trying to think of a way of counting the number of clicks, to then use a different array of sounds. Is that even possible? Any help would be greatly appreciated! A: How about using a variable to track number of button taps?
doc_5251
this.store .select(s => s.products && s.products.name) .filter(name => !!name) .subscribe(name => { // Now if there is a `name` in the store, it will run immediately // However, I want to get the `name`, only if a new value comes after subscribing console.log(name); }); I tried to add .publish() before .subscribe, but then I cannot get any value. How can I get name, only if a new value comes after subscribing? Thanks A: When you subscribe, the current state of the store will be returned. If you don't want the current state, then you can skip the first response. this.store.select(...).skip(1) A: You need to understand the following for this: * *Hot vs. cold observables *Back pressure (in your case a tolerance of 0)
doc_5252
(...).catch(e) => { if(e.response.status === 401) { console.log("Wrong username or password") } else { console.log(e.statustext) }} And I have error like this: Unhandled Exception (TypeError): cannot read property status of undefined How can I fix it? A: catch block is passed an Error object and it doesn't contains any property named response. Inside the then() block, check if status code is 401, if it is, throw an Error with the message "Wrong username or password" and inside the catch block, log the message using Error.prototype.message .then(response => { if (response.status === 401) { throw new Error("Wrong username or password"); } .... }) .catch(e) => console.log(e.message));
doc_5253
writeIntoVector( vector<char>& aVector, int nr_of_bytes ); I am reading data in chunks from the socket and want to place the content read from the socket directly into a vector. Such that the first writeIntoVector writes the data into the vector from position 0, the next call to writeIntoVector writes the data from the socket into the vector at position nr_of_bytes/2 (in the case of a char) and so on. I suspect this can be done using pointers but I am not sure how to do it. A: Assuming writeIntoVector() is your own function, you could try something like this, using indices: size_t writeIntoVector(const size_t startPos, std::vector<char> & out) { // write from startPos to at most out.size() - 1 // return number of written elements } An iterator-based approach could look like this: typedef std::vector<int>::iterator Iter; Iter writeIntoRange(Iter begin, Iter end) { // write from begin to at most end - 1 // return last iterator, that was actually modified }
doc_5254
I have cloned a github project into IntelliJ that uses gradle. I import and first thing it says is that gradle is not set up right, so I set it up according to the following: gradle prefrences Java version 14.0.1. Then it said the SDK was still not set up so I again set that up for again version even though I am not using Android. I can successfully run a few of the grade tests but all of my java code no longer links methods and when I run the tests (directly from github without any changes yet) I get an error: cannot find symbol @javax.annotation.Generated( Also all of the methods in my example seem to no longer link. I have a screenshot of this too. Any guidance is appreciated, probably a problem in the set up? I found this symbol error a few times but no resolution that helped. I tried invalidating caches and restarting a few times. I deleted the .idea files a few times. tried a different repository in git and still having the same errors. Thanks! A: Simply add the javax annotation dependency into your build.gradle. dependencies { //... implementation 'javax.annotation:javax.annotation-api:1.3.2' //... } like so.
doc_5255
There are 2 similar posts on this, they say that you would need to use independent keys for every element. I tried to do that, I even created a different variable and increment it after every use. It just deletes the top element of the list. How it works - 1) I have an array which is stored with some names channels, and I get data with that names and save that data into another array renderAll. 2) After that I filter those on how I want to render them, and then I render them with a function renderCards(). It also renders a button which if clicked, should delete the channel from the channel array and the respective data from the renderAll array 3) It also have a input field from which you can add more channels. What doesn't work - The delete button deletes the top element instead of the element which is clicked. I have the app running without the delete functionality var App = React.createClass({ getInitialState() { return { status: 2 } }, changeStatus(i) { this.setState({ status: i }); }, render() { return ( <div> <header><h1>Twitch Streamers</h1></header> <Tabs status = {this.changeStatus} /> <Cards status = {this.state.status} /> </div> ); } }); const Cards = React.createClass({ getInitialState() { return { renderAll: [], check: this.props.status, channels: ["freecodecamp", "storbeck", "habathcx","meteos","RobotCaleb","noobs2ninjas","brunofin","comster404","cretetion","sheevergaming","TR7K","OgamingSC2","ESL_SC2"] }; }, //AJAX REQUEST FUNCTION getData(last) { if(last === undefined) { for(let i =0; i<this.state.channels.length;i++) { let channel = this.state.channels[i]; $.getJSON("https://api.twitch.tv/kraken/streams/" + channel, (data) => { $.getJSON("https://api.twitch.tv/kraken/channels/" + channel, (logo) => { if(data.hasOwnProperty(status) === false) { if(data.stream === null) { this.setState({ renderAll: this.state.renderAll.concat([{channel: channel, url: `https://www.twitch.tv/${channel}`, status: 'offline', logo: logo.logo}]) }); } else { this.setState({ renderAll: this.state.renderAll.concat([{channel: data.stream.channel.name, url: `https://www.twitch.tv/${channel}`, current: data.stream.channel.game + ' - ' + data.stream.channel.status, status: 'online', logo: logo.logo}]) }); } } }); }) .fail((jqxhr) => { this.setState({ renderAll: this.state.renderAll.concat([{channel: channel, status: 'closed'}]) }); }); } } else { let channel = this.state.channels[this.state.channels.length - 1]; $.getJSON("https://api.twitch.tv/kraken/streams/" + channel, (data) => { $.getJSON("https://api.twitch.tv/kraken/channels/" + channel, (logo) => { if(data.hasOwnProperty(status) === false) { if(data.stream === null) { this.setState({ renderAll: this.state.renderAll.concat([{channel: channel, url: `https://www.twitch.tv/${channel}`, status: 'offline', logo: logo.logo}]) }); } else { this.setState({ renderAll: this.state.renderAll.concat([{channel: data.stream.channel.name, url: `https://www.twitch.tv/${channel}`, current: data.stream.channel.game + ' - ' + data.stream.channel.status, status: 'online', logo: logo.logo}]) }); } } }); }) .fail((jqxhr) => { this.setState({ renderAll: this.state.renderAll.concat([{channel: channel, status: 'closed'}]) }); }); } }, componentWillMount() { this.getData(); }, componentWillReceiveProps(prop) { this.setState({ check: prop }); }, //DELETE FUNCTION THAT DOESN'T WORK delete(index) { let newArr = this.state.channels.slice(); let newArrSecond = this.state.renderAll.slice(); newArr.splice(index, 1); newArrSecond.splice(index, 1); this.setState({ channels: newArr, renderAll: newArrSecond }); }, //RENDER CARDS FUNCTION renderCards(i) { if(i === 0 || i.status === 0) { let cards = this.state.renderAll.map((item, i) => { if(item.status === 'online') { return <div className="online cards" key={i}><img src={item.logo} width="30px" height="30px" /><a target="_blank" href={item.url}><h3>{item.channel}</h3></a><button className="cross" onClick={this.delete}>✕</button><p>{item.current}</p></div> } }); return ( cards ) } else if(i === 1 || i.status === 1) { let cards = this.state.renderAll.map((item, i) => { if(item.status === 'offline') { return <div className="offline cards" key={i}><img src={item.logo} width="30px" height="30px"/><a target="_blank" href={item.url}><h3>{item.channel}</h3></a><button className="cross" onClick={this.delete}>✕</button><p>Channel is offline</p></div> } }); return ( cards ) } else if(i === 2 || i.status === 2) { let cards = this.state.renderAll.map((item, i) => { if(item.status === 'offline') { return <div className="offline cards" key={i}><img src={item.logo} width="30px" height="30px" /><a target="_blank" href={item.url}><h3>{item.channel}</h3></a><button className="cross" onClick={this.delete}>✕</button><p>Channel is offline</p></div> } else if(item.status === 'online') { return <div className="online cards" key={i}><img src={item.logo} width="30px" height="30px" /><a target="_blank" href={item.url}><h3>{item.channel}</h3></a><button className="cross" onClick={this.delete}>✕</button><p>{item.current}</p></div> } else { return <div className="closed cards" key={i}><h3>{item.channel}</h3><p>Account Closed</p></div> } }); return ( cards ) } }, newChannel(i) { if(i.keyCode === 13) { this.setState({channels: this.state.channels.concat([i.target.value])}, function() { this.getData(1); }); } }, leave(i) { i.target.value = ''; }, render() { return ( <div id="cards-inside"> <input type='text' placeholder="+ Channel" onKeyDown={this.newChannel} onBlur={this.leave}/> <ReactCSSTransitionGroup transitionName="example" transitionEnterTimeout={500} transitionLeaveTimeout={300}> {this.renderCards(this.state.check)} </ReactCSSTransitionGroup> </div> ) } }); ReactDOM.render(<App />, document.getElementById("container-second")); A: Your index is always 0, because you do not pass it when you call delete. Therefore it always deletes top element. Inside the JSX bit where you render your X, you should do: onClick={this.delete.bind(this, i)} Or try OnClick={() => {this.delete(i)} } to pass the index of the card clicked. A: In React, you don't really want to "delete" nodes like you'd do with jQuery. Let's say you have a list of names in your initial state: class MyComponent extends React.Component { state = { names: ['Foo', 'Bar', 'Git', 'Get'] }; [...] } In your render() method, you are rendering them inside a ul: render() { const names = this.state.names.map(name => { return <li key={name} onClick={this.remove.bind(this, name)}>{name}</li>; }); return <ul>{names}</ul>; } In your remove() method you will have: remove(name) { this.setState({ names: this.state.names.filter(cur => cur !== name) }); } Now, every time you click on a name to remove it, you are removing the name from the names list, the component renders itself again, and the removed name will be removed from the DOM. Working example: http://codepen.io/FezVrasta/pen/MeWpzm?editors=0010
doc_5256
I know that the Jeditable has a callback function for the SUBMIT button, so I would like to know if there is a way to have a callback for the CANCEL button? I haven't found on the plugin docs. Thanks for reply, Carlos PD. This is the source I see for COMPLETE from AJAX callback: $("#editable_text").editable(submitEdit, { indicator : "Saving...", tooltip : "Click to edit...", name : "Editable.FieldName", id : "elementid", type : "text", }); function submitEdit(value, settings) { var edits = new Object(); var origvalue = this.revert; var textbox = this; var result = value; edits[settings.name] = [value]; var returned = $.ajax({ url: "http://URLTOPOSTTO", type: "POST", data : edits, dataType : "json", complete : function (xhr, textStatus) { var response = $.secureEvalJSON(xhr.responseText); if (response.Message != "") { alert(Message); } } }); return(result); } A: Yes, there is a "onreset" parameter that is called when clicking cancel, or more generally, before jEditable resets the control back to the state before it was clicked. Add this to your code: $("#editable_text").editable(submitEdit, { //... onreset: jeditableReset, //... }); function jeditableReset(settings, original) { // whatever you need to do here } This is documented in the header of the jquery.jeditable.js file. Another note - if you don't submit on blur (you don't appear to be in the sample), the onreset event will fire then too.
doc_5257
#include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <limits.h> #include <pthread.h> #define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) #ifndef MAP_FILE /* 44BSD defines this & requires it to mmap files */ #define MAP_FILE 0 /* to compile under systems other than 44BSD */ #endif #define SIZE 20 #define N 3 struct stat statbuf; struct pixel { char R; char G; char B; }; char * src; int size; struct pixel *get_pixel(char *buf, int *pos) { struct pixel pix; struct pixel *ppix = &pix; ppix->R = buf[*pos]; ppix->G = buf[(*pos)+1]; ppix->B = buf[(*pos)+2]; (*pos) += 3; return ppix; } void write_pixel(struct pixel *ppix, char *buf, int *pos) { buf[*pos] = ppix->G; buf[(*pos)+1] = ppix->B; buf[(*pos)+2] = ppix->R; (*pos) += 3; } void * do_rotation(void *rotation) { int fdout; char *dst; char fich[SIZE]; int counter,index, pos, x, y; int xmax = 0; int ymax = 0; int colormax = 0; /* Construção do nome do ficheiro de saída */ sprintf(fich, "rot%d.ppm", *((int*)rotation)); /* Zona #2 */ if ( (fdout = open(fich, O_RDWR | O_CREAT | O_TRUNC,FILE_MODE)) < 0) { fprintf(stderr,"can't creat %s for writing\n", fich); exit(1); } /* set size of output file */ if (lseek(fdout, size - 1, SEEK_SET) == -1) { fprintf(stderr,"lseek error\n"); exit(1); } if (write(fdout, "", 1) != 1) { fprintf(stderr,"write error\n"); exit(1); } if ( (dst = mmap(0, size, PROT_READ | PROT_WRITE,MAP_SHARED,fdout, 0)) == (caddr_t) -1) { fprintf(stderr,"mmap error for output\n"); exit(1); } /* Fim da Zona #2 */ sscanf(src,"P6\n%d %d\n%d\n",&xmax,&ymax,&colormax); struct pixel imagem [ymax][xmax]; for (counter=0, index=0; counter<3;index++) { if (src[index]=='\n') ++counter; } pos=index-1; for (y=0;y<ymax;y++) for (x=0;x<xmax;x++) imagem[y][x] = *(get_pixel(src,&pos)); pos=index; switch (*((int*)rotation)) { case 0 : //Rotação 90º clockwise sprintf(dst,"P6\n%d %d\n%d\n",ymax,xmax,colormax); for (x=0; x<xmax; x++) for (y=ymax-1; y> -1;y--) write_pixel(&(imagem[y][x]),dst,&pos); break; case 1: //Rotação 180º sprintf(dst,"P6\n%d %d\n%d\n",xmax,ymax,colormax); for (y=ymax-1;y>-1;y--) for (x = xmax-1; x>-1; x--) write_pixel(&(imagem[y][x]),dst,&pos); break; case 2: //Rotação 270º clockwise sprintf(dst,"P6\n%d %d\n%d\n",ymax,xmax,colormax); for (x=xmax-1; x>-1; x--) for (y=0; y<ymax;y++) write_pixel(&(imagem[y][x]),dst,&pos); break; } /* Zona #3 */ munmap(dst,size); close(fdout); /* Fim da Zona #3 */ pthread_exit(NULL); } int get_stat(int fdin) { struct stat pstatbuf; if (fstat(fdin, &pstatbuf) < 0) /* need size of input file */ { fprintf(stderr,"fstat error\n"); exit(1); } return pstatbuf.st_size; } int main(int argc, char *argv[]) { int id[N]; int fdin, i; if (argc != 2) { fprintf(stderr,"usage: trab11 <fromfile>\n"); exit(1); } if ( (fdin = open(argv[1], O_RDONLY)) < 0) { fprintf(stderr,"can't open %s for reading\n", argv[2]); exit(1); } size = get_stat(fdin); /* Zona # 1*/ if ( (src = mmap(0, size, PROT_READ, MAP_FILE | MAP_SHARED, fdin, 0)) == (caddr_t) -1) { fprintf(stderr,"mmap error for input\n"); exit(1); } /* Fim da Zona #1 */ /* Zona #5 */ pthread_t tid[N]; for (i=0; i<N; i++){ id[i]=i; pthread_create (&tid[i], NULL, do_rotation, &id[i]); } for (i=0; i<N; i++) pthread_join (tid[i], NULL); /* Fim da Zona #5 */ /* Zona #4 */ munmap(src,size); close(fdin); /* Fim da Zona #4 */ exit(0); } Every time I run this on Mac it gives me Bus error: 10, but if I run it on Linux it doesn't give me any error can someone give me a solution. PS: The error is on get_pixel function but I still can't figure it out. A: In get_pixel you are returning a pointer to an automatic variable that will not exist when you exit the function here: return ppix; This declares an automatic variable: struct pixel pix; whose lifetime ends at the end of the function and therefore referring to that memory after you return from get_pixel is undefined behavior. You can dynamically allocate using malloc: struct pixel *ppix = malloc( sizeof( struct pixel ) ) ; but you must remember to call free on the memory when you are done with it.
doc_5258
Task runner - Grunt When I run the project in local my local page will load with URL http://localhost:9000/#!/ I was expecting http://localhost:9000/#/ When clicked on About link browser is routed to http://localhost:9000/#!/%23%2Fabout Expectation: http://localhost:9000/#/about When I click home link browser is routed to http://localhost:9000/#!/%23%2F Expectation: http://localhost:9000/#/ What might be the issue? I have no such issues in my other system where I'm using AngularJS 1.5.8. A: I got resolved with following code.You can write in your app.js file $locationProvider.hashPrefix('');
doc_5259
My database uses utf_general_ui for text fields, but I want to strip out stuff that isn't used in names (like most special characters). Examples: はやお みやざき Michael O'Doul, Jr. Eiður Smári Guðjohnsen A: This is my solution for checking, but I don't know how to remove wrong characters: <?php function valid($value) { return (strlen(preg_replace('/\p{L}|[., \' ]/u',"",$value)) == 0); } function showBoolean($bool) { if($bool) { echo "true"; } else { echo "false"; } } showBoolean(valid("やお みやざき")); showBoolean(valid("Michael O'Doul, Jr.")); showBoolean(valid("Eiður Smári Guðjohnsen")); showBoolean(valid("やお みやざき ?$")); showBoolean(valid("Michael O'Doul, Jr. %$")); showBoolean(valid("Eiður Smári Guðjohnsen \"")); ?> Result: true true true false false false
doc_5260
From the client, I want to access the response and the image what so ever, but this doesn't seem to work, as the response only shows the image binary encoded. Any solutions to this? Or how would you access an image that is user:password protected on the server (so a basic auth header is required for that)
doc_5261
How can I update the xlink attribute with my link? component.js if(this.state.image) { const backgrounds = svg.find('#bg') $(backgrounds).attr('xlink:href', https://local.devel:5601/media/material/uni-348-01_material.jpg); } svg <defs> <pattern id="img1" patternUnits="userSpaceOnUse" width="100%" height="100%"> <image id="bg" xlink:href="" x="0" y="0" width="100%" height="100%" /> </pattern> </defs>
doc_5262
I tried to see via the Pythagorean theorem to exclude excess cords but I don't know how to put it in my python script
doc_5263
var main = function(){ function proceed(mapType){ switch(mapType) { case "showevent" : action = "events/index"; @page = events_path ; break; //index events case "addplace" : action = "places/new"; @page = new_place_path; break; case "addevent" : action ="events/new"); @page = places_path; break; //index places = new event } $('form').on('submit', function(event){ event.preventDefault(); $.ajax('$action', { //action as variable type: 'GET', data: $('form').serialize(), dataType: 'json', success: function(result){ redirect: @page } }); }); } $(document).ready(main); ` A: Firstly, rename your .js file to .js.erb to enable ruby expression evaluations. (For more details look at this Rails Guides page.) Then, what you need looks roughly like this (not tested, but you can get the idea): <% url = MyRailsApp::Application.routes.url_helpers %> switch(mapType) { case "showevent" : action = "events/index"; page = "<%= url.events_path %>"; break; //index events case "addplace" : action = "places/new"; page = "<%= url.new_place_path%>"; break; case "addevent" : action ="events/new"; page = "<%= url.places_path %>"; break; //index places = new event } // ... use the 'action' and 'page' variables as you need here. Good luck. EDIT: Added url variable. Still you can use js-routes A: ok so I here's my updated code js-rails is not working, so I turned for this post on SO Link_to for static pages - and in fact this was Zajo's tip so here's my full code ` var main = function(){ function proceed(mapType){ var action,page; switch(mapType) { case "showevent" : action = "events/index"; page = "<%= url.events_path %>" ; break; //index events case "addplace" : action = "places/new"; page = "<%= url.new_place_path %>"; break; case "addevent" : action = "events/new"; page = "<%= url.places_path %>"; break; //index places = new event(to je v podstate len form) // var event_path = "<%#= CGI.unescape url.event_path('{event_id}') %>"; } $('form').on('submit', function(event){ event.preventDefault(); $.ajax({ type: 'GET', url: action, data: $('form').serialize(), dataType: 'json', success: function(result){ redirect: page // alebo solve in controller } }); }); } } $(document).ready(main); ` but another problem that rose in the meantime is linking static pages Link_to for static pages and this also (the high_voltage gem did not generate pages folder in view) adn also the 2nd answer won't work
doc_5264
react js file: ( this function is called when the user enters some text and clicks on a button ) handleSubmit = () => { console.log("its running"); let databody = { message: this.state.val, }; console.log(" the message is :" + this.state.val); return fetch("http://localhost:5000/stored", { method: "POST", body: databody, headers: { "Content-Type": "application/json", }, }) .then((res) => res.json()) .then((data) => console.log(data)); }; index.js - nodejs file: (Here is where I'm getting my error which says "TypeError: connectDB.collection is not a function") const express = require("express"); const cors = require("cors"); // Importing cors var request = require("request"); const dotenv = require("dotenv"); const port = 5000; var util = require("util"); const connectDB = require("./config/db"); require("dotenv").config({ path: "./config/config.env" }); const app = express(); dotenv.config(); const db = connectDB(); app.get("/", (req, res) => { res.send("Hey there!"); }); app.get("/Pinged", function (req, res) { res.send("Pinged!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); }); app.use(cors({ origin: "*" })); app.post("/stored", (req, res) => { console.log("its running 2: " + req.body); db.collection().insertOne(req.body, (err, data) => { if (err) return console.log(err); res.send("saved to db: " + data); }); }); app.listen(port, () => console.log(`Example app listening on port ${port}!`)); db.js file inside config folder: const mongoose = require("mongoose"); const connectDB = async () => { try { const conn = await mongoose.connect(process.env.MONGO_URI, { useUnifiedTopology: true, useNewUrlParser: true, }); console.log(`MongoDB Connected : ${conn.connection.host}`); return conn; } catch (err) { console.error(err.message); process.exit(1); } }; module.exports = connectDB; A: Here, in db.js you should return conn.connection const connectDB = async () => { try { const conn = await mongoose.connect(process.env.MONGO_URI, { useUnifiedTopology: true, useNewUrlParser: true, }) console.log(`MongoDB Connected : ${conn.connection.host}`) return conn.connection } catch (err) { console.error(err.message) process.exit(1) } }
doc_5265
In this book, there are examples. So, I'm trying to replicate this example in R. However, I have got an error message in this example. To be specific, this is the data of example. data y s 1 1 Reginald 2 0 Reginald 3 1 Reginald 4 1 Reginald 5 1 Reginald 6 1 Reginald 7 1 Reginald 8 0 Reginald 9 0 Tony 10 0 Tony 11 1 Tony 12 0 Tony 13 0 Tony 14 1 Tony 15 0 Tony y<-data$y s<-as.numeric(data$s) Ntotal=length(y) Nsubj=length(unique(s)) dataList=list(y=y, s=s, Ntotal=Ntotal, Nsubj=Nsubj) Also, this is my model. modelString=" model{ for(i in 1:Ntotal){ y[i] ~ dbern(theta[s[i]]) } for(s in 1:Nsubj){ theta[s] ~ dbeta(2,2) } } " writeLines(modelString, con="TEMPmodel.txt") library(rjags) library(runjags) jagsModel=jags.model(file="TEMPmodel.txt",data=dataList) In this case, I got an error message. Error in jags.model(file = "TEMPmodel.txt", data = dataList) : RUNTIME ERROR: Cannot insert node into theta[1...2]. Dimension mismatch I don't know what I have made mistake in this code. Please give me advice. Thanks in advance. A: As suggested by @nicola, the problem is that you're passing s as data to your model, but also using s as the counter iterating over 1:Nsubj. As JAGS indicates, this causes confusion about the dimension of theta... does it have length 15, or 2? The following works: model{ for(i in 1:Ntotal){ y[i] ~ dbern(theta[s[i]]) } for(j in 1:Nsubj){ theta[j] ~ dbeta(2,2) } }
doc_5266
<mx:FileSystemList id="fs" visible="false" /> private function onCreationComplete():void { fs.directory = File.applicationDirectory.resolvePath('../../assets'); if (fs.directory.exists) addEventListener(FileEvent.DIRECTORY_CHANGE, onDirectoryChange); } private function onDirectoryChange(e:FileEvent):void { trace("file was changed"); } This doesn't seem to fire when a file changes A: Use the FileMonitor class. http://www.mikechambers.com/blog/2009/03/11/monitoring-file-changes-in-adobe-air/ Code from the tutorial: import com.adobe.air.filesystem.FileMonitor; import flash.filesystem.File; import flash.events.Event; import com.adobe.air.filesystem.events.FileMonitorEvent; private var monitor:FileMonitor; private function onSelectButtonClick():void { var f:File = File.desktopDirectory; f.addEventListener(Event.SELECT, onFileSelect); f.browseForOpen("Select a File to Watch."); } private function onFileSelect(e:Event):void { var file:File = File(e.target); if(!monitor) { monitor = new FileMonitor(); monitor.addEventListener(FileMonitorEvent.CHANGE, onFileChange); monitor.addEventListener(FileMonitorEvent.MOVE, onFileMove); monitor.addEventListener(FileMonitorEvent.CREATE, onFileCreate); } monitor.file = file; monitor.watch(); } private function onFileChange(e:FileMonitorEvent):void { trace("file was changed"); } private function onFileMove(e:FileMonitorEvent):void { trace("file was moved"); } private function onFileCreate(e:FileMonitorEvent):void { trace("file was created"); }
doc_5267
doc_5268
var testCanvas = document.getElementById("canvas") function testFocus() { if (document.activeElement === testCanvas[0]) { console.log('canvas has focus'); } else { console.log('canvas not focused'); }}; window.setInterval(testFocus, 1000); JSFiddle replicating the problem A: You have two errors in your code 1st it's tabindex not tab-index 2nd it's if (document.activeElement === testCanvas) // not testCanvas[0] <canvas id="canvas" width="578" height="480" tabindex="1"> </canvas> var testCanvas = document.getElementById("canvas") var testSpan = document.getElementById("plswork") var context = canvas.getContext('2d'); var imageObj = new Image(); imageObj.onload = function() { context.drawImage(imageObj, 69, 50); }; imageObj.src = 'https://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'; function testFocus() { if (document.activeElement === testCanvas) { console.log('canvas has focus'); } else { console.log('canvas not focused'); } }; window.setInterval(testFocus, 1000); fiddle: https://jsfiddle.net/42x34k68/6/
doc_5269
I am developing some independent tool so i am working with class library. Now i want to save some information into same project which is class library. I tried with appsetting.json and App.config but it only works in web project. My project looks like below i tried below code var id = System.Configuration.ConfigurationManager.AppSettings["client_id"]; but it is not working. if i put that same file in web project it is reading successfully. In my case config/json file must be in class library and must read from itself A: In a .net core application you need to use Dependency Injection to inject IConfiguration into your class which will expose your appsettings json values: public class Foo { private IConfiguration _config { get; set; } public Foo(IConfiguration config) { this._config = config; } } Now you can read settings: public void DoBar() { var id = _config.GetSection("client_id").Value; } Just keep chaining .GetSection() to move down your hierarchy. A: I found a soultion to this problem. You can add Resource.resx from property window of class library. here are the screen shots. and then use code as below using AdobeSign.Properties; var id = Resources.client_id.ToString(); A: If you want to have config.json in your class library separately, I recommend that you define your configuration model and implement deserialization for the file. let's just assume your config.json content is like, { "MyValue1": "Hello", "MyValue2": "World" } you can define Configuration class like below, using Newtonsoft.Json; using System; using System.IO; namespace Example { public class Configuration { public string MyValue1 { get; set; } public string MyValue2 { get; set; } public static Configuration Load(string path) { if (File.Exists(path)) { var json = File.ReadAllText(path); return JsonConvert.DeserializeObject<Configuration>(json); } else { throw new Exception("Configuration file not found!"); } } } } then you can load your config object from the file and use it like below, var config = Configuration.Load(Path.Combine(Directory.GetCurrentDirectory(), "config.json")); Console.Write(config.MyValue1); Console.Write(config.MyValue2);
doc_5270
* *In PHP I used to place files in public_html folder. I did the same for nodejs and started my application using "forever start app.js". Routers worked as expected, but I can able to see my nodejs source codes in the browser e.g. http://example.com/app.js showed the source code of app.js. *In some tutorials, They placed the files in /var/www/html/ and started the application. What's the difference between public_html and /var/www/html? *I'm using shared hosting, so I don't have permissions to place the files in /var/www/html/. I deployed nodejs files in /home/%username% folder and visited http://example.com/app.js. This time source codes are not visible and router thrown 404 error page as expected. (Deleted files in public_html before deploying in /home/%username%) *The index page router didn't work as expected. Instead of '/' or '/index', router received '/index.html.var' for the index page (http://example.com/). Please guide me on deploying nodejs app securely on shared hosting. A: Er, no, Node.js is different, it's not PHP. A programme in Node.js is just like C/C++, Python, or any other general purpose programming language, it can control (likely) the whole server, so it's not to be deployed onto shared hosting. You will need a cheap VPS (virtual private server, cloud server) at least, very cheap nowadays, on a par with shared hosting. For starting, I suggest Heroku, free server: https://www.heroku.com Programming notes: Node.js is server-side language, it doesn't run in browser like traditional JS, you won't visit it by URL, unless you create a webserver using Express.js or that kind of library. Example using Express.js to server static files in public_html: * *Put your server.js (or app.js, or whatever you put) outside public_html, don't put your Node.js code there. *For example when you put your app.js right outside public_html, serve static files this way: app.use('/static', express.static('public_html')) *Access your files at URL paths starting with /static, or use the following middleware use to server static files at root URL path.: app.use('/', express.static('public_html')) Reference: http://expressjs.com/en/starter/static-files.html
doc_5271
I started by disabled any terraform job that would create AKS objects. Now I am to the poing where stuck with a bunch of Error messages: null_resource.storage_account_enc_keys["event_hub"]: Refreshing state... [id=7769823871044950433] null_resource.storage_account_enc_keys["network"]: Refreshing state... [id=4738858682472456831] null_resource.storage_account_enc_keys["ssrs"]: Refreshing state... [id=7895464809071918822] null_resource.storage_account_enc_keys["cdn"]: Refreshing state... [id=6960405350375997435] null_resource.storage_account_enc_keys["webjob"]: Refreshing state... [id=1824168849553984961] null_resource.storage_account_enc_keys["app"]: Refreshing state... [id=4341458091367408638] null_resource.storage_account_enc_keys["media_services"]: Refreshing state... [id=7860082878767368564] Error: Get "http://localhost/apis/rbac.authorization.k8s.io/v1/clusterroles/k8s-cluster-reader": dial tcp 127.0.0.1:80: connect: connection refused Error: Kubernetes cluster unreachable: invalid configuration: no configuration has been provided, try setting KUBERNETES_MASTER environment variable Error: Get "http://localhost/apis/rbac.authorization.k8s.io/v1/clusterroles/cluster-writers": dial tcp 127.0.0.1:80: connect: connection refused Error: Get "http://localhost/apis/rbac.authorization.k8s.io/v1/clusterrolebindings/cluster-admins-binding": dial tcp 127.0.0.1:80: connect: connection refused Error: Get "http://localhost/api/v1/namespaces/pod-identity/limitranges/pod-identity": dial tcp 127.0.0.1:80: connect: connection refused Error: Get "http://localhost/api/v1/namespaces/nginx-ingress/limitranges/nginx-ingress": dial tcp 127.0.0.1:80: connect: connection refused Error: Get "http://localhost/apis/rbac.authorization.k8s.io/v1/clusterrolebindings/k8s-cluster-writer-binding": dial tcp 127.0.0.1:80: connect: connection refused Error: Get "http://localhost/api/v1/namespaces/linkerd/limitranges/linkerd": dial tcp 127.0.0.1:80: connect: connection refused Terraform Plan Exit Code: 1 Any idea how i can get past this without having to rebuild the environment completely??? Note: Most reference found only regarding this error points to adding load_config_file = false to the kubernetes provider. This was already in there. Plus my goal is using the next apply to remove anything related to AKS. A: This is a common issue, when the kubernetes provider is configured based on attributes returned by the cluster resource. Certain changes to the cluster resource, cause the attributes the provider is configured with to be in known-after-apply state. In that case, the provider will not have a configuration and return that localhost connection error. The solution is, to first manually apply the changes to the cluster resource using terraform apply --target .... Then, after that you can run apply again, without the --target parameter.
doc_5272
/// <reference name="MicrosoftAjax.js"/> Type.registerNamespace("MyNamespace.Controls.FloatingErrorPane"); MyNamespace.Controls.FloatingErrorPane = function (element) { ... } MyNamespace.Controls.FloatingErrorPane.prototype = { ... } Does anyone know if it is possible to specify namespaces in typescript that include periods? We reference those same names in our C# classes like: [assembly: WebResource("MyNamespace.FloatingErrorPane.js", "text/javascript")] ScriptControlDescriptor descriptor = new ScriptControlDescriptor("MyNamspace.Controls.Floating ErrorPane", this.ClientID); A: You can use nested modules and classes to get a namespace style syntax. This first example matches the example in your question... module MyNamespace { export module Controls { export class FloatingErrorPane { constructor(private element: HTMLElement) { } } } } var errorPane = new MyNamespace.Controls.FloatingErrorPane(myElement); You can declare modules across multiple files if you want to, so a second file can add to MyNamespace by declaring it again... module MyNamespace { export module Messaging { export class MessageHandler { } } } A: Yes, you can use the . notation to create nested namespaces, e.g. module MyNamespace.Controls { export class FloatingErrorPane { constructor(element: HTMLElement) { } } } var errorPane = new MyNamespace.Controls.FloatingErrorPane(myElement); Or you can use the syntax as shown by Sohnee where you declare modules successively. You cannot define a class or function directly in this way, though. So this is not valid: MyNamespace.Controls.FloatingErrorPane = function() { ... }
doc_5273
Below is the profile schema: var ProfileSchema = new Schema({ name: { type: String, required: true }, roles: [{ application: { type: Schema.Types.ObjectId, required: true, ref: 'Application' }, role: { type: String, required: true, enum: [ 'admin', 'author', 'publisher' ] } }] }); Each profile has a role for an application, and when I send the request to the controller action 'update', it fails: profile update controller: // Updates an existing Profile in the DB export function update(req, res) { try { if (req.body._id) { delete req.body._id; } console.log('ENDPOINT HIT...'); console.log(`REQUEST PARAM ID: ${req.params.id}`); console.log('REQUEST BODY:'); console.log(req.body); console.log('ENTIRE REQUEST: '); return Profile.findByIdAsync(req.params.id) .then(handleEntityNotFound(res)) .then(saveUpdates(req.body)) .then(respondWithResult(res)) .catch(handleError(res)); } catch(ex) { console.error('FAILED TO UPDATE PROFILE'); return handleError(res); } } I made sure that the id and body was being sent properly, and I am hitting the end point. This is an example of the request body JSON: { _id: 57e58ad2781fd340563e29ff, __updated: Thu Oct 27 2016 15:41:12 GMT-0400 (EDT), __created: Fri Sep 23 2016 16:04:34 GMT-0400 (EDT), name: 'test', __v: 11, roles:[ { application: 57b70937c4b9fe460a235375, role: 'admin', _id: 58125858a36bd76d8111ba16 }, { application: 581b299f0145b48adf8f57bd, role: 'publisher', _id: 581b481898eefb19ed8a73ee } ] } When I try to find the Profile by Id, the promise chain goes straight to the catch(handleError(res)); part of the code and shows an empty object in my console. My handle error function: function handleError(res, statusCode) { console.error('HANDLE PROFILE ERROR: ', statusCode); statusCode = statusCode || 500; return function(err) { console.error('PROFILE ERROR:'); console.error(JSON.stringify(err, null, 2)); res.status(statusCode).send(err); }; } UPDATE I am realizing the code is breaking when it hits my saveUpdates function (Note: I am using lodash): function saveUpdates(updates) { /// the code is fine here /// return function(entity) { /// once it enters in here, is where it begins to break /// var updated = _.merge(entity, updates); if(updated.roles.length != updates.roles.length) { updated.roles = updates.roles; } for(var i in updates.roles) { updated.roles.set(i, updates.roles[i]); } return updated.saveAsync() .then(updated => { return updated; }); }; } A: Lesson learned: Read Documentation properly. Since I am using bluebird promises for this application, I forgot to use .spread() within my saveUpdates() callback function. Solution: function saveUpdates(updates) { return function(entity) { var updated = _.merge(entity, updates); if(updated.roles.length != updates.roles.length) { updated.roles = updates.roles; } for(var i in updates.roles) { updated.roles.set(i, updates.roles[i]); } return updated.saveAsync() // use `.spread()` and not `.then()` // .spread(updated => { return updated; }); }; } I want to thank the following SOA that led to this conclusion: https://stackoverflow.com/a/25799076/5994486 Also, here is the link to the bluebird documentation in case anyone was curious on .spread(): http://bluebirdjs.com/docs/api/spread.html
doc_5274
ServletContext sc = getServletContext(); for (Map.Entry<String,String> entry : mergedParams.entrySet()) { sc.setInitParameter(entry.getKey(), entry.getValue()); // <---this one } I've set all kinds of breakpoints and they don't indicate that there's a problem. I've even used stopped the program at that line and used reflection in the NetBeans expression evaluator to no avail - reflection works! java.lang.reflect.Method[] ms = sc.getClass().getMethods(); java.lang.reflect.Method sip = null; for (java.lang.reflect.Method m : ms) { if ("setInitParameter".equalsIgnoreCase(m.getName()) { sip = m; } } sip.invoke(sc, entry.getKey(), entry.getValue()); That returns true, the first time and false subsequent times, as is expected for the method when using the same key. I've checked the classpath and only see these up-to-date versions of libraries. There is a proprietary dependency that I have to include that relies on servlet-api, but I've added an exclusion to that in the dependencyManagement section of the pom so that it, too, should only be using 2.5 (or 3.1.0 - neither works). I've checked the dependency tree of the root as well as the integration module and don't see any stale or old cruft in there. I'm looking for any debugging tips to help find the culprate or other ways to include/exclude the RIGHT version of this. It doesn't seem to cause a problem when running the actual server (which doesn't use embedded tomcat) but I'd like my tests to work, or even just understand wtf is going on. I'll answer all questions as I'm sure this isn't quite clear. Sadly I can't provide running code to demonstrate, either at all or maybe just right now. I'll try to reproduce the scenario without proprietary jar's. tl;dr(ish) - org.apache.catalina.core.StandardContext has a private method mergeParameters() that calls getServletContext().setInitParameter(String, String). The ServletContext returned is an ApplicationContextFacade which appears to have that method, and the method can be called with reflection, but when directly called throws NoSuchMethodException... Please help me find other ways to debug or ferret out the REAL class (that doesn't have the method).
doc_5275
Thanks Error: Value cannot be null.Parameter name: routeData StackTrace: at System.Web.Routing.RequestContext..ctor(HttpContextBase httpContext, RouteData routeData) at System.Web.Mvc.ControllerContext..ctor(HttpContextBase httpContext, RouteData routeData, ControllerBase controller) at Mvc.Mailer.MailerBase.CreateControllerContext() at Mvc.Mailer.MailerBase.ViewExists(String viewName, String masterName) at Mvc.Mailer.MailerBase.TextViewExists(String viewName, String masterName) at Mvc.Mailer.MailerBase.PopulateBody(MailMessage mailMessage, String viewName, String masterName, Dictionary`2 linkedResources) at Mvc.Mailer.MailerBase.Populate(Action`1 action) at App.Api.Mailers.UserMailer.NewCandidate() in e:\VS2013 Projects\App.Api\Mailers\UserMailer.cs:line 15 at App.Api.Controllers.CandidatesController.Get() in e:\VS2013 Projects\App.Api\Controllers\CandidatesController.cs:line 31 controller: private readonly UserMailer _mailer = new UserMailer(); [Authorize] [Route("")] [HttpPost] // POST api/requests public HttpResponseMessage Post(Candidate candidate) { _repository.CandidateRepository.Insert(candidate); _repository.Save(); _mailer.NewCandidate().Send(); return Request.CreateResponse(HttpStatusCode.OK, candidate); } UserMailer Class: public class UserMailer : MailerBase, IUserMailer { public UserMailer() { MasterName="_Layout"; } public virtual MvcMailMessage NewCandidate() { //ViewBag.Data = someObject; return Populate(x => { x.Subject = "NewCandidate"; x.ViewName = "NewCandidate"; x.To.Add("test@test.test"); }); } } Folder Structure: Thanks A: I have also hit this issue with a mail being sent form a WebAPI2 project - that also has the MVC references, but only with a specific mailer in one of my API controllers. I have another mailer in a different API controller that has no problems at all. but I simply added : this.ControllerContext = new System.Web.Mvc.ControllerContext(this.CurrentHttpContext, new System.Web.Routing.RouteData(), this); into the mailer constructor and it all works fine now. I presume in this particular instance that the context/routedata is getting lost - possibly because of the format of my attribute routing on this particular method - as the API methods that work (with sending mails) have a slightly different uri. but i may be way off the mark there maybe someone could explain what is really going on .. EDIT: I slightly altered the route and low and behold the method worked fine. was [RoutePrefix("api/bookings")] on the controller and then [Route("{ref}/sendmail")] public async Task<IHttpActionResult> SendMail(string ref) on the method which didn't work but if i remove the parameter from the route and do [Route("sendmail")] public async Task<IHttpActionResult> SendMail(string ref) getting the param from a querystring value - it works fine A: I don't think its the view being not found. I use this successfully and whilst your code is slightly different to mine, the difference I see is in your controller. At the top declaration I have: private IUserMailer _UserMailer = new UserMailer(); public IUserMailer UserMailer { get { return _UserMailer; } set { _UserMailer = value; } } I have updated this to reflect your mailer name. Hope this helps.
doc_5276
* *If the height of the sidebar is taller then the viewport, it should scroll through the content and the bottom of the div should stick to the bottom of the viewport when scrolling further down. *If the height of the sidebar is taller then the viewport, the divs underneath should only be shown when you are at the bottom of the page. *When user scrolls back up, the sidebar scrolls back to the top and sticks back onto the top of the viewport. *If the height of the sidebar is less then the viewport, it should be sticky from the top on when scrolling down. So all in all quite some functionality and not that simple (I think). The closest I've seen to what I'm trying to achieve is this example: http://demo.techbrij.com/730/fix-sidebar-scrolling-jquery.php but the way the code is written doesn't fit into mine. So far, this is what I've made: DEMO And the jQuery code I used: jQuery(document).ready(function($) { var $sidebar = $('.sidebar'), $content = $('.content'); if ($sidebar.length > 0 && $content.length > 0) { var $window = $(window), offset = $sidebar.offset(), timer; $window.scroll(function() { clearTimeout(timer); timer = setTimeout(function() { if ($content.height() > $sidebar.height()) { var new_margin = $window.scrollTop() - offset.top; if ($window.scrollTop() > offset.top && ($sidebar.height()+new_margin) <= $content.height()) { // Following the scroll... $sidebar.stop().animate({ marginTop: new_margin }); } else if (($sidebar.height()+new_margin) > $content.height()) { // Reached the bottom... $sidebar.stop().animate({ marginTop: $content.height()-$sidebar.height() }); } else if ($window.scrollTop() <= offset.top) { // Initial position... $sidebar.stop().animate({ marginTop: 0 }); } } }, 100); }); } }); A: You are using margins to move the sticky sidebar around - I've found this to be a tricky way to handle your current ask (and potentially a heavier way). In general, I like to simply add a class to the sidebar that makes it be "position: fixed" so the browser does the heavy lifting on keeping it locked. For your current ask, you simply have to scroll that position fixed div (which is also made 100% height) programmatically based on how far down they have scrolled. Take a look at my example and see if this is the effect you are after: http://jsfiddle.net/ZHP52/1/ here's the jquery: jQuery(document).ready(function($) { var $sidebar = $('.sidebar'), $content = $('.content'); //Since our CSS is going to monkey with the height as you scroll, I need to know the initial height. var sidebarHeight = $sidebar.height(); if ($sidebar.length > 0 && $content.length > 0) { var $window = $(window), offset = $sidebar.offset(), timer; $window.scroll(function() { if ($content.height() > sidebarHeight) { var new_margin = $window.scrollTop() - offset.top; if ($window.scrollTop() > offset.top) { // Fix sidebar $sidebar.addClass("fixed"); // Scroll it the appropriate ammount $sidebar.scrollTop(new_margin); }else{ $sidebar.removeClass("fixed"); } } }); } }); A: Check out hcSticky, I was just looking for this. It's kind of the "perfect" sticky sidebar and can also emulate the other libraries with options. The first demo is probably what everyone needs, it scrolls a container independently from the main content. (you can go through the whole sidebar before reaching the bottom of the page or when you scroll bar up, before reaching the top of the page). Check it out: http://someweblog.com/demo/hcsticky/ A: I belive this is functionality you are looking for: http://jsfiddle.net/JVe8T/7/ Sorry for messy code but it should be fairly easy to optimize it. I also assumed that sidebar2 (the non-sticky one) has defined height, if that is not the case you could just detect it with jquery and use .css selector for bottom offset. Here's my code: jQuery(document).ready(function() { var tmpWindow = $(window), sidebar = $('.sidebar'), content = $('.content'), sidebar1 = $('.sidebar1'), sidebar2 = $('.sidebar2'), viewportHeight = $(window).height(), sidebarHeight = sidebar.height(), sidebar1Height = sidebar1.height(), sidebar2Height = sidebar2.height(), offsetBottom; tmpWindow.scroll(function(){ offsetBottom = content.height() - sidebar2Height; //if sidebar height is less that viewport if (viewportHeight > sidebarHeight) { sidebar.addClass('fixed'); } //sticky sidebar1 if ((tmpWindow.scrollTop() + viewportHeight) > sidebar1Height ) { sidebar1.addClass('bottom'); } else { sidebar1.removeClass('bottom'); } //end of content, visible sidebar2 if ((tmpWindow.scrollTop() + viewportHeight) > offsetBottom) { sidebar1.removeClass('bottom'); sidebar1.addClass('fixedBottom'); } else { sidebar1.removeClass('fixedBottom'); } }); });
doc_5277
<html> <head> </head> <body> <img src="test.png" width="550" height="405"> <canvas id="image"></canvas> </body> <script type="text/javascript"> var canvas = document.getElementById('image'); var ctx = canvas.getContext('2d'); ctx.mozImageSmoothingEnabled = false; ctx.webkitImageSmoothingEnabled = false; ctx.msImageSmoothingEnabled = false; ctx.imageSmoothingEnabled = false; canvas.width = 550; canvas.height = 405; canvas.style.width = canvas.width.toString() + "px"; canvas.style.height = canvas.height.toString() + "px"; var img = new Image(); img.onload = function() { ctx.drawImage(img, 0, 0, canvas.width, canvas.height); }; img.src = 'test.png'; </script> A: You seem to be on a retina-like display. This can be confirmed by looking at the size of your screenshot (2264 × 886). These displays do have an higher pixel density. To keep the sizes of web-pages consistent with what the author intended, they do up-scale automatically all the content of the page. This means that your <img> tag is actually drawn at 1100x810px, so is your canvas. However, this automation is only done at a presentation level (CSS). Your canvas context still contains only 550x405 pixels. So when passed at presentation level, it has to upscale it, via CSS, which produces this loss of quality. There is no bullet-proof method to know the PPI (Pixels Per Inch) ratio of a screen, but you can still try to get it thanks to the window.devicePixelRatio property. This may be inaccurate if your user does play a lot with its browser's zoom level, but in 90% of cases, it works fine. Once you've got this, you can do manually for the canvas what the browser does for the <img> : upscale its content and downscale its presentation. var canvas = document.getElementById('image'); var ctx = canvas.getContext('2d'); // upscale the canvas content canvas.width = 550 * devicePixelRatio; canvas.height = 405 * devicePixelRatio; // downscale the presentation canvas.style.width = (canvas.width / devicePixelRatio).toString() + "px"; canvas.style.height = (canvas.height / devicePixelRatio).toString() + "px"; var img = new Image(); img.onload = function() { ctx.drawImage(img, 0, 0, canvas.width, canvas.height); }; img.src = 'https://i.stack.imgur.com/s15bD.png'; <img width="550" height="405" src="https://i.stack.imgur.com/s15bD.png" /> <canvas id="image"></canvas>
doc_5278
example 1 using bind method : const [obj, setObj] = useState({ a: 1, b: 1 }); const handleClick = (val) => setObj({ ...obj, [val]: obj[val] + 1 }); return ( <div> <button onClick={handleClick.bind(null, "a")}>add to A</button> <button onClick={handleClick.bind(null, "b")}>add to B</button> </div> ); example 2 without bind method : const [obj, setObj] = useState({ a: 1, b: 1 }); const handleClick = (val) => setObj({ ...obj, [val]: obj[val] + 1 }); return ( <div> <button onClick={() => handleClick("a")}>add to A</button> <button onClick={() => handleClick("b")}>add to B</button> </div> ); I would really appreciate an explanation of the difference between example 1 and example 2 or even if the example 1 is a valid way in React functional Components. thanks for your help :)
doc_5279
componentDidMount() { let languages = [] base('Languages').select({ view: 'Grid view' }).firstPage(function(err, records) { if (err) {console.error(err); return; } records.forEach(function(record) { let languageObject = {} languageObject['id'] = record.id languageObject['name'] = record.get('Language Name') languages.push(languageObject) }) }) this.setState({ languageList: languages, }) } render() { return ( ... <select> {this.state.languageList.map((language, key) => ( <option key={key} value={language.id}>{language.name}</option> ))} </select> ) } I've verified that state.languageList is an array of objects, each with an id and name. What am I missing? A: Move the setState into the API callback....when the data has been made available You are calling it before the data is received since it is asynchronous base('Languages').select({ view: 'Grid view' }).firstPage((err, records) => {// arrow function to not block `this` if (err) { console.error(err); return; } records.forEach(function(record) { let languageObject = {} languageObject['id'] = record.id languageObject['name'] = record.get('Language Name') languages.push(languageObject) }) // languages array has been updated here this.setState({ languageList: languages, }) }) A: Try this <select> { this.state.languageList && this.state.languageList.map((language, key) => ( <option key={key} value={language.id}>{language.name}</option> )) } </select>
doc_5280
* *Extract IS installer into temp directory. *Run InstallShield setup.exe. *Remove temporary directory after IS finish. We haven't done installer in WiX technology before, those are our problems: * *We don't know how to embed directory with all it's files (installer) into msi using WiX. *We don't know how to ONLY run msi (it shouldn't install data, only run embeded IS setup.exe during installation and remove after). *We don't know how to run exe during installation. This is *.wxs file which I've created so far: <?xml version="1.0" encoding="UTF-8"?> <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"> <Product Id="*" Name="ISSetupPackeger" Language="1033" Version="1.0.0.0" Manufacturer="MyCompany" UpgradeCode="8804d459-2ea5-4bbc-85f7-dfc8419cafe4"> <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" Id="*" InstallPrivileges="elevated" /> <!-- TODO setup.exe starts but we don't want to run it using cmd --> <CustomAction Id="LaunchInstaller" Directory="InstallerDir" ExeCommand="cmd /C setup.exe" Impersonate="yes" Return="ignore" /> <InstallExecuteSequence> <Custom Action="LaunchInstaller" After="InstallFinalize" /> </InstallExecuteSequence> <Media Id='1' Cabinet='data.cab' EmbedCab='yes'/> <Feature Id="ProductFeature" Title="WixInstallerProject" Level="1"> <ComponentGroupRef Id="ProductComponents" /> </Feature> <!-- TODO How to extract files to temp dir? Is there some TEMP constant? --> <Directory Id="TARGETDIR" Name="SourceDir" > <Directory Id="TempDir" Name="inst"> <Directory Id="InstallerDir" Name="Installer"/> </Directory> </Directory> <!-- component group which will be installed into tempdir --> <ComponentGroup Id="ProductComponents" Directory="InstallerDir"> <Component Id="Installer" Guid="7b8bd37f-7eda-4c3a-8155-9dae1a6bbf98"> <!-- TODO How to embed directory with all its files/subdirectories? --> <File Id="_Setup.dll" Name="_Setup.dll" DiskId="1" Source="installer\_Setup.dll"/> <File Id="data1.cab" Name="data1.cab" DiskId="1" Source="installer\data1.cab"/> <File Id="data1.hdr" Name="data1.hdr" DiskId="1" Source="installer\data1.hdr"/> <File Id="data2.cab" Name="data2.cab" DiskId="1" Source="installer\data2.cab"/> <File Id="data2.hdr" Name="data2.hdr" DiskId="1" Source="installer\data2.hdr"/> <File Id="ISSetup.dll" Name="ISSetup.dll" DiskId="1" Source="installer\ISSetup.dll"/> <File Id="layout.bin" Name="layout.bin" DiskId="1" Source="installer\layout.bin"/> <File Id="setup.exe" Name="setup.exe" DiskId="1" Source="installer\setup.exe"/> <File Id="setup.ini" Name="setup.ini" DiskId="1" Source="installer\setup.ini"/> </Component> </ComponentGroup> </Product> </Wix> A: Some alternatives: From the files, it looks like the installer you have created with InstallShield is an InstallScript non-MSI installer. You might be able to convert it to an InstallScript MSI installer with an InstallShield converter. See this question and answer. I read the requirement to convert to MSI differently than you do. For any kind of wrapping or converting to be worthwhile, it should take advantage of Windows Installer managing the installation of the files that are actually installed. To do that, you'd have to rewrite the installer from scratch if a conversion is not feasible. Your approach simply uses an MSI as a bundle. You should get clarification on what you want to do. If you due go with the bundling route, WiX now offers a bootstrapper/downloader/chainer/bundler called Burn. With it, you can create a single .exe that will extract and run your existing installer. And, if you want, you can create an InstallShield response file so the existing install can be run silently. (See the InstallShield documentation for that.) A: You can use a WiX Bootstrapper to embed your existing InstallShield executable. No conversion needed. In our case the Setup.exe as built from InstallShield actually has an MSI inside. (I think this is usually the case). So then you have two options: - you can either extract that MSI (google "extract MSI from InstallShield") and embedded it in the bootstapper using MsiPackage - or you can embed the whole Setup.exe, using ExePackage Passing Parameters to an MSI: easy <MsiPackage Id="bla" SourceFile="path-to-msi> <MsiProperty Name="PUBLIC_PROPERTY_IN_UPPERCASE" value="yourvalue"/> </MsiPackage> Passing parameters to an InstallShield Setup.exe: tricky In our case Setup.exe ends up passing the parameters to the MSI anyway, use /v"the-parameters-go-here-but-you-have-to-escape-properly" Sounds easy, but it was complicated to properly escape slashes (\), single-quotes ('), double quotes ("). Also, WiX escapes \ differently if the whole InstallArgument is enclosed in ' (single quotes) or " (double quotes). I started with single quotes because it looked easier, but ended up using double quotes. Use the install log to see what gets actually passed through each layer. <Wix> <Bundle> <BootstrapperApplicationRef Id="WixStandardBootstrapperApplication.HyperlinkLicense"> <bal:WixStandardBootstrapperApplication xmlns:bal="http://schemas.microsoft.com/wix/BalExtension" LicenseUrl=""/> </BootstrapperApplicationRef> <!-- rumor has it Windows Installer needs the trailing slash for paths --> <Variable Name="InstallPath" Value="C:\path\to\destination\on\target\machine\" Type="string" bal:Overridable="yes"/> <Chain> <MsiPackage Id="package_your_msi" SourceFile="path-to-msi" DisplayInternalUI="no" ForcePerMachine="yes" Compressed="yes" After="package_some_other_msi"> <MsiProperty Name="TEST_PROPERTY_5" Value="5"/> </MsiPackage> <ExePackage Id="package_installshield_setup_exe" SourceFile="C:\path\to\Setup.exe" Compressed="yes" PerMachine="yes"> <CommandLine InstallArgument="/s /v&quot;/qn INSTALLDIR=\&quot;[InstallPath] \&quot; HOST_ADDRESS=[HostAddress] HOST_PORT=[HostPort] SCANNER_MODEL=[ScannerType]&quot;" Condition="use_registry_values=1 AND other_cond=1"/> </ExePackage> </Bundle> </Wix> Sources: https://social.msdn.microsoft.com/Forums/windows/en-US/1a113abd-dca1-482b-ac91-ddb0dcc5465c/is-it-possible-to-pass-commandline-arguments-to-an-installshield-executable?forum=winformssetup http://helpnet.installshield.com/installshield22helplib/helplibrary/IHelpSetup_EXECmdLine.htm
doc_5281
Document.ready() code is as follows: $(document).ready(function () { tempName = GetParameterValues("templateName"); //alert(tempName); if (tempName != "" || tempName != null) { $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "DesignCenter_Static.aspx/loadTemplatePackage", data: "{'template_name':'" + tempName.toString() + "'}", dataType: "JSON", success: function (data) { var temp_data = data.d.toString(); var temp_arr = new Array(); temp_arr = temp_data.split("|"); $("#divTemplateLayout").html(temp_arr[0].toString()); $("#inputForm").html(temp_arr[1].toString()); $("#divButtonSet").html(temp_arr[2].toString()); $("#inputForm").find('[id^="txt"]').each(function () { var cName, labelControlName, divControlName, resizeClassName, existingClassName, txtName; txtName = $(this).attr("id"); cName = txtName.slice(3, txtName.length); divControlName = "lbl" + cName; $("#" + divControlName + "").resizable({ maxWidth: 300, minHeight: 16, minWidth: 50, containment: "parent", autoHide: true, handles: "n, e, s, w, ne, se, sw, nw" }); $("#" + divControlName + "").draggable({ cursor: 'move', containment: ".setLimit" }); }); }, error: function (result) { alert("Error"); } }); } $("#ddlZoom").val("100%"); currentZoomLevel = $("#ddlZoom").val(); fillInitialDesignStudio(); }); Back Button Code of another page is as follows: $(function () { $("#btnBack").click(function () { var resPage = GetParameterValues("responsePage"); var tempName = GetParameterValues("templateName"); window.location.href = resPage + "?returnPage=BC_Proof.aspx&templateName=" + tempName; }); }); Master page code for adding jquery library: <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/jquery.placeholder.js"></script> <script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script> <script type="text/javascript" src="js/holder.js"></script> <%--<script src="js/colpick.js" type="text/javascript"></script>--%> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script type="text/javascript" src="js/placeholders.min.js"></script> <script type="text/javascript" src="js/jquery.uploadify.js"></script> <script type="text/javascript" src="js/jquery.uploadify.min.js"></script> <script type="text/javascript" src="js/spectrum.js"></script> <script type="text/javascript" src="js/scolor.js"></script> <script type="text/javascript" src="js/jquery.cookie.js"></script> <script type="text/javascript" src="js/jquery.Jcrop.js"></script> <script src="js/ui/jquery.ui.core.js"></script> <script src="js/ui/jquery.ui.widget.js"></script> <script src="js/ui/jquery.ui.button.js"></script> <script src="js/ui/jquery.ui.position.js"></script> <script src="js/ui/jquery.ui.menu.js"></script> <script src="js/ui/jquery.ui.autocomplete.js"></script> <script src="js/ui/jquery.ui.tooltip.js"></script> Thanks in advance A: issue is templateName not getting properly , Check Ajax data, data: "{'template_name':'" + tempName.toString() + "'}", Your BackButton Code: var tempName = GetParameterValues("templateName"); use GetParameterValues("template_name"); instead of GetParameterValues("templateName");
doc_5282
(If you will check it via phone you will get what I mean) Link: www.eufrazia.sk/sitex/ I would like the page to be loaded here "www.eufrazia.sk/sitex/home" when visited via phone I'm not sure if below code may help to understand, but I think this code has something to do with it. (function($){ window.FJSCore = { local:location.protocol == "file:", basepath:location.pathname.slice(0, location.pathname.lastIndexOf('/') + 1), defState:'', defStateMobileText:'Úvod', emptyNavigationText:'-- Sekcie --', ajaxFolder:"/ajax/", indexFile:'index.html', modules:{}, mobileFolowLinks:false, } A: It doesn't look like media queries because the menu only appears when navigating with a Phone's user-agent and not when changing the browser window size. I suggest trying to remove the device.js file from your <head> element in the index file and then see whether any errors are thrown. This should resolve the issue. <script type="text/javascript" src="js/jquery.js"></script> <!-- REMOVE THIS --> <script type="text/javascript" src="js/device.js"></script> <script type="text/javascript" src="js/bootstrap.js"></script> <script type="text/javascript" src="js/core.js"></script><script src="js/history.js?redirect=true&amp;basepath=/sitex/" type="text/javascript"></script> <script type="text/javascript" src="js/script.js"></script><script type="text/javascript" src="js/jquery.easing.js"></script><script type="text/javascript" src="js/TMForm.js"></script><script type="text/javascript" src="js/randomLettersGenerator.js"></script><script type="text/javascript" src="js/spin.min.js"></script><style type="text/css"></style><script type="text/javascript" src="js/jquery.touchSwipe.min.js"></script><script type="text/javascript" src="js/tmMultimediaGallery.js"></script> Hope this helps
doc_5283
Program in python3/qt5/matplotlib. I am plotting three subplots and few plots in each. I wanted to update plots if user changes any data. That proved rather complicated hence the button 'Replot'. It calls a function that clears canvas and ... reloads the entire widget. It doesn't work as expected: when I press the button nothing happens, but when window gets resized after button clicked it does update the plot. What would be a correct way to do it without having to put all the plots in that reload function? I've managed to cut out a minimum code that does what I described - only it'd require the GUI file (created in qt5 designer), sensor log files and a settings file for configparser. (That indentation change on mplwidget is botched on purpose so that code displays as code. Didn't know how to make it display correctly otherwise) #!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys, os from PyQt5.QtCore import Qt from PyQt5 import QtCore, QtGui, QtWidgets, QtQuick import matplotlib from matplotlib.figure import Figure from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib import dates import numpy as np import pandas as pd import configparser from RPGH_main_gui_signals_sorted import Ui_MainWindow sys.path.append('..') LOCAL_DIR = os.path.dirname(os.path.realpath(__file__)) + "/" config_f = 'settings_config_parser.py' cfg = configparser.ConfigParser() cfg.read('settings_config_parser.py') class DesignerMainWindow(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self, parent = None): super(DesignerMainWindow, self).__init__(parent) self.setupUi(self) self.replot_pushButton.clicked.connect(self.mpl_replot) self.temperature_temp_max.setValue(cfg.getint('temperature', 'temp_max')) self.temperature_temp_max.valueChanged.connect(self.write_temp_max) self.mplwidget() def mplwidget(self): temp_max = cfg.getint('temperature', 'temp_max') temp_log = 'sensor_logs/temperature_out.dat' time_format = '%d,%m,%Y,%X' temp_data = pd.read_csv(temp_log, header=None, delim_whitespace=True) temp_data.columns = ['timestamp', 'temp_up', 'temp_down', 'temp_ground'] timestamp = pd.to_datetime(pd.Series(temp_data.timestamp), format=time_format) self.mpl.canvas.ax.plot(timestamp, temp_data.temp_up) self.mpl.canvas.ax.fill_between(timestamp, temp_data.temp_up, temp_max, where=temp_data.temp_up>=temp_max, edgecolor='red', facecolor='none', hatch='/', interpolate=True) def mpl_replot(self): self.mpl.canvas.ax.clear() self.mplwidget() def write_temp_max(self): send = self.temperature_temp_max.value() message = str(send) cfg.set('temperature', 'temp_max', message) with open(config_f, 'w') as conffile: cfg.write(conffile) if __name__ == '__main__': app = QtWidgets.QApplication([sys.argv]) gui = DesignerMainWindow() gui.show() sys.exit(app.exec_())
doc_5284
"value = 10" how would I make it so the value is equal to 10 A: You can use the built-in exec method: exec("value = 10") A: >>> exec("value = 10") >>> print(value) 10 >>> exec("value = 11") >>> print(value) 11
doc_5285
object1_from_class_main = constructor_class_A() object2_from_class_main = constructor_class_B() object3_from_class_main = constructor_class_C() with class_A / class_B / class_C inherit from class_main. This means there should exist a main_class that handles all user input, and inside of this class, all other subclasses are constructed/maintained. I dont know if there is a big mistake in this, but would appreciate, if you have any suggestions. A: By design, the constructor must return an object of the class that the constructor belongs to or the output should be unassigned. It cannot return an object of a different class. From the documentation. The only output argument from a constructor is the object constructed. If you do not want to assign the output argument, you can clear the object variable in the constructor. You could define a static method for classA, classB, etc. that returns an object of class Main classdef ClassA < handle methods (Static) function mainobj = create_main() % Construct Main object and do whatever you need to here mainobj = Main(); end end end class_of_main = ClassA.create_main(); Alternately, you could make your Main instance a property of your classes classdef ClassA < handle properties mainobj end methods function self = ClassA() self.mainobj = Main() end end end A better question though is why you need to do this. Update Based on your clarification, you want basically a controller to keep track of all of the Furniture objects that you create. You can do this with a class which keeps track of Furniture objects classdef FurnitureController < handle properties furnitures = furniture.empty() end methods function addFurniture(self, furniture) self.furnitures = [self.furnitures, furniture]; end end end classdef Furniture < handle end classdef Chair < Furniture end classdef Desk < Furniture end controller = FurnitureController() controller.addFurniture(Desk()) controller.addFurniture(Chair())
doc_5286
Tell us how you can be restarted automatically turn on the docker container. A: For existing containers you can find the "Enable auto-restart" setting under Docker > Container > Edit > General Setttings. The container must be stopped to edit the settings. A: When launching an image in Docker > Image, you can find "Enable auto-restart" behind the "Advanced Settings" button.
doc_5287
what are the best options? 1) Change the access modifier to protected or default? I have already seen the question of how to test private method. 2) Use reflection? 3) how best to work towards increasing branch coverage? Example: Class A { public Object complexLogicMethodA(){ //1.Call private method B methodB(); //2.Call private method C methodC(); //3.Call private method D methodD(); //Based on } private methodD(){ if(){ //some code here }else{ //Some code here } } }
doc_5288
public static int[] removeNull(int[] array){ int j = 0; for( int i=0; i<array.length; i++ ) { if (array[i] != 0) array[j++] = array[i]; } int [] newArray = new int[j]; System.arraycopy( array, 0, newArray, 0, j ); return newArray; } What is this method performance? I was expecting it to be n. A: Yes, your method's time complexity is O(n) - your loop has n (the length of the array) iterations, and copying an array requires time proportional to the size of the copied array, which in this case is O(n) in the worst case. And you can't do better than that (in terms of time complexity), since you have to iterate over the entire array in order to locate the elements that should be removed. If your goal is to reduce code complexity (i.e. write the shortest amount of code), you can use an IntStream (requires Java 8 or later): public static int[] removeNull(int[] array) { return Arrays.stream(array).filter(i -> i != 0).toArray(); } As Andreas commented, this solution has the advantage of leaving the original array unchanged. A: Use filter method, import java.util.Arrays; import java.util.stream.Collectors; public class RemoveNullValue { public static void main( String args[] ) { String[] firstArray = {"test1", "", "test2", "test4", "", null}; firstArray = Arrays.stream(firstArray) .filter(s -> (s != null && s.length() > 0)) .toArray(String[]::new); } }
doc_5289
Module name: test.py class A(): def postit(self, D): try: ''' request = urllib2.Request("localhost:8079" + '/check/hello-test', D, headers) response = urllib2.urlopen(request) ''' conn = httplib.HTTPConnection("http://xxx.xxx.x.x:8079") conn.request("GET", "/check/hello-test") response = conn.getresponse() print ("Whey") except: print("Failed to connect!" ) There is a server listening at the above port given. When I run the uncommented code inside as a python code, the script sends request to the server, but when I do from test import A, then call the postit function. It fails and I get the error returned. The above postit() function is called internally for a purpose and it fails to send a request and get response. I need to know why. I have also tried removing the 'D' argument and it still fails.
doc_5290
i.e. I have AZM, I want Azerbaijan Manat A: Such a mapping would again be Locale-dependent… I think your best bet would be to take a long, hard look at ISO 4217 and create a Map from currency code to currency name. A: It's not supported by Java but a few libraries can do this. My number one choice would be ICU, http://icu-project.org/apiref/icu4j/com/ibm/icu/util/Currency.html#getName%28java.util.Locale,%20int,%20boolean[]%29 This call can get you the name of a currency in multiple locales. ICU also supports all other i18n features not available in JRE. However, it's pretty big. Another option is jPOS, http://gl.jpos.org/ If you do anything with financial data, this is the de-facto standards. Watch for its license. Our lawyers didn't like it for some reason. A: Class java.util.Currency implements this since java 1.7. Currency curr = Currency.getInstance("AZM"); System.out.println(curr.getCurrencyCode()); // AZM System.out.println(curr.getNumericCode()); // 31 System.out.println(curr.getDisplayName()); // Azerbaijani Manat (1993-2006) Unfortunatelly, this class is still far from usability... e.g. missing constructor from numericCode, some displayNames containings not event DisplayName, ... A: Not in the standard API. The data behind the Currency class is loaded from the package-private class java.util.CurrencyData, and there's simply no text description present there. You can look at it if you have the source code installed with your JDK. A: You will have to set up your own mapping. Google or Stackoverflow questions will point to the ISO site However you'll have to scrape the page as there seems to be no XML or text file as there is for country A: openexchangerates.org provides this info live online in machine-readable JSON format: http://openexchangerates.org/api/currencies.json It returns information as simple as this: { "AED": "United Arab Emirates Dirham", "AFN": "Afghan Afghani", ... "ZMK": "Zambian Kwacha", "ZWL": "Zimbabwean Dollar" } It's almost free but there are some terms and conditions. Here is the online documentation.
doc_5291
<nav> <ul> <li class="menu-item-has-children"> <a href="#">Parent item</a> <ul> <li><a href="#">Child item</a></li> <li><a href="#">Child item</a></li> </ul> </li> <li class="menu-item-has-children"> <a href="#">Parent item</a> <ul> <li><a href="#">Child item</a></li> <li><a href="#">Child item</a></li> </ul> </li> </ul> </nav> The child submenu is by default hidden: .menu-item-has-children > ul { display: none; } I'd like to achieve the following: * *When the top level menu item is clicked, I would like to toggle (show/hide) its associated submenu and hide any other submenus that might be opened. *When anywhere else on the page is clicked other than the submenu or its parent item, I'd like to hide all submenus. I'm using the following code, but instead of showing the correct submenu it shows/hides all submenus: $(document).on('click', function(e) { if($(e.target).parent().hasClass('menu-item-has-children')) { $(this).find('ul').show(); } else { $('.menu-item-has-children > ul').toggle(); } }); See fiddle: https://jsfiddle.net/gs9q6kwh/ Any idea what I am doing wrong? A: This can easily be achieved by hiding all the submenus first, and then showing only the submenu which is sibling of the clicked parent: $(document).on('click', function(e) { $('.menu-item-has-children > ul').hide(); if ($(e.target).parent().hasClass('menu-item-has-children')) { $(e.target).siblings('ul').toggle(); } }); .menu-item-has-children>ul { display: none; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <nav> <ul> <li class="menu-item-has-children"> <a href="#">Parent item</a> <ul> <li><a href="#">Child item</a></li> <li><a href="#">Child item</a></li> </ul> </li> <li class="menu-item-has-children"> <a href="#">Parent item</a> <ul> <li><a href="#">Child item</a></li> <li><a href="#">Child item</a></li> </ul> </li> </ul> </nav> A: There are a few problems with the jQuery code: * *Clicking on the submenu items causes all the menus to collapse. You need to restructure the jQuery to check for those items as well as the parent items. *jQuery is searching for all instances of 'ul' and showing them, not just the children of the target. Instead of using .find(), try using children(). *Clicking on the parent item doesn't toggle between show and hide. I suggest adding a class to the parent item that lets the code know its state (shown or hidden) and then toggles accordingly.
doc_5292
var path = NSBundle.mainBundle().pathForResource("sample", ofType: "mp4") var data1 = NSData(contentsOfFile:path!) var videodata:NSData=NSData(data:data1!) var len = videodata.length println() var postlength:NSString = NSString(format:"%d",len) var request = NSMutableURLRequest(URL: NSURL(string:"(liveurl)/mobile/post/video_post")!) request.HTTPMethod = "POST" var boundary = NSString(format:"---------------------------14737809831466499882746641449") request.setValue(postlength, forHTTPHeaderField: "Content-Length") var contentType = NSString(format:"multipart/form-data; boundary=%@",boundary) request.addValue(contentType, forHTTPHeaderField: "Content-Type") var postData = NSMutableData.alloc() println(request) postData.appendData(NSString(format:"\r\n--%@\r\n",boundary).dataUsingEncoding(NSUTF8StringEncoding)!) postData.appendData(NSString(format:"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"video.mp4\"\r\n").dataUsingEncoding(NSUTF8StringEncoding)!) postData.appendData(NSString(format:"Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!) postData.appendData(videodata) println(videodata) postData.appendData(NSString(format:"\r\n--%@--\r\n",boundary).dataUsingEncoding(NSUTF8StringEncoding)!) println("postData") println(postData) request.HTTPBody = postData println("request") println(request) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response: NSURLResponse!, data: NSData?, error: NSError!) -> Void in if (data != nil) { println(response) if let jsonArray: NSArray = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves, error: nil) as NSArray? { let jsonObject: NSDictionary? = jsonArray.objectAtIndex(0) as? NSDictionary println(jsonObject!) if (jsonObject != nil) { println("object: %@", jsonObject!) if (jsonObject != nil) { println("\(jsonObject)") // process jsonResult } else { println("no response \(error)") // couldn't load JSON, look at error } } } } } A: var path = NSBundle.mainBundle().pathForResource("sample", ofType: "mp4") var data1 = NSData() var videodata: NSData? = NSData.dataWithContentsOfMappedFile(path!) as? NSData var request = NSMutableURLRequest(URL: NSURL(string:"the request url")!) var session = NSURLSession.sharedSession() request.HTTPMethod = "POST" //the encoding begins var boundary = NSString(format: "---------------------------14737809831466499882746641449") var contentType = NSString(format: "multipart/form-data; boundary=%@",boundary) request.addValue(contentType, forHTTPHeaderField: "Content-Type") var body = NSMutableData.alloc() // Title body.appendData(NSString(format: "\r\n--%@\r\n",boundary).dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData(NSString(format:"Content-Disposition: form-data; name=\"title\"\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData("Hello World".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!) body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData("Content-Disposition: form-data; name=\"fileToUpload\"; filename=\"sample.mp4\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData(NSString(format: "Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData(videodata!) body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!) request.HTTPBody = body NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response: NSURLResponse!, data: NSData?, error: NSError!) -> Void in if (data != nil) { if let jsonArray: NSArray = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSArray? { println("json array\(jsonArray)") } else { } } } }
doc_5293
Given a number and a string of size consisting of 5 different uppercase characters only {V,W,X,Y,Z}. * *V: Adds to the score 5 points. *W: Adds to the score 2 points. *X: Removes the next consecutive character from the score. *Y: Moves the next consecutive character to the end of the string. *Z: If the next consecutive character is V it divides the total score by 5 but if it is W it divides the total score by 2. Then it removes the next consecutive character from the string if and only if the next character is V or W. Note: In case the string ends with X or Y or Z ignore their operations. The score is calculated from left to right and starts with 0. I Tried this code but unfortunately I get time limit exceeded on test 11 The code: N = int(input()) S = list(input()) C = 0 for i in range(N): if i == len(S)-1 and (S[len(S)-1] == "X" or S[len(S)-1] == "Y" or S[len(S)-1] == "Z"): break if i >= len(S): break if S[i] == "V" and S[i-1] == "Z": C //= 5 elif S[i] == "V" and (S[i-1] != "X" and S[i-1] != "Z"): C += 5 if S[i] == "W" and S[i-1] == "Z": C //= 2 elif S[i] == "W" and (S[i-1] != "X" and S[i-1] != "Z"): C += 2 if S[i] == "Y": S.append(S[i+1]) del S[i+1] print(C) Can you help me with that. A: This is really cheating, but I don't know how to describe the optimizations without showing the code. You can speed up your loop by enumerating through the string instead of trying indexing. And instead of trying to modify the list in place, just keep track of the added letters and reprocess them later. Don't try to look ahead, instead remember what the last letter was and use that to affect the current character. For example: def compute(S): C = 0 while S: last = None more = [] for c in S: # Handle special actions from the last X, Y, or Z. if last == 'X': pass elif last == 'Y': more.append( c ) elif last == 'Z' and c == 'V': C //= 5 elif last == 'Z' and c == 'W': C //= 2 elif c == 'V': C += 5 elif c == 'W': C += 2 last = c S = more return C print(compute('VYWZW')) print(compute('WZYVXW')) A: I am still learning as well, but would like to provide a possible recursive solution here as an alternative. I am not sure how to test for performance, but it seems to get the right output for the test cases above. Edit: Fixes for index out of bound when string ends in Y, Z. ''' V - Add 5 Points W - Add 2 Points X - Remove next character from score Y - Move next character to end of string Z - Look at next character. If V, divide score by 5. If W, divide score by 2. If V or W, remove character ''' def calculate(S, Score=0): if type(S) == str: S = list(S) if len(S) == 0: return Score if S[0] == "V": Score += 5 return calculate(S[1:], Score) if S[0] == "W": Score += 2 return calculate(S[1:], Score) if S[0] == "X": return calculate(S[2:], Score) if S[0] == "Y": try: next_letter = S[1] S = S[2:] S.append(next_letter) return calculate(S, Score) except IndexError: return calculate(S[1:], Score) if S[0] == "Z": try: if S[1] == "V": Score //= 5 return calculate(S[2:], Score) if S[1] == "W": Score //= 2 return calculate(S[2:], Score) if S[1] not in ["V","W"]: return calculate(S[1:], Score) except IndexError: return calculate(S[1:], Score) print(calculate('VYWZW')) # 4 print(calculate('WZYVXW')) # 7
doc_5294
Looking at the little number of contributors and stars in the Github projects, I wonder if there is a canonical way of doing these tasks instead of installing these modules? Maybe there is a native way in Node or in ES6 to do this that I am missing? A: Examples First see some examples - scroll below for an explanation. Callbacks: Example with async and functions that take Node-style callbacks: async.parallel([ (cb) => { setTimeout(() => { cb(null, 'one'); }, 200); }, (cb) => { setTimeout(() => { cb(null, 'two'); }, 100); }, ], (err, results) => { if (err) { // there was an error: console.log('Error:', err); return; } // we have ['one', 'two'] in results: console.log('Results:', JSON.stringify(results)); }); Promises: Example using functions that return promises - with Bluebird's delay() function: const { delay } = require('bluebird'); Promise.all([ delay(200, 'one'), delay(100, 'two'), ]).then((results) => { // we have ['one', 'two'] in results: console.log('Results:', JSON.stringify(results)); }).catch((err) => { // there was an error: console.log('Error:', err); }); ES2017 async/await: Using async/await: const { delay } = require('bluebird'); try { const results = await Promise.all([ delay(200, 'one'), delay(100, 'two'), ]); // we have ['one', 'two'] in results: console.log('Results:', JSON.stringify(results)); } catch (err) { // there was an error: console.log('Error:', err); } I'm using JSON.stringify() to make it explicit what is the format of the data in results. Note that even though the first value comes last, the original order is still preserved. The last example must be run inside of a function declared with an async keyword, or wrapped in (async () => { ... })() like this: (async () => { try { const results = await Promise.all([ delay(200, 'one'), delay(100, 'two'), ]); // we have ['one', 'two'] in results: console.log('Results:', JSON.stringify(results)); } catch (err) { // there was an error: console.log('Error:', err); } })(); Generators and coroutines: With no support for async/await you can use some generator-based coroutines, like those that comes from Bluebird: const { delay, coroutine } = require('bluebird'); coroutine(function* () { try { const results = yield Promise.all([ delay(200, 'one'), delay(100, 'two'), ]); // we have ['one', 'two'] in results: console.log('Results:', JSON.stringify(results)); } catch (err) { // there was an error: console.log('Error:', err); } })(); Explanation There are many ways to do that and it all depends on the kind of functions that you want to run. If you want to run a traditional Node-style functions that take error-first callbacks as their last arguments then the most popular way to run those in parallel or in series is the async module on npm: * *https://www.npmjs.com/package/async There is no built-in support for things like that in ES6 because those error-first callbacks are really a Node thing, not very popular in JavaScript outside of Node. The ES6/ES7/ES8 goes in the direction of functions that return promises (instead of functions that take callbacks) and there is a new async/await syntax to make them look kind-of-like synchronous, with try/catch working for error handling. So, the most popular way in Node to combine functions taking callbacks is async module: * *https://www.npmjs.com/package/async To work with promises a popular modules is Bluebird: * *https://www.npmjs.com/package/bluebird For more advanced tasks there is Task.js: * *https://github.com/mozilla/task.js See those answers for more info: * *try/catch blocks with async/await *node.js ~ constructing chained sequence of Promise resolves *How to run Generator Functions in Parallel? *node.js ~ constructing chained sequence of Promise resolves *Using async/await + Bluebird to promisifyAll *jQuery: Return data after ajax call success A: Remember that functions can just be passed around like any other object in JavaScript, so it's actually pretty straightforward to do things like this. For example, to run things in series you could just use map to generate an array of results by executing each of your functions - like this... let functions = [ function() { return 'abc'; }, function() { return 123; }, function() { return { key: 'value' }; } ]; let results = functions.map(fn => fn()); Obviously, what you get from using these libraries is nice - hopefully well tested - handling for when things go wrong etc. but it's perfectly possible to do it without them. A: You can use Array.prototype.map() to loop through all functions in your array sequentially, using an anonymous function that executes each function in the array as a parameter. Using Function.prototype.apply() instead of directly calling the function allows you to pass an array to each function with its parameters. Example var functions = [ function(x){return 3 * x}, function(x){return 4 * x}, function(x){return 8 * x}, function(x){return 10 * x}, function(){return Array.prototype.map.call(arguments, function(name){ return "Hello, " + name })} ]; var results = functions.map(function(value, index) { return value.apply(value, this[index]); }, [[5], [1], [8], [8], ["Dolly", "major Tom"]]); document.body.innerHTML = '<pre>' + JSON.stringify(results, null, '\t') + '</pre>'; See also this Fiddle. A: The structure depends on what you want to implement. :D functions = {}; async function getArticle(id = 0) { // const result = await articles.get(id); get result of a db. const result = { id: 10, name: "apple" } if (result) return result; return false; } async function validatePermission(id = 0) { // const result = await users.get(id); get result of a db. const result = { id: 25 } if (result) return result; return false; } functions.getArticle = async params => { const { userId, articleId } = params; const [validUser, article] = await Promise.all([ validatePermission(userId), getArticle(articleId), ]); if (validUser === false || article === false) { return { status: 400, message: 'Error', data: [] } } return { status: 200, message: 'Success', data: article }; } const params = { userId: 25, articleId: 10 }; functions.getArticle(params) .then(result => { console.log(result); });
doc_5295
A: It should support Google out of the box because it uses pkgcloud lib which has support for Google Cloud. Try simply adding a config entry to the providers.json file. For more info on how to do that check Loopback storage component documentation and also pkgcloud config format for Google Cloud. I'd just try something like this in the providers.json: { "google": { "keyFilename": "/path/to/a/keyfile.json", "projectId": "your-project-id" } }
doc_5296
I have a JavaScript function. In this function, I need to fire a button event. Any suggestions/link? EDIT I have a validation function in javascript that i validate on clicking this button. I have a situation, like when i click the button then i need the validation but when I am performing the click(through $("#ID").trigger("click");) then it is not required. Any suggestion? A: $("#mybutton").trigger("click"); // just fires click event on the button $("#mybutton").click(); // simulates button click A: Since you didn't tag as jQuery, I'll assume you're not using it. If you're setting the event like this: var someButton = document.getElementById("yourButtonId"); someButton.addEventListener('click', clickEvent); Then you can raise the click event later like this: clickEvent(); This also works for me, but I'm not sure how cross-browser safe it is: var button = document.getElementById("yourButtonId"); button.click();
doc_5297
I saved the model checkpoints. Now, I want to run this model on my eval set. But, I cannot find the script that I use to run on eval set. I have tfrecord files for eval set. How do I run the eval script from the object-detection api for my own saved model checkpoint? I couldn't find the script. A: You are looking fot the eval.py. Run this script with the command: python eval.py \ --logtostderr \ --pipeline_config_path=PATH_TO_YOUR_CONFIG_FILE \ --checkpoint_dir=PATH_TO_CHECKPOINT \ --eval_dir=OUTPUT_PATH
doc_5298
missing required :bucket option\n/home/server_username/project_folder_name/shared/bundle/ruby/2.2.0/gems/paperclip-4.3.0/lib/paperclip/storage/s3.rb:218:in 'bucket_name'...etc In application.rb config.paperclip_defaults = { :storage => :s3, :url =>':s3_domain_url', :s3_protocol => 'https', :path => '/:class/:attachment/:id_partition/:style/:filename', :bucket => ENV['s3_bucket_name'], :s3_credentials => { :access_key_id => ENV['s3_id'], :secret_access_key => ENV['s3_key'] } } In my class file has_attached_file :uploaded_file, :styles => { original: "990x990#",large: "300x300#", medium: "200x200#", thumb: "100x100#"}, only_process: [:medium] process_in_background :uploaded_file, queue: "queue_name", only_process: [:original, :large, :thumb] Uploading to s3 works without using delayed_paperclip. I just wanted to use this library so people didn't have to wait for these to be uploaded/resiszed. I'm working on Ubuntu14.04. Deploying w/ Capistrano. I saw a couple places that the bucket should be outside of the s3_credentials, so I moved it to where it is now. So I've tried it there and inside s3_credentials -- no change either way. The medium image is uploaded and resized immediately and works. Let me know if there is some info I didn't provide.
doc_5299
Also how can I search students by their ids in this case? A: You can do it using before-create hook in your model, something like follow - class Student < ActiveRecord::Base # Callbacks before_create :set_student_id def set_student_id self.student_id = "STU" + "%04d" % self.id end end output - $> student = Student.create() $> puts student.student_id $> STU0001 A: IMHO if you want id to be prefixed as STU just for a nice display purpose then I would suggest not to store that way in database. Let current implementation of auto incrementing id be untouched. Just while displaying you can prepend it with STU. For handy use you can create method to wrap this logic as def formatted_id # OR friendly_id or whatever you like "STU#{'%04d' % self.id}" end Reasons for not storing prefixed id: * *You will have to write a setter *Your column data type will change to string *Your performance will go down as compared to integer column *In future if you decide to change the prefix, then you will have to update existing ids. With my solution you can change all (existing and future) ids formatting anytime by just changing formatting in the method. Searching depends on exactly what is your usecase. If you can explain that then I can guide you better. To search students you can write a handy method like below in model (i assume it will be Student or User) def self.find_by_formatted_id(formatted_id) self.find(formatted_id.gsub(/^STU/, '')) end def self.find_by_formatted_ids(formatted_ids) # formatted_ids will be an array self.where(id: formatted_ids.map{ |fid| fid.gsub(/^STU/, '') }) end