_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d17501
val
You can use filters. Here's an example of how to use filters: http://viralpatel.net/blogs/2009/01/tutorial-java-servlet-filter-example-using-eclipse-apache-tomcat.html Basically you define the url's where you want the filters to apply, the filter authorizes the user and then calls chain.doFilter(request, response); to call the requested method after authorization. You can also take a look at this jax-rs rest webservice authentication and authorization Personally, I use tokens for authorization. A: It all depends on how is your web service implemented/or its going to be. If you still have a choice I would recommend going with REST approach, authenticate the user with some kind of login functionality and then maintain users session.
unknown
d17502
val
Try 100 - abs(100 - $percent). abs(100 - $percent) gives you the distance between the two values. It is 1 for both 99 and 101. Subtracting this distance from 100 gives you the desired ouput. A: I think that the elegant mathematical approach is the following: $true_percent = 100 - abs(100 - $percent);
unknown
d17503
val
For backend server-side validation, you must use verifiable ID tokens to securely get the user IDs of signed-in users on the server side. ref. : https://developers.google.com/identity/sign-in/web/backend-auth Seems that the current flutter google sign in plugin does not support getting AuthCode for backend server-side OAuth validation. ref. : https://github.com/flutter/flutter/issues/16613 I think the firebaseUser.getIdToken() cannot be used for Google API. For https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=mytoken , you may need to pass the googleSignInAuthentication.idToken For https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=mytoken , you may need to pass the googleSignInAuthentication.accessToken Getting user information like user id and pass it to backend server-side is vulnerable to hackers. You should verify the idToken in backend server-side by Google API Client Libraries. A: I recently had a similar problem. this was my code: Future<void> googleLogin() async { final googleUser = await googleSignIn.signIn(); if (googleUser == null) { print('no google user??'); return; } _user = googleUser; final googleAuth = await googleUser.authentication; final credential = GoogleAuthProvider.credential( accessToken: googleAuth.accessToken); try { await FirebaseAuth.instance.signInWithCredential(credential); } catch (e) { print('could not sign in with goodle creds, and heres why: \n $e'); } } I was not providing all the information in the credential variable. So all I had to do was to add the accessTokenId there. So replace the: final credential = GoogleAuthProvider.credential( accessToken: googleAuth.accessToken); with: final credential = GoogleAuthProvider.credential( idToken: googleAuth.idToken, accessToken: googleAuth.accessToken); and when that got passed to FirebaseAuth.instance, it worked! How this helps.
unknown
d17504
val
You can write a loop for it: const n = 4 let elem = e.target for(let i = 0; i < n; i++) elem = elem.parentElement console.log(elem) However, as mentioned in the comments, if you're looking for a specific element, it might be better to just write a selector for the element you're looking for. This applies to your case even more, as event.target can return child nodes of the watched element (if the event bubbles), making your parent count shift around a bit. A: You might define a function which ascends up in the parent hierarchy with a loop, e.g.: function nthParent(n, el) { while (n--) { el = el.parentElement; if (!el) return null; } return el; }
unknown
d17505
val
You could give prettypr a try. I've never used it myself, and might not give the exact output you specified, but it does format the source code according to the available horizontal space. A: It should be possible to do this through erl_tidy, by passing an option {printer, fun (Tree, Opts) -> erl_prettypr:format(Tree, [{paper, P}, {ribbon, R} | Opts]) end}. See http://erlang.org/doc/man/erl_prettypr.html#format-2 for details about the ribbon and paper options, and http://erlang.org/doc/man/erl_tidy.html#file-2 for info about the printer option.
unknown
d17506
val
data.table solution sample data # sgid stid spid sch sst snd qgid qtid qpid qch qst qnd # 1: sg1 <NA> <NA> sch1 11 21 qg1 qt1 qp1 qch1 111 211 # 2: sg1 st1 <NA> sch1 11 21 qg1 qt1 qp1 qch1 111 211 # 3: sg2 <NA> <NA> sch2 32 46 qg1 qt1 qp1 qch1 234 267 # 4: sg3 <NA> sp3 sch2 21 34 qg1 qt1 qp1 qch1 21 34 code library( data.table ) setDT( df ) #get columns you wish to exclude from duplication-check cols <- c( "stid", "spid" ) #keep non-duplicated rows, based on a subset of df (without the columns in `cols`) df[ !duplicated( df[, !..cols] ), ][] # sgid stid spid sch sst snd qgid qtid qpid qch qst qnd # 1: sg1 <NA> <NA> sch1 11 21 qg1 qt1 qp1 qch1 111 211 # 2: sg2 <NA> <NA> sch2 32 46 qg1 qt1 qp1 qch1 234 267 # 3: sg3 <NA> sp3 sch2 21 34 qg1 qt1 qp1 qch1 21 34 alternative if you do not wish to keep the first row of a duplicate, but the last, use: df[ !duplicated( df[, !..cols], fromLast = TRUE ), ][] #<-- note fromlast-argument! # sgid stid spid sch sst snd qgid qtid qpid qch qst qnd # 1: sg1 st1 <NA> sch1 11 21 qg1 qt1 qp1 qch1 111 211 # 2: sg2 <NA> <NA> sch2 32 46 qg1 qt1 qp1 qch1 234 267 # 3: sg3 <NA> sp3 sch2 21 34 qg1 qt1 qp1 qch1 21 34 A: How about something like this with dplyr: cols <- setdiff(names(df), c("stid", "spid")) df %>% group_by_at(cols) %>% summarise(stid = ifelse(length(unique(stid)) == 1, unique(stid), unique(stid)[! is.na(unique(stid))]), spid = ifelse(length(unique(spid)) == 1, unique(spid), unique(spid)[! is.na(unique(spid))])) Or you can use the function Coalesce from the package DescTools (or even define you own function to select the first non NA value): df %>% group_by_at(cols) %>% summarise(stid = DescTools::Coalesce(stid), spid = DescTools::Coalesce(spid))
unknown
d17507
val
What's likely happening is that npx react-native init MyProject is sub-shelling into Bash where you do not have rbenv configured. When it tries to run ruby from Bash it looks in $PATH and finds the default macOS version of Ruby -- 2.6.10 -- and errors out. This is discussed thoroughly in the react-native repo where there are many solutions, but what it boils down to is react-native init is not finding the right version of Ruby, for whatever reason. You can bypass that by completing the failing part of the init process yourself with: cd MyProject bundle install cd ios && bundle exec pod install The longer version of the solution is to configure rbenv for Bash as well, but this isn't necessary as you can likely use just the workaround above: echo 'eval "$(~/.rbenv/bin/rbenv init - bash)"' >> ~/.bash_profile
unknown
d17508
val
I don't seem to have an issue. Please find the code below <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> @media (max-width: 1000px) and (min-width: 400px) { .tooltiptext { margin-left: 10em !important; } .homeInternetToolTip .tooltiptext i { left: 9% !important; } } @media (min-width: 1000px) and (max-width: 1400px) { .tooltiptext { margin-left: 3em !important; } } </style> </head> <body></body> </html> A: You can use as many @media queries as you want in a single css file, or also inside style tag. But when I copied your code in editor your } bracket at the end have some character code issue, either it is some other character that looks like }, or it have an invisible whitespace character after it making it not actually a }. So in your code remove the last bracket and type again from keyboard, don't copy from anywhere.
unknown
d17509
val
Here is a solution that shows you how to delete all contacts in a loop. how to delete all contacts in contact list on android mobile programatically You just need some of the contacts information to tell which one to delete which you already have from the list. You may need the WRITE_CONTACTS permission.
unknown
d17510
val
IIS is a web server, it is not java application server. Normally IIS can not execute Servlets and Java Server Pages (JSPs), configuring IIS to use the JK ISAPI redirector plugin will let IIS send servlet and JSP requests to Tomcat (and this way, serve them to clients). You can use IIS as proxy to tomcat. Please read this link for configuring IIS to use the JK ISAPI redirector plugin. How to configure IIS with tomcat? How does it work?? * *The IIS-Tomcat redirector is an IIS plugin (filter + extension), IIS load the redirector plugin and calls its filter function for each in-coming request. *The filter then tests the request URL against a list of URI-paths held inside uriworkermap.properties, If the current request matches one of the entries in the list of URI-paths, the filter transfer the request to the extension. *The extension collects the request parameters and forwards them to the appropriate worker using the defined protocol like ajp13 . *The extension collects the response from the worker and returns it to the browser.
unknown
d17511
val
Looks like the OAuth library is being built against 3.0 frameworks. If you want to target 2.2.1, it'll need to be built against those frameworks.
unknown
d17512
val
These warnings are caused by a missing path. If you want to shut them off, you can either disable them using warning off or add the input_folders to the Compiler path before compiling. But since mcc does that anyway (and displays a warning), you can safely ignore them. Basically, they're just mcc telling you "Couldn't you have done that to start with? Now I'll have to do it myself...". I can't answer your second question the way it is worded, so I'll have to go with this: You will not run into trouble caused by these warnings or any implications. If you do run into trouble, it's for a different reason.
unknown
d17513
val
Assuming that LinkedBag refers to the LinkedList data structure, then yes you are correct in that Set would be a third section, with SortedSet inheriting from it. However, I would not define it as an "interface". Interfaces are a type of class which is generally used as a blueprint for inheriting classes to follow, and does not implement their own class functions. Instead, they declare functions which their derivative classes will implement. For additional information, Abstract Classes are similar, except that they can implement their class functions. Neither Interfaces nor Abstract classes can (usually) be initialized as an object. This becomes a lot more blurry in Python which uses the general "Python Abstract Base Classes" and doesn't do Interfaces directly, but can be mocked through the abstract classes. However, as a term for general programming, the distinctions between normal classes, interfaces, and abstract classes can be important, especially since interfaces and abstract classes (usually) are not/ can not be initialized as objects. The exact rules of inheritance regarding Interfaces and Abstract Classes can differ between languages, for example in Java you can't inherit from more than one abstract class, so I won't directly address it here. Since a Set is a data structure on its own that can, and usually should, have functionality separate from a sorted set, you would not make the set an interface, but rather a normal class. You can still inherit from normal classes, which is what you would do with SortedSet inheriting from Set. A: A sorted set according to the narrative is a set, but with some variations in some behavior: A sorted set behaves just like a set, but allows the user to visit its items in ascending order with a for loop, and supports a logarithmic search for an item. This means that SortedSet would inherit from Set, just like SortedArrayBag inherits from ArrayBag. Inheritance should by the way shown in UML with a big hollow array head (small arrows like in your diagram mean a navigable association, which has nothing to do with inheritance). A set is however not a bag. A set contains an item at maximum once, whereas a bag may contain multiple times the same item. This could lead to a completely different interface (e.g. membership on an item is a boolean for a set, whereas it could be an integer for a bag). The safe approach would therefore be to insert an AbstractSet inheriting from AbstractCollection: A shortcut could be to deal with the set like a bag, and return a count of 1 for any item belonging to the set, ignoring multiple inserts. This would not be compliant with the Liskov Substitution Principle, since it would not respect all the invariants and weaken post-conditions. But if you'd nevertheless go this way, you should insert Set as extending AbstractBag, and SortedSet as a specialization of Set. In this case, your set (and sorted set) would also realise the BagInterface (even if it'd twist it). Shorn's answer analyses this situation very well.
unknown
d17514
val
I worked on the same issue and found this working shell solution: https://community.infura.io/t/ipfs-http-api-add-directory/189/8 you can rebuild this in go package main import ( "bytes" "github.com/stretchr/testify/assert" "io" "io/ioutil" "mime/multipart" "net/http" "os" "strings" "testing" ) func TestUploadFolderRaw(t *testing.T) { ct, r, err := createForm(map[string]string{ "/file1": "@/my/path/file1", "/dir": "@/my/path/dir", "/dir/file": "@/my/path/dir/file", }) assert.NoError(t, err) resp, err := http.Post("http://localhost:5001/api/v0/add?pin=true&recursive=true&wrap-with-directory=true", ct, r) assert.NoError(t, err) respAsBytes, err := ioutil.ReadAll(resp.Body) assert.NoError(t, err) t.Log(string(respAsBytes)) } func createForm(form map[string]string) (string, io.Reader, error) { body := new(bytes.Buffer) mp := multipart.NewWriter(body) defer mp.Close() for key, val := range form { if strings.HasPrefix(val, "@") { val = val[1:] file, err := os.Open(val) if err != nil { return "", nil, err } defer file.Close() part, err := mp.CreateFormFile(key, val) if err != nil { return "", nil, err } io.Copy(part, file) } else { mp.WriteField(key, val) } } return mp.FormDataContentType(), body, nil } or use https://github.com/ipfs/go-ipfs-http-client which seems to be a better way. I'm working on it and tell you when I know how to use it Greetings
unknown
d17515
val
One possibility is to use the usage command, which displays both the amount of RAM currently being used, as well as the User and the System time used by the tool since when it was started (thus, usage should be called both before and after each operation which you want to profile). An example execution: NuSMV > usage Runtime Statistics ------------------ Machine name: ***** User time 0.005 seconds System time 0.005 seconds Average resident text size = 0K Average resident data+stack size = 0K Maximum resident size = 6932K Virtual text size = 8139K Virtual data size = 34089K data size initialized = 3424K data size uninitialized = 178K data size sbrk = 30487K Virtual memory limit = -2147483648K (-2147483648K) Major page faults = 0 Minor page faults = 2607 Swaps = 0 Input blocks = 0 Output blocks = 0 Context switch (voluntary) = 9 Context switch (involuntary) = 0 NuSMV > reset; read_model -i nusmvLab.2018.06.07.smv ; go ; check_property ; usage -- specification (L6 != pc U cc = len) IN mm is true -- specification F (min = 2 & max = 9) IN mm is true -- specification G !((((max > arr[0] & max > arr[1]) & max > arr[2]) & max > arr[3]) & max > arr[4]) IN mm is true -- invariant max >= min IN mm is true Runtime Statistics ------------------ Machine name: ***** User time 47.214 seconds System time 0.284 seconds Average resident text size = 0K Average resident data+stack size = 0K Maximum resident size = 270714K Virtual text size = 8139K Virtual data size = 435321K data size initialized = 3424K data size uninitialized = 178K data size sbrk = 431719K Virtual memory limit = -2147483648K (-2147483648K) Major page faults = 1 Minor page faults = 189666 Swaps = 0 Input blocks = 48 Output blocks = 0 Context switch (voluntary) = 12 Context switch (involuntary) = 145
unknown
d17516
val
You need to link with the QuartzCore framework. Linking to a Library or Framework
unknown
d17517
val
The issue here is probably that you have an akka-actor.jar in your scala distributuion that is Akka 2.1.x and you're trying to use Akka 2.2.x. You'll have to run your code by running the java command and add the scala-library.jar and the correct akka-actor.jar and typesafe-config.jar to the classpath. A: Are you using Scala 2.10? This is the Scala version you need for Akka 2.2. What does the following yield? scala -version It should show something like $ scala -version Scala code runner version 2.10.3 -- Copyright 2002-2013, LAMP/EPFL
unknown
d17518
val
Thiss assumes that entries is a list/collection of DeptLibraryEntry. Note that log (and not Log, capitalization is important!) is itself a list of items, so to get the value of each item you have to iterate over it again <c:forEach items="${entries}" var="entry"> <c:forEach items="${entry.log}" var="logItem"> <tr><td>${logItem.num}</td></tr> .... </c:forEach> </c:forEach> Of course, your classes will need to have the appropiate getters to access the properties.
unknown
d17519
val
Worked here in 8.7.1 without any problems. Maybe you wann update to the latest release? A: There are two different concepts you are mixing up here, namely colspan and width. The colspan attribute is used to tell a cell of a table how many of the other cells of another row it should overlap. So this has nothing to do with fixed widths even though it might feel like that, when you got the same content in each cell or no content at all. As soon as you fill the table cells with different content, the width of each cell might differ even though some of these cells might use the same colspan value. So colspan actually just defines the relation between the cells but not their width. Still the core somehow circumvents that behaviour by applying min and max width values to several parts of the page module via CSS, so the cells will stay within a certain width range. Now that you have installed gridelements, there can not be such a range anymore, because there might be nested grid structures that have to consume way more space. So gridelements uses a CSS removing that range and thereby restores the default behaviour of HTML table cells.
unknown
d17520
val
1) Use this function to retrieve the minimum and maximum date func getTimeIntervalForDate()->(min : Date, max : Date){ let calendar = Calendar.current var minDateComponent = calendar.dateComponents([.hour], from: Date()) minDateComponent.hour = 09 // Start time let formatter = DateFormatter() formatter.dateFormat = "h:mma" let minDate = calendar.date(from: minDateComponent) print(" min date : \(formatter.string(from: minDate!))") var maxDateComponent = calendar.dateComponents([.hour], from: date) maxDateComponent.hour = 17 //EndTime let maxDate = calendar.date(from: maxDateComponent) print(" max date : \(formatter.string(from: maxDate!))") return (minDate!,maxDate!) } 2) Assign these dated to your pickerview func createPickerView(textField : UITextField, pickerView : UIDatePicker){ pickerView.datePickerMode = .time textField.delegate = self textField.inputView = pickerView let dates = getTimeIntervalForDate() pickerView.minimumDate = dates.min pickerView.maximumDate = dates.max pickerView.minuteInterval = 30 pickerView.addTarget(self, action: #selector(self.datePickerValueChanged(_:)), for: UIControlEvents.valueChanged) } That's it :) A: Just use this: datePicker.maximumDate = myMaxDate; datePicker. minimumDate = myMinDate; Where myMaxDate and myMinDate are NSDate objects A: As for my problem, the answer with maximumDate and minimumDate isn't what I am looking for. Maybe my solution is not that clear and right, but it worked great for me. I have changed the UIDatePicker with UIPickerView, wrote a separate delegate for it: @interface CHMinutesPickerDelegate () <UIPickerViewDelegate, UIPickerViewDataSource> @property (nonatomic, strong) NSArray *minutesArray; @end @implementation CHMinutesPickerDelegate - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent: (NSInteger)component { return [self.minutesArray count]; } - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { return 1; } - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { return [self.minutesArray objectAtIndex: row]; } - (NSArray *)minutesArray { if (!_minutesArray) { NSMutableArray *temporaryMinutesArray = [NSMutableArray array]; for (int i = 0; i < 6; i++) { for (int j = 0; j < 2; j++) { [temporaryMinutesArray addObject: [NSString stringWithFormat: @"%i%i", i, j * 5]]; } } _minutesArray = temporaryMinutesArray; } return _minutesArray; } The minutesArray returns array of: { "05", "10"... etc}. It is an example for custom minutes picker, you can write the same thing for hour or etc, choosing your own maximum and minimum value. This worked nice for me.
unknown
d17521
val
yes, It is also working for me check public class SerializationIssue { private static final String fileName = "testFile"; public static void main(String[] args) { TestObject object1= new TestObject(); TestObject object2=new TestObject(); object1.setName("object1"); object2.setName("object2"); List<TestObject> list=new ArrayList<TestObject>(); list.add(object1); list.add(object2); serializeList(list); ArrayList<TestObject> deserializedList=desializeDemo(); System.out.println(deserializedList.get(0).getName()); } private static ArrayList desializeDemo() { ArrayList<TestObject> deserializedList; try { FileInputStream fileIn = new FileInputStream(fileName); ObjectInputStream in = new ObjectInputStream(fileIn); deserializedList= (ArrayList<TestObject>) in.readObject(); in.close(); fileIn.close(); }catch(IOException i) { i.printStackTrace(); return null; }catch(ClassNotFoundException c) { System.out.println("Employee class not found"); c.printStackTrace(); return null; } return deserializedList; } private static void serializeList(List<TestObject> list) { // TODO Auto-generated method stub try { FileOutputStream fos = new FileOutputStream(fileName); ObjectOutputStream os = new ObjectOutputStream ( fos ); os.writeObject ( list ); fos.close (); os.close (); } catch ( Exception ex ) { ex.printStackTrace (); } } } TestObject bean public class TestObject implements Serializable{ /** * serial version. */ private static final long serialVersionUID = 1L; String name; public TestObject(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Output:object1
unknown
d17522
val
Should work as is - verified locally: 127.0.0.1:6379> FLUSHALL OK 127.0.0.1:6379> MSET a "" e "" f "" eSz "" fSx "" efg "" fgi "" SSX "" OK 127.0.0.1:6379> scan 0 MATCH "[ef]S*" 1) "0" 2) 1) "eSz" 2) "fSx" 127.0.0.1:6379>
unknown
d17523
val
If it's a yearly investment, you should add it every year: yearly = float(input("Enter the yearly investment: ")) apr = float(input("Enter the annual interest rate: ")) years = int(input("Enter the number of years: ")) total = 0 for i in range(years): total += yearly total *= 1 + apr print("The value in 12 years is: ", total) With your inputs, this outputs ('The value in 12 years is: ', 3576.427533818945) Update: Responding to your questions from the comments, to clarify what's going on: 1) You can use int() for yearly and get the same answer, which is fine if you always invest a whole number of currency. Using a float works just as well but also allows the amount to be 199.99, for example. 2) += and *= are convenient shorthand: total += yearly means total = total + yearly. It's a little easier to type, but more important, it more clearly expresses the meaning. I read it like this for i in range(years): # For each year total += yearly # Grow the total by adding the yearly investment to it total *= 1 + apr # Grow the total by multiplying it by (1 + apr) The longer form just isn't as clear: for i in range(years): # For each year total = total + yearly # Add total and yearly and assign that to total total = total * (1 + apr) # Multiply total by (1 + apr) and assign that to total A: It can be done analytically: """ pmt = investment per period r = interest rate per period n = number of periods v0 = initial value """ fv = lambda pmt, r, n, v0=0: pmt * ((1.0+r)**n-1)/r + v0*(1+r)**n fv(200, 0.09, 10, 2000) Similarly, if you are trying to figure out the amount you need to invest so you get to a certain number, you can do: pmt = lambda fv, r, n, v0=0: (fv - v0*(1+r)**n) * r/((1.0+r)**n-1) pmt(1000000, 0.09, 20, 0) A: As suggested in the comments, you shouldn't use eval() here. (More info on eval can be found in the Python Docs). -- Instead, change your code to use float() or int() where applicable, as shown below. Also, your print() statement printed out the parenthesis and comma, which I expect you didn't want. I cleaned it up in the code below, but if what you wanted is what you had feel free to put it back. principal = float(input("Enter the yearly investment: ")) apr = float(input("Enter the annual interest rate: ")) # Note that years has to be int() because of range() years = int(input("Enter the number of years: ")) for i in range(years): principal = principal * (1+apr) print "The value in 12 years is: %f" % principal
unknown
d17524
val
I'd bet dribble is rebinding some streams that are different from the ones being used by SLIME to get output to and from the REPL. (Issue DRIBBLE-TECHNIQUE might be worth reading.) Your solution depends on what your are doing. If you just want a record of your interactions with Lisp, remember that emacs is a text editor and you can save the contents of the REPL buffer to a file or copy an excerpt. If you want to write a program that saves output to a file, dribble is not a good mechanism for this. Have a look at open, close, print, format, and with-open-file.
unknown
d17525
val
2nd. Because you will only open your BD connection one time to insert your data and close. :)
unknown
d17526
val
I think del *param* should work for this... c:\test>dir /w Volume in drive C is HP Volume Serial Number is 0EBF-B242 Directory of c:\test [.] [..] a.txt b.param b.param.config 3 File(s) 29 bytes 2 Dir(s) 185,518,833,664 bytes free c:\test>dir /w *param* Volume in drive C is HP Volume Serial Number is 0EBF-B242 Directory of c:\test b.param b.param.config 2 File(s) 20 bytes 0 Dir(s) 185,518,833,664 bytes free c:\test>del *param* c:\test>dir /w Volume in drive C is HP Volume Serial Number is 0EBF-B242 Directory of c:\test [.] [..] a.txt 1 File(s) 9 bytes 2 Dir(s) 185,518,833,664 bytes free What happened when you tried this? What version of MS-DOS are you running?
unknown
d17527
val
There's no "restore" feature on the iPad. But in all probability there's nothing to worry about. There's nothing about your code that would delete multiple files. It would delete just that file from the Documents directory that you supplied the name of as fileName. If you didn't call deleteFileFromDisk: multiple times, you didn't delete multiple files. Perhaps at some point you deleted the app. That would delete its entire sandbox and thus would take with it anything in the Documents directory. That sort of thing is perfectly normal during repeated testing.
unknown
d17528
val
The security issues in OkHttp 2.7.4 are in parts of the code not used by gRPC. In particular, none of the TLS code from OkHttp is used. There are no security issues in your configuration unless you also use OkHttp 2.7.4’s APIs directly. Later releases of OkHttp use a different package name: okhttp3 instead of com.squareup.okhttp, so upgrading OkHttp won't help you anyway.
unknown
d17529
val
My issue at first time when i add a job job_count goes to 1 and from there taht job_count value is not increasing The problem is probably because you're using an instance variable From what I can see, you're reloading the page each time you wish to load job (it's a one time thing); meaning the data is not going to persist between requests If you want to store a variable over different requests, you'll either have to populate it continuously in the backend, or use a persistent data store - such as a cookie or session Try this: <% session[:job_count] = 0 %> <script type="text/html" id="new_company_job_div"> <%= render 'job', job: Job.new(company_id: @company.id), f: f %> </script> <% session[:job_count] += 1 %> <%= session[:job_count] %> This is the best I can do without any further context A: Use collection partial: In app/views/companies/show.html.erb <%= render @company.jobs %> In app/views/jobs/_job.html.erb <%= job_counter %> # value based on the number of jobs you have <%= job.foo %>
unknown
d17530
val
I found my issue, A stupid issue. My 3rd DLL uses too much another DLL. I missed a library, (I developed my App by C#, It did not notify me missed library)
unknown
d17531
val
Without knowing your markup, I'd suspect that your .yell-box-txt is in the same block as your .yell-button. So for markup like this: <div> <a class="yell-button">text button</a> <span class="yell-box-txt">text</a> </div> you'd want to use something like this: $('.yell-button').hover(function() { $(this).closest('div').find('.yell-box-txt').remove(); }); A: Classes are, by definition, accessors for, potentially, multiple elements. If you want to access this element on its own, consider using an id and accessing it via $('#idname') A: $('.yell-button:first').hover(function(){ $('.yell-box-txt').remove(); }) Of course it'd be better to make sure to only use this class once. It would be even better to use an ID instead, which is supposed to be unique (of course it's up to you and you have to check your code for inconsistencies such as multiple elements with the same id) A: Example of using id and class JS $('.yell-button').hover(function(){ $('#box2.yell-box-txt').remove() }) HTML <div id ="box1" class="yell-box-txt">Text in box 1</div> <div id ="box2" class="yell-box-txt">Text in box 2</div> <div id ="box3" class="yell-box-txt">Text in box 3</div> A: As others said, without an idea of your markup it's difficult to help you, however here are some ways to do it, depending on your markup: Ideally, you would be able to assign each button and associated text-box a unique identifier like yell-button-1 and make it remove the associated yell-box-txt-1 on hover. However, this method might be "difficult" to implement because you need to retrieve the ID # from the button. The second way to do this is to make use of jQuery traversing. Find where the text box is in relation to the button and navigate from the button to the text box using methods such as parent(), siblings(), etc. To make sure you only receive one element, append :first to your .yell-box-txt class. More info about jQuery Traversing. Hope this helps!
unknown
d17532
val
There are two places that w is used: w[al](w[pi]("0")); ^ ^ So you need to substitute in w[gg]() twice: w[gg]()[al](w[gg]()[pi]("0")); ^^^^^^^ ^^^^^^^ Note also that this transformation might still not equivalent, for example if w[gg]() has side-effects or is non-deterministic.
unknown
d17533
val
The last lines of your PHP code are if (...) { ... } else { ... Note that there is no closing brace for the else. That's what it's upset about.
unknown
d17534
val
public class TestActivity extends AppCompatActivity implements View.OnClickListener { ..... @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); .... for (int i = 0; i < letterBttns.length; i++) { letterBttns[i].setOnClickListener(this); } } @Override public void onClick(View v) { String text = ((Button) v).getText().toString(); } }
unknown
d17535
val
I'm guessing you have enabled the "Import Maven projects automatically" option. To disable it, go to Preferences... > Build, Execution, Deployment > Build Tools > Maven > Importing, then uncheck the option from there, like so: After doing so, it will be up to you to run the imports when you're ready. To import manually, right-click your project in the Project view, then click Maven > Reimport:
unknown
d17536
val
Please try below: adb shell am start -n com.android.certinstaller/.CertInstallerMain -a android.intent.action.VIEW -t application/x-x509-ca-cert -d file:///sdcard/test.cer if throw com.android.certinstaller E/CertInstaller: Failed to read certificate: java.io.FileNotFoundException: /sdcard/cer (Permission denied) please root your devices and push cer to /system/etc/ adb shell am start -n com.android.certinstaller/.CertInstallerMain -a android.intent.action.VIEW -t application/x-x509-ca-cert -d file:///system/etc/test.cer A: You need to make sure the file is readable if you are getting "Permission denied" or "Cloud not find the file" toast. chmod o+r /sdcard/test.cer and then adb shell am start -n com.android.certinstaller/.CertInstallerMain -a android.intent.action.VIEW -t application/x-x509-ca-cert -d file:///sdcard/test.cer
unknown
d17537
val
This is not a bug, it's the intended behavior. I updated the Hibernate User Guide to make it more obvious. The @Filter does not apply when you load the entity directly: Account account1 = entityManager.find( Account.class, 1L ); Account account2 = entityManager.find( Account.class, 2L ); assertNotNull( account1 ); assertNotNull( account2 ); While it applies if you use an entity query (JPQL, HQL, Criteria API): Account account1 = entityManager.createQuery( "select a from Account a where a.id = :id", Account.class) .setParameter( "id", 1L ) .getSingleResult(); assertNotNull( account1 ); try { Account account2 = entityManager.createQuery( "select a from Account a where a.id = :id", Account.class) .setParameter( "id", 2L ) .getSingleResult(); } catch (NoResultException expected) { expected.fillInStackTrace(); } So, as a workaround, use the entity query (JPQL, HQL, Criteria API) to load the entity.
unknown
d17538
val
Since you are creating views in code and not in the xml, you need to create and set LayoutParams for both the RelativeLayout and the Button. A: I am not sure you wrote that correct because setContentView connects Java file with xml file and the correct way to do this is to write this setContentView(R.layout.your_layout_name); in main which in android is onCreate method.
unknown
d17539
val
There are no "arrays" in Python, often when we talk of an "array" in Python context, we refer to NumPy array (this is not what you want here). But Python has lists that can hold objects of different types, thus it is feaseable to have e.g.: [[str, int, int, int],[str, int, int, int],...] which might be what you need. Not sure if it helps, I'd rather add it in a comment, but my account is not allowed to add comments yet.
unknown
d17540
val
Did you try googling for "boost random number" first? Here's the relevant part of their documentation generating boost random numbers in a range You want something like this: #include <time.h> #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int_distribution.hpp> std::time(0) gen; int random_number(start, end) { boost::random::uniform_int_distribution<> dist(start, end); return dist(gen); } edit: this related question probably will answer most of your questions: why does boost::random return the same number each time?
unknown
d17541
val
I'm just going to give you an indication to try to put you on the right way. You can to do something looks like that : $("#yourBtnID").click(function(elem){ $("#yourDivID").append("<td>" + elem + "</td>"); }); it will add a line td to the each click basically Now you can try to modify your own code and come back if you don't succeed Good luck ;)
unknown
d17542
val
You can use custom database initializer - it means implementing IDatabaseInitializer and registering this initializer by calling Database.SetInitializer. A: I'd like to add to Ladislav's answer. The article he pointed to shows how to create an initializer but does not show how to use an initializer to populate a newly created database. DbInitializer has a method called Seed that you can overwrite. You can see an example of how to use this in this article (or video if you prefer, which is on the same page) http://msdn.microsoft.com/en-us/data/hh272552
unknown
d17543
val
Yes, a bot can do that. There's many ways of creating bots, and different methods will make most bots undetectable unless you have some really complex checks in place. I believe reCaptcha has a tonne of checks for example, ranging from the movement of the mouse, the react time of the user, user agents and so on and so forth. Bots can come in all shapes and forms, including some that might use Selenium to imitate a user using an actual browser, or they could even be written in a lower level and move the mouse and cause key presses on a system level. What it comes down to is how much energy/time you're willing to expend to make it harder for bots to do their thing. I doubt you'll ever get 100% accuracy on stopping bots. But yes, a bot can trigger a button press event, or even press the button directly like a normal user would
unknown
d17544
val
TransactionScope sets Transaction.Current. That's all it does. Anything that wants to be transacted must look at that property. I believe EF does so each time the connection is opened for any reason. Probably, your connection is already open when the scope is installed. Open the connection inside of the scope or enlist manually. EF has another nasty "design decision": By default it opens a new connection for each query. That causes distributed transactions in a non-deterministic way. Be sure to avoid that.
unknown
d17545
val
Socket communication, and having the server send a message to the clients when the state changes, instead of the clients polling the server, seems like the way to go here. Almost a textbook example for sockets vs polling, I would say. In applications for public web, socket communication in Flash can sometimes be troublesome because of firewall settings and using other ports than 80 and so on, but in your internal system, it should work fine. A: Do you need the state to be a 14 Byte string (14 Bytes is 112-bits which would support 5.19 x 10^33 different status'), are there really that many states that you need to communicate? How many states do you need to convey?
unknown
d17546
val
wow, interesting behavior. I had a look at the requests using fiddler and I found a request to context/protected/RES_NOT_FOUND. This request came from a css file which was referenced in my template, but did not exist yet. When I remove this reference to the style sheet it works!!!
unknown
d17547
val
You can't change the PayPal payment notification sent as a result of your DoExpressCheckout call. You can, however, send them an email yourself in addition to it.
unknown
d17548
val
For better performing collections libraries, try trove. But, in general, you want to tackle these kinds of issues by streaming, or another form of lazy loading, such that you can do things like aggregation without loading the entire dataset into memory. You could also use a key value store like Redis or CouchDB for storing this data.
unknown
d17549
val
Most js libs that get TS types use either ...* as.... Or require allowSyntheticDefaultImports: true in your tsconfig for default exports to work correctly. import * as CleaveOptions from 'cleave.js/options' // AND import Cleave from 'cleave.js' //tsconfig.json ... { allowSyntheticDefaultImports: true } ...
unknown
d17550
val
You have a small error with document.createElement("node") - there is no tag node so appending other elements to that is also incorrect. The code could be simplified though as below ( the add to local storage will throw an error in the snippet though ) let data = { "quiz": { "q1": { "question": "Which one is correct team name in NBA?", "options": ["New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket"], "answer": "Huston Rocket" }, "q2": { "question": "'Namaste' is a traditional greeting in which Asian language?", "options": ["Hindi", "Mandarin", "Nepalese", "Thai"], "answer": "Hindi" }, "q3": { "question": "The Spree river flows through which major European capital city?", "options": ["Berlin", "Paris", "Rome", "London"], "answer": "Berlin" }, "q4": { "question": "Which famous artist had both a 'Rose Period' and a 'Blue Period'?", "options": ["Pablo Picasso", "Vincent van Gogh", "Salvador Daly", "Edgar Degas"], "answer": "Pablo Picasso" } } }; // utility prototype to shuffle an array Array.prototype.shuffle=()=>{ let i = this.length; while (i > 0) { let n = Math.floor(Math.random() * i); i--; let t = this[i]; this[i] = this[n]; this[n] = t; } return this; }; let list = document.createElement("ul"); Object.keys(data.quiz).forEach((q, index) => { // the individual record let obj = data.quiz[q]; // add the `li` item & set the question number as data-attribute let question = document.createElement("li"); question.textContent = obj.question; question.dataset.question = index + 1; question.id = q; // randomise the answers obj.options.shuffle(); // Process all the answers - add new radio & label Object.keys(obj.options).forEach(key => { let option = obj.options[key]; let label = document.createElement('label'); label.dataset.text = option; let cbox = document.createElement('input'); cbox.type = 'radio'; cbox.name = q; cbox.value = option; // add the new items label.appendChild(cbox); question.appendChild(label); }); // add the question list.appendChild(question); }); // add the list to the DOM document.getElementById('container').appendChild(list); // Process the checked radio buttons to determine score. document.querySelector('input[type="button"]').addEventListener('click', e => { let score = 0; let keys = Object.keys(data.quiz); document.querySelectorAll('[type="radio"]:checked').forEach((radio, index) => { if( radio.value === data.quiz[ keys[index] ].answer ) score++; }); console.log('%d/%d', score, keys.length); localStorage.setItem("answers", score); }) #container>ul>li { font-weight: bold } #container>ul>li>label { display: block; padding: 0.1rem; font-weight: normal; } #container>ul>li>label:after { content: attr(data-text); } #container>ul>li:before { content: 'Question 'attr(data-question)': '; color: blue } <div id="container"></div> <input type="button" value="Submit answers" /> A: You need to make minor changes to your nest loop so that the option labels are inserted in the correct location. See the code snippet where it is marked "remove" and "add" for the changes you need to make. As @ProfessorAbronsius noted, there isn't an html tag called "node", though that won't stop your code from working. let data = {"quiz": {"q1": {"question": "Which one is correct team name in NBA?", "options": ["New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket"], "answer": "Huston Rocket"}, "q2": {"question": "'Namaste' is a traditional greeting in which Asian language?", "options": ["Hindi", "Mandarin", "Nepalese", "Thai"], "answer": "Hindi"}, "q3": {"question": "The Spree river flows through which major European capital city?", "options": ["Berlin", "Paris", "Rome", "London"], "answer": "Berlin"}, "q4": {"question": "Which famous artist had both a 'Rose Period' and a 'Blue Period'?", "options": ["Pablo Picasso", "Vincent van Gogh", "Salvador Daly", "Edgar Degas"], "answer": "Pablo Picasso"}}}; let list = document.createElement("ul"); for (let questionId in data["quiz"]) { let item = document.createElement("node"); let question = document.createElement("strong"); question.innerHTML = questionId + ": " + data["quiz"][questionId]["question"]; item.appendChild(question); list.appendChild(item); let sublist = document.createElement("ul"); item.appendChild(sublist); // The problem is here in this nested loop for (let option of data["quiz"][questionId]["options"]) { item = document.createElement("input"); item.type = "radio"; item.name = data["quiz"][questionId]; var label = document.createElement("label"); label.htmlFor = "options"; // remove 1 // label.appendChild(document.createTextNode(data["quiz"][questionId]["options"])); // add 1 label.appendChild(document.createTextNode(option)); var br = document.createElement('br'); sublist.appendChild(item); // remove 2 //document.getElementById("container").appendChild(label); //document.getElementById("container").appendChild(br); // add 2 sublist.appendChild(label); sublist.appendChild(br); } } document.getElementById("container").appendChild(list); function results() { var score = 0; if (data["quiz"][questionId]["answer"].checked) { score++; } } // Removed because snippets don't allow localStorage // localStorage.setItem("answers", "score"); <div id="container"></div> <input type="submit" name="submit" value="Submit answers" onclick="results()"> A: Here's the answer to your question. Please let me know if you have any issues. <div id="container"></div> <input type="submit" name="submit" value="Submit answers" onclick="results()"> <script> let data = { "quiz": { "q1": { "question": "Which one is correct team name in NBA?", "options": ["New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket"], "answer": "Huston Rocket" }, "q2": { "question": "'Namaste' is a traditional greeting in which Asian language?", "options": ["Hindi", "Mandarin", "Nepalese", "Thai"], "answer": "Hindi" }, "q3": { "question": "The Spree river flows through which major European capital city?", "options": ["Berlin", "Paris", "Rome", "London"], "answer": "Berlin" }, "q4": { "question": "Which famous artist had both a 'Rose Period' and a 'Blue Period'?", "options": ["Pablo Picasso", "Vincent van Gogh", "Salvador Daly", "Edgar Degas"], "answer": "Pablo Picasso" } } }; data = data.quiz; let list = document.createElement("ul"); for (let questionId in data) { let item = document.createElement("node"); let question = document.createElement("strong"); let i = Object.keys(data).indexOf(questionId) + 1; question.innerHTML = "Question" + i + ": " + questionId["question"]; item.appendChild(question); list.appendChild(item); let sublist = document.createElement("ul"); item.appendChild(sublist); for (let option of data[questionId]["options"]) { item = document.createElement("input"); item.type = "radio"; item.name = questionId; var label = document.createElement("label"); label.htmlFor = option; label.appendChild(document.createTextNode(option)); var br = document.createElement('br'); sublist.appendChild(item); sublist.appendChild(label); sublist.appendChild(br); } } document.getElementById("container").appendChild(list); function results() { var score = 0; if (data[questionId]["answer"].checked) { score++; } } //localStorage.setItem("answers", "score"); </script>
unknown
d17551
val
Unpivot using Power Query: * *Data --> Get & Transform --> From Table/Range *Select the country column * *Unpivot Other columns *Rename the resulting Attribute and Value columns to date and count *Because the Dates which are in the header are turned into Text, you may need to change the date column type to date, or, as I did, to date using locale M-Code Source = Excel.CurrentWorkbook(){[Name="Table2"]}[Content], #"Changed Type" = Table.TransformColumnTypes(Source,{{"country", type text}, {"20/01/2020", Int64.Type}, {"21/01/2020", Int64.Type}, {"22/01/2020", Int64.Type}}), #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"country"}, "date", "count"), #"Changed Type with Locale" = Table.TransformColumnTypes(#"Unpivoted Other Columns", {{"date", type date}}, "en-150") in #"Changed Type with Locale" A: Power Pivot is the best way, but if you want to use formulas: In F1 enter: =INDEX($A$2:$A$4,ROUNDUP(ROWS($1:1)/3,0)) and copy downward. In G1 enter: =INDEX($B$1:$D$1,MOD(ROWS($1:1)-1,3)+1) and copy downward. H1 enter: =INDEX($B$2:$D$4,ROUNDUP(ROWS($1:1)/3,0),MOD(ROWS($1:1)-1,3)+1) and copy downward The 3 in these formulas is because we have 3 dates in the original table.
unknown
d17552
val
Please use http://pytest.readthedocs.org/en/2.0.3/xdist.html, it enables pytest to run tests across multiple processes/machines
unknown
d17553
val
I find that LINQ to SQL is much, much faster when I'm prototyping code. It just blows away any other method when I need something now. But there is a cost. Compared to hand-rolled stored procs, LINQ is slow. Especially if you aren't very careful as seemingly minor changes can suddenly make a single turn into 1+N queries. My recommendation. Use LINQ to SQL at first, then swtich to procs if you aren't getting the performance you need. A: A good question but a very controversial topic. This blog post from Frans Bouma from a few years back citing the pros of dynamic SQL (implying ORMs) over stored procedures sparked quite the fiery flame war. A: There was a great discussion on this topic at DevTeach in Montreal. If you go to this URL: http://www.dotnetrocks.com/default.aspx?showNum=240 you will be able to hear two experts in the field (Ted Neward and Oren Eini) discuss the pros and cons of each approach. Probably the best answer you will find on a subject that has no real definite answer.
unknown
d17554
val
Use, mainAxisAlignment: MainAxisAlignment.center in Row. Like this, Widget StepText() => Container( child: Row( mainAxisAlignment: MainAxisAlignment.center, // Add this line... children: [ Text( 'STEP 2/5', textAlign: TextAlign.center, style: TextStyle( fontSize: 12, color: Colors.deepPurple, fontWeight: FontWeight.w700, ), ), ]), ); For more info : https://docs.flutter.dev/development/ui/layout For remove shadow of AppBar use elevation, appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0.0,) For more info : https://api.flutter.dev/flutter/material/Material/elevation.html A: You can use this way to achieve the layout you want import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class babyNameScreen extends StatefulWidget { const babyNameScreen({Key? key}) : super(key: key); @override _babyNameScreenState createState() => _babyNameScreenState(); } class _babyNameScreenState extends State<babyNameScreen> { @override @override void initState() { // TODO: implement initState super.initState(); SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []); } Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.white, leading: IconButton( icon: new Icon( Icons.arrow_back_rounded, color: Colors.black, ), onPressed: () { // Navigator.push( // context, // MaterialPageRoute( // builder: (context) => WelcomeScreen())); }, ), ), body: Padding( padding: const EdgeInsets.only(top: 40), child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ StepText(), SizedBox( height: 25, ), NameText(), SizedBox( height: 25, ), EnterNameText(), // SizedBox( // height: 25, // ), TextBox(), //text field ContinueButton(), //elevated button ], ), ), ); } } Widget StepText() => Container( child: Text( 'STEP 2/5', textAlign: TextAlign.center, style: TextStyle( fontSize: 12, color: Colors.deepPurple, fontWeight: FontWeight.w700, ), ), ); Widget NameText() => Container( child: Text( 'What is her name?', textAlign: TextAlign.center, style: TextStyle( fontSize: 25, color: Colors.black, fontWeight: FontWeight.w700, ), ), ); Widget EnterNameText() => Container( child: Text( 'Enter name of your new profile.', textAlign: TextAlign.center, style: TextStyle( fontSize: 15, color: Colors.grey, fontWeight: FontWeight.w500, ), ), ); //text field Widget TextBox()=> Container( child: TextField( decoration: InputDecoration( border: OutlineInputBorder(), hintText: 'Enter a search term', ), ), ); //elevated button Widget ContinueButton()=> Container ( child: ElevatedButton( onPressed: () { //playSound(soundNumber); }, child: Text('Continue'), style: ButtonStyle( backgroundColor: MaterialStateProperty.all<Color>(Colors.deepPurple), ), ), );
unknown
d17555
val
This question is rather vague but the API documentation should be able to help you here. https://developers.google.com/maps/documentation/api-picker Just pick out which API you need. It should be something like setLocation(Coordinates) in all of them.
unknown
d17556
val
A simple start for a PHP based REST API would be: <?php // get the HTTP method, path and body of the request $method = $_SERVER['REQUEST_METHOD']; $request = explode('/', trim($_SERVER['PATH_INFO'],'/')); $input = json_decode(file_get_contents('php://input'),true); // connect to the mysql database $link = mysqli_connect('localhost', 'user', 'pass', 'dbname'); mysqli_set_charset($link,'utf8'); // retrieve the table and key from the path $table = preg_replace('/[^a-z0-9_]+/i','',array_shift($request)); $key = array_shift($request)+0; // escape the columns and values from the input object $columns = preg_replace('/[^a-z0-9_]+/i','',array_keys($input)); $values = array_map(function ($value) use ($link) { if ($value===null) return null; return mysqli_real_escape_string($link,(string)$value); },array_values($input)); // build the SET part of the SQL command $set = ''; for ($i=0;$i<count($columns);$i++) { $set.=($i>0?',':'').'`'.$columns[$i].'`='; $set.=($values[$i]===null?'NULL':'"'.$values[$i].'"'); } // create SQL based on HTTP method switch ($method) { case 'GET': $sql = "select * from `$table`".($key?" WHERE id=$key":''); break; case 'PUT': $sql = "update `$table` set $set where id=$key"; break; case 'POST': $sql = "insert into `$table` set $set"; break; case 'DELETE': $sql = "delete `$table` where id=$key"; break; } // excecute SQL statement $result = mysqli_query($link,$sql); // die if SQL statement failed if (!$result) { http_response_code(404); die(mysqli_error()); } // print results, insert id or affected row count if ($method == 'GET') { if (!$key) echo '['; for ($i=0;$i<mysqli_num_rows($result);$i++) { echo ($i>0?',':'').json_encode(mysqli_fetch_object($result)); } if (!$key) echo ']'; } elseif ($method == 'POST') { echo mysqli_insert_id($link); } else { echo mysqli_affected_rows($link); } // close mysql connection mysqli_close($link); source For a more complete implementation check out: https://github.com/mevdschee/php-crud-api Disclosure: I am the author.
unknown
d17557
val
The best way is to write your own code. Using a library will work but it will be generic and by definition slower than what you can write for your specific use case. You are far, far better off learning the few lines of code it takes to download an image and display it. Learn how to use a NSURLSession. Learn how to consume NSData and turn it into a UIImage. Learn how to use a NSNotification or a block to propagate the loaded image to your user interface. Your code will be stronger and you will become a better developer.
unknown
d17558
val
Well, yes and no. The simplest way is to check if the condition is met, and if not, regenerate the randoms. But the result of this is your variables are no longer characterized by the statistical distributions you started with: the filtering process biases x1 low and x2 high. But if you're okay with this, then just loop until the desired condition is met... in theory this could take an infinite number of iterations, but I assume you're not that unlucky :). If the two distributions are the same, it's simpler: just swap them if x1 > x2 (I assume they're not equal!)
unknown
d17559
val
its working fine for me php function will return the rows/No Results as response public function shamsearchJSON () { $search = $this->input->post('search'); $query = $this->user_model->getmessages($search); if(!empty($query)){ echo json_encode(array('responses'=> $query)); } else{ echo json_encode(array('responses'=> 'No Results')); } } javascript code $( "#search-inbox" ).autocomplete({ minLength: 2, source: function( request, response ) { // $.getJSON( "<?php echo base_url(); ?>index.php/user/shamsearchJSON?search="+request.term,response ); $.ajax({ url: "<?php echo base_url(); ?>index.php/user/shamsearchJSON", data: {"search": request.term}, type:"POST", success: function( data ) { var parsed = JSON.parse(data); if(parsed.responses == "No Results") { alert("no results::"); var newArray = new Array(1); var newObject = { sub: "No Results", id: 0 }; } else{ var newArray = new Array(parsed.length); var i = 0; parsed.responses.forEach(function (entry) { var newObject = { sub: entry.subject, id: entry.mID }; newArray[i] = newObject; i++; }); } response(newArray); }, error:function(){ alert("Please try again later"); } }); }, focus: function( event, ui ) { //$( "#search-inbox" ).val( ui.item.sub ); return false; }, select: function( event, ui ) { if(ui.item.id != 0){ $( "#search-inbox" ).val( ui.item.sub ); openInboxMessage(ui.item.id); } else { } return false; } }).data( "ui-autocomplete" )._renderItem = function( ul, item ){ return $( "<li>" ).append("<a>" + item.sub +"</a>" ).appendTo(ul); };
unknown
d17560
val
import { First, Second } from './containers' This is not a valid import statement. If you are importing a directory, then it should contain an index.js file which have exports for the files. A simple solution is to import the components as: import First from './containers/First'; import Second from './containers/Second'; Hope this works for you.
unknown
d17561
val
I'm slightly unclear in the question whether %x and %y are CMD variables (in which case you should be using %x% to substitute it in, or a substitution happening in your other application. You need to escape the single quote you are passing to PowerShell by doubling it in the CMD.EXE command line. You can do this by replacing any quotes in the variable with two single quotes. For example: C:\scripts>set X=a'b C:\scripts>set Y=c'd C:\scripts>powershell .\test.ps1 -name '%x:'=''%' '%y:'=''%' Name is 'a'b' Data is 'c'd' where test.ps1 contains: C:\scripts>type test.ps1 param($name,$data) write-output "Name is '$name'" write-output "Data is '$data'" If the command line you gave is being generated in an external application, you should still be able to do this by assigning the string to a variable first and using & to separate the commands (be careful to avoid trailing spaces on the set command). set X=a'b& powershell .\test.ps1 -name '%x:'=''%' The CMD shell supports both a simple form of substitution, and a way to extract substrings when substituting variables. These only work when substituting in a variable, so if you want to do multiple substitutions at the same time, or substitute and substring extraction then you need to do one at a time setting variables with each step. Environment variable substitution has been enhanced as follows: %PATH:str1=str2% would expand the PATH environment variable, substituting each occurrence of "str1" in the expanded result with "str2". "str2" can be the empty string to effectively delete all occurrences of "str1" from the expanded output. "str1" can begin with an asterisk, in which case it will match everything from the beginning of the expanded output to the first occurrence of the remaining portion of str1. May also specify substrings for an expansion. %PATH:~10,5% would expand the PATH environment variable, and then use only the 5 characters that begin at the 11th (offset 10) character of the expanded result. If the length is not specified, then it defaults to the remainder of the variable value. If either number (offset or length) is negative, then the number used is the length of the environment variable value added to the offset or length specified. %PATH:~-10% would extract the last 10 characters of the PATH variable. %PATH:~0,-2% would extract all but the last 2 characters of the PATH variable. A: This is actually a lot trickier than you'd think. Escaping nested quotes in strings passed from cmd to PowerShell is a major headache. What makes this one especially tricky is that you need to make the replacement in a variable expanded by cmd in the quoted argument passed to powershell.exe within a single-quoted argument passed to a PowerShell script parameter. AFAIK cmd doesn't have any native functionality for even basic string replacements, so you need PowerShell to do the replacement for you. If the argument to the -data paramater (the one contained in the cmd variable x) doesn't necessarily need to be single-quoted, the simplest thing to do is to double-quote it, so that single quotes within the value of x don't need to be escaped at all. I say "simplest", but even that is a little tricky. As Vasili Syrakis indicated, ^ is normally the escape character in cmd, but to escape double quotes within a (double-)quoted string, you need to use a \. So, you can write your batch command like this: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass "G:\test.ps1 -name \"%x%\" -data '%y%'" That passes the following command to PowerShell: G:\test.ps1 -name "value of x, which may contain 's" -data 'value of y' If, however, x can also contain characters that are special characters in PowerShell interpolated strings (", $, or `), then it becomes a LOT more complicated. The problem is that %x is a cmd variable that gets expanded by cmd before PowerShell has a chance to touch it. If you single-quote it in the command you're passing to powershell.exe and it contains a single quote, then you're giving the PowerShell session a string that gets terminated early, so PowerShell doesn't have the opportunity to perform any operations on it. The following obviously doesn't work, because the -replace operator needs to be supplied a valid string before you can replace anything: 'foo'bar' -replace "'", "''" On the other hand, if you double-quote it, then PowerShell interpolates the string before it performs any replacements on it, so if it contains any special characters, they're interpreted before they can be escaped by a replacement. I searched high and low for other ways to quote literal strings inline (something equivalent to perl's q//, in which nothing needs to be escaped but the delimiter of your choice), but there doesn't seem to be anything. So, the only solution left is to use a here string, which requires a multi-line argument. That's tricky in a batch file, but it can be done: setlocal EnableDelayedExpansion set LF=^ set pscommand=G:\test.ps1 -name @'!LF!!x!!LF!'@ -data '!y!' C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass "!pscommand!" * *This assumes that x and y were set earlier in the batch file. If your app can only send a single-line command to cmd, then you'll need to put the above into a batch file, adding the following two lines to the beginning: set x=%~1 set y=%~2 Then invoke the batch file like this: path\test.bat "%x%" "%y%" The ~ strips out the quotes surrounding the command line arguments. You need the quotes in order to include spaces in the variables, but the quotes are also added to the variable value. Batch is stupid that way. *The two blank lines following set LF=^ are required. That takes care of single quotes which also interpreting all other characters in the value of x literally, with one exception: double quotes. Unfortunately, if double quotes may be part of the value as you indicated in a comment, I don't believe that problem is surmountable without the use of a third party utility. The reason is that, as mentioned above, batch doesn't have a native way of performing string replacements, and the value of x is expanded by cmd before PowerShell ever sees it. BTW...GOOD QUESTION!! UPDATE: In fact, it turns out that it is possible to perform static string replacements in cmd. Duncan added an answer that shows how to do that. It's a little confusing, so I'll elaborate on what's going on in Duncan's solution. The idea is that %var:hot=cold% expands to the value of the variable var, with all occurrences of hot replaced with cold: D:\Scratch\soscratch>set var=You're such a hot shot! D:\Scratch\soscratch>echo %var% You're such a hot shot! D:\Scratch\soscratch>echo %var:hot=cold% You're such a cold scold! So, in the command (modified from Duncan's answer to align with the OP's example, for the sake of clarity): powershell G:\test.ps1 -name '%x:'=''%' -data '%y:'=''%' all occurrences of ' in the variables x and y are replaced with '', and the command expands to powershell G:\test.ps1 -name 'a''b' -data 'c''d' Let's break down the key element of that, '%x:'=''%': * *The two 's at the beginning and the end are the explicit outer quotes being passed to PowerShell to quote the argument, i.e. the same single quotes that the OP had around %x *:'='' is the string replacement, indicating that ' should be replaced with '' *%x:'=''% expands to the value of the variable x with ' replaced by '', which is a''b *Therefore, the whole thing expands to 'a''b' This solution escapes the single quotes in the variable value much more simply than my workaround above. However, the OP indicated in an update that the variable may also contain double quotes, and so far this solution still doesn't pass double quotes within x to PowerShell--those still get stripped out by cmd before PowerShell receives the command. The good news is that with the cmd string replacement method, this becomes surmountable. Execute the following cmd commands after the initial value of x has already been set: * *Replace ' with '', to escape the single quotes for PowerShell: set x=%x:'=''% *Replace " with \", to escape the double quotes for cmd: set x=%x:"=\"% The order of these two assignments doesn't matter. *Now, the PowerShell script can be called using the syntax the OP was using in the first place (path to powershell.exe removed to fit it all on one line): powershell.exe -ExecutionPolicy Bypass "G:\test.ps1 -name '%x' -data '%y'" Again, if the app can only send a one-line command to cmd, these three commands can be placed in a batch file, and the app can call the batch file and pass the variables as shown above (first bullet in my original answer). One interesting point to note is that if the replacement of " with \" is done inline rather than with a separate set command, you don't escape the "s in the string replacement, even though they're inside a double-quoted string, i.e. like this: powershell.exe -ExecutionPolicy Bypass "G:\test.ps1 -name '%x:"=\"' -data '%y'" ...not like this: powershell.exe -ExecutionPolicy Bypass "G:\test.ps1 -name '%x:\"=\\"' -data '%y'" A: I beleive you can escape it with ^: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass "G:\test.ps1 -name ^'%x^' -data ^'%y^'" A: Try encapsulating your random single quote variable inside a pair of double quotes to avoid the issue. C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass "G:\test.ps1 -name `"%x`" -data `"%y`"" The problem arises because you used single quotes and the random extra single quote appearing inside the single quotes fools PowerShell. This shouldn't occur if you double quote with backticks, as the single quote will not throw anything off inside double quotes and the backticks will allow you to double/double quote. A: Just FYI, I ran into some trouble with a robocopy command in powershell and wanting to exclude a folder with a single quote in the name (and backquote didn't help and ps and robocopy don't work with double quote); so, I solved it by just making a variable for the folder with a quote in it: $folder="John Doe's stuff" robocopy c:\users\jd\desktop \\server\folder /mir /xd 'normal folder' $folder A: One wacky way around this problem is to use echo in cmd to pipe your command to 'powershell -c "-" ' instead of using powershell "arguments" for instance: ECHO Write-Host "stuff'" | powershell -c "-" output: stuff' Couple of notes: * *Do not quote the command text you are echoing or it won't work *If you want to use any pipes in the PowerShell command they must be triple-escaped with carats to work properly ^^^|
unknown
d17562
val
If you want exactly specific number of packets, then we can use a queue/array that stores random indices of constrained value to be stored. class packet_1; packet p1; int NUM_CONSTRAINED_PKTS=10; // Number of pkts to be constrained int NUM_TOTAL_PKTS=30; // total number of pkts to be generated rand int q[$]; constraint c1{ q.size == NUM_CONSTRAINED_PKTS; // random indices = total constrained pkts generated foreach(q[i]){q[i]>=0; q[i]<NUM_TOTAL_PKTS;} // indices from 0-total_pkts unique {q}; // unique indices }; task pack(); p1=new; p1.num=0; this.randomize(); // randomize indices in q for(int i=0;i<NUM_TOTAL_PKTS;i++) begin if(i inside {q}) begin // check if index matches p1.randomize with {(p1.length==6);} ; p1.num++; // debug purpose end else p1.randomize ; $display("packet is %p",p1); end if(p1.num != NUM_CONSTRAINED_PKTS) $error("Error: p1.num=%0d",p1.num); // 10 pkts with constrained value else $display("Pass!!"); endtask endclass Another method is to use dist operator on length variable with some glue logic to generate a weighted distribution in the output.
unknown
d17563
val
You can create a RegExp pattern from string "abcdefghijklmnopqrstuvwxyz " with RegExp() constructor with case insensitive flag i; iterate elements using a loop; if .textContent of element begins with one of the characters of string cast to RegExp or every character of element .textContent is one of the characters within RegExp, set element .className to "ENGLISH", else set element .className to "ARAB". Note that id of element in document should be unique. Also, <p> is not a valid child element of <p> element. Substituted class="posttextareadisplay" for id="posttextareadisplay" at parent <p> element and <span> for child <p> element. const en = "abcdefghijklmnopqrstuvwxyz "; for (let el of document.querySelectorAll(".ENGLISH")) { if (new RegExp(`^[${en.slice(0, en.length -1)}]`, "i").test(el.textContent) || [...el.textContent].every(char => new RegExp(`${char}`, "i").test(en))) { el.className = "ENGLISH" } else { el.className = "ARAB" } } PART 1 <p class="posttextareadisplay"> <span class="ENGLISH">This is a samplasde textssss</span> <span class="ENGLISH"><b>فَإِذَا جَلَسْتَ فِي وَسَطِ الصلَاةِ فَاطْمَئِن، وَافْتَرِشْ فَخِذَكَ الْيُسْرَى ثُم تَشَهدْ</b></span> </p> PART 2 <p class="posttextareadisplay"> <span class="ENGLISH">This is a samplasde textssss <b>فَإِذَا جَلَسْتَ فِي وَسَطِ الصلَاةِ فَاطْمَئِن، وَافْتَرِشْ فَخِذَكَ الْيُسْرَى ثُم تَشَهدْ</b></span> </p>
unknown
d17564
val
Everything does happen on one thread unless you explicitly tell it not to. However, showing a Dialog happens asynchronously. Basically, when you ask the Dialog to show, it adds that information to a list of UI events that are waiting to happen, and it will happen at a later time. This has the effect that the code after asking the Dialog to show will execute right away. To have something execute after a Dialog choice is made, add an onDismissListener to the dialog and do whatever it is you want to do in onDismiss.
unknown
d17565
val
well, you could try hacks like this.... ​$(':radio:disabled').removeAttr('disabled').click(function(){ this.checked=false; })​; this will select all disabled radio buttons and enabled it but when click, will not be checked... demo and on <select> you could do like, $('select:disabled').removeAttr('disabled').change(function(){ $(this).find('option').removeAttr('selected'); // this.value = this.defaultValue; // you may also try this.. }); A: Just replace them with your own more controllable HTML/CSS construct, à la Niceforms, et al. (with disabled or readonly attribute, as appropriate, as fallback). A: A suggestion rather an answer: you can associate an event with the state change of an element, and cancel the change. You can do it the same way as the validate tools which allows to enter only digits or only some characters in <input type="text" /> fields. See a StackOverflow post about this. Another solution is to put something in front of your controls. For example: <div style="position:absolute;width:200px;height:200px;"></div> <input type="radio" /> will make your radio button unclickable. The problem is that doing so will prevent the users to copy-paste text or using hyperlinks, if the <div/> covers the whole page. You can "cover" each control one by one, but it may be quite difficult to do.
unknown
d17566
val
Try this echo "<a href='" . $cl . "'> Please click here to redeem the coupon</a>"; If you still have the issue, check how $cl was created. A: I really appreciate all the responses. But I just want to post the code that finally worked for me after 7 hours of work. I understand that it looks silly but this is the best I could do for now. Here's what worked for me: ?> <a href='<?php echo trim($cl); ?>'> <span color="#557da1">Click here to take <?php echo ' '.$_product_name.'</span></a>'; A: I just encountered the same issue, but I'm using ASP.NET. All I did was delete the single quote and type it again. Now it works. <asp:HyperLink ... NavigateUrl='<%# Eval("Url") %>' Text='<%# Eval("Name") %>' /> There were possibly some extra invisible characters which needed to be deleted.
unknown
d17567
val
You can't install Node or NPM globally with the Frontend maven plugin. If we take a look at the documentation we'll see that the entire purpose of the plugin is to be able to install Node and NPM in an isolated environment solely for the build and which does not affect the rest of the machine. Node/npm will only be "installed" locally to your project. It will not be installed globally on the whole system (and it will not interfere with any Node/npm installations already present.) Not meant to replace the developer version of Node - frontend developers will still install Node on their laptops, but backend developers can run a clean build without even installing Node on their computer. Not meant to install Node for production uses. The Node usage is intended as part of a frontend build, running common javascript tasks such as minification, obfuscation, compression, packaging, testing etc. You can try to run the plugin with two different profiles, one for install and one for day-to-day use after installation. In the below example, you should be able to install Node and NPM by running: mvn clean install -PinstallNode Then every build after: mvn clean install -PnormalBuild Or because normalBuild is set to active by default, just: mvn clean install Notice install goals are not in the day-to-day profile: <profiles> <profile> <id>installNode</id> <build> <plugins> <plugin> <groupId>com.github.eirslett</groupId> <artifactId>frontend-maven-plugin</artifactId> <version>0.0.26</version> <!-- optional --> <configuration> <workingDirectory>DIR</workingDirectory> <nodeVersion>v4.2.1</nodeVersion> <npmVersion>3.5.1</npmVersion> <installDirectory>node</installDirectory> </configuration> <executions> <execution> <id>node and npm install</id> <goals> <goal>install-node-and-npm</goal> </goals> <configuration> <arguments>install</arguments> <installDirectory>node</installDirectory> </configuration> </execution> <execution> <id>npm install</id> <goals> <goal>npm</goal> </goals> <configuration> <arguments>install</arguments> <installDirectory>node</installDirectory> </configuration> </execution> <execution> <id>grunt build</id> <goals> <goal>grunt</goal> </goals> <configuration> <arguments>build</arguments> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> <profile> <id>normalBuild</id> <activation> <activeByDefault>true</activeByDefault> </activation> <build> <plugins> <plugin> <groupId>com.github.eirslett</groupId> <artifactId>frontend-maven-plugin</artifactId> <version>0.0.26</version> <!-- optional --> <configuration> <workingDirectory>DIR</workingDirectory> <nodeVersion>v4.2.1</nodeVersion> <npmVersion>3.5.1</npmVersion> <installDirectory>node</installDirectory> </configuration> <executions> <execution> <id>grunt build</id> <goals> <goal>grunt</goal> </goals> <configuration> <arguments>build</arguments> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles>
unknown
d17568
val
There's a long-ish walkthrough here: How to Cache Entity Framework Reference Data But profile first. Writing good projections may be faster than materializing entire entities with cached references. Even loading single referenced objects is quite fast. Don't "optimize" stuff which isn't slow.
unknown
d17569
val
I need to add the parameter --service-ports when using docker-compose run [service-name]. So the right command is: docker-compose -f docker-compose.local.yml run --service-ports blacklist-service which allows me to curl to localhost:8080/status and get the response I was expecting.
unknown
d17570
val
Try this: $sql = "INSERT INTO writings (uid, TaskID, Date, Text, Title, comment) VALUES ('$uid','$TaskID','$Date','$Text','$Title','')"; $result = mysql_query( $sql, $MySQLiconn ); if(! $result ) { die('Could not enter data: ' . mysql_error()); } echo "Entered data successfully\n";
unknown
d17571
val
I was playing around and ran into the same error a minute ago. Here's what worked for me. Have a look on the Accessing the Developer APIs page. The important part is: @Override public void onCreate(Bundle savedInstanceState) { // set requested clients (games and cloud save) setRequestedClients(BaseGameActivity.CLIENT_GAMES | BaseGameActivity.CLIENT_APPSTATE); … } The flags BaseGameActivity.CLIENT_GAMES | BaseGameActivity.CLIENT_APPSTATE ask for the Play Games and the Cloud Save APIs. There's also a different option to get the same thing if you're extending the BaseGameActivity class. In the CollectAllTheStars sample they pass the requested APIs to the BaseGameActivity constructor: public MainActivity() { // request that superclass initialize and manage the AppStateClient for us super(BaseGameActivity.CLIENT_APPSTATE); } This game is only using Cloud Save so it only has the CLIENT_APPSTATE flag.
unknown
d17572
val
Found out that should have used fragments, not activities for this as activities disconnect you and connect you to the Play Mobile Services.
unknown
d17573
val
FIRST You cannot do this struct Shelf{ int clothes; int books; }; struct Shelf b; b.clothes=5; b.books=6; In global scope You can assign value inside a function int main (void ) { b.clothes=5; b.books=6; } Or initializing values on declaration struct Shelf b = { .clothes = 5, .books = 6 }; Moreover as you can see b is not a pointer so using -> is not correct: use . to access members of struct. SECOND Your struct has a pointer member book struct Shelf{ int clothes; int *books; }; What you can do is to set it to the address of another variable, like int book = 6; struct Shelf b = { .clothes = 5, .books = &book }; Or allocate memory for that pointer like int main (void ) { b.clothes=5; b.books=malloc(sizeof(int)); if (b.books != NULL) { *(b.books) = 6; } } BTW I guess you want an array of books, so int main (void ) { b.clothes=5; b.books=malloc(sizeof(int) * MAX_N_OF_BOOKS); if (b.books != NULL) { for (int i=0; i<MAX_N_OF_BOOKS; i++) b.books[i] = 6; } } COMPETE TEST CODE #include <stdio.h> #include <stdlib.h> struct Shelf { int clothes; int *books; }; int main(void) { struct Shelf b; b.clothes = 5; b.books = malloc(sizeof(int)); if (b.books != NULL) { *(b.books) = 6; } printf ("clothes: %d\n", b.clothes); printf ("book: %d\n", *(b.books) ); } OUTPUT clothes: 5 book: 6 A: b is a struct, not a pointer, so -> is not correct. It's like doing (*b).books, which is wrong. struct Shelf{ int clothes; int *books; }; One data member of the struct is a pointer, however: struct Shelf b; is not a pointer, it is just a struct as I said before. As for your question in comment: b.clothes=5; is correct. Also something like this would be ok: int number = 6; b.books = &number; A: -> operator used to access of member of struct via pointer. b is not dynamically allocated so b->books=6; is wrong. You should first allocate memory for member books and then dereference it. b.books = malloc(sizeof(int)); *(b.books)= 6;
unknown
d17574
val
You can not only open an application. you e.g. can tell an application that registered a protocol to do an action. You can tell iTunes to open an album with the itmss:// protocol. Instant messenger may have registered e.g. aim://, skype:// or similar so that you can directly open a chat window. You can create a link with mailto:[email protected] to tell the default mail application to start a new mail with this address. But you can not start the application directly by default. If you have control over the system where the webpage ist opened, e.g. an in-house launching service or something like that. You could think of creating an protocol default handler for launching applications.
unknown
d17575
val
{ foo b = a; b.Inc(); a = b; } // Here is where the problem is seen Your problem is here. a = b; request a call to assignment operator, that you are don't implement, so, default one will do memberwise-assignment. After this, your char pointer will be dangling pointer. Following code will do correct work. class foo { public: foo ( std::string szTemp ) : nOffset( 0 ) { vec.resize( szTemp.size() ); std::memcpy( &vec[ 0 ], szTemp.c_str(), szTemp.size() ); pChar = &vec[ 0 ]; } foo( const foo & Other ) : vec( Other.vec ) , nOffset( Other.nOffset ) { pChar = &vec[ nOffset ]; } foo& operator = (const foo& other) { foo tmp(other); swap(tmp); return *this; } void Inc ( void ) { ++nOffset; pChar = &vec[ nOffset ]; } void Swap(foo& other) { std::swap(vec, other.vec); std::swap(nOffset, other.nOffset); std::swap(pChar, other.pChar); } size_t nOffset; char * pChar; std::vector< char > vec; }; A: Your class doesn't follow the rule of three. You have a custom copy constructor, but not a custom assignment operator (and no custom destructor, but this particular class probably doesn't need it). Which means foo b = a; does what you want (calls your copy ctor), but a = b; does not (calls the default assignment op). A: As mentioned in the other two answers, aftert he assignment a = b, a.pChar points into b.vec, and since b has left scope, it is a dangling pointer. You should either obey the rule of three (rule of five with C++11's move operations), or make that rule unnecessary by avoiding the storage of pChar, since that seems to be just a convenience alias for offset: class foo { public: foo ( std::string szTemp ) : nOffset( 0 ) { vec.resize( szTemp.size() ); std::coyp( begin(szTemp), end(szTemp), begin(vec) ); } //special members: foo(foo const&) = default; foo(foo&&) = default; foo& operator=(foo const&) = default; foo& operator=(foo&&) = default; ~foo() = default; void Inc ( void ) { ++nOffset; } char* pChar() //function instead of member variable! { return &vec[nOffset]; } size_t nOffset; std::vector< char > vec; }; This way, pChar() will always be consistent with nOffset, and the special members can be just defaulted (or omitted completely).
unknown
d17576
val
You can calculate the height of the .content-wrapper and adjust it. .content-wrapper { height: calc(100% - 70px); } Output: /* Styles go here */ html, body { height: 100%; min-height: 100%; } body { min-width: 1024px; font-family: 'Open Sans', sans-serif; margin: 0; padding: 0; border: 0; } .pull-right { float: left; } .pull-left { float: left; } .main-wrapper { width: 100%; height: 100%; } aside { width: 48px; height: 100%; float: left; background: #dedede; position: absolute; } aside.full-nav { width: 168px; } section.wrapper { width: 100%; height: 100%; float: left; padding-left: 168px; background: #eeeeee; } section.wrapper.full-size { padding-left: 48px; } aside ul.full-width { width: 100%; list-style-type: none; } aside nav ul li { height: 34px; } aside nav ul li:hover { opacity: 0.9; } aside.full-nav nav ul li.company-name { width: 100%; height: 80px; background: #717cba; position: relative; } aside.full-nav nav ul li.company-name span { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } aside nav ul li a { height: 34px; line-height: 1; max-height: 34px; font-size: 14px; font-weight: 400; color: #ffffff; margin: 5px 0 0 12px; text-decoration: none; display: block; } aside.full-nav nav ul li a.first { margin: 20px 0 0 12px; text-decoration: none; } aside nav ul li a:hover { color: #ffffff; } aside nav ul li.company-name .nav-company-overflow { display: none; } aside nav ul li.company-name .nav-company-logo { display: none; } aside.full-nav nav ul li.company-name a { height: 16px; color: #ffffff; margin: 10px 0 0 12px; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.35); position: absolute; z-index: 20; } aside.full-nav nav ul li.company-name .nav-company-overflow { width: 168px; height: 80px; position: absolute; top: 0; background: rgba(78, 91, 169, 0.8); z-index: 15; display: block; } aside.full-nav nav ul li.company-name .nav-company-logo { width: 168px; height: 80px; position: absolute; top: 0; z-index: 10; display: block; } aside nav ul li a em { line-height: 100%; display: inline-block; vertical-align: middle; margin: 0 18px 0 0; } aside nav ul li a span { width: 110px; display: inline-block; line-height: 100%; vertical-align: middle; max-width: 110px; } aside nav ul li a.profile em { width: 18px; height: 18px; background: url(../images/png/profile_spritesheet.png); background-position: -10px -676px; margin: 6px 8px 0 0; } aside.full-nav nav ul li a.profile em { margin: 0 8px 0 0; } aside nav ul li a.contacts em { width: 20px; height: 20px; background: url(../images/png/profile_spritesheet.png); background-position: -10px -224px; } aside nav ul li a.events em { width: 20px; height: 22px; background: url(../images/png/profile_spritesheet.png); background-position: -10px -268px; } aside nav ul li a.policy em { width: 20px; height: 23px; background: url(../images/png/profile_spritesheet.png); background-position: -10px -310px; } aside nav ul li a.admins em { width: 18px; height: 18px; background: url(../images/png/profile_spritesheet.png); background-position: -10px -676px; } aside.full-nav nav ul li a span { display: inline-block; } aside nav ul li a span { display: none; } aside .hide-sidebar { width: 100%; height: 34px; background: #455095; position: absolute; bottom: 0; } #hide-sidebar-btn { width: 30px; height: 34px; line-height: 40px; background: #394485; float: right; text-align: center; } #hide-sidebar-btn:hover { cursor: pointer; } aside .collapse-btn-icon { width: 8px; height: 15px; display: inline-block; background: url(../images/png/profile_spritesheet.png); background-position: -10px -353px; -webkit-transform: rotate(180deg); transform: rotate(180deg); } aside.full-nav .collapse-btn-icon { -webkit-transform: rotate(360deg); transform: rotate(360deg); } .innner-wrapper { height: 100%; margin: 0 12px 0 12px; } .main-partial { height: 100%; } header { height: 40px; background: #ffffff; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3); } header .buttons-header-area { float: right; } header .company-header-avatar { width: 28px; height: 28px; -webkit-border-radius: 28px; -webkit-background-clip: padding-box; -moz-border-radius: 28px; -moz-background-clip: padding; border-radius: 28px; background-clip: padding-box; margin: 7px 0 0 5px; float: left; } header .info { height: 40px; line-height: 40px; margin: 0 5px 0 0; } header .info em { width: 28px; height: 28px; display: inline-block; vertical-align: middle; background: url(../images/png/profile_spritesheet.png); background-position: -10px -53px; } header .dropdown-toggle { width: 170px; height: 40px; border: none; padding: 0; background: transparent; font-size: 12px; color: #444444; } header .btn-group { height: 40px; vertical-align: top; } header .btn-group.open { background: #eeeeee; } header .open > .dropdown-menu { width: 170px; font-size: 12px; border-color: #d9d9d9; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.11); margin: 2px 0 0 0; } header .dropdown-toggle:hover { background: #eeeeee; } header .profile-name { width: 100px; height: 40px; line-height: 40px; display: inline-block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } header .caret { height: 40px; border-top: 6px solid #bfbfbf; border-right: 6px solid transparent; border-left: 6px solid transparent; } .content { height: 100%; margin: 12px 0; overflow: hidden; } .content-wrapper { background: #ffffff none repeat scroll 0 0; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3); height: calc(100% - 70px); width: 100%; } .content-row.company { height: 300px; } .content-row-wrapper { margin: 0 18px; } <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="style.css"> <script src="script.js"></script> </head> <body> <div class="main-wrapper"> <aside class="full-nav" action-bar> </aside> <section class="wrapper"> <header> </header> <div class="content"> <div class="innner-wrapper"> <div class="main-partial"> <div class="content-wrapper">Content</div> </div> </div> </div> </section> </div> </body> </html> A: I think the problem is that you are assigning 100% height to the container and this one is getting the relative window height. The problem is the header at the top of the page does not let this to work. Maybe you have to calculate with javascript or something to apply the correct height to that container.
unknown
d17577
val
Roman Nurik posted an answer here: https://plus.google.com/111335419682524529959/posts/QJcExn49ZrR For performance. When the settings activity loads of the watch first shows up, I didn't want to wait for an IPC call to complete before showing anything For a detailed description checkout my medium post.
unknown
d17578
val
* *Read the file line by line (each line is a separate json) *Parse the line json text to JavaScript object *Put/push/append JavaScript object into a JavaScript array A: This is not valid JSON, so JSON.parse would not work, but assuming you have the text in a string variable, you can convert it to JSON with something like: data = "[" + data.replace(/\}/g, "},").replace(/,$/,"") + "]"; and then parse it. UPDATE: var array = []; // for each input line var obj = JSON.parse(line); array.push(obj); var id = obj.id; var time = obj.time; ... A: Appreciate the responses but I believe I have managed to solve my own question. Furthermore, as @Mr. White mentioned above, I did have my property names in error which I have now sorted - thanks. Using the data above, all I was after was the following: UPDATED var s = '{"id":"value1","time":"valuetime1"},{"id":"value2","time":"valuetime2"},{"id":"value3","time":"valuetime3"},{"id":"value4","time":"valuetime4"},{"id":"value5","time":"valuetime5"}, {"id":"value6","time":"valuetime6"},{"id":"value7","time":"valuetime7"},{"id":"value8","time":"valuetime8"}'; var a = JSON.parse('[' + s + ']'); a.forEach(function(item,i){ console.log(item.id + ' - '+ item.time); }); Thanks for the heads up @torazaburo - have updated my answer which I should've done much earlier.
unknown
d17579
val
As suggested by @VioletaGeorgieva, upgrading to Spring boot 2.6.8 has fixed the issue.
unknown
d17580
val
The first step is to parse the dest_prod column into a usable format: library(tidyverse) parsed <- df %>% mutate_at(c("id", "year"), as.integer) %>% separate_rows(dest_prod, sep = "[+]") %>% separate(dest_prod, into = c("dest", "prod")) parsed #> # A tibble: 18 × 4 #> id year dest prod #> <int> <int> <chr> <chr> #> 1 1 2000 FRA coke #> 2 1 2001 FRA coke #> 3 1 2002 USA coke #> 4 1 2003 FRA coke #> 5 1 2003 USA coke #> 6 2 2002 FRA coke #> 7 2 2003 SPA ham #> 8 2 2004 FRA coke #> 9 2 2004 SPA ham #> 10 2 2005 GER coke #> 11 3 2001 CHN water #> 12 3 2002 CHN oil #> 13 3 2003 CHN water #> 14 3 2003 CHN oil #> 15 3 2003 FRA coke #> 16 3 2005 CHN water #> 17 3 2005 CHN oil #> 18 3 2005 FRA coke Then: parsed %>% # Add previous year's data in a list column nest_join( mutate(., year = year + 1L), name = "previous", by = c("id", "year") ) %>% # Check if any dest/prod appeared in previous year rowwise() %>% mutate( new_dest = !dest %in% previous$dest, new_prod = !prod %in% previous$prod, ) %>% # Set to missing if previous year was not observed mutate( across(c(new_dest, new_prod), replace, !nrow(previous), NA) ) %>% # Aggregate indicators on year level group_by(id, year) %>% summarise( new_dest = any(new_dest), new_prod = any(new_prod), ) #> # A tibble: 12 × 4 #> # Groups: id [3] #> id year new_dest new_prod #> <int> <int> <lgl> <lgl> #> 1 1 2000 NA NA #> 2 1 2001 FALSE FALSE #> 3 1 2002 TRUE FALSE #> 4 1 2003 TRUE FALSE #> 5 2 2002 NA NA #> 6 2 2003 TRUE TRUE #> 7 2 2004 TRUE TRUE #> 8 2 2005 TRUE FALSE #> 9 3 2001 NA NA #> 10 3 2002 FALSE TRUE #> 11 3 2003 TRUE TRUE #> 12 3 2005 NA NA A: If you do want to fight the way dplyr wants to work, here's a non-pivot solution :) library(dplyr) library(purrr) library(stringr) df %>% mutate(year = as.numeric(year)) %>% left_join(., mutate(., year = year + 1), by = c('id', 'year'), suffix = c('', '_previous')) %>% rowwise() %>% mutate(dests = str_extract_all(dest_prod, '\\w{3}_'), prods = str_extract_all(dest_prod, '_\\w+'), new_dest = max(map_int(dests, \(x) !str_detect(dest_prod_previous, x))), new_prod = max(map_int(prods, \(x) !str_detect(dest_prod_previous, x)))) %>% select(-c(dests, prods, dest_prod_previous)) %>% ungroup() #> # A tibble: 12 × 5 #> id year dest_prod new_dest new_prod #> <chr> <dbl> <chr> <int> <int> #> 1 1 2000 FRA_coke NA NA #> 2 1 2001 FRA_coke 0 0 #> 3 1 2002 USA_coke 1 0 #> 4 1 2003 FRA_coke+USA_coke 1 0 #> 5 2 2002 FRA_coke NA NA #> 6 2 2003 SPA_ham 1 1 #> 7 2 2004 FRA_coke+SPA_ham 1 1 #> 8 2 2005 GER_coke 1 0 #> 9 3 2001 CHN_water NA NA #> 10 3 2002 CHN_oil 0 1 #> 11 3 2003 CHN_water+CHN_oil+FRA_coke 1 1 #> 12 3 2005 CHN_water+CHN_oil+FRA_coke NA NA
unknown
d17581
val
you can do with a query like this. 1) create a temp table 2) insert all unique row in temp 3) rename table ( is atomic) so the application not fails CREATE TABLE tmp_4_even LIKE 4_even; INSERT INTO tmp_4_even SELECT e2.* FROM ( SELECT id FROM ( SELECT min(id) AS id, GROUP_CONCAT(e1 SEPARATOR '-') AS g FROM ( SELECT id,e1 FROM 4_even UNION ALL SELECT id,e2 FROM 4_even UNION ALL SELECT id,e3 FROM 4_even UNION ALL SELECT id,e4 FROM 4_even ORDER BY id,e1 ) AS res GROUP BY id ) res2 GROUP BY g ) e1 LEFT JOIN 4_even e2 ON e1.id = e2.id; RENAME TABLE 4_even TO 4_even_org, tmp_4_even TO 4_even; sample inner query mysql> SELECT * FROM ( -> SELECT min(id) AS id, GROUP_CONCAT(e1 SEPARATOR '-') AS g -> FROM ( SELECT id,e1 FROM 4_even UNION ALL SELECT id,e2 FROM 4_even UNION ALL SELECT id,e3 FROM 4_even UNION ALL SELECT id,e4 FROM 4_even -> ORDER BY id,e1 -> ) AS res -> GROUP BY id -> ) res2 -> GROUP BY g ; +------+---------+ | id | g | +------+---------+ | 1 | 1-3-5-7 | | 4 | 5-7-1-5 | +------+---------+ 2 rows in set, 1 warning (0,00 sec) mysql> sample mysql> select * from 4_even; +----+------+------+------+------+ | id | e1 | e2 | e3 | e4 | +----+------+------+------+------+ | 1 | 1 | 5 | 3 | 7 | | 2 | 1 | 5 | 7 | 3 | | 3 | 5 | 1 | 7 | 3 | | 4 | 5 | 1 | 7 | 5 | +----+------+------+------+------+ 4 rows in set (0,00 sec) mysql> CREATE TABLE tmp_4_even LIKE 4_even; Query OK, 0 rows affected (0,02 sec) mysql> mysql> INSERT INTO tmp_4_even -> SELECT e2.* FROM ( -> SELECT id FROM ( -> SELECT min(id) AS id, GROUP_CONCAT(e1 SEPARATOR '-') AS g -> FROM ( SELECT id,e1 FROM 4_even UNION ALL SELECT id,e2 FROM 4_even UNION ALL SELECT id,e3 FROM 4_even UNION ALL SELECT id,e4 FROM 4_even -> ORDER BY id,e1 -> ) AS res -> GROUP BY id -> ) res2 -> GROUP BY g -> ) e1 -> LEFT JOIN 4_even e2 ON e1.id = e2.id; Query OK, 2 rows affected, 1 warning (0,00 sec) Records: 2 Duplicates: 0 Warnings: 1 mysql> mysql> RENAME TABLE 4_even TO 4_even_org, tmp_4_even TO 4_even; Query OK, 0 rows affected (0,00 sec) mysql> select * from 4_even; +----+------+------+------+------+ | id | e1 | e2 | e3 | e4 | +----+------+------+------+------+ | 1 | 1 | 5 | 3 | 7 | | 4 | 5 | 1 | 7 | 5 | +----+------+------+------+------+ 2 rows in set (0,00 sec) mysql>
unknown
d17582
val
Process.Kill() command for some reason, does, in fact, fire process exited event. Easiest way for me to know that the process was killed, was by making a volatile string that holds information about how it ended. (Change it to "killed" before process.kill etc...) A: First of all you do not need Threads at all. Starting a process is async in itself, so Process.Start(...) does not block and you can create as many processes as you want. Instead of using the static Process.Start method you should consider creating Process class instances and set the CanRaiseEvents property to true. Further there are a couple of events you can register (per instance) - those will only raise if CanRaiseEvents is set to true, but also after a process is/has exited (including Kill() calls). A: When you call Process.Start() it returns a Process class instance, which you can use to retrieve information from it output and kill that process any time Process p = Process.Start("process.exe"); //some operations with process, may be in another thread p.Kill()
unknown
d17583
val
SIMD is meant to work on multiple small values at the same time, hence there won't be any carry over to the higher unit and you must do that manually. In SSE2 there's no carry flag but you can easily calculate the carry as carry = sum < a or carry = sum < b like this. Worse yet, SSE2 doesn't have 64-bit comparisons either, so you must use some workaround like the one here Here is an untested, unoptimized C code based on the idea above: inline bool lessthan(__m128i a, __m128i b){ a = _mm_xor_si128(a, _mm_set1_epi32(0x80000000)); b = _mm_xor_si128(b, _mm_set1_epi32(0x80000000)); __m128i t = _mm_cmplt_epi32(a, b); __m128i u = _mm_cmpgt_epi32(a, b); __m128i z = _mm_or_si128(t, _mm_shuffle_epi32(t, 177)); z = _mm_andnot_si128(_mm_shuffle_epi32(u, 245),z); return _mm_cvtsi128_si32(z) & 1; } inline __m128i addi128(__m128i a, __m128i b) { __m128i sum = _mm_add_epi64(a, b); __m128i mask = _mm_set1_epi64(0x8000000000000000); if (lessthan(_mm_xor_si128(mask, sum), _mm_xor_si128(mask, a))) { __m128i ONE = _mm_setr_epi64(0, 1); sum = _mm_add_epi64(sum, ONE); } return sum; } As you can see, the code requires many more instructions and even after optimizing it may still be much longer than a simple 2 ADD/ADC pair in x86_64 (or 4 instructions in x86) SSE2 will help though, if you have multiple 128-bit integers to add in parallel. However you need to arrange the high and low parts of the values properly so that we can add all the low parts at once, and all the high parts at once See also * *practical BigNum AVX/SSE possible? *Can long integer routines benefit from SSE?
unknown
d17584
val
var hashMap : HashMap<String, Object> = HashMap<String, Object> () hashMap.put("someName", true); and pass this hash map to set method databaseRefernce.addSnapshotListener(new EventListener<DocumentSnapshot or QuerySnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) { if (value.exists()) { } } });
unknown
d17585
val
Check for window focus: var window_focus; $(window).focus(function() { window_focus = true; }).blur(function() { window_focus = false; }); Check if location.host matches specified domain and window is focused: if((location.host == "example.com")&&(window_focus == true)) { //window is focused and on specified domain for that website. //sounds, notifications, etc. here } Not completely sure if this is what you mean, but I hope it helps.
unknown
d17586
val
Your problem is in this line: id_application = models.CharField(default=document_id(), unique=True, editable=False) Although it might seem intuitive that document_id() is called every time you create a new instance of Document, this is not true. This is evaluated only once and later the randomly generated value will be the same. So, in case you didn't provide the value for id_application when instantiating your model, you will get a duplicated value error when creating a second instance. To avoid this, you need to provide the default in the __init__ of the model instead and remove the default kwarg from the field definition for clarity. def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.id_application is None: self.id_application = document_id() Or, you can also pass the function to the default and it will get called when creating each object. See the docs. # Note that there are no parenthesis id_application = models.CharField(default=document_id, unique=True, editable=False)
unknown
d17587
val
In general, the best way to record something like this is to attach it to the RequestHandler instance. For logging, you can override Application.log_request, which has access to the handler. You may need to pass either the request ID or the RequestHandler instance around to other parts of your code if you need to use this in multiple places. It is possible but tricky to use StackContext as something like a threading.Local if you really need this to be pervasive, but explicitly passing it around is probably best.
unknown
d17588
val
Maple's usual evaluation model is that arguments passed to commands are evaluated up front, prior to the computation done within the body of the command's own procedure. So if you pass test(x) to the plot command then Maple will evaluate that argument test(x) up front, with x being simply a symbolic name. It's only later in the construction of the plot that the plot command would substitute actual numeric values for that x name. So, the argument test(x) is evaluated up front. But let's see what happens when we try such an up front evaluation of test(x). test:=proc(n) local i,t; for i from 1 to n do t:=1; od; return t; end: test(x); Error, (in test) final value in for loop must be numeric or character We can see that your test procedure is not set up to receive a non-numeric, symbolic name such as x for its own argument. In other words, the problem lies in what you are passing to the plot command. This kind of problem is sometimes called "premature evaluation". It's a common Maple usage mistake. There are a few ways to avoid the problem. One way is to utilize the so-called "operator form" calling sequence of the plot command. plot(test, 1..10); Another way is to delay the evaluation of test(x). The following use of so-called unevalution quotes (aka single right ticks, ie. apostrophes) delays the evaluation of test(x). That prevents test(x) from being evaluated until the internal plotting routines substitute the symbolic name x with actual numeric values. plot('test(x)', x=1..10); Another technique is to rewrite test so that any call to it will return unevaluated unless its argument is numeric. test:=proc(n) local i,t; if not type(n,numeric) then return 'procname'(args); end if; for i from 1 to n do t:=1; od; return t; end: # no longer produces an error test(x); test(x) # the passed argument is numeric test(19); 1 plot(test(x), x=1..10); I won't bother showing the actual plots here, as your example produces just the plot of the constant 1 (one). A: @acer already talked about the technical problem, but your case may actually have a mathematical problem. Your function has Natural numbers as its domain, i.e. the set of positive integers {1, 2, 3, 4, 5, ...} Not the set of real numbers! How do you interpret doing a for-loop for until a real number for example Pi or sqrt(2) to 5/2? Why am I talking about real numbers? Because in your plot line you used plot( text(x), x = 1..10 ). The x=1..10 in plot is standing for x over the real interval (1, 10), not the integer set {1, 2, ..., 10}! There are two ways to make it meaningful. * *Did you mean a function with integer domain? Then your plot should be a set of points. In that case you want a points-plot, you can use plots:-pointplot or adding the option style=point in plot. See their help pages for more details. Here is the simplest edit to your plot-line (keeping the part defininf test the same as in your post). plot( [ seq( [n, test(n)], n = 1..10 ) ], style = point ); And the plot result is the following. *In your function you want the for loop to be done until an integer in relation with a real number, such as its floor? This is what the for-loop in Maple be default does. See the following example. t := 0: for i from 1 by 1 to 5/2 do t := t + 1: end do; As you can see Maple do two steps, one for i=1 and one for i=2, it is treated literally as for i from 1 by 1 to floor(5/2) do, and this default behavior is not for every real number, if you replace 5/2 by sqrt(2) or Pi, Maple instead raise an error message for you. But anyway the fix that @acer provided for your code, plots the function "x -> test(floor(x))" in your case when x comes from rational numbers (and float numbers ^_^). If you change your code instead of returning constant number, you will see it in your plot as well. For example let's try the following. test := proc(n) local i,t: if not type(n, numeric) then return 'procname'(args): end if: t := 0: for i from 1 to n do t := t + 1: end do: return(t): end: plot(test(x), x=1..10); Here is the plot. It is indeed "x -> test(floor(x))".
unknown
d17589
val
Is there a way to tell the difference between such a click, in the empty space at the end of the table, and a click on a "proper" cell of the table? Yes. For the cheap and easy solution only do what you are trying to do if you actually get an indexPath: NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:p]; if(indexPath != nil){ // do everything in here } Basically, your indexPath is returning nil because it can't find a row. From the docs: An index path representing the row and section associated with point, or nil if the point is out of the bounds of any row. You could do it the way that you're currently doing it but is there any reason why you aren't using: -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath This is a much more standard way of detecting the cell that the user tapped on. This method won't be called if you tap on something that isn't a cell and has a number of other benefits. Firstly you get a reference to the tableView and the indexPath for free. But you also won't need any gesture recognisers this way either. Try something like this: -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; // Do stuff with cell here... } Obviously this all assumes that you have correctly set a class as your table view's delegate. NB: It's very easy to mistakenly write didDeselectRowAtIndexPath instead of didSelectRowAtIndexPath when using Xcode's autocompletion to do this. I always do this and then inevitably realise my mistake 20 minutes later.
unknown
d17590
val
before moving it in the last for-loop you can check if the file already exists and depending of the result moving it. I made an recursive function that checks the name of the files and incrementing it until the filename is new: import os def renamefile(ffpath, idx = 1): #Rename the file from test.jpeg to test1.jpeg path, ext = os.path.splitext(ffpath) path, filename = path.split('/')[:-1], path.split('/')[-1] new_filename = filename + str(idx) path.append(new_filename + ext) path = ('/').join(path) #Check if the file exists. if not return the filename, if it exists increment the name with 1 if os.path.exists(path): print("Filename {} already exists".format(path)) return renamefile(ffpath, idx = idx+1) return path for filename in filelistsrc: if os.path.exists(filename): renamefile(filename) shutil.move(filename, dictfiles[filename]) A: Here is another solution, def move_files(str_src, str_dest): for f in os.listdir(str_src): if os.path.isfile(os.path.join(str_src, f)): # if not .html continue.. if not f.endswith(".html"): continue # count file in the dest folder with same name.. count = sum(1 for dst_f in os.listdir(str_dest) if dst_f == f) # prefix file count if duplicate file exists in dest folder if count: dst_file = f + "_" + str(count + 1) else: dst_file = f shutil.move(os.path.join(str_src, f), os.path.join(str_dest, dst_file)) A: If the file already exists, we want to create a new one and not overwrite it. for filname in filelistsrc: if os.path.exists(dictfiles[filename]): i, temp = 1, filename file_name, ext = filename.split("/")[-1].split(".") while os.path.exists(temp): temp = os.path.join(strdest, f"{file_name}_{i}.{ext}") dictfiles[filename] = temp i += 1 shutil.move(filename, dictfiles[filename]) Check if the destination exists. If yes, create a new destination and move the file.
unknown
d17591
val
CLR require some communication overhead (to pass data between the CLR and SQL Server) Rule of thumb is: * *If your logic mostly includes transformations of massive sets of data, which can be performed using set operations, then use TSQL. *If your logic mostly includes complex computations of relatively small amounts of data, use CLR. With set operations much more can be done than it seems. If you post your requirements here, probably we'll be able to help. A: Please see Performance of CLR Integration: This topic discusses some of the design choices that enhance the performance of Microsoft SQL Server integration with the Microsoft .NET Framework common language runtime (CLR). A: The question of "Will writing a stored procedure in C# using the .net CLR as part of SQL Server 2008 cause my stored procedure to be less efficient than if it were written in T-SQL?" is really too broad to be given a meaningful answer. Efficiency varies greatly depending on not just what types of operations are you doing, but also how you go about those operations. You could have a CLR Stored Procedure that should out-perform an equivalent T-SQL Proc but actually performs worse due to poor coding, and vice versa. Given the general nature of the question, I can say that "in general", things that can be done in T-SQL (without too much complexity) likely should be done in T-SQL. One possible exception might be for TVFs since the CLR API has a very interesting option to stream the results back (I wrote an article for SQL Server Central--free registration required--about STVFs). But there is no way to know for certain without having both CLR and T-SQL versions of the code and testing both with Production-level data (even poorly written code will typically perform well enough with 10k rows or less). So the real question here boils down to: I know C# better than I know T-SQL. What should I do? And in this case it would be best to simply ask how to tackle this particular task in T-SQL. It could very well be that there are non-complex solutions that you just don't happen to know about yet, but would be able to understand upon learning about the feature / technique / etc. And you can still code an equivalent solution in SQLCLR and compare the performance between them. But if there is no satisfactory answer for handling it in T-SQL, then do it in SQLCLR. That being said, I did do a study 3 years ago regarding SQLCLR vs T-SQL Performance and published the results on Simple-Talk.
unknown
d17592
val
Terraform does not support variables inside a variable. If you want to generate a value based on two or more variables then you can try Terraform locals (https://www.terraform.io/docs/configuration/locals.html). Locals should help you here to achieve goal. something like locals { tags = { Environment = "${var.EnvironmentName}" CostCentre = "C1234" Project = "TerraformTest" Department = "Systems" } } And then you can use as local.tags resource “azurerm_resource_group” “TestAppRG” { name = “EUW-RGs-${var.EnvShortName}” location = “${var.Location}” tags = “${local.tags}” } Hope this helps A: You need to use locals to do the sort of transform you are after variables.tf: variable "EnvironmentName" { type = "string" } locals.tf locals { tags = { Environment = var.EnvironmentName CostCentre = "C1234" Project = "TerraformTest" Department = "Systems" } } Variables-dev.tfvars: EnvShortName = "Dev" EnvironmentName = "Development1" #Location Location = "westeurope" main.tf: resource “azurerm_resource_group” “TestAppRG” { name = “EUW-RGs-${var.EnvShortName}” location = var.Location tags = local.tags } You can do things like `tags = merge(local.tags,{"key"="value"}) to extend your tags.
unknown
d17593
val
The answer to your first question is simply that you did not tell ICETOOL's COUNT operator how long you wanted the output data to be, so it came up with its own figure. This is from the DFSORT Application Programming Guide: WRITE(countdd) Specifies the ddname of the count data set to be produced by ICETOOL for this operation. A countdd DD statement must be present. ICETOOL sets the attributes of the count data set as follows: v RECFM is set to FB. v LRECL is set to one of the following: – If WIDTH(n) is specified, LRECL is set to n. Use WIDTH(n) if your count record length and LRECL must be set to a particular value (for example, 80), or if you want to ensure that the count record length does not exceed a specific maximum (for example, 20 bytes). – If WIDTH(n) is not specified, LRECL is set to the calculated required record length. If your LRECL does not need to be set to a particular value, you can let ICETOOL determine and set the appropriate LRECL value by not specifying WIDTH(n). And: DIGITS(d) Specifies d digits for the count in the output record, overriding the default of 15 digits. d can be 1 to 15. The count is written as d decimal digits with leading zeros. DIGITS can only be specified if WRITE(countdd) is specified. If you know that your count requires less than 15 digits, you can use a lower number of digits (d) instead by specifying DIGITS(d). For example, if DIGITS(10) is specified, 10 digits are used instead of 15. If you use DIGITS(d) and the count overflows the number of digits used, ICETOOL terminates the operation. You can prevent the overflow by specifying an appropriately higher d value for DIGITS(d). For example, if DIGITS(5) results in overflow, you can use DIGITS(6) instead. And: WIDTH(n) Specifies the record length and LRECL you want ICETOOL to use for the count data set. n can be from 1 to 32760. WIDTH can only be specified if WRITE(countdd) is specified. ICETOOL always calculates the record length required to write the count record and uses it as follows: v If WIDTH(n) is specified and the calculated record length is less than or equal to n, ICETOOL sets the record length and LRECL to n. ICETOOL pads the count record on the right with blanks to the record length. v If WIDTH(n) is specified and the calculated record length is greater than n, ICETOOL issues an error message and terminates the operation. v If WIDTH(n) is not specified, ICETOOL sets the record length and LRECL to the calculated record length. Use WIDTH(n) if your count record length and LRECL must be set to a particular value (for example, 80), or if you want to ensure that the count record length does not exceed a specific maximum (for example, 20 bytes). Otherwise, you can let ICETOOL calculate and set the appropriate record length and LRECL by not specifying WIDTH(n). For your second question, yes it can be done in one step, and greatly simplified. The thing is, it can be further simplified by doing something else. Exactly what else depends on your actual task, which we don't know, we only know of the solution you have chosen for your task. For instance, you want to know when one file is within 10% of the size of the other. One way, if on-the-dot accuracy is not required, is to talk to the technical staff who manage your storage. Tell them what you want to do, and they probably already have something you can use to do it with (when discussing this, bear in mind that these are technically data sets, not files). Alternatively, something has already previously read or written those files. If the last program to do so does not already produce counts of what it has read/written (to my mind, standard good practice, with the program reconciling as well) then amend the programs to do so now. There. Magic. You have your counts. Arrange for those counts to be in a data set of their own (preferably with record-types, headers/trailers, more standard good practice). One step to take the larger (expectation) of the two counts, "work out" what 00% would be (doesn't need anything but a simple subtraction, with the right data) and generate a SYMNAMES format file (fixed-length 80-byte records) with a SORT-symbol for a constant with that value. Second step which uses INCLUDE/OMIT with the symbol in comparison to the second record-count, using NULLOUT or NULLOFL. The advantage of the above types of solution is that they basically use very few resources. On the Mainframe, the client pays for resources. Your client may not be so happy at the end of the year to find that they've paid for reading and "counting" 7.3m records just so that you can set an RC. OK, perhaps 7.3m is not so large, but, when you have your "solution", the next person along is going to do it with 100,000 records, the next with 1,000,000 records. All to set an RC. Any one run of which (even with the 10,000-record example) will outweigh the costs of a "Mainframe" solution running every day for the next 15+ years. For your third question: OUTREC OVERLAY=(15:X,1,6,ZD,DIV,+2,M11,LENGTH=6,X, (8,6,ZD,MUL,+100),DIV,1,6,ZD,MUL,+100,EDIT=(TTT.TT)) OUTREC is processed after SORT/MERGE and SUM (if present) otherwise after INREC. Note, the physical order in which these are specified in the JCL does not affect the order they are processed in. OVERLAY says "update the information in the current record with these data-manipulations (BUILD always creates a new copy of the current record). 15: is "column 15" (position 15) on the record. X inserts a blank. 1,6,ZD means "the information, at this moment, at start-position one for a length of six, which is a zoned-decimal format". DIV is divde. +2 is a numeric constant. 1,6,ZD,DIV,+2 means "take the six-digit number starting at position one, and divide it by two, giving a 'result', which will be placed at the next available position (16 in your case). M11 is a built-in edit-mask. For details of what that mask is, look it up in the manual, as you will discover other useful pre-defined masks at the time. Use that to format the result. LENGTH=6 limits the result to six digits. So far, the number in the first six positions will be divided by two, treated (by the mask) as an unsigned zoned-decimal of six digits, starting from position 16. The remaining elements of the statement are similar. Brackets affect the "precedence" of numeric operators in a normal way (consult the manual to be familiar with the precedence rules). EDIT=(TTT.TT) is a used-defined edit mask, in this case inserting a decimal point, truncating the otherwise existing left-most digit, and having significant leading zeros when necessary.
unknown
d17594
val
Solution: Set AutoRefresh to ON on the mv (as it defaults to off). Or manually trigger the refresh.
unknown
d17595
val
Here's a nice solution that works great for iOS 8 and iOS 7 on iPhone and iPad. You simply detect if there is a split view controller and if so, check if it's collapsed or not. If it's collapsed you know only one view controller is on screen. Knowing that info you can do anything you need to. //remove right bar button item if more than one view controller is on screen if (self.splitViewController) { if ([UISplitViewController instancesRespondToSelector:@selector(isCollapsed)]) { if (!self.splitViewController.collapsed) { self.navigationController.navigationBar.topItem.rightBarButtonItem = nil; } } else { self.navigationController.navigationBar.topItem.rightBarButtonItem = nil; } }
unknown
d17596
val
You can do the same in multiple ways. * *Using command line. mvn exec:java -Dexec.mainClass="com.example.Main" -Dexec.args="arg0 arg1" * *Using exec-maven-plugin. A: You have not configured your pom.xml to run the main class .Also , you can configure more than one main class to execute from the main class. The question is already been answered in stackoverflow by Mr Kai Sternad. i am sharing the link you can let me know if you are satisfied or not How to Configure pom.xml to run 2 java mains in 1 Maven project
unknown
d17597
val
What you're seeing here is a combination of Javascript's notion of closure combined with the pattern of an immediately invoked function expression. I'll try to illustrate what's happening as briefly as possible: _getUniqueID = (function () { var i = 1; return function () { return i++; }; }()); <-- The () after the closing } invokes this function immediately. _getUniqueID is assigned the return value of this immediately invoked function expression. What gets returned from the IIFE is a function with a closure that includes that variable i. i becomes something like a private field owned by the function that returns i++ whenever it's invoked. s = _getUniqueID(); Here the returned function (the one with the body return i++;) gets invoked and s is assigned the return value of 1. Hope that helps. If you're new to Javascript, you should read the book "Javascript, the Good Parts". It will explain all of this in more detail. A: _getUniqueID = (function () { var i = 1; return function () { return i++; }; }()); s = _getUniqueID(); console.log(s); // 1 console.log(_getUniqueID()); // 1 * *when you do () it calls the function, a- makes function recognize i as global for this function. b- assigns function to _getUniqueID *you do s = _getUniqueID();, a - it assigns s with return value of function in _getUniqueID that is 1 and makes i as 2 *when you do _getUniqueID() again it will call the return function again a- return 2 as the value and b makes value of i as 3. A: This is a pattern used in Javascript to encapsulate variables. The following functions equivalently: var i = 1; function increment() { return i ++; } function getUniqueId() { return increment(); } But to avoid polluting the global scope with 3 names (i, increment and getUniqueId), you need to understand the following steps to refactor the above. What happens first is that the increment() function is declared locally, so it can make use of the local scope of the getUniqueId() function: function getUniqueId() { var i = 0; var increment = function() { return i ++; }; return increment(); } Now the increment function can be anonymized: function getUniqueId() { var i = 0; return function() { return i ++; }(); } Now the outer function declaration is rewritten as a local variable declaration, which, again, avoids polluting the global scope: var getUniqueId = function() { var i = 0; return (function() { return i ++; })(); } You need the parentheses to have the function declaration act as an inline expression the call operator (() can operate on. As the execution order of the inner and the outer function now no longer make a difference (i.e. getting the inner generator function and calling it, or generate the number and returning that) you can rewrite the above as var getUniqueId = (function() { var i = 0; return function() { return i ++; }; })(); The pattern is more or less modeled after Crockford's private pattern A: _getUniqueID = (function () { var i = 1; return function () { return i++; }; }()); console.log(_getUniqueID()); // 1 , this surprised me initially , I was expecting a function definition to be printed or rather _getUniqueID()() to be called in this fashion for 1 to be printed So the above snippet of code was really confusing me because I was't understanding that the above script works in the following manner, by the time the IFFE executes _getUniqueID is essentially just the following: _getUniqueID = function () { i = 1 return i++; }; and hence, _getUniqueID() // prints 1. prints 1. Note: please note that I understand how closures and IFFE's work.
unknown
d17598
val
you could use map. func main() { var m map[string]int m = make(map[string]int) b := []int{os.O_APPEND,os.O_CREATE,os.O_EXCL,os.O_RDONLY,os.O_RDWR,os.O_SYNC,os.O_TRUNC,os.O_WRONLY} a := []string{"os.O_APPEND","os.O_CREATE","os.O_EXCL","os.O_RDONLY","os.O_RDWR","os.O_SYNC","os.O_TRUNC","os.O_WRONLY"} for index, value := range a { m[value] = b[index] } var i =0 for index,mapValue := range m{ fmt.Println(i," - ",index,"-",mapValue ) i++ } } out put will be: 0 - os.O_RDWR - 2 1 - os.O_SYNC - 1052672 2 - os.O_TRUNC - 512 3 - os.O_WRONLY - 1 4 - os.O_APPEND - 1024 5 - os.O_CREATE - 64 6 - os.O_EXCL - 128 7 - os.O_RDONLY - 0 or you could define custom struct type CustomClass struct { StringValue string IntValue int } func main() { CustomArray:=[]CustomClass{ {"os.O_APPEND",os.O_APPEND}, {"os.O_CREATE",os.O_CREATE}, {"os.O_EXCL",os.O_EXCL}, {"os.O_RDONLY",os.O_RDONLY}, {"os.O_RDWR",os.O_RDWR}, {"os.O_SYNC",os.O_SYNC}, {"os.O_TRUNC",os.O_TRUNC}, {"os.O_WRONLY",os.O_WRONLY}, } for k, v := range CustomArray { fmt.Println(k," - ", v.StringValue," - ", v.IntValue) } }
unknown
d17599
val
The text field is expected to be unicode or str, not any other type (boot_time is float, and len() is int). So just convert to string the non-string compliant elements: # First system/hostname, so we know what machine this is etree.SubElement(child1, "name").text = socket.gethostname() # nothing to do # Then boot time, to get the time the system was booted. etree.SubElement(child1, "boottime").text = str(psutil.boot_time()) # and process count, see how many processes are running. etree.SubElement(child1, "proccount").text = str(len(psutil.pids())) result: b'<metrics>\n <basic>\n <name>JOTD64</name>\n <boottime>1473903558.0</boottime>\n <proccount>121</proccount>\n </basic>\n</metrics>\n' I suppose the library could do the isinstance(str,x) test or str conversion, but it was not designed that way (what if you want to display your floats with leading zeroes, truncated decimals...). It operates faster if the lib assumes that everything is str, which it is most of the time.
unknown
d17600
val
Select the <td> elements in the first row, and iterate over them using the each()(docs) method. Inside the .each(), use the index parameter it provides to select from your Array of widths. // Use the "index" parameter--------------v $('#MyGrid tr:first > td').each(function( i ) { $(this).width( thewidtharray[i] ); }); Or here's an alternative if you're using jQuery 1.4.1 or later: // Use the "index" parameter---------------v $('#MyGrid tr:first > td').width(function( i ) { return thewidtharray[i]; });
unknown