_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d1201
train
This code has 3 problems. * *You should change const http=require('https') to const http=require('http'). If you want to use HTTPS please see the nodejs document for how to configure the https server *In nodejs HTTP request URL start with / and your condition statement does not work *Cuz request URL does not match with the condition statement server does not respond any things and this error happens. You should change code like that: const http=require('http') const PORT=8000 const server=http.createServer() server.on('request',(req,res)=>{ if (req.url==='/friend'){ res.writeHead(200,{ 'Content-Type':'text/plain', }); res.end(JSON.stringify({ id:1, name:'Sir Issac Newton', })); return; } if (req.url==='/foe'){ res.writeHead(200,{ 'Content-Type':'text/plain', }); res.end('The Enemy is Ego Bro'); return; } res.writeHead(400,{ 'Content-Type':'text/plain', }); res.end('URL not match'); }) server.listen(PORT,()=>{ console.log(`the respnse is exectued at ${PORT}`) })
unknown
d1202
train
Okay so couldn't find a specific way to do it with photoshop so I worked out the math based off the RGB values and came up with a formula to do the job. For each colour channel I used this formula: Colour value = Desired Colour + (Background Colour - Desired Colour)*(1-1/Desired Opacity) eg. 30 = 120 + (255-120)*(1-1/0.6) Obvious only values between 0-255 are applicable and you may need to round values. This also needs to be done 3 times for red, green and blue.
unknown
d1203
train
The following PowerShell script should help: $oldIp = "172.16.3.214" $newIp = "172.16.3.215" # Get all objects at IIS://Localhost/W3SVC $iisObjects = new-object ` System.DirectoryServices.DirectoryEntry("IIS://Localhost/W3SVC") foreach($site in $iisObjects.psbase.Children) { # Is object a website? if($site.psbase.SchemaClassName -eq "IIsWebServer") { $siteID = $site.psbase.Name # Grab bindings and cast to array $bindings = [array]$site.psbase.Properties["ServerBindings"].Value $hasChanged = $false $c = 0 foreach($binding in $bindings) { # Only change if IP address is one we're interested in if($binding.IndexOf($oldIp) -gt -1) { $newBinding = $binding.Replace($oldIp, $newIp) Write-Output "$siteID: $binding -> $newBinding" $bindings[$c] = $newBinding $hasChanged = $true } $c++ } if($hasChanged) { # Only update if something changed $site.psbase.Properties["ServerBindings"].Value = $bindings # Comment out this line to simulate updates. $site.psbase.CommitChanges() Write-Output "Committed change for $siteID" Write-Output "=========================" } } }
unknown
d1204
train
Here's a solution I've recently found when looking for a solution to the same issue. Using quilt: dev-util/quilt-0.65::gentoo was built with the following: USE="-emacs -graphviz" ABI_X86="(64)" from gentoo, and the following command line session, I was able to painlessly convert a context diff into a unified diff, and adjust the strip level (option -p in patch) from -p0 to -p1 (always use -p1 guys, it will make your and others' lives much easier!) $ tar xf SDL2-2.0.8.tar.gz $ cd SDL2-2.0.8 $ quilt new SDL2-2.0.8.unified.patch $ quilt --quiltrc - fold -p 0 < ../SDL2-2.0.8.context.patch # arbitrary -p0 context diff I created for this exercise $ quilt refresh # your new -p1 unified diff can be found at SDL2-2.0.8/patches/SDL2-2.0.8.unified.patch Answering this here as this is one of the highest results in google for queries related to converting a context diff to a unified one. Should work in any distro, I'm just reporting exactly what I have for posterity's sake. Just found a 'better' way, but requires its own sort of prep work. For this you just need the patch file itself. You will require patchutils dev-util/patchutils-0.3.4::gentoo was built with the following: USE="-test" ABI_X86="(64)" $ $EDITOR SDL2-2.0.8.context.patch # remove all lines like: 1 diff -cr SDL2-2.0.8/src/SDL.c SDL2-2.0.8.new/src/SDL.c (apparently not needed in current git) # save and quit $ filterdiff --format=unified < SDL2-2.0.8.context.patch > SDL2-2.0.8.unified.patch # you can even do this inside vim with :%!filterdiff --format=unified Hope this helps! A: Since git diff can only be configured to produce a context diff (or be filtered to produce one), a possible simple approach would be to use patch to apply manually that context diff, then use git add to detect the change.
unknown
d1205
train
You can use it like this $array_holder = array("drilldown"=>$sImageUrl, "type"=>$Type, "job_no"=>$Job_No,"customer"=>$Customer); $plates_data['data'][] = $array_holder;
unknown
d1206
train
Your screenshot is showing Firestore, but your code is working with Realtime Database. These are completely different database products. Your code needs to match the product you're using. Be sure the check the product documentation for examples of correct usage.
unknown
d1207
train
I assume that the class MyWeightedEdge already contains a method such as public void setWeight(double weight) If this is indeed the case, then what you need to do is: Derive your own subclass from ListenableDirectedWeightedGraph (e.g., ListenableDirectedWeightedGraph). I would add both constructor versions, delegating to "super" to ensure compatibility with the original class. Create the graph as in your question, but using the new class ListenableDirectedWeightedGraph g = new CustomListenableDirectedWeightedGraph( MyWeightedEdge.class); Override the method setEdgeWeight as follows: public void setEdgeWeight(E e, double weight) { super.setEdgeWeight(e, weight); ((MyWeightedEdge)e).setWeight(weight); } And, last but not least, override the toString method of the class MyWeightedEdge to return the label you want the edge to have (presumably including the weight, which is now available to it). I hope this helps.
unknown
d1208
train
The problem is not the tracking or the click event, the problem is timing and possibly browser size. Maximize the browser window and add explicit wait when searching for the banner close button browser = webdriver.Firefox(options=options) browser.maximize_window() browser.get(url) wait = WebDriverWait(browser, 10) wait.until(EC.element_to_be_clickable((By.ID, 'appd_wrap_close'))).click() wait.until(EC.invisibility_of_element_located((By.ID, 'appd_wrap_default'))) current_page = int(browser.find_element_by_css_selector('a.current').text) next_page = current_page + 1 page_number_field = wait.until(EC.visibility_of_element_located((By.ID, 'cPageNum'))) page_number_field.clear() page_number_field.send_keys(next_page) wait.until(EC.element_to_be_clickable((By.ID, 'cPageBtn'))).click()
unknown
d1209
train
Your source checks for a folder called myDir being created, but when you create new_file.txt, it isn't creating it in the myDir folder, it looks to be creating it in the externalDataDirectory folder. So check the externalDataDirectory folder rather than your myDir folder, and you'll probably see your file there.
unknown
d1210
train
To make it a single match use (.*) The single . matches a single character. The additional * means "zero or more". Edit In response to the comment about two matches (the first match contains the string, and the second is an empty match): The Matches documentation indicates that it gives empty matches special treatment. There is a good example on that page to show the behavior. But the end result is that after the match, it does not do forward movement, so it picks up an empty match. To prevent that, you could use beginning of line and end of line anchors: (^.*$) or use the + to force at least one character to be included: (.+). A: Since you want to match any number of any characters, change the . to .* to match zero or more, or .+ to match one or more.
unknown
d1211
train
A few issues. * *Your form's selector, $('addForm'), is missing the # as everyone is pointing out. *You're missing the $(document).ready() function since your form does not yet exist when the JavaScript is called, this is required. *You don't need another submit handler since the jQuery Validate plugin has a submitHandler callback function built in. As per docs, "The right place to submit a form via Ajax after it validated." Something like this: (assuming that the OP's .ajax function is already correct.) <script src="jquery.min.js"></script> <script src="jquery.validate.js"></script> <script> $(document).ready(function() { $('#addForm').validate({ //other options, submitHandler: function (form) { // your ajax code return false; // <-- stop form redirection since you used ajax } }); }); </script> A: There are several problems, most discussed in comments already: * *Your selector when you set up the "submit" handler was wrong. It should have been $('#addForm') *You're trying to use $.get() to process a form that includes a "file" <input> element. That can't be done. To upload a file, you can either: * *POST your form (has to be POST, not GET) and give it a "target" attribute of a hidden <iframe> element on the page. The response from the server should include JavaScript to update the parent page (the page with the form on it) as appropriate. *Use the HTML5 File API to grab the file contents and then upload via XHR. I've never tried to do this, but here is an older SO question about it.
unknown
d1212
train
you can use singleton, but I would advise you not to use singleton for UIView elements. UIView elements can only have one superview, so if you use singleton.activityindicator everywhere, you will have to remove it from superview before adding it to new view, so alot of bookkeeping is required. For example, you have to remove it from prev superview when showing it else where, and when you come back to prev superview (through user clicking on some nav control or something), you have to determine if you need to now add it back to the new superview, etc. I do use singleton for one UIView in my design, that is Ad banner view. I wanted to keep one ad across the app, to have same ad in different nav controllers. However it was big pain in the butt. Just create one, add to the view, and remove when done.. simpler in my opinion :) A: You can try to add a UIView to the custom class and then add the activityIndicator to it. A: Take a UIView Class inside initWithFrame methode: //this method create custom activity indicator UIImage *startImage = [UIImage imageNamed:@"1.png"]; customActivityIndicator = [[UIImageView alloc] //take in in .h file initWithImage:startImage ]; //Add more images which to be used for the animation customActivityIndicator.animationImages = [NSArray arrayWithObjects: [UIImage imageNamed:@"1.png"], [UIImage imageNamed:@"2.png"], [UIImage imageNamed:@"3.png"], [UIImage imageNamed:@"4.png"], [UIImage imageNamed:@"5.png"], [UIImage imageNamed:@"6.png"], [UIImage imageNamed:@"7.png"], [UIImage imageNamed:@"8.png"], nil]; //Set animation duration customActivityIndicator.animationDuration = 0.5; //set frame at the middle of the imageview customActivityIndicator.frame = self.frame; Take a methode: // call this methode from the class where u want to animate custom indicator (void)startAnimating { [customActivityIndicatorstartAnimating]; } Take a methode: // call this methode from the class where u want to stope animate custom (void)stopAnimating { [customActivityIndicatorstaopAnimating]; }
unknown
d1213
train
Now it will work word = gets.chomp while word != '' list = list.push word word = gets.chomp end In your case, before pushing the first word to list( when you just entered into the while loop), you are calling again Kernel#gets and assigned it to word. That's why you lost the first word, and from that second one you started to pushing the words into the array. A: Compare with functional approach: sorted_words = (1..Float::INFINITY) .lazy .map { gets.chomp } .take_while { |word| !word.empty? } .sort A: You can make this cleaner if you realize that assignment returns the assigned value. list = [] until (word = gets.chomp).empty? do list << word end A: Here is another way your program can be rewritten, perhaps in a little more intuitive and expressive way: word = 'word' list = [] puts 'enter some words, man. ill tell em to you in alphabetical order.' puts 'when your\'re done, just press enter without typing anything before.' puts '' keep_going = true while keep_going word = gets.chomp keep_going = false if word.empty? list = list.push word if keep_going end puts '' puts 'Your alphabetically ordered words are:' puts list.sort puts ''
unknown
d1214
train
In the context of this expression: qsort (values, 6, sizeof(int), compare); the subexpression compare that identifies a function decays into a pointer to that function (and not a function call). The code is effectively equivalent to: qsort (values, 6, sizeof(int), &compare); This is exactly the same thing that happens to arrays when used as arguments to a function (which you might or not have seen before but is more frequently asked): void f( int * x ); int main() { int array[10]; f( array ); // f( &array[0] ) } A: When calling qsort, you're passing a pointer to the function which is why you don't specify any parameters. Inside the qsort implementation choses values from the 'values' array and calls the 'compare' function. That's how 'a' and 'b' get passed. A: qsort passes the addresses of whichever items in the array it wants to compare. For example, &values[3] and &values[5]. Since it doesn't really know the actual types of the items in the array, it uses the size parameter to correctly compute the addresses. See this implementation for example: http://insanecoding.blogspot.ie/2007/03/quicksort.html
unknown
d1215
train
While this is straight-forward in XSLT 2.0, in XSLT a two-pass transformation can produce the wanted results: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ext="http://exslt.org/common" exclude-result-prefixes="ext"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:key name="kSolByVal" match="solution" use="."/> <xsl:template match="node()|@*" name="identity"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="/"> <xsl:variable name="vrtfPass1"> <xsl:apply-templates/> </xsl:variable> <xsl:apply-templates select= "ext:node-set($vrtfPass1) /*/*/*/* /solutions/solution [generate-id() = generate-id(key('kSolByVal', .)[1]) ]" mode="pass2"/> </xsl:template> <xsl:template mode="pass2" match="solution"> <div id="#{.}"> <xsl:apply-templates mode="pass2" select="key('kSolByVal', .)/../../../.."/> </div> </xsl:template> <xsl:template match="profile" mode="pass2"> <xsl:if test="position() = 1"> <xsl:text>&#xA;</xsl:text> </xsl:if> <xsl:value-of select= "concat(customer, ', ', */summary, '&#xA;')"/> </xsl:template> <xsl:template match="solutions"> <solutions> <xsl:apply-templates select="." mode="split"/> </solutions> </xsl:template> <xsl:template match="solutions" name="split" mode="split"> <xsl:param name="pText" select="."/> <xsl:if test="string-length($pText)"> <xsl:variable name="vText1" select="concat($pText, ',')"/> <xsl:variable name="vPart" select= "substring-before($vText1, ',')"/> <solution> <xsl:value-of select="$vPart"/> </solution> <xsl:call-template name="split"> <xsl:with-param name="pText" select="substring($pText, string-length($vPart)+2)"/> </xsl:call-template> </xsl:if> </xsl:template> </xsl:stylesheet> when this transformation is applied on the provided XML document (corrected for well-formedness): <profiles> <profile> <customer>customer a </customer> <collateral> <summary>summary a</summary> <related> <solutions>sol1,sol2</solutions> </related> </collateral> </profile> <profile> <customer>customer b </customer> <collateral> <summary>summary b</summary> <related> <solutions>sol1</solutions> </related> </collateral> </profile> <profile> <customer>customer c </customer> <collateral> <summary>summary c</summary> <related> <solutions>sol2,sol3</solutions> </related> </collateral> </profile> </profiles> the wanted, correct result is produced: <div id="#sol1"> customer a , summary a customer b , summary b </div> <div id="#sol2"> customer a , summary a customer c , summary c </div> <div id="#sol3"> customer c , summary c </div> Explanation: * *We carry out the transformation in two passes. Pass2 is applied on the result of applying Pass1 on the provided XML document. *Pass 1 is essentially the identity rule overriden for any solutions element. The processing of a solutions element consists in recursive splitting of its string value. The final result of Pass1 is the following: -- <profiles> <profile> <customer>customer a </customer> <collateral> <summary>summary a</summary> <related> <solutions> <solution>sol1</solution> <solution>sol2</solution> </solutions> </related> </collateral> </profile> <profile> <customer>customer b </customer> <collateral> <summary>summary b</summary> <related> <solutions> <solution>sol1</solution> </solutions> </related> </collateral> </profile> <profile> <customer>customer c </customer> <collateral> <summary>summary c</summary> <related> <solutions> <solution>sol2</solution> <solution>sol3</solution> </solutions> </related> </collateral> </profile> </profiles> .3. We then apply templates (in mode="pass2") on the result of Pass1. This is a typical and traditional Muenchian grouping.
unknown
d1216
train
one of the possible solutions is to define the event function before calling the bind method on the element, and then reuse it to rebind when you focusout. it goes something like this: (this code should work...) keyDownFn = function() { console.log('this will happen only on the first keydown event!'); $(this).unbind('keydown') } $('input.text').bind({ click: function(e) {}, focusin: function(e) {}, focusout: function() { $(this).bind('keydown', keyDownFn); }, keydown: keyDownFn }) enjoy. A: You have to save a reference to the function. By saving a reference to the function, you can rebind the original function: var keydown_func = function() { $(this).unbind('keydown'); }; $('input.text').bind({ click : function(e) { },focusin : function(e) { },focusout : function() { // rebind keydown $(this).bind('keydown', keydown_func); },keydown : keydown_func }
unknown
d1217
train
Bro, you need few arrows of style. Do like this:) .centre-vertical-common-styles { position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%); } .debug-border-common-styles { border: 3px solid black; height:40px; width:200px; display:flex; align-items:center; justify-content:center; }
unknown
d1218
train
The standard ComboBox simply doesn't have states to distinguish between having something selected and having nothing selected. There are a number of ways to go about solving the underlying problem, and it depends mostly on the answer to the following question: Do you really need to change the visual appearance of the ComboBox itself or does it suffice to style the selected item more prominently? If it's the latter, you're best served with the rather easy way of using a custom control template for the ComboBoxItems. If you really want to style the ComboBox itself that way, there are two options I can think of: A) Add custom states to a ComboBox with a custom template. Copy your ComboBox's control template and add another state group to the already present states. Both of this is typically done in Expression Blend. After that you can update the new states in code with VisualStateManager.GoToState(this, "Selected", true); for example. You will have to set those states yourself when the first item is chosen. This could be done on the SelectionChanged event. B) Derive from ComboBox If you want to use the control in this way often, it might be worthwhile to derive from ComboBox to make your own custom control. It would look somthing like this: [TemplateVisualState(Name = "SelectedStates", GroupName = "Unselected")] [TemplateVisualState(Name = "SelectedStates", GroupName = "Selected")] // ... (more attributes copied from the ComboBox ones) public class MyComboBox : ComboBox { public MyComboBox() { SelectionChanged += HandleSelectionChanged; DefaultStyleKey = typeof(MyComboBox); } void HandleSelectionChanged(object sender, SelectionChangedEventArgs e) { VisualStateManager.GoToState(this, SelectedItem != null ? "Selected" : "Unselected", true); } } And you would then need a default style based on the default ComboBox style (or whatever you usually use). Note that I didn't test this in any way.
unknown
d1219
train
You can use parse_url to do the heavy lifting and then split the hostname by the dot, checking if the last two elements are the same: $url1 = parse_url($url1); $url2 = parse_url($url2); $host_parts1 = explode(".", $url1["host"]); $host_parts2 = explode(".", $url2["host"]); if ($host_parts1[count($host_parts1)-1] == $host_parts2[count($host_parts2)-1] && ($host_parts1[count($host_parts1)-2] == $host_parts2[count($host_parts2)-2]) { echo "match"; } else { echo "no match"; } A: You could use parse_url for parsing the URL and get the root domain, like so: * *Add http:// to the URL if not already exists *Get the hostname part of the URL using PHP_URL_HOST constant *explode the URL by a dot (.) *Get the last two chunks of the array using array_slice *Implode the result array to get the root domain A little function I made (which is a modified version of my own answer here): function getRootDomain($url) { if (!preg_match("~^(?:f|ht)tps?://~i", $url)) { $url = "http://" . $url; } $domain = implode('.', array_slice(explode('.', parse_url($url, PHP_URL_HOST)), -2)); return $domain; } Test cases: $a = 'http://example.com'; $urls = array( 'example.com/test', 'example.com/test.html', 'www.example.com/example.html', 'example.net/foobar', 'example.org/bar' ); foreach ($urls as $url) { if(getRootDomain($url) == getRootDomain($a)) { echo "Root domain is the same\n"; } else { echo "Not same\n"; } } Output: Root domain is the same Root domain is the same Root domain is the same Not same Not same Note: This solution isn't foolproof and could fail for URLs like example.co.uk and you might want to additional checks to make sure that doesn't happen. Demo! A: I think that this answer can help: Searching partial strings PHP Since these URLs are just strings anyway
unknown
d1220
train
[HttpPost] public HttpResponseMessage PostStartWorkingDay([FromBody] StartWorkingDay startWorkingDay) { //here above startWorkingDay is body your mobile developer will send //you and data can be viewed while debugging , //tell mobile developer to set content-type header should be JSON. return Request.CreateResponse(HttpStatusCode.Created, "Success"); } Why your return type is Json ? you should use HttpResponse . I believe you are using Web api 2 . With Attribute routing and if you want to send response in json format then remove Xml formatter from WebApiConfig.cs file inside App_Start folder
unknown
d1221
train
This breaks in cases where it's more efficient to divide into non-equivalent stacks. For example, the case 1 9 where one person has 9 pancakes. Dividing as evenly as possible into groups of 2 gives the solution: min 1: 9 min 2: 5 4 min 3: 4 3 min 4: 3 2 min 5: 2 1 min 6: 1 0 min 7: 0 0 where as dividing unevenly gives the solution min 1: 9 min 2: 3 6 min 3: 3 3 3 min 4: 2 2 2 min 5: 1 1 1 min 6: 0 0 0 which is more efficient.
unknown
d1222
train
EOFException is thrown when end-of-file is reached. That is, you have read the whole file. Therefore you should not close your streams within the try statement, but use try-with-resources to automatically close them. Try something simple like this: public void loadFromFileStudent() throws IOException, ClassNotFoundException { try (InputStream inputStream = new FileInputStream("student.txt"); ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) { this.repo = (Dictionary<Integer, Student>) objectInputStream.readObject(); } catch (FileNotFoundException e) { System.out.println ("File not found"); } catch (IOException e) { System.out.println ("Error while reading"); } catch (ClassNotFoundException e) { System.out.println ("No class"); } catch (ClassCastException e) { System.out.println ("Could not cast to class"); } } Writing is equally simple: public void writeObject ( Object o ) { try (FileOutputStream fos = new FileOutputStream ( this.filename ); ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeObject(o); oos.flush(); } catch (NotSerializableException e) { System.out.println ("Object wont be serialized"); e.printStackTrace(); } catch (IOException e) { System.out.println ("Error while writing to file"); e.printStackTrace(); } } A: From my understanding of the question I assume OP is doing some thing like below, and which should works. May be OP would have missed something during writing/reading. Hope this helps to figure out. public class Test2 { public static void main(String[] args) { Test2 t = new Test2(); t.create(); t.read(); } public void create(){ try{ ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("D:\\test\\ab.txt")); Student st = new Student("chevs"); Dictionary<Integer, Student> dict = new Hashtable<Integer, Student>(); dict.put(1, st); os.writeObject(dict); }catch(Exception e){ e.printStackTrace(); } } public void read() { try{ InputStream inputStream = new FileInputStream("D:\\test\\a.txt"); System.out.println(inputStream.toString()); ObjectInputStream objectInputStream; objectInputStream = new ObjectInputStream(inputStream); System.out.println(objectInputStream.toString()); private Dictionary<Integer, Student> repo=(Dictionary<Integer, Student>) objectInputStream.readObject(); System.out.println(repo.get(1)); objectInputStream.close(); inputStream.close(); }catch (Exception e){ e.printStackTrace();; } } public class Student implements Serializable{ public String name=null; public Student(String name){ this.name=name; } public String toString() { return name.toString(); } } }
unknown
d1223
train
You probably haven't initialized either mapArray or moonGateArray thats why you are getting 0 count. In objective-c calling count on nil object doest not give any exception but instead returns 0. hope that helps! A: However for your count=0, this is straight forward you missed to alloc/init any of the array you used. Are you creating a 2D array or 3D array? It is creating confusion to get your logic? Edit: if your MAIN_APP is always 0, why you need an array, a simple object or instead of storing in 2D array you could have used dictionary. However the entire logic I can guess. And I would like to add one more thing about your naming conventions... Name suffix or prefix your variable with Array, Button etc. you can use "maps", "moonGates", all plural symbolizes its gonna to be an array. A: Most likely you haven't properly initialize your arrays. Make your like easier and change your code a bit to make it easier to read and easier to debug. You don't get points for writing highly nested method calls. It makes your life harder. Split the code up to make things easier. Change this: for (int i = 0; i < 8; i++) { [[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] addObject:[Moongate new]]; } to this: // replace "SomeMapClass" with your actual class name SomeMapClass *mainMap = mapArray[MAIN_MAP]; NSMutableArray *moonArray = mainMap.moonGateArray; for (int i = 0; i < 8; i++) { [moonArray addObject:[Moongate new]]; } Now you can run this code in the debugger or add NSLog statements and verify each step of the process. Is mapArray properly initialized? Is moonArray property initialized? Remember, simply defining a property doesn't actually create the object. You still need to initialize it.
unknown
d1224
train
I don't know why are you all mixing up all things, just keep it easy and clean. Make two files called 'app.py' and 'index.html' and make a folder in your app root dirrectory called "upload" index.html <h1>Upload File</h1> <form action="/uploader" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="Upload"> </form> app.py from flask import Flask, request,render_template from werkzeug import secure_filename import os app = Flask(__name__) uploads_dir = "upload" @app.route("/") def index(): return render_template('index.html') @app.route('/uploader', methods = ['GET', 'POST']) def uploader(): if request.method == 'POST': input = request.files['file'] input.save(os.path.join(uploads_dir, secure_filename(input.filename))) #print(input) return "<h2>Successfully uploaded</h2>" if __name__ == '__main__': app.run() You can also redirect to other page after saving the file: return render_template(otherpage.html) A: It looks like the \a is being interpreted as a control character. You should write the path like this: s = "C:\\Users\\admin\\Desktop\\test" If you're calling .save() you must also close the file: http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.FileStorage.save Also you need to provide a buffer size to .save(). So try: f.save(s, buffer_size=16384) f.close()
unknown
d1225
train
Consider the following code snippet to dynamically change tables: var mainList = [{tableId:1}, {tableId:2}, {tableId:3}] function mainController(){ var vm = this; vm.mainList = mainList; vm.currentIndex = 0; vm.currentTable = currentTable(); function showNext(){ vm.currentIndex++; vm.currentTable = currentTable(); } function currentTable(){ return vm.mainList[currentIndex]; } } <div tableId="{{'table'+currentTable.tableId}}" > <table class="animate-if"> <thead> <tr> <th>Names</th> <th>Address</th> </tr> </thead> <tbody> <tr ng-repeat=" one in currentTable | limitTo: 4 "> <td>{{one.name}}</td> <td>{{one.address}}</td> </tr> </tbody> </table> </div> Next If you really need to have ng-repeat of all available tables and show/hide tables on next press than modify code in such way: var mainList = [{tableId:1}, {tableId:2}, {tableId:3}] function mainController(){ var vm = this; vm.mainList = mainList; vm.currentIndex = 0; vm.currentTable = currentTable(); function showNext(){ vm.currentIndex++; vm.currentTable = currentTable(); } function currentTable(){ return vm.mainList[currentIndex]; } function isActive(table){ var tableIndex = mainList.indexOf(table); return tableIndex === currentIndex; } } <div tableId="{{'table'+currentTable.tableId}}" ng-repeat="table in mainList" ng-if="isActive(table)"> <table class="animate-if"> <thead> <tr> <th>Names</th> <th>Address</th> </tr> </thead> <tbody> <tr ng-repeat=" one in currentTable | limitTo: 4 "> <td>{{one.name}}</td> <td>{{one.address}}</td> </tr> </tbody> </table> </div> <button class="btn " ng-click="showNext() "> Next </button> A: Replace the below code with your appropriate data structures since it is unclear from question. var myApp = angular.module('myApp',[]); //myApp.directive('myDirective', function() {}); //myApp.factory('myService', function() {}); function MyCtrl($scope) { $scope.mainList=[[{name:"dummy1"},{name:"dummy2"}],[{name:"dummy3"},{name:"dummy4"}]]; $scope.count=1; $scope.showNext = function () { $scope.count=$scope.count+1; } } <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="MyCtrl"> <div ng-repeat="oneList in mainList | limitTo: count "> <table class="animate-if"> <thead> <tr> <th>Names</th> </tr> </thead> <tbody> <tr ng-repeat="one in oneList | limitTo: 4 "> <td>{{one.name}}</td> </tr> </tbody> </table> </div> <button class="btn" ng-click="showNext()"> Next </button> </div> A: After some workaround I found the answer what I was looking for. Thanks to @Ihor Korotenko. One modification in html file is "ng-show" attribute. <div ng-init="outerIndex=($index)" tableId="{{'table'+outerIndex}}" ng-repeat="oneList in mainList" ng-show="oneList.flagValue"> <table class="animate-if"> <thead> <tr> <th>Names</th> <th>Address</th> </tr> </thead> <tbody> <tr ng-repeat=" one in oneList | limitTo: 4 "> <td>{{one.name}}</td> <td>{{one.address}}</td> </tr> </tbody> </table> </div> <button class="btn " ng-click="more()"> More </button> <button class="btn " ng-click="less()"> Less </button> Now here is the jQuery code: $scope.getValueFromSvc= function ($index) { Service.myMethod().then(function (response) { var total = response.responseData; var mainList= []; // contains all oneList var oneList = []; //contain one table $.each(total, function (i, value){ // iterate data here to put in oneList then mainList } }); // assigning flag which will be helpful on applying condition in next jQuery segment $.each(mainList, function (i, value) { if (i == 0) value.flagValue = true; else value.flagValue = false; }); $scope.mainList = mainList; }); } And finally to show table on button click jQuery goes like... $scope.more = function () { $.each($scope.mainList, function (i, value) { if (!value.flagValue) { value.flagValue = true; return false; } }); }; $scope.less = function () { for (var v = $scope.mainList.length - 1; v > 0; v--){ if ($scope.mainList[v].flagValue) { $scope.mainList[v].flagValue = false; break; } } };
unknown
d1226
train
If you can control other server output, put header: Access-Control-Allow-Origin: * in http response, and load with ajax without plugins or using YQL https://developer.mozilla.org/en/HTTP_access_control A: It looks like the plugin is making a JSONP request via YQL (see line 18 here). If you load up Firebug or the developer tools in Chrome, do you see the JSONP request being made?
unknown
d1227
train
Z") ' Define your own range here If strPattern <> "" Then ' If the cell is not empty If regEx.Test(Cell.Value) Then ' Check if there is a match Cell.Interior.ColorIndex = 6 ' If yes, change the background color End If End If Next A: I have made the Changes. * *Use Find function to locate the column. used cnum for that *Use Worksheets("Consolidated") without the . *Pass the column number found to the loop range Dim strPattern As String: strPattern = "[^a-z0-9-]" Dim regEx As Object Dim Cell As Range Dim cnum As Integer Set regEx = CreateObject("VBScript.RegExp") regEx.Global = True regEx.IgnoreCase = True regEx.Pattern = strPattern cnum = Worksheets("Consolidated").Range("A1:Z1").Find("First Name").Column 'column number to search in For Each Cell In Worksheets("Consolidated").Range(Cells(2, cnum), Cells(1000, cnum)) If strPattern <> "" Then ' If the cell is not empty If regEx.Test(Cell.Value) Then ' Check if there is a match Cell.Interior.ColorIndex = 6 ' If yes, change the background color End If End If Next
unknown
d1228
train
If you get an exception, that means you cannot represent your value as an double within specified error range. In other words, the maxRelErrDbl is too small. Try with maxRelErrDbl = 0,0000000001 or something to test if I am right.
unknown
d1229
train
Off the top of my head... If the determinant is 0 then the matrix cannot be inverted, which can be useful to know. If the determinant is negative, then objects transformed by the matrix will reversed as if in a mirror (left handedness becomes right handedness and vice-versa) For 3x3 matrices, the volume of an object will be multiplied by the determinant when it is transformed by the matrix. Knowing this could be useful for determining, for example, the level of detail / number of polygons to use when rendering an object. A: In 3D vector graphics there are used 4x4 homogenuous transform matrices and we need booth direct and inverse matrices which can be computed by (sub)determinants. But for orthogonal matrices there are faster and more accurate methods like * *full pseudo inverse matrix. Many intersection tests use determinants (or can be converted to use them) especially for quadratic equations (ellipsoids,...) for example: * *ray and ellipsoid intersection accuracy improvement as Matt Timmermans suggested you can decide if your matrix is invertible or left/right handed which is useful to detect errors in matrices (accuracy degradation) or porting skeletons in between formats or engines etc. And I am sure there area lot of other uses for it in vector math (IIRC IGES use them for rotational surfaces, cross product is determinant,...) A: The incircle test is a key primitive for computing Voronoi diagrams and Delaunay triangulations. It is given by the sign of a 4x4 determinant. (picture from https://www.cs.cmu.edu/~quake/robust.html)
unknown
d1230
train
Im sure this answer is here already but i will post a generic code i always use. Just place the whole block and change related values, swf properties. <object id="FlashID" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="950" height="377"> <param name="movie" value="myMovie.swf"> <param name="quality" value="high"> <param name="wmode" value="direct" > <param name="swfversion" value="6.0.65.0"> <!-- This param tag prompts users with Flash Player 6.0 r65 and higher to download the latest version of Flash Player. Delete it if you don’t want users to see the prompt. --> <param name="expressinstall" value="Scripts/expressInstall.swf"> <param name="SCALE" value="noborder"> <!-- Next object tag is for non-IE browsers. So hide it from IE using IECC. --> <!--[if !IE]>--> <object type="application/x-shockwave-flash" data="myMovie.swf" width="950" height="377"> <!--<![endif]--> <param name="quality" value="high"> <param name="wmode" value="direct" > <param name="swfversion" value="6.0.65.0"> <param name="expressinstall" value="Scripts/expressInstall.swf"> <param name="SCALE" value="noborder"> <!-- The browser displays the following alternative content for users with Flash Player 6.0 and older. --> <div> <h4>Content on this page requires a newer version of Adobe Flash Player.</h4> <p><a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></p> </div> <!--[if !IE]>--> </object> <!--<![endif]--> </object>
unknown
d1231
train
i solve this problem by this code PendingIntent receiveCallPendingIntent; PendingIntent cancelCallPendingIntent; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) { receiveCallPendingIntent = PendingIntent.getBroadcast(this, 1200, receiveCallAction, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); cancelCallPendingIntent = PendingIntent.getBroadcast(this, 1201, cancelCallAction, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); }else{ receiveCallPendingIntent = PendingIntent.getBroadcast(this, 1200, receiveCallAction, PendingIntent.FLAG_UPDATE_CURRENT); cancelCallPendingIntent = PendingIntent.getBroadcast(this, 1201, cancelCallAction, PendingIntent.FLAG_UPDATE_CURRENT); } also add this permission for force Android 12^ (AndroidManifest.xml) <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /><receiver android:name=".receiver.CallReceiver" android:exported="false" android:enabled="true" android:permission="android.permission.RECEIVE_BOOT_COMPLETED" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </receiver>
unknown
d1232
train
As stated in the documentation, The path-style syntax, however, requires that you use the region-specific endpoint when attempting to access a bucket. In other words, with path style access, you've to tell to the SDK in which region is the bucket, it doesn't try to determine it on its own. Performance wise, there should not be a difference. A: If you need the client to access objects in different region, you probably want to use the option: AmazonS3ClientBuilder builder.withForceGlobalBucketAccessEnabled(true) to build your client... See the s3 client builder documentation this with ensure successful requests even if the client default region is not the same as the bucket/object targeted. Also, if you need to get the bucket "mybucketname" exact end-point, you can use (headBucketResult ref page): s3client.headBucket(HeadBucketRequest("mybucketname")).getBucketRegion()
unknown
d1233
train
You have not specified the size of the data member of struct scs_data_tag. This declares a C99 flexible array member. This member has size 0 by default, and you'd need to malloc more than the actual struct size in order for it to be able to contain data. According to the standard, it should not be possible for struct scs_data_tag to be an element of an array (because it contains a flexible array member). But this is supported by some compilers as an extension. If you instead give this array a large enough size (e.g. char data[40]), your code should work. A: Adding to interjay's answer,. You see adsafe_tags[1].key_size = 11888 which is 0x2e70 in hex, which denotes ASCII characters p (= 0x70) and . (= 0x2e), therefore "p.". Similarly, adsafe_tags[1].val_size = 29537, which is 0x7361 or "as", rest is printed correctly as a string. This shows that no space is allocated to adsafe_tags[0].data. The string you provided for initializing it got mapped to next data set.
unknown
d1234
train
You could use an EnumMap (smaller and faster then a HashMap), like this: enum Key { KEY_001, .... } EnumMap<Key, Runnable> enumMap = new EnumMap<>(Key.class); enumMap.put(Key.KEY_001, YourClass::translate001); .... And usage: enumMap.get(someKey).run();
unknown
d1235
train
LibGDX uses real-pixel-to-screen-pixel mapping. You're using an ExtendViewport to initialize the game, which takes its minimum height and width from the actual window size in Gdx.graphics.getWidth(), Gdx.graphics.getHeight(). This means that the 'fake screen' you have, which you can then resize as much as you want, is actually determined by the size of the window. I would advise you start with a fixed size for the ExtendViewport - say, 600 width, 400 height - and later you can change this to suit different sizes if necessary. ExtendViewport with fixed sizes works fantastically well, even when displaying on extremely large screens. A: It works smoothly once I calculate and set the desired button manually. Width and height are calculated depending on screen size. I changed this: table.add(textButton1).expandX().pad(padding); to this: float buttonWidth = Gdx.graphics.getWidth()/2 * 0.9f; float buttonHeight = buttonWidth * 1.3f; table.add(textButton1).width(buttonWidth).height(buttonHeight).expandX().pad(padding);
unknown
d1236
train
I managed to solve this for whoever needs something similar. However, I think this way is inefficient and I would love for someone to tell me a better method. I first ran this SQL query: WITH CTE_Make AS ( SELECT [Year], [Make] FROM VehicleInformation GROUP BY [Year], [Make] ) SELECT ( SELECT [Year] AS Year, STRING_AGG([Make],',') AS MakeList FOR JSON PATH, WITHOUT_ARRAY_WRAPPER) FROM CTE_Make GROUP BY [Year] This gave me the JSON in a different format from what I wanted. I stored this in a file "VehicleInformationInit.json", and loaded it in JS as variable vehicleInfoInitJsonFile and ran the following code in JavaScript: var dict = {}; $.getJSON(vehicleInfoInitJsonFile, function (result) { result.forEach(x => { var makeList = x.MakeList.split(','); dict[x.Year] = makeList; }) var newJSON = JSON.stringify(dict); }); I simply copied the contents of newJSON by attaching a debugger into my required file. However, you can easily use fs and store it in a file if you want to.
unknown
d1237
train
So the way the new embedded DNS "server" works is that it isn't a formal server. It's just an embedded listener for traffic to 127.0.0.11:53 (udp of course). When docker sees that query traffic on the container's network interface, it steps in with its embedded DNS server and replies with any answers it might have to the query. The documentation has some options you can set to affect how this DNS server behaves, but since it only listens for query traffic on that localhost address, there is no way to expose this to an overlay network in the way that you are thinking. However this seems to be a moving target, and I have seen this question before in IRC, so it may one day be the case that this embedded DNS server at least becomes pluggable, or possibly exposable in the way you would like.
unknown
d1238
train
Before dealing with menu items, let's start saying that a ContextMenu is a popup window, so it has Windowproperties. You can ask for (x,y) left, top origin, and for (w,h). But you have to take into account the effects, since by default it includes a dropshadow. And when it does, there's an extra space added of 24x24 pixels to the right and bottom. .context-menu { -fx-effect: dropshadow( gaussian , rgba(0,0,0,0.2) , 12, 0.0 , 0 , 8 ); } Since this default dropshadow has a radius of 12px, and Y-offset to the bottom of 8px, the right and bottom coordinates of the context menu, including the 24x24 area, are given by: X=t.getX()+cm.getWidth()-12-24; Y=t.getY()+cm.getHeight()-(12-8)-24; where t could be a MouseEvent relative to the scene, and values are hardcoded for simplicity. Let's see this over an example. Since you don't say how your custom menu items are implemented, I'll just create a simple Menu Item with graphic and text: private final Label labX = new Label("X: "); private final Label labY = new Label("Y: "); @Override public void start(Stage primaryStage) { final ContextMenu cm = new ContextMenu(); MenuItem cmItem1 = createMenuItem("mNext", "Next Long Option",t->System.out.println("next")); MenuItem cmItem2 = createMenuItem("mBack", "Go Back", t->System.out.println("back")); SeparatorMenuItem sm = new SeparatorMenuItem(); cm.getItems().addAll(cmItem1,cmItem2); VBox root = new VBox(10,labX,labY); Scene scene = new Scene(root, 300, 250); scene.setOnMouseClicked(t->{ if(t.getButton()==MouseButton.SECONDARY || t.isControlDown()){ // t.getX,Y->scene based coordinates cm.show(scene.getWindow(),t.getX()+scene.getWindow().getX()+scene.getX(), t.getY()+scene.getWindow().getY()+scene.getY()); labX.setText("Right X: "+(t.getX()+cm.getWidth()-12-24)); labY.setText("Bottom Y: "+(t.getY()+cm.getHeight()-4-24)); } }); scene.getStylesheets().add(getClass().getResource("root.css").toExternalForm()); primaryStage.setScene(scene); primaryStage.show(); primaryStage.setTitle("Scene: "+scene.getWidth()+"x"+scene.getHeight()); } private MenuItem createMenuItem(String symbol, String text, EventHandler<ActionEvent> t){ MenuItem m=new MenuItem(text); StackPane g=new StackPane(); g.setPrefSize(24, 24); g.setId(symbol); m.setGraphic(g); m.setOnAction(t); return m; } If you remove the effect: .context-menu { -fx-effect: null; } then these coordinates are: X=t.getX()+cm.getWidth(); Y=t.getY()+cm.getHeight(); Now that we have the window, let's go into the items. MenuItem skin is derived from a (private) ContextMenuContent.MenuItemContainer class, which is a Region where the graphic and text are layed out. When the context menu is built, all the items are wrapped in a VBox, and all are equally resized, as you can see if you set the border for the item: .menu-item { -fx-border-color: black; -fx-border-width: 1; } This is how it looks like: So the X coordinates of every item on the custom context menu are the same X from their parent (see above, with or without effect), minus 1 pixel of padding (by default). Note that you could also go via private methods to get dimensions for the items: ContextMenuContent cmc= (ContextMenuContent)cm.getSkin().getNode(); System.out.println("cmc: "+cmc.getItemsContainer().getBoundsInParent()); Though this is not recommended since private API can change in the future. EDIT By request, this is the same code removing lambdas and css. private final Label labX = new Label("X: "); private final Label labY = new Label("Y: "); @Override public void start(Stage primaryStage) { final ContextMenu cm = new ContextMenu(); MenuItem cmItem1 = createMenuItem("mNext", "Next Long Option",action); MenuItem cmItem2 = createMenuItem("mBack", "Go Back", action); SeparatorMenuItem sm = new SeparatorMenuItem(); cm.getItems().addAll(cmItem1,cmItem2); VBox root = new VBox(10,labX,labY); Scene scene = new Scene(root, 300, 250); scene.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent t) { if(t.getButton()==MouseButton.SECONDARY || t.isControlDown()){ // t.getX,Y->scene based coordinates cm.show(scene.getWindow(),t.getX()+scene.getWindow().getX()+scene.getX(), t.getY()+scene.getWindow().getY()+scene.getY()); labX.setText("Right X: "+(t.getX()+cm.getWidth()-12-24)); labY.setText("Bottom Y: "+(t.getY()+cm.getHeight()-4-24)); } } }); primaryStage.setScene(scene); primaryStage.show(); primaryStage.setTitle("Scene: "+scene.getWidth()+"x"+scene.getHeight()); } private MenuItem createMenuItem(String symbol, String text, EventHandler<ActionEvent> t){ MenuItem m=new MenuItem(text); StackPane g=new StackPane(); g.setPrefSize(24, 24); g.setId(symbol); SVGPath svg = new SVGPath(); svg.setContent("M0,5H2L4,8L8,0H10L5,10H3Z"); m.setGraphic(svg); m.setOnAction(t); return m; } private final EventHandler<ActionEvent> action = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { System.out.println("action"); } };
unknown
d1239
train
Your code won't work but the error you get is wrong so you should ignore it. The real problem is you can't just blindly call init() on the type of an Any. There are a lot of types that don't have an init() at all. It works on type(of: s) in your first example because the compiler knows at compile-time that the type is String (and that String has an init()). But if you wrap it in Any then it fails as well: let s = String("Foo") as Any let typeClone = type(of: s).init() Unfortunately this means there's no way to do what you're trying to do.
unknown
d1240
train
For the 3rd case, you did not use the MOUSEEVENTF_MOVE flag to move the mouse, so the mouse did not actually move. And also according to the document: If MOUSEEVENTF_ABSOLUTE value is specified, dx and dy contain normalized absolute coordinates between 0 and 65,535 void mouseMove(int x, int y) { INPUT move[2] = {}; DWORD fScreenWidth = ::GetSystemMetrics(SM_CXSCREEN); DWORD fScreenHeight = ::GetSystemMetrics(SM_CYSCREEN); move[0].type = move[1].type = INPUT_MOUSE; move[0].mi.dwFlags = MOUSEEVENTF_LEFTUP;// Release the mouse before moving it move[1].mi.dx = MulDiv(x, 65535, fScreenWidth); move[1].mi.dy = MulDiv(y, 65535, fScreenHeight); move[1].mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE; SendInput(2, move, sizeof(INPUT)); } Then use the MOUSEEVENTF_LEFTDOWN and MOUSEEVENTF_LEFTUP to click the current postion. Or you can directly merge the mouse move into the click event: void mouseMoveClick(int x, int y) { INPUT click[3] = {}; click[0].type = INPUT_MOUSE; click[0].mi.dwFlags = MOUSEEVENTF_LEFTUP;// Release the mouse before moving it DWORD fScreenWidth = ::GetSystemMetrics(SM_CXSCREEN); DWORD fScreenHeight = ::GetSystemMetrics(SM_CYSCREEN); click[1].type = INPUT_MOUSE; click[1].mi.dx = click[2].mi.dx= MulDiv(x, 65535, fScreenWidth); click[1].mi.dy = click[2].mi.dy= MulDiv(y, 65535, fScreenHeight); click[1].mi.dwFlags = MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE; click[2].type = INPUT_MOUSE; click[2].mi.dwFlags = MOUSEEVENTF_LEFTUP | MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE; SendInput(3, click, sizeof(INPUT)); } If you want to move back to the original position after the mouse click, you can use GetCursorPos to record the current position before moving. Then use mouseMove event or simpler SetCursorPos to return to the position. void click(int xCord, int yCord) { //mouseMove(xCord, yCord); POINT p = {}; GetCursorPos(&p); mouseMoveClick(xCord, yCord); SetCursorPos(p.x, p.y); }
unknown
d1241
train
I would suggest using an integration-test for testing your controller rather than a unit-test. integration-test threats the app as a black box where the network is the input (HTTP request) and 3rd party services as dependency that should be mocked (DB). * *Use unit-test for services, factories, and utils. *Use integration-test for external interfaces like HTTP and WebSockets You can add e2e-test as well but if you have only one component in your setup you integration-test will suffice.
unknown
d1242
train
If I understand what you're attempting, I think you can extend DynamicObject to achieve this. class Proxy : System.Dynamic.DynamicObject { public Proxy(object someWrappedObject) { ... } public override bool TryInvokeMember(System.Dynamic.InvokeMemberBinder binder, object[] args, out object result) { // Do whatever, binder.Name will be the called method name } } //Do whatever... would become some code that pokes at some other object's internal members (via reflection, presumably) using binder.Name as part of the lookup process. There are TryGetMember and TryGetIndex methods to override if you need to wrap up anything fancier that simple method invokes. You will have to cast instances of Proxy to dynamic after construction to make arbitrary calls, just like when dealing with ExpandoObject. A: You could leverage inheritance and have your tests defined in an abstract base class with a factory method to create your selenium instance, then inherit this for each type of browser you want to model. The tests will then be run for each inherited class with the appropriate browser. Using NUnit as an example: public abstract class AbstractTests { protected abstract DefaultSelenium CreateSelenium(); [Test] public void TestSomethingA() { DefaulSelenium selenium = CreateSelenium(); //Do some testing with selenium. } } [TestFixture] public class IETests : AbstractTests { protected override DefaultSelenium CreateSelenium() { return new DefaultSelenium("iexplore"); } } [TestFixture] public class FirefoxTests : AbstractTests { protected override DefaultSelenium CreateSelenium() { return new DefaultSelenium("firefox"); } }
unknown
d1243
train
Assuming eventtimes is a cell array of strings, you can do this: eventtimes={'0h 0m 19.72s' '0h 1m 46s' '0h 6m 45.9s' '0h 6m 53.18s'}; for i=1:length(eventtimes) %// Read each line of data individually M(i,:)=sscanf(eventtimes{i},'%d%*s%d%*s%f%*s').'; end s=(M(:,1)*60+M(:,2))*60+M(:,3) %// Convert into seconds which gives s = 19.7200 106.0000 405.9000 413.1800 A: With respect to the answer provided by @David, the last line of code: s=(M(:,1)*24+M(:,2))*60+M(:,3) %// Convert into seconds should be: s=(M(:,1)*60+M(:,2))*60+M(:,3) %// Convert into seconds Since M(:,1) contains hours, to convert them into seconds, they have to be multiplied by 3600 (60 min. * 60 sec.) The expected resuls as described in the question and the ones provided by @David seem correct only because all input have "0h". In case any of the input times last more than 1h, the results will be: 0h 0m 19.72s 2h 1m 46s 3h 6m 45.9s 0h 6m 53.18s s= 19.72 7306.00 11205.90 413.18 Hope this helps. A: I've found a solution using etime that bypasses the "between" function and its odd calendarDuration type output: %read in with fractions times=datetime(myCellArray(:,1),'InputFormat','HH:mm:ss.SS'); %turn into datevectors (uses today's date: works as long as midnight isn't crossed) timevect=datevec(times); %separate start time from subsequent times starttime=timevect(1,:); othertimes=timevect(2:end,:); %use etime with repmat of starttime to get differences: relativetimes=etime(othertimes,repmat(starttime,[size(othertimes,1) 1])); relativetimes(1:4) ans = 19.72 106 405.9 413.18
unknown
d1244
train
Please, forget pointers here. getTerritories() was returning a pointer to a local object. This object is destroyed after the function return. You just need to return the object and you'll then find in back in your generatedTeritories variable. class Map { public: Map(); vector<Territory> getTerritories(); }; vector<Territory> Map::getTerritories() { vector<Territory> t; for (int i = 0; i < 8; i++) { Territory ter; ter.setName("Territory " + std::to_string(i + 1)); t.push_back(ter); } return t; } void GameSetup::assignTerritories() { vector<Territory> generatedTeritories = (*map).getTerritories(); // dereferenced } Now you can get the address of the vector like that: vector<Territory>* addressOfGeneratedTeritories = &generatedTeritories; But it's only safe to use it while generatedTeritories remains alive (in the code above, it's alive untill assignTerritories() execution ends as it is a local variable of this function). To make it persistent, it has to be an attribute of another object...it will then remain alive untill the parent object gets destroyed...and so on. It could allso be a global variable which is definitely not recommended (it's a bad practice, object oriented design always have alternatives to that). BTW, I would recommend that you follow some tutorials about C++ before starting to code a game.....;-)
unknown
d1245
train
AR/SQL (faster): Review.select("rating").where(:reviewable_id => self.reviewable_id).sum(:rating) Ruby (slower): Review.select("rating").where(:reviewable_id => self.reviewable_id).map(&:rating).sum A: How about just doing this: def calculate_rating all_rating = Review.select(:rating).where(:reviewable_id => reviewable_id).map(&:rating) all_rating.inject(:+) # or you could just do all_rating.sum end
unknown
d1246
train
Suppose you deploy your app.config with this connectionstring "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\yourFile.accdb;" In a WinForms application the |DataDirectory| shortcut represent your application working folder, but you can change at runtime where it points to using this code. // appdomain setup information AppDomain currentDomain = AppDomain.CurrentDomain; //Create or update a value pair for the appdomain currentDomain.SetData("DataDirectory", "Your user choosen path"); It eliminates the need to hard-code the full path which, has you have discovered, leads to several problems to resolve during install. Of course your setup should deliver your database in your user choosen path. A: You can build ConnectionString at run-time by SqlConnectionStringBuilder // Create a new SqlConnectionStringBuilder and // initialize it with a few name/value pairs. SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(GetConnectionString()); // The input connection string used the // Server key, but the new connection string uses // the well-known Data Source key instead. Console.WriteLine(builder.ConnectionString); // Pass the SqlConnectionStringBuilder an existing // connection string, and you can retrieve and // modify any of the elements. builder.ConnectionString = "server=(local);user id=ab;" + "password= a!Pass113;initial catalog=AdventureWorks"; // Now that the connection string has been parsed, // you can work with individual items. Console.WriteLine(builder.Password); builder.Password = "new@1Password"; builder.AsynchronousProcessing = true; // You can refer to connection keys using strings, // as well. When you use this technique (the default // Item property in Visual Basic, or the indexer in C#), // you can specify any synonym for the connection string key // name. builder["Server"] = "."; builder["Connect Timeout"] = 1000; builder["Trusted_Connection"] = true; Console.WriteLine(builder.ConnectionString); Console.WriteLine("Press Enter to finish."); Console.ReadLine(); Edit: you can use this : Finding SQL Servers on the Network A: I have met this problem before. I solve it in such a way. (1)in your app.config file, put a placeholder in the connection string. the connection string will contains the file path of the access db file. replace the path with a special string. <connectionStrings> <!-- original connection string , change it to the below line --> <!-- <add name="test" connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=d:\test\test.mdb "/> --> <add name="test" connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=##path##\test.mdb "/> </connectionStrings> (2)when your application start, use Directory.GetCurrentDirectory to get app path. before create a connection, replace the ##path## with the actual path on client computer. static void test() { string s = ConfigurationManager.ConnectionStrings["test"].ConnectionString; s.Replace("##path##", Directory.GetCurrentDirectory()); OleDbConnection conn = new OleDbConnection(s); } A: In case of deploying the application, along with SQLLocalDB, the user (machine\user) should be added in your database to have access.
unknown
d1247
train
auth = str(base64.b64encode(bytes(f'{self.user}:{self.password}', "utf-8")), "ascii").strip() You may not be using the f-string correctly, change f'{self.user, self.password}' to f'{self.user}:{self.password}' More info
unknown
d1248
train
It means that dnx cannot find Startup.cs file. Try to run dnx . kestrel inside folder which contains Startup.cs
unknown
d1249
train
You should be updating the underlying dataset that is passed to the adapter before calling notifyDatasetChanged(); EG: For ArrayAdapter in a ListActivity ("arraylist" is the ArrayList you've used to back your ArrayAdapter) arraylist.add(data); arrayadapter = this.getListAdapter(); arrayadapter.notifyDatasetChanged(); A: Personally, everytime user like press refresh button i repopulate listView initializing Cursor again. Like this: calling this function... public void repopulateListView(){ cursor = dbHelper.fetchAll(); columns = new String[] { DBAdapter.KEY_NAME, DBAdapter.KEY_DATE, DBAdapter.KEY_VOTE, DBAdapter.KEY_CREDIT }; to = new int[] { R.id.one, R.id.two, R.id.three, R.id.four }; dataAdapter = new SimpleCursorAdapter( getActivity(), R.layout.YOUR_ID, cursor, columns, to, 0) { @Override public View getView(int position, View convertView, ViewGroup parent) { final View row = super.getView(position, convertView, parent); } } } ...from Refresh onClick: @Override public void onClick(View view) { switch (view.getId()){ case R.id.refresh:{ repopulateListView(); break; } } }
unknown
d1250
train
$(document).ready(function() { $(".reply").click(function(event) { event.preventDefault(); $('.placeholder').html(''); var form = '<form id="rform" action="/sendme" method="POST"><input class="title" name="title" type="text" /><textarea rows="8" name="body"></textarea><input type="submit" value="Submit"></form>'; $(".placeholder").append(form); $("input.title").focus(); }); }); input, textarea { display: block; width: 100%; margin-top: 10px; box-sizing: border-box; } form { max-width: 400px; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a class="reply" href="#">Reply</a> <div class="placeholder"></div> First , if you donot want it to scroll to top. Use the event.preventDefault(); Second , use $('.placeholder').html(''); if you donot want repeated comment form on click. third , $("input.title").focus(); works just fine. Already tested A: Use this code it works $("[data-scroll-to]").click(function() { var form = '<form id="rform" action="/sendme" method="POST"><input class="title" id="id2" name="title" type="text" /><textarea rows="8" name="body"></textarea><input type="submit" value="Submit"></form>'; $("#id1").append(form); var $this = $(this), $toElement = $this.attr('data-scroll-to'), $focusElement = $this.attr('data-scroll-focus'), $offset = $this.attr('data-scroll-offset') * 1 || 0, $speed = $this.attr('data-scroll-speed') * 1 || 500; $('html, body').animate({ scrollTop: $($toElement).offset().top + $offset }, $speed); if ($focusElement) $($focusElement).focus(); }); https://codepen.io/Thaks123/pen/byWmGo?editors=1111 It works with scroll also. A: The page is jumping to the top because you are navigating to an anchor. Remove href="#" from the reply link. You could replace it with href="javascript:void(0);" You should then be able to use .focus() to position the page where you like.
unknown
d1251
train
You must use the capistrano/bundler gem to get the bundler tasks (like bundle install) in your deploy. Basically, you must add the capistrano/bundler in your Gemfile and require it in your Capfile using the command below: require 'capistrano/bundler' Thereby the Capistrano will run the bundle install task during the deploy and this problem will be solved.
unknown
d1252
train
We recently published a PESQ variant for the PyTorch framework, you can find it here: https://github.com/audiolabs/torch-pesq This allows you to use an perceptual metric for wideband speech quality in context of deep learning and generate gradients for your training. A: Measurements of audio quality or asthetic is done both with and without machine learning. However most of the work focuses on speech reproduction, much less on general audio. One can conduct listening tests, where a panel of human asessors listen to audio and give their score, to establish a Mean Opinion Score (MOS). There exists several standards for conducting these, such as MUSHRA. Such subjective scores form the basis of developing "objective metrics", which are algorithmic ways to estimate qualities of the audio. Some early examples are PESQ for Speech Quality (ITU standard since 2001) and PEAQ for Audio Quality (ITU standard since 1998). More advanced include POLQA (ITU standard since 2011) and ViSQOLAudio (proposed in research). The last years several papers have shown that one can learn such metrics using deep neural networks. For speech quality, one recent paper (2019) is Intrusive and Non-Intrusive Perceptual Speech Quality Assessment Using a Convolutional Neural Network. The only learned evaluation I have found for general Audio Quality or music quality is Fréchet Audio Distance.
unknown
d1253
train
Edit: This issue was fixed by this PR which appears to have first landed in Flutter 1.22.0. It took some sleuthing, but I eventually found the mechanism for this behavior. TextField wraps EditableText. When the latter gains focus, it will invoke _showCaretOnScreen, which includes a call to renderEditable.showOnScreen. This bubbles up and eventually causes the scrolling behavior. We can force _showCaretOnScreen to return early here if we supply to the TextField a hacked ScrollController that always returns false from hasClients: class _HackScrollController extends ScrollController { // Causes early return from EditableText._showCaretOnScreen, preventing focus // gain from making the CustomScrollView jump to the top. @override bool get hasClients => false; } The behavior does not seem intentional, so I reported it as bug #60422. Caveats This workaround may not be very stable. I don't know what adverse effects the hasClients override might have. The docs for TextField say that the scrollController is used "when vertically scrolling the input". In this use case we don't want vertical scrolling anyway, so the workaround might not cause any problems. In my brief testing it didn't seem to cause problems with horizontal (overflow) scrolling. A: Just like the documentation mentions try and use resizeToAvoidBottomInset parameter to false (defaults to true) in the scaffold widget https://api.flutter.dev/flutter/material/Scaffold/resizeToAvoidBottomInset.html Also I would recommend creating ValueListenableBuilder after the scaffold (as the first widget in the body) to avoid rebuilding the whole scaffold and just the body widget
unknown
d1254
train
You need the C# code to receive a pointer. Like this: [DllImport("MyDLL.dll")] static extern uint getSampleFunctionValue(out IntPtr argument); Call it like this: IntPtr argument; uint retval = getSampleFunctionValue(out argument); // add a check of retval here string argstr = Marshal.PtrToStringUni(argument); And you'll also presumably need to then call the native function that deallocates the memory that it allocated. You can do that immediately after the call to Marshal.PtrToStringUni because at that point you no longer need the pointer. Or perhaps the string that is returned is statically allocated, I can't be sure. In any case, the docs for the native library will explain what's needed. You may also need to specify a calling convention. As written, the native function looks like it would use __cdecl. However, perhaps you didn't include the specification of __stdcall in the question. Again, consult the native header file to be sure.
unknown
d1255
train
Moving declaration of case class out of scope did the trick! Code structure will then be like: package main.scala.UserAnalytics // case class *outside* the main object case class User(name: string, dept: String) object UserAnalytics extends App { ... ds = df.map { row => User(row.getString(0), row.getString(1)) } }
unknown
d1256
train
Just write the fields you want to change and the new values ​​separated by commas. const id= req.params.id; const email = "newemail"; const date = "1991/13/01"; const user = await User.findByIdAndUpdate( { _id: id, }, { email, registrationDate: date}, { upsert: false } );
unknown
d1257
train
My guess would be that _c.getWorld() returns a null object on which you call a method. Hence the NullPointerException.
unknown
d1258
train
onRowClick={(rows)=>{selectComponents(rows.id)}} This is the answer. Now when I click a row, it will return the row id as an argument in my function. Now I can simply click a row and use that info to open a dataform modal that comes pre-filled out with info that can change and then either be pushed to the database or canceled without saving
unknown
d1259
train
First, please remove already created .netrc files with this command. sed -i '' '/^machine api.mydomain.com$/{N;N;d;}' ~/.netrc Then Try To create new .netrc file with this steps: To create .netrc file do next Fire up Terminal cd ~ (go to the home directory) touch .netrc (create file) open .netrc (open .netrc) Set required data. Save .netrc file should be like this machine api.mapbox.com login mapbox password <secret_key_created_from_your_mapbox_account> May be it will help to you. If Its Help then please upvote to my answer.
unknown
d1260
train
I am not able understand it very clearly because of language barrier But if you have a arraylist you can call sort method on it an pass a comparator to get the desired sorting , something like below. It is just to give you an idea ArrayList<String> list = new ArrayList<>(); list.sort(new Comparator() { @Override public int compare(Object o1, Object o2) { if(o1.account.equals(o2.account)) return 0; return o1.amount - o2.amount; } }); as Lambda ArrayList<String> list = new ArrayList<>(); list.sort((o1,o2) -> if(o1.account.equals(o2.account)) return 0; return o1.amount - o2.amount; }); A: Thank you everyone for the comments. Next time i'll translate the Spanish code to English. I'll post my solution incase someone comes across this question. (in my case I had to use a comparable interface and a compareTo method). @Override public int compareTo(Account anAccount) { String b = this.title.toString(); Client aTitle = anAccount.title; String c = aTitle.toString(); if(b.compareTo(c) == 0) { if(balance == anAccount.balance) { return 0; } else if (balance < anAccount.balance) { return 1; } else { return -1; } } return b.compareTo(c); } As stated, I had to compare both object values first, if they are the same I then check the condition of the balance to change the order. -1 = object is less than the parameter. 0 = when both objects are the same. 1 = the object is more than the parameter. And I called the method from the Bank.java class with: Collections.sort(cuentas); Where cuentas is the ArrayList.
unknown
d1261
train
I see 2 options here: * *You have a break that gets executed where it is says My code with conditions here. *rp doesn't return a Promise. As for the second option, here's a quick code to show you that the final line of an async function gets executed only when all awaits are finished: const delay = (ms) => { return new Promise(r => { setTimeout(r, ms); console.log("delayed", ms); }); } const run = async () => { for (var i = 0; i < 3; i++) { await delay(1000); } console.log("finished"); } run();
unknown
d1262
train
Does moving the X-UA-Compatible tag to be immediately underneath the tag make a difference? See answer by neoswf: X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode Cheers,
unknown
d1263
train
try: function goto() { document.getElementById("iframe").src = document.getElementById('webLinks').options[document.getElementById('webLinks').selectedIndex].text; } A: you have a js error, edit following function function goto() { document.getElementById("iframe").src = document.getElementsByTagName("option")[1].value; } or common approach function goto() { document.getElementById("iframe").src = document.getElementById('webLinks').options[document.getElementById('webLinks').selectedIndex].text; }
unknown
d1264
train
In Windows, you must open the file in binary mode by adding the _O_BINARY flag: fd = open(argv[1], O_RDONLY | _O_BINARY, 0) If you don't, the C++ runtime will perform translations on the contents of the file as it's read in. The most obvious result will be to remove all the \r characters from the input, but an even greater danger is that it will signal end-of-file when it reads \x1a and you'll stop prematurely. The first is an attempt to normalize the line-endings between text files on the *nix systems where C was first developed (which uses \n by itself), and text files on Windows (which uses the pair \r\n). The second is backwards compatibility run amok, retaining a convention that existed before DOS when file sizes couldn't be specified in blocks less than 128 characters.
unknown
d1265
train
If you are using Word 2003 or 2007 you can convert xhtml documents to Word Xml documents using xslt. If you google for html to docx xsl you will find many examples of the opposite (converting docx to html) so you might one of those examples as a basis for a conversion. The only challenge would be downloading and embedding the images in the document, but that is also possible. A: There are several possibilities for converting HTML to RTF. These links should get you started: * *DocFrac, conversion between HTML, RTF and text. Free, runs on Windows. *XHTML2RTF: An HTML to RTF conversion tool based on XSL *Writing an RTF to HTML converter Converting to MS Word .doc is much harder and probably not worthwhile for you. For the reasons this is such a pain, read Joel's interesting article on .doc. If you have to write .doc for some reason, COM interop with MSOffice is probably your best bet.
unknown
d1266
train
You have an unclosed tag somewhere on your page. This results in the browser not being able to parse the DOM properly, resulting in your script tag not being "rendered". Chrome has some better error handling for cases like that, which makes it work in that browser. Also, there's a typo: scr="./js/web3.min.js" Should be src="./js/web3.min.js"
unknown
d1267
train
You need to change that condition to only execute the code if it matches the cell address, rather than not execute the code unless the address is matched. This will allow you to add further conditions matched on cell address. I'd recommend changing a hard-coded cell address like "$C$37" to a named range and that named range should ideally be unique throughout the workbook. arCases = Array("Term", "Indeterminate", "Transfer", "Student", "Term extension", "As required", "Assignment", "Indéterminé", "Mutation", "Selon le besoin", "Terme", "prolongation du terme", "affectation", "Étudiant(e)") If Target.Address = "$C$37" Then res = Application.Match(Target, arCases, 0) If IsError(res) Then Rows("104:112").Hidden = False Else Rows("104:112").Hidden = True End If ElseIf Target.Address = "$H$4" Then ' Do something else End If End Sub
unknown
d1268
train
Is there a better way to do this? No. Are scripts like this unwanted? No. That's normal. Is there another way to go about this? My fingers are used to typing "$(dirname "$(readlink -f "$0")")", but that's not better. Also do not use UPPER CASE VARIABLES. Not only they shout, but are meant for environment variables, like PWD LINES COLUMNS DISPLAY UID IFS USER etc. Prefer lower case variables in your scripts. (I would say that ROOT is a very common and thus bad variable name.) A: In a git repo, you might use git rev-parse --show-toplevel to find the root of the worktree, and then go from there. In general, it is a somewhat hard problem. There are too many ways to invoke a script that can alter what $0 actually means, so you can't really rely on it. In my opinion, the best you can do there is to establish a standard (for example, by expecting certain values in the environment or insisting the script be executed as ./path/from/root/to/script) and try to exit with good error messages if not. A: Can this improve scripts management and readability ? #!/usr/bin/env bash source $HOME/common-tools/include.sh "${BASH_SOURCE[0]}" echo $ROOT in $HOME/common-tools/include.sh : SCRIPT_DIR=$(cd "$( dirname "$1" )" >/dev/null 2>&1 && pwd) ROOT=$(realpath "$SCRIPT_DIR/..")
unknown
d1269
train
Try: Example1 String[] separated = CurrentString.split("am"); separated[0]; // I am separated[1]; // Vahid Example2 StringTokenizer tokens = new StringTokenizer(CurrentString, "am"); String first = tokens.nextToken();// I am String second = tokens.nextToken(); //Vahid A: Try: String text = "I am Vahid"; String after = "am"; int index = text.indexOf(after); String result = ""; if(index != -1){ result = text.substring(index + after.length()); } System.out.print(result); A: Just use like this, call the method with your string. public String trimString(String stringyouwanttoTrim) { if(stringyouwanttoTrim.contains("I am") { return stringyouwanttoTrim.split("I am")[1].trim(); } else { return stringyouwanttoTrim; } } A: If you prefer to split your sentence by blank space you could do like this : String [] myStringElements = "I am Vahid".split(" "); System.out.println("your name is " + myStringElements[myStringElements.length - 1]);
unknown
d1270
train
I think you shouldn't use the tmp file but instead store the file with it's real name somewhere, pass it to the POSTFIELDS param and after executing remove it. That seems to easiest way to me. curl doesn't care about the original request, it just does what you tell it to do and that is ... send the temp file over. A: Faced similar situation and this is how I solved it Pass the actual file name along with the request $arrInputs["uploadvia"] = 'curl'; $arrInputs["actualfilename"]= $_FILES["upfile1"]["name"]; $arrInputs["upfile1"] = "@".$_FILES["upfile1"]["tmp_name"].";type=".$_FILES["upfile1"]["type"].";"; curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $arrInputs); And at the other end, put this block if($_POST['uploadvia'] == "curl") { $_FILES["upfile1"]["name"] = $_REQUEST['actualfilename']; }
unknown
d1271
train
Without seeing code, this is gonna be a guess. I'm having a little trouble visualizing what you're describing. If I understand correctly, the first thing I would try is editing the FileInformationsScreen_Saving method (or whatever your screen is called). From the screen designer, click the little arrow next to Write Code, and select the _Saving method. There, you can manually save the fields you need, by using the DataWorkspace object. Private Sub MyScreen_Saving(ByRef handled As Boolean) Dim parent resolution = DataWorkspace.ApplicationData.Resolutions_SingleOrDefault(resolutionID) 'Process the record as needed End Sub Hopefully this is what you're looking for. Although if the relationship between the tables is set up correctly, you should have a field in the FileInformation entity for the ID key of the "parent" Resolution, which would make all of this unnecessary. You can verify that by looking at your tables in the designer, you should see lines connecting the related entities.
unknown
d1272
train
As mentioned in the comment on your question, it's probably the easiest to just shuffle the numbers in the range [1,50] and then take the first 25 or however many you want. The reason your code isn't working properly and you see a lot of repeats is because you're calling the RandomValue() function multiple separate times and the list variable you're comparing against if a value is already on the chart is inside of that function. Meaning that it will only ever check the values it has generated in that call, in this case meaning only for one row. Also, if you make a list that you know will always be the same size, you should use an array instead. Lists are for when you want the size to be adjustable. Solution 1: A very simple way to generate an array with the numbers 1-50 would be to do this: //Initialize Array int[] numbers = new int[50]; for (int i = 1; i <= numbers.Length; i++) { numbers[i] = i; } //Shuffle Array for (int i = 0; i < numbers.Length; i++ ) { int tmp = numbers[i]; int r = Random.Range(i, numbers.Length); numbers[i] = numbers[r]; numbers[r] = tmp; } //Get first 'n' numbers int[] result = Array.Copy(numbers, 0, result, 0, n); return result; I'm not sure if it's the most efficient way, but it would work. Solution 2: To change your code to check against the entire list, I would change this section: for (int x = 0; x <= 4; x++) { RandomValue(0, x); RandomValue(1, x); RandomValue(2, x); RandomValue(3, x); RandomValue(4, x); } To something like this: List<int> values = new List<int>(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int r = RandomValue(1, 50); while (values.Contains(r)) { r = RandomValue(1, 50); } values[y * width + x].Add(r); gridArray[x, y] = r; } } int RandomValue(int min, int max) { return UnityEngine.Random.Range(min, max); } Hope this helps! A: Basically your concept in function RandomValue() is correct, but problem is it only check in same column, so you have to bring the concept of RandomValue() to Grid() level. You need a List contain all approved value, then check Contains() at Grid(). But in fact you can do it in all one go. Make sure your width*height not larger than maxValue. Dictionary<Vector2Int, int> CreateBingoGrid(int width, int height, int maxValue) { var grid = new Dictionary<Vector2Int, int>(); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { var num = Random.Range(1, maxValue); while (grid.ContainsValue(num)) { num = Random.Range(1, maxValue); } grid.Add(new Vector2Int(x, y), num); } } return grid; }
unknown
d1273
train
For me, the fix was to switch to the 32 bit version of InternetExplorerDriver.exe from https://code.google.com/p/selenium/downloads/list Seemingly named IEDriverServer nowadays, but works if you just rename it to InternetExplorerDriver.exe. A: Using the C#, NUnit, C# webdriver client and IEDriverServer, I originally had the problem with slow input (e.g., sending keys to an input box would take about 5 seconds between keys, or clicking on a button same kind of delay). Then, after reading this thread, I switched to the 32-bit IEDriverServer, and that seemed to solve the problem. But today I was experimenting with the InternetExplorerOptions object in order to set some options on IE according to this documentation: https://code.google.com/p/selenium/wiki/InternetExplorerDriver Per the documentation, I created the registry value HKCU\Software\Microsoft\Internet Explorer\Main\TabProcGrowth with a value of 0 in order to use ForceCreateProcessApi = true and BrowserCommandLineArguments = "-private." After doing this, I noticed that the slow-input problem was back. I had made several changes to my code, but after rolling all of them back, the problem still persisted. When I removed the aforementioned registry key, however, the input was back to full speed (no delay). A: check 'prefer 32 bit' is not checked in your build properties. If it is and you are using the 64 bit IE driver it will run like an asthmatic snail.
unknown
d1274
train
I have used the myApp.xcworkspace instead of myApp.xcodeproj and the problem fixed.
unknown
d1275
train
if(splitMessage[0] === '!cmd'){ var c = message.content.split(/ (.+)/)[1]; try { eval(c); } catch (err) { console.log('There is an error!') } } Modifying a code in runtime is so bad though.
unknown
d1276
train
The following works for me without error in ImageMagick 7.0.7.22 Q16 Mac OSX Sierra with Ghostscript 9.21 and libpng @1.6.34_0. Your PDF has an alpha channel, so you might want to flatten it. magick -density 300 PointOnLine.pdf -flatten -quality 90 result.png This also works without error, but leaves the alpha channel in the png, though you won't see it here until you extract the image: magick -density 300 PointOnLine.pdf -quality 90 result2.png Note that in IM 7 you should just use magick and not magick convert. Check that you are using a current version of Ghostscript and libpng, if you do not get the same results. Your delegates.xml file for PS:alpha should show sDEVICE=pngalpha rather than pnmraw as follows. <delegate decode="ps:alpha" stealth="True" command="&quot;gs&quot; -sstdout=%%stderr -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 &quot;-sDEVICE=pngalpha&quot; -dTextAlphaBits=%u -dGraphicsAlphaBits=%u &quot;-r%s&quot; %s &quot;-sOutputFile=%s&quot; &quot;-f%s&quot; &quot;-f%s&quot;"/> USER REQUESTED RESULTING IMAGES THAT I POSTED TO BE REMOVED! A: Command which worked for me was: magick -density 300 PointOnLine.pdf -depth 8 -strip -background white -alpha off PointOnLine.tiff It did not gave any warning, also removed black blackground as well. I was able to convert it to the text afterwards using tesseract: tesseract PointOnLine.tiff PointOnLine A: I understand you are using ImageMagick under Windows, even if not stated (and the respective versions of IM, Win were not posted) I am under Ubuntu 16.04 LTS, and I will provide an answer possibly useful. (Under Win, prepend everything with Magick). For me, convert -density 300 -quality 90 PointOnLine.pdf PointOnLine.png works fine, with no warnings, producing a suitable output. I tried other things which work as well, some of them may suit you. * *First convert your pdf to RGB and then to png. convert -density 300 -colorspace RGB PointOnLine.pdf PointOnLine_rgb.pdf convert -density 300 PointOnLine_rgb.pdf PointOnLine_rgb.png A: If you post your PDF, I can check it out. Otherwise, perhaps it is CMYK, which PNG does not support. So try magick -quiet -density 300 -colorspace srgb PointOnLine.pdf -quality 90 PointOnLine.png Note in IM 7, use magick not magick convert. Also not that -quality is different for PNG than JPG. See https://www.imagemagick.org/script/command-line-options.php#quality A: I had the same issue and resolved adding -colorspace RGB before the output filename. convert -density 300 PointOnLine.pdf -quality 90 -colorspace RGB PointOnLine.png
unknown
d1277
train
Probably the debug_print_backtrace() from PHP can help you. These way you can see all the functions that have been called. More details: http://php.net/manual/en/function.debug-print-backtrace.php
unknown
d1278
train
It sounds like you're trying to determine if a given point (city) is within a circle centered on a specific lat/lon. Here's a similar question. Run a loop over each city and see if it satisfies the following condition: if ( (x-center_x)2 + (y-center_y)2 <= radius2 ) If this is too slow, you could turn it into a lookup based on rounding the lat/lon. The more values you precompute, the closer to exact you can get.
unknown
d1279
train
incase anyone googles this: JsonParser parser = objectMapper.getFactory().createJsonParser(inputStream); // Keep going until we find filters: String fieldName = null; JsonToken token = null; while (!"filters".equals(fieldName)) { token = parser.nextToken(); while (token != JsonToken.START_ARRAY) { token = parser.nextToken(); } fieldName = parser.getCurrentName(); } // We're at the filters node while (parser.nextToken() == JsonToken.START_OBJECT) { Map x = objectMapper.readValue(parser, Map.class); }
unknown
d1280
train
Here are the rules for classes extending Abstract class * *First concrete/non-abstract class must implement all methods *If abstract class extends Abstract class, it can but need not implement abstract methods. Option 1: Interface Segregation separate search(XXX) into two abstract classes Option 2: Generics. Make search a Generic Type public abstract class ClassA { public abstract <T> void search(T t); public static void main(String ...args){ ClassA classA = new ClassB(); classA.search(new Animal()); } } class Animal{ } class ClassB extends ClassA { @Override public <Animal> void search(Animal t) { System.out.println("called"); } } Option 3: Interface public class ClassA { public static void main(String... args) { Searchable classA = new ClassB(); classA.search(new Animal()); } } interface Searchable { public <T> void search(T t); } class Animal { } class ClassB implements Searchable { @Override public <Animal> void search(Animal t) { System.out.println("called"); } } Option 4: Throw UnsupportedOperationException Exception(Not recomended) class ClassB extends ClassA { @Override void search(Position p) { throw new UnsupportedOperationException("Not Supported"); } @Override void search(Animal a) { } }
unknown
d1281
train
Do you have the SharePointContextFilterAttribute on the method? That filter handles the authentication bits from the request context.
unknown
d1282
train
You are looking for a read/write lock (or reader-writer lock). I believe there is one in pthreads (pthread_rwlock_*).
unknown
d1283
train
Please try using SMTP ? PHPmailler.class Download : https://github.com/PHPMailer/PHPMailer
unknown
d1284
train
You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators: /** * Used to stitch together functional operators into a chain. * @method pipe * @return {Observable} the Observable result of all of the operators having * been called in the order they were passed in. * * @example * * import { map, filter, scan } from 'rxjs/operators'; * * Rx.Observable.interval(1000) * .pipe( * filter(x => x % 2 === 0), * map(x => x + x), * scan((acc, x) => acc + x) * ) * .subscribe(x => console.log(x)) */ In brief: Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above). Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().
unknown
d1285
train
Your following code doesn't work: for (String i : list) { if (i.equals("1")) { i = "4"; } } because you're replacing the value of String i instead of the selected item of list. You need to use set method: for (int i = 0; i < list.size(); i++) { String item = list.get(i); if (item.equals("1")) { list.set(i, "4"); } } UPDATE If you want to remove and change the item in one loop, you need to use listIterator and change for loop with while loop: ListIterator<String> iterator = list.listIterator(); while(iterator.hasNext()){ String item = iterator.next(); // Change item value if(item.equals("1") iterator.set("4"); // remove item if(item.equals("2") iterator.remove(); } Please be noted, I haven't test the code yet. A: You need to be careful to avoid a ConcurrentModificationException when attempting to remove an element from a list while iterating over it. You can use this: list = list.stream() .filter(element -> element != 1) .map(element -> 4) .collect(Collectors.toList());
unknown
d1286
train
Peer authentication works by checking the user the process is running as. In your command line example you switch to gitlab-psql using sudo. There are two ways to fix this: * *Assign a password to the gitlab-psql postgres user (not the system user!) and use that to connect via python. Setting the password is just another query you need to run as a superuser like so: sudo -u postgres psql -c "ALTER USER gitlab-psql WITH PASSWORD 'ReplaceThisWithYourLongAndSecurePassword';" *Run your python script as gitlab-psql like so: sudo -u gitlab-psql python /path/to/your/script.py
unknown
d1287
train
Maybe it is possible to do something via .inherited and .undef_method, isn't it? Yes, it is possible. But the idea smells, as for me - you're going to break substitutability. If you don't want the "derived" classes to inherit the behavior of the parent, why do you use inheritance at all? Try composition instead and mix in only the behavior you need. For example, something like this could work (very dirty example, but I hope you got the idea): class A module Registry def register_as(name) A.register_as(name, self) end end @registered = {} def self.register_as(name, klass) @registered[name] = klass end def self.known @registered end end class B extend A::Registry register_as :b end class C extend A::Registry register_as :c end A.known # => {:b => B, :c => C}
unknown
d1288
train
You probably don't actually need to use nogil. The GIL only stops multiple Python threads being run simulatenously. However, given you're using C++ threads they can quite happily run in the background irrespective of the GIL, provided they don't try to use PyObjects or run Python code. So my suspicion is that you've misunderstood the GIL and you can get away with not thinking about it. However, assuming that you do actually want to release it, you need to do 2 things: * *Mark the C++ functions as nogil to tell Cython that they don't need the GIL. Note that this doesn't actually release it - it just lets Cython know it isn't a problem if it is released: cdef cppclass Rectange: Rectangle(int, int, int, int) nogil except + int getArea() nogil # ... *Use with nogil: blocks in your Cython wrapper class to mark the areas where the GIL is actually released. cdef class PyRectangle: # ... def __cinit__(self, int x0, int y0, int x1, int y1): with nogil: self.c_rect = Rectangle(x0, y0, x1, y1) def get_area(self): cdef int result with nogil: result = self.c_rect.getArea() return result get_area becomes slightly more complicated since the return statement can't exist inside the with nogil block since it involves generating a Python object.
unknown
d1289
train
The user smilepleeeaz helped me at another question, and that can also be used to answered this. The code with the feature that I wanted is down below: !include "MUI2.nsh" !include FileFunc.nsh !insertmacro GetDrives var newCheckBox !define NOME "S-Monitor" Name "${NOME}" OutFile "${NOME}.exe" InstallDir "C:\${NOME}" ShowInstDetails show AllowRootDirInstall true ;--- Paginas --- !define MUI_ICON Labels\SetupICO.ico !define MUI_HEADERIMAGE !define MUI_HEADERIMAGE_RIGHT !define MUI_HEADERIMAGE_BITMAP Labels\Header.bmp !define MUI_WELCOMEFINISHPAGE_BITMAP Labels\Left.bmp !insertmacro MUI_PAGE_WELCOME !insertmacro MUI_PAGE_DIRECTORY !insertmacro MUI_PAGE_INSTFILES Page Custom CustomCreate CustomLeave !define MUI_FINISHPAGE_NOAUTOCLOSE !define MUI_FINISHPAGE_RUN !define MUI_FINISHPAGE_RUN_CHECKED !define MUI_FINISHPAGE_RUN_TEXT "Criar atalho na Área de Trabalho" !define MUI_FINISHPAGE_RUN_FUNCTION "AtalhoDesktop" !define MUI_PAGE_CUSTOMFUNCTION_SHOW showNewCheckbox !define MUI_PAGE_CUSTOMFUNCTION_LEAVE launchNewLink !insertmacro MUI_PAGE_FINISH ;--- Idiomas --- !insertmacro MUI_LANGUAGE "Portuguese" !insertmacro MUI_LANGUAGE "English" !insertmacro MUI_LANGUAGE "Spanish" Function .onInit !insertmacro MUI_LANGDLL_DISPLAY InitPluginsDir GetTempFileName $0 Rename $0 '$PLUGINSDIR\custom.ini' FunctionEnd ;-------------------------------- ;Arquivos a serem instalados Section "Instalacao" SetShellVarContext all SetOutPath "$INSTDIR" File /r Ficheiros\*.* ; LOCALIZACAO DA APLICACAO DO S-MONITOR MessageBox MB_OK "O software BDE (Borland Database Engine) será instalado agora" ExecWait "Ficheiros\bde_install_Win7_32_e_64.exe" FileOpen $1 '$INSTDIR\S-monitor.cpy' w FileWrite $1 "CPY Location=C:\S-Monitor.cpy" FileClose $1 writeUninstaller $INSTDIR\uninstall.exe SectionEnd Section "Uninstall" MessageBox MB_YESNO "Deseja desinstalar o S-Monitor?" IDYES true IDNO false true: SetShellVarContext all delete $INSTDIR\uninstall.exe RMDir /R /REBOOTOK $INSTDIR Goto +2 false: MessageBox MB_OK "Desinstalação cancelada." SectionEnd Function AtalhoDesktop createShortCut "$DESKTOP\S-Monitor.lnk" "C:\SMonitor.exe" FunctionEnd Function showNewCheckbox ${NSD_CreateCheckbox} 120u 110u 100% 10u "&Iniciar o S-Monitor ao terminar a instalação" Pop $newCheckBox FunctionEnd Function launchNewLink ${NSD_GetState} $newCheckBox $0 ${If} $0 <> 0 Exec "C:\S-Monitor\Smonitor.exe" ${EndIf} FunctionEnd Function CustomCreate WriteIniStr '$PLUGINSDIR\custom.ini' 'Settings' 'NumFields' '6' WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Type' 'Label' WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Left' '5' WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Top' '5' WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Right' '-6' WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Bottom' '17' WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Text' \ 'Selecione o drive a ser instalada a licensa do S-Monitor:' StrCpy $R2 0 StrCpy $R0 '' ${GetDrives} "HDD+FDD" GetDrivesCallBack WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Type' 'DropList' WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Left' '30' WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Top' '26' WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Right' '-31' WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Bottom' '100' WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Flags' 'Notify' WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'State' '$R1' WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'ListItems' '$R0' push $0 InstallOptions::Dialog '$PLUGINSDIR\custom.ini' pop $0 pop $0 FunctionEnd Function CustomLeave ReadIniStr $0 '$PLUGINSDIR\custom.ini' 'Settings' 'State' StrCmp $0 '2' 0 next ReadIniStr $0 '$PLUGINSDIR\custom.ini' 'Field 2' 'State' strcpy $R0 $0 StrCpy $0 $0 3 FileOpen $1 '$INSTDIR\S-monitor.cpy' w FileWrite $1 "CPY Location=$R0S-Monitor.cpy" FileClose $1 Abort next: ReadIniStr $0 '$PLUGINSDIR\custom.ini' 'Field 2' 'State' StrCpy '$INSTDIR' '$0' FunctionEnd Function GetDrivesCallBack StrCmp $R2 '0' 0 next StrCpy $R3 '$R4' StrCpy $R1 '$9' IntOp $R2 $R2 + 1 next: StrCpy $R0 '$R0$9|' Push $0 FunctionEnd
unknown
d1290
train
The problem, as stated, doesn't make sense. If you're holding z to zero rotation, you've converted a 3D problem to 2D already. Also, it seems the angle you're measuring is from the y-axis which is fine but will change the ultimate formula. Normally, the angle is measured from the x-axis and trigometric functions will assume that. Finally, if using Cartesian coordinates, holding y constant will not keep the angle constant (and from the system you described for x, the angle would be in the range from -90 to 90 - but exclusive of the end points). The arctangent function mentioned above assumes an angle measured from the x-axis. A: Angle can be calculated using the inverse tangent of the y/x ratio. On unity3d coordinated system (left-handed) you can get the angle by, angle = Mathf.Rad2Deg * Mathf.Atan(y/x); A: Your question is what will a 3-d vector look like. (edit after posted added perspective info) If you are looking at it isometrically from the z-axis, it would not matter what the z value of the vector is. (Assuming a starting point of 0,0,0) 1,1,2 looks the same as 1,1,3. all x,y,z1 looks the same as any x,y,z2 for any values of z1 and z2 You could create the illusion that something is coming "out of the page" by drawing higher values of z bigger. It would not change the angle, but it would be a visual hint of the z value. Lastly, you can use Dinal24's method. You would apply the same technique twice, once for x/y, and then again with the z. This page may be helpful: http://www.mathopenref.com/trigprobslantangle.html Rather than code this up yourself, try to find a library that already does it, like https://processing.org/reference/PVector.html
unknown
d1291
train
The problem is that you are calling an instance of class Window but not ComboBox. I see to possible reasons why this happens. Either you are referring to the wrong ui property from UIMap or Coded UI Test Builder recorded wrong element or not the whole hierarchy of your wanted test control. Moreover, if you are trying to select an item in combobox, then just use comboBox.SelectedIndex = 3; // to select an item by its zero-based index comboBox.SelectedItem = "Item Text"; // to select an item by its text If it does not help, provide additional information on the problem, particularly on the technology of your Windows Application (UIA/WPF or MSAA/WinForms).
unknown
d1292
train
You can declare it as nullable: List<MessageModel> ?messageList = []; A: The reason you get the error is data is null. Try my solution: List<MessageModel> messageList = []; String? message; bool success = false; @override MessageService decode(dynamic data) { messageList = data?.map((e) => MessageModel.fromJsonData(e))?.toList() ?? []; return this; }
unknown
d1293
train
I can't reproduce the problem: File: /path/to/file/data.csv ZwpBHCrWObHE61rSOpp9dkUfJ, '{"bodystyle": {"SUV/MUV": 2}, "budgetsegment": {"EP": 2}, "models": {"Grand Cherokee": 1, "XC90": 1}}', '{"bodystyle": "SUV/MUV", "budgetsegment": "EP", "models": "Grand Cherokee,XC90"}' MySQL Command Line: mysql> \! lsb_release --description Description: Ubuntu 16.04.2 LTS mysql> SELECT VERSION(); +-----------+ | VERSION() | +-----------+ | 5.7.19 | +-----------+ 1 row in set (0.00 sec) mysql> DROP TABLE IF EXISTS `table`; Query OK, 0 rows affected (0.00 sec) mysql> CREATE TABLE IF NOT EXISTS `table` ( -> `cookie` VARCHAR(25) NOT NULL, -> `userdata` JSON NOT NULL, -> `userprefernce` JSON NOT NULL -> ); Query OK, 0 rows affected (0.01 sec) mysql> LOAD DATA LOCAL INFILE '/path/to/file/data.csv' -> INTO TABLE `table` -> FIELDS TERMINATED BY ', ' -> OPTIONALLY ENCLOSED BY '\'' -> LINES TERMINATED BY '\n'; Query OK, 1 row affected (0.00 sec) Records: 1 Deleted: 0 Skipped: 0 Warnings: 0 mysql> SELECT -> `cookie`, -> `userdata`, -> `userprefernce` -> FROM -> `table`\G *************************** 1. row *************************** cookie: ZwpBHCrWObHE61rSOpp9dkUfJ userdata: {"models": {"XC90": 1, "Grand Cherokee": 1}, "bodystyle": {"SUV/MUV": 2}, "budgetsegment": {"EP": 2}} userprefernce: {"models": "Grand Cherokee,XC90", "bodystyle": "SUV/MUV", "budgetsegment": "EP"} 1 row in set (0.00 sec)
unknown
d1294
train
The code has these problems: * *the data is space separated but the code specifies that it is comma separated *the data does not describe dates since there is no day but the code is using the default of dates *the data is not provided in reproducible form. Note how one can simply copy the data and code below and paste it into R without any additional work. Try this: Lines <- "Date NoDur 198901 5.66 198902 -1.44 198903 5.51 198904 5.68 198905 5.32 " library(zoo) read.zoo(text = Lines, format = "%Y%m", FUN = as.yearmon, header = TRUE, colClasses = c("character", NA)) The above converts the index to "yearmon" class which probably makes most sense here but it would alternately be possible to convert it to "Date" class by using FUN = function(x, format) as.Date(as.yearmon(x, format)) in place of the FUN argument above.
unknown
d1295
train
The logic to get all elements with class .adminhours should not check with val in selector if(jQuery(".adminhours").val().length > 0). I have updated your code below : var totalAdminhours = 0; if(jQuery(".adminhours").length > 0){ jQuery(".adminhours").each(function () { totalAdminhours += totalAdminhours + jQuery(this).val(); }); } else { totalAdminhours = 0; }
unknown
d1296
train
Two things worked for me: * *Make sure your collection view itself has layout constraints defined for placement within its superview. *I got this crash when the estimated size was larger than the final size. If I set the estimated size to a smaller value the crash stopped. A: If any size or frame position changed, it will trigger all cells' preferredLayoutAttributesFittingAttributes until all cells' frames did not change. The behavior flow is as the following: 1. Before self-sizing cell 2. Validated self-sizing cell again after other cells recalculated. 3. Did changed self-sizing cell If second steps can't get stable all cells' position and size, it will become infinite loop. Please reference my post here: UICollectionView Self Sizing Cells with Auto Layout
unknown
d1297
train
Your type can be defined in a simpler way, you don't need slist: type 'a sexp = Symbol of 'a | L of 'a sexp list Your problem is that subst a b S[q] is read as subst a b S [q], that is the function subst applied to 4 arguments. You must write subst a b (S[q]) instead.
unknown
d1298
train
The timing wasn't really working. The second timeout would have to start after the initial one has finished - or you could interrupt the animation (or both to be sure) : setTimeout(function(){ $('html, body') .css({overflow: 'auto'}) .animate({scrollTop: $('.second').offset().top}, 1500); }, 2000); setTimeout(function() { $('.first').hide(); $('html, body').stop().scrollTop($('.second').offset().top); }, 3400); http://jsfiddle.net/em9yycj5/16/ Not sure what is meant with 'a click function' in the comment above...
unknown
d1299
train
See dumpting a table using mysqldump. Assuming you have the table names, or a list of table names, you could either dump them all with one command or loop: : > db_sync.sql for table in tableNames; do mysqldump -u root -ppassword db_name table >> db_sync.sql done To get the table names: number=17 echo "select TABLE_NAME from information_schema.tables where TABLE_NAME like '%\_$number\_%' and TABLE_SCHEMA = 'databasename'" | \ mysql -udbuser -pdbpassword databasename So, if you have multiple numbers, e.g. as command line arguments, you can put this all together: sql="select TABLE_NAME from information_schema.tables where TABLE_NAME like '%\_$number\_%' and TABLE_SCHEMA = 'databasename'" # truncate/create the dump file : > db_sync.sql # loop through the command line arguments for number in $@; do # for each tableName from the sql ... while read tableName; do # append to the dump file mysqldump -u root -ppassword db_name $tableName >> db_sync.sql done < <( echo $sql | mysql -udbuser -pdbpassword databasename | tail -n +2) done This will work if you put the numbers on the command line: ./push.sh 17 18 19 See the getopts tutorial for more information about processing command line arguments if you want to get complicated. Here is a short example of getting multiple arguments in an array: numbers=() while getopts ":t:" opt "$@"; do case "$opt" in t) numbers+=($OPTARG) ;; esac done for number in ${numbers[@]}; do echo $number done For example: $ ./test.sh -t 17 -t 18 -t 19 17 18 19
unknown
d1300
train
I guess you would want to simply cut the last 5 digits out of the string. That's also what answers to python datetime: Round/trim number of digits in microseconds suggest. import numpy as np import matplotlib.pyplot as plt from matplotlib.dates import MicrosecondLocator, DateFormatter from matplotlib.ticker import FuncFormatter x = np.datetime64("2018-11-30T00:00") + np.arange(1,4, dtype="timedelta64[s]") fig, ax = plt.subplots(figsize=(8,4)) seconds=MicrosecondLocator(interval=500000) myFmt = DateFormatter("%S:%f") ax.plot(x,[2,1,3]) def trunc_ms_fmt(x, pos=None): return myFmt(x,pos)[:-5] ax.xaxis.set_major_locator(seconds) ax.xaxis.set_major_formatter(FuncFormatter(trunc_ms_fmt)) plt.gcf().autofmt_xdate() plt.show() Note that this format is quite unusual; so make sure the reader of the plot understands it.
unknown