input
stringlengths
51
42.3k
output
stringlengths
18
55k
Reading and Printing Weird Things in file Java <p>Well, i'm trying to make an input/output file, so at the start of my application it reads the file and put the information on the right places, and when I'm in the app, i could add info to this file.</p> <p>The problem is that it reads and writes really weird things like "1". This is my Reading function:</p> <pre><code>private Vector&lt;GEPlayer&gt; ReadPlayers() { Vector&lt;GEPlayer&gt; play_aux = new Vector&lt;&gt;(); String path = System.getProperty("user.dir"); try { File fread = new File(path + "/bin/Players.txt"); System.out.println(fread.length()); if (fread.length() &gt; 3) { BufferedReader bread = new BufferedReader(new InputStreamReader(new FileInputStream(fread), "ISO-8859-1")); String linea; int i = 0; while ((linea = bread.readLine()) != null) { GEPlayer p_aux = new GEPlayer(-1); if (linea != null) { switch (i) { case 0: currentidplayer = Integer.parseInt(linea); p_aux.setId_player(currentidplayer); System.out.println("GEModel -- ReadPlayers -- Readed Player ID: " + currentidplayer); i++; break; case 1: currentidteam = Integer.parseInt(linea); p_aux.setId_team(currentidteam); System.out.println("GEModel -- ReadPlayers -- Readed Player Team ID: " + currentidplayer); i++; break; case 2: p_aux.setName(linea); System.out.println("GEModel -- ReadPlayers -- Readed Player Name: " + linea); i++; break; case 3: p_aux.setSurname(linea); System.out.println("GEModel -- ReadPlayers -- Readed Player Surname: " + linea); i++; break; case 4: p_aux.setNacionality(linea); System.out.println("GEModel -- ReadPlayers -- Readed Player Nacionality: " + linea); i++; break; case 5: p_aux.setActualTeam(linea); System.out.println("GEModel -- ReadPlayers -- Readed Player Actual Team: " + linea); i++; break; case 6: p_aux.setBornDate(linea); System.out.println("GEModel -- ReadPlayers -- Readed Player Born Date: " + linea); i++; break; case 7: p_aux.setNumber(Integer.parseInt(linea)); System.out.println("GEModel -- ReadPlayers -- Readed Player Number: " + linea); play_aux.add(p_aux); i = 0; break; } } } if (i != 0) { currentidplayer = 0; play_aux.removeAllElements(); } } } catch (FileNotFoundException | UnsupportedEncodingException ex) { Logger.getLogger(GEModel.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(GEModel.class.getName()).log(Level.SEVERE, null, ex); } return play_aux; } </code></pre> <p>And this is my Writing Function:</p> <pre><code>private void writePlayer(GEPlayer aux) { File fw; BufferedWriter bw = null; try { String path = System.getProperty("user.dir"); fw = new File(path + "/bin/Players.txt"); ///&lt; The true will append the new data FileOutputStream fos = new FileOutputStream(fw); bw = new BufferedWriter(new OutputStreamWriter(fos)); bw.write(aux.getId_player()); ///&lt; Appends the string to the file System.out.println("GEModel -- writePlayer -- Printed: " + aux.getId_player()); bw.newLine(); bw.write(aux.getId_team()); ///&lt; Appends the string to the file System.out.println("GEModel -- writePlayer -- Printed: " + aux.getId_team()); bw.newLine(); bw.write(aux.getName()); ///&lt; Appends the string to the file System.out.println("GEModel -- writePlayer -- Printed: " + aux.getName()); bw.newLine(); bw.write(aux.getSurname()); ///&lt; Appends the string to the file System.out.println("GEModel -- writePlayer -- Printed: " + aux.getSurname()); bw.newLine(); bw.write(aux.getNacionality()); ///&lt; Appends the string to the file System.out.println("GEModel -- writePlayer -- Printed: " + aux.getNacionality()); bw.newLine(); bw.write(aux.getActualTeam()); ///&lt; Appends the string to the file System.out.println("GEModel -- writePlayer -- Printed: " + aux.getActualTeam()); bw.newLine(); bw.write(aux.getBornDate()); ///&lt; Appends the string to the file System.out.println("GEModel -- writePlayer -- Printed: " + aux.getBornDate()); bw.newLine(); bw.write(aux.getNumber()); ///&lt; Appends the string to the file System.out.println("GEModel -- writePlayer -- Printed: " + aux.getNumber()); bw.newLine(); bw.close(); } catch (IOException ex) { Logger.getLogger(GEModel.class.getName()).log(Level.SEVERE, null, ex); } finally { try { bw.close(); } catch (IOException ex) { Logger.getLogger(GEModel.class.getName()).log(Level.SEVERE, null, ex); } } } </code></pre> <p>When i execute the program without information in the txt, i can read perfectly all things, it shows the correct information, and tells me that the information is right. But when I restart the app, it throws me an error like this:</p> <pre><code>Exception in thread "main" java.lang.NumberFormatException: For input string: "1" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at GEModel.GEModel.ReadPlayers(GEModel.java:55) ///&lt; This line is this: "currentidplayer = Integer.parseInt(linea);" at GEModel.GEModel.&lt;init&gt;(GEModel.java:34) at GEMain.GEMainClass.main(GEMainClass.java:22) </code></pre> <p>Java Result: 1</p> <p>What can I do to resolve this problem?</p>
<p>This because when you read you set explicit encoding. But when writing not and the default one is used - usually UTF-8.</p> <p>Use the same text encoding when writing and when reading (and UTF-8 is would be best choice).</p> <p>Try with something simple:</p> <pre><code> File f=new File("/tmp/test.txt"); try (FileOutputStream fos=new FileOutputStream(f)){ int id=1; BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8")); bw.write(String.valueOf(id)); //write player id bw.newLine(); bw.close(); } catch (Exception e) { e.printStackTrace(); } try (FileInputStream fis=new FileInputStream(f)){ BufferedReader br = new BufferedReader(new InputStreamReader(fis,"UTF-8")); String idstr=br.readLine(); System.out.printf("readstr: '%s'\n",idstr); int id=Integer.parseInt(idstr); // parse player id System.out.printf("parse id: '%d'\n",id); br.close(); } catch (Exception e) { e.printStackTrace(); } </code></pre>
How can i make the contents of the mail to be in html format rather than string of text? <p>In the below code whenever the button is clicked sendmail function is called and makes a ajax post request to the php page.The php intern sends the mail.I am getting the contents sent by the ajax function in the text format rather than the original html format displayed on the browser.How to get the contents of the mail to be in the html format.</p> <pre><code>function sendmail(){ $.ajax({ dataType: 'application/html', type: 'POST',url: 'process.php', data: { 'number': $('#div_content').html() }//div_content has all the content displayed on the html page }).done(function() { $('#div_content').html( "Mail Sent" ); }); } </code></pre> <p>PHP for sending the mail <code>process.php</code></p> <pre><code>&lt;?php $var1=$_POST['div_content']; $var2=fopen("somefile.txt","w+"); mail("example@gmail.com","My subject",$var1);//How to make the content in the html format rather than a string of text fwrite($var2,$var1); ?&gt; </code></pre>
<p>You just have to add headers to your mail</p> <pre><code>&lt;?php $headers = "From: ... \r\n"; $headers .= "Reply-To: ... \r\n"; $headers .= "CC: ... \r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1 \r\n"; $var1=$_POST['div_content']; $var2=fopen("somefile.txt","w+"); mail("example@gmail.com","My subject",$var1, $headers); fwrite($var2,$var1); ?&gt; </code></pre>
Using strlen to strikeout specified words in string <p>Using the following function, I am able to pass in two strings (char *hide, char *phrase). The *phrase is the overall string and * hide is what words (can be repeated) have to be censored by replacing all letters in the word with '*'. It currently works so that it goes on to find the first letter of the *hide, then the second letter of the *hide word despite it not being next to each other in the string eg. </p> <pre><code>*phrase = 'hello my name is' *hide = 'lame' result = 'he*lo my n*** is' { int i, j=0; int lengthPhrase = strlen(phrase); int lengthCensor = strlen(hide); for (i = 0; i &lt; lengthPhrase; i++) { if (phrase[i] == hide[j]) { phrase[i] = '*'; j++; } } } </code></pre> <p>Where is the issue so that it works correctly by striking out the whole words??</p> <p>Thank you for your time.</p>
<p>Since I don't seem to understand your question, I thought of making a function for you to see if this is what you're looking for:</p> <pre><code> string phrase = "hello my name is" string hide = "lame" //strikeout function void strikeout(string phrase, string hide) { for (int i = 0; i &lt; hide.size(); i++) { for (int j = 0; j &lt; phrase.size(); j++) { if (hide[i] == phrase[j]) { phrase[j] = '*'; } } } cout &lt;&lt; phrase &lt;&lt; endl; } </code></pre> <p>Output based on your testcase: "h***o *y n*** is"</p>
Spring Security / MVC / JPA --> Request method 'POST' not supported <p>I am having errors login from the HTML using Spring Security, Spring MVC and JPA.</p> <p>This is my login.HTML</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html xmlns:th="http://www.thymeleaf.org"&gt; &lt;head lang="en" xmlns:th="http://www.thymeleaf.org"&gt;&gt; &lt;title&gt;Spring Framework Guru&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/&gt; &lt;/head&gt; &lt;body class="security-app"&gt; &lt;div class="details"&gt; &lt;h2&gt;Spring Security - App&lt;/h2&gt; &lt;/div&gt; &lt;form action="/login" method="post"&gt; &lt;div class="lc-block"&gt; &lt;div&gt; &lt;input type="text" class="style-4" name="username" placeholder="User Name" /&gt; &lt;/div&gt; &lt;div&gt; &lt;input type="password" class="style-4" name="password" placeholder="Password" /&gt; &lt;/div&gt; &lt;div&gt; &lt;input type="submit" value="Sign In" class="button red small" /&gt; &lt;/div&gt; &lt;th:if test="${param.error ne null}"&gt; &lt;div class="alert-danger"&gt;Invalid username and password.&lt;/div&gt; &lt;/th:if&gt; &lt;th:if test="${param.logout ne null}"&gt; &lt;div class="alert-normal"&gt;You have been logged out.&lt;/div&gt; &lt;/th:if&gt; &lt;/div&gt; &lt;input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>This is WebSecurity class:</p> <pre><code>@Configuration @EnableWebSecurity @ComponentScan(basePackageClasses = CustomUserDetailsService.class) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordencoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/hello").access("hasRole('ROLE_ADMIN')") .anyRequest().permitAll() .and() .formLogin().loginPage("/login") .usernameParameter("username").passwordParameter("password") .and() .logout().logoutSuccessUrl("/login?logout") .and() .exceptionHandling().accessDeniedPage("/403") .and() .csrf(); } @Bean(name = "passwordEncoder") public PasswordEncoder passwordencoder() { return new BCryptPasswordEncoder(); } } </code></pre> <p>UserDetails service class:</p> <pre><code>@Service("customUserDetailsService") public class CustomUserDetailsService implements UserDetailsService { private final UserRepository userRepository; private final UserRolesRepository userRolesRepository; @Autowired public CustomUserDetailsService(UserRepository userRepository, UserRolesRepository userRolesRepository) { this.userRepository = userRepository; this.userRolesRepository = userRolesRepository; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUserName(username); if (null == user) { throw new UsernameNotFoundException("No user present with username: " + username); } else { List&lt;String&gt; userRoles = userRolesRepository.findRoleByUserName(username); return new CustomUserDetails(user, userRoles); } } } </code></pre> <p>I always have 405 error:</p> <blockquote> <p>2016-10-16 12:15:30.710 WARN 2932 --- [nio-8080-exec-3] o.s.web.servlet.PageNotFound : Request method 'POST' not supported</p> </blockquote> <p>Any ideas why is not calling the "configure(HttpSecurity http)". Am I missing something?</p> <p>Thank you very much</p> <p>Andres</p>
<p>Try adding</p> <pre><code>.formLogin().loginPage("/xxx").permitAll() .defaultSuccessUrl("/xxx") .failureUrl("/xxx?error") </code></pre> <p>In addition</p> <p>One typical reason in Spring MVC Applications for controller methods and pages not found is Spring's weird mapping convention to build URLs by adding a new link (or the form action="x") to the end of current URL. 'Request Method POST Not Supported' only means that your request is pointed to somewhere where nothing is accepting the POST request => URL mapping fails. On JSP sites you should always specify URLs like</p> <pre><code>&lt;form action="${pageContext.request.contextPath}/login" method="post"&gt; </code></pre> <p>or with JSTL</p> <pre><code>&lt;c:url value="/login" var="loginUrl" /&gt; &lt;form action="${loginUrl}" method="post"&gt; </code></pre> <p>Then you can be sure that your link is set right after the application root in URL. This will save you from a lot of unnecessary problems in the future.</p>
Angular / Jasmine Testing - How to Stub Both a Constructor and Property <p>In Jasmine, I can mock a constructor function with the following:</p> <pre><code>window.Notification = jasmine.createSpy('Notification').and.returnValue('returned value'); </code></pre> <p>I can stub a property for the same object with an assignment operation:</p> <pre><code>window.Notification = { permission: 'granted' }; </code></pre> <p>How do I do both? I have the following code I'd like to test:</p> <pre><code>if(Notification.permission == 'granted'){ var notificationObject = new Notification('new message', { body: 'body of message' } } </code></pre>
<p><code>jasmine.createSpy</code> returns function and functions like any other objects can have properties. As long as you don't override properties used by Jasmine like <code>and</code> or <code>calls</code> it should be safe to add properties to created spy functions:</p> <p><code>var mockNotification = jasmine.createSpy('Notification').and.returnValue('returned value'); mockNotification.permission = 'granted'; window.Notification = mockNotification; </code></p>
Copy (update if exists) document from one collection to another <p>I want to copy a document from one collection of mongodb to another collection (or update if exist) through java.</p> <p>I don't want to append each field of existing collection and then insert to another. How can I do this?</p> <p>Here are two collections, <code>temp</code> and <code>national</code>. <code>temp</code> has only one collection, which I have to copy to <code>national</code> or update if it exists.</p> <pre><code>MongoCursor&lt;Document&gt; cursor = db.getCollection("temp").find().iterator(); try { Document doc = new Document(cursor.next()); Document new_doc = new Document("$set",doc); doc.append("booking_id",cursor.next().get("booking_id")); MongoCursor&lt;Document&gt; cursor1 = db.getCollection("national").find(doc).iterator(); Bson filter = Filters.eq("booking_id", args); Bson update = Filters.elemMatch("booking_id", filter); UpdateOptions options = new UpdateOptions().upsert(true); national.updateOne(filter, new_doc, options); } finally { cursor.close(); } </code></pre>
<p>If you want replace Doc2 with Doc1 you can use replaceOne()</p> <p><strong>replaceOne() replaces the first matching document in the collection that matches the filter, using the replacement document.</strong></p> <p><a href="https://docs.mongodb.com/v3.2/reference/method/db.collection.replaceOne/" rel="nofollow">https://docs.mongodb.com/v3.2/reference/method/db.collection.replaceOne/</a></p>
array undeclared ,first used in the function error during dynamic memory allocation <p>Here i am writing a program which will do two things</p> <p>1.get a number between 0 to 102,separate them and store them in an array</p> <p>2.print the array for each number</p> <p>For that purpose i wrote an if-else block which will initialize an array each time exactly according to the size of the current integer value which is denoted by variable called <code>num</code></p> <p>Meaning that if i have a number of single digit it will create an array of one element,If number is two digit long it will create an array of two element.But whenever i run the code i get the error mentioned in question title.</p> <p>What might be the reason for that and how to solve this issue?</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;math.h&gt; int mirror(int num,int *arr,int i); int main(){ int num=0,range=1; while(num&lt;102){ if(num&lt;(int)pow(10,range)) { int *arr =(int *)malloc(range*sizeof(int)); }else{ range+=1; int *arr =(int *)malloc(range*sizeof(int)); } int i = 0; mirror(num,arr,i); for(i=0;i&lt;range;i++){ printf("%d ",arr[i]); } printf("\n"); num++; } } int mirror(int num,int *arr,int i){ if(num == 0){ return 0; } arr[i] = num%10; mirror(num/10,arr,++i); } </code></pre>
<p>The scope of pointer <code>arr</code> is only within the if-else block. So, it's not available outside of it. Declare it outside the if-else block and you'll be able to use it as you have.</p> <pre><code> int *arr; if(num&lt;(int)pow(10,range)) { arr = malloc(range*sizeof(int)); }else{ range += 1; arr = malloc(range*sizeof(int)); } </code></pre> <p>Notice I have removed the cast of the malloc() return value. It's needless in C and error-prone. See: <a href="http://c-faq.com/malloc/mallocnocast.html" rel="nofollow">http://c-faq.com/malloc/mallocnocast.html</a></p>
Java class getdata <p>I can't find the problem. When i use the class and use first setpostcode to 5000. and then getUrl i get still 1000 in my url idk why. when i debug the postcode is changed to 5000 but when i print the url i get 1000.</p> <pre><code>public class weer { private int postcode = 1000; private String url = "http://www.meteo.be/services/widget/.?postcode="+ postcode +"&amp;nbDay=2&amp;type=4&amp;lang=nl&amp;bgImageId=1&amp;bgColor=567cd2&amp;scrolChoice=0&amp;colorTempMax=A5D6FF&amp;colorTempMin=fffff"; public int getPostcode() { return postcode; } public void setPostcode(int postcode) { this.postcode = postcode; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } </code></pre> <p>}</p> <pre><code> public static void main(String[] args) { weer w = new weer(); w.setPostcode(5000); System.out.println(w.getPostcode()); System.out.println(w.getUrl()); } </code></pre>
<p>The URL member variable is declared and initialized once upon creation of the class instance. It starts at 1000 and never changes. </p> <p>Updates to one value aren't reflected to the other. </p> <p>You don't really don't need the URL member variable if you only are updating the postcode, just change the getter to </p> <pre><code>return "http://www.meteo.be/services/widget/.?postcode="+ postcode +"&amp;nbDay=2&amp;type=4&amp;lang=nl&amp;bgImageId=1&amp;bgColor=567cd2&amp;scrolChoice=0&amp;colorTempMax=A5D6FF&amp;colorTempMin=fffff"; </code></pre> <p>Or, if you do need the setter for the URL, update the other setter </p> <pre><code>public void setPostcode(int postcode) { this.postcode = postcode; this.url = "http://www.meteo.be/services/widget/.?postcode="+ postcode +"&amp;nbDay=2&amp;type=4&amp;lang=nl&amp;bgImageId=1&amp;bgColor=567cd2&amp;scrolChoice=0&amp;colorTempMax=A5D6FF&amp;colorTempMin=fffff"; } </code></pre>
How to register a User in Firebase using Node.js? <p><strong>PROBLEM:</strong></p> <p>0) The user is created in the auth system in Firebase (I see it in the Auth tab),</p> <p>1) But no changes are made to the database. </p> <p>2) The page seems to be stuck infinitely loading. </p> <p>3) Only "Started 1..." is logged to the console.</p> <hr> <p><strong>CODE:</strong> </p> <pre><code>router.post('/register', function(req, res, next) { var username = req.body.username; var email = req.body.email; var password = req.body.password; var password2 = req.body.password2; // Validation req.checkBody('username', 'Username is required').notEmpty(); req.checkBody('email', 'Email is required').notEmpty(); req.checkBody('email', 'Email is not valid').isEmail(); req.checkBody('password', 'Password is required').notEmpty(); req.checkBody('password2', 'Passwords do not match').equals(req.body.password); var errors = req.validationErrors(); if(errors){ res.render('users/register', { errors: errors }); } else { console.log("Started 1..."); firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error, userData) { console.log("Started 2..."); if(error){ var errorCode = error.code; var errorMessage = error.message; req.flash('error_msg', 'Registration Failed. Make sure all fields are properly filled.' + error.message); res.redirect('/users/register'); console.log("Error creating user: ", error); } else { console.log("Successfully created"); console.log("Successfully created user with uid:", userData.uid); var user = { uid: userData.uid, email: email, username: username } var userRef = firebase.database().ref('users/'); userRef.push().set(user); req.flash('success_msg', 'You are now registered and can login'); res.redirect('/users/login'); } }); } }); </code></pre> <hr> <p>EDIT 1:</p> <p>This is what seems to be happening:</p> <p>The user is created in the auth System. The page loads for about 5 minutes (very long!), then tells me the registration failed because the email address is already in use (it was not).</p> <p>It seems the user is created but the registration fails because the code loops back after the user is created as if it had not been created, therefore creating an error of type : this email address is already in our database.</p> <p>But why does this happen ?</p>
<p>not sure this is all, but here's what i think happens:</p> <p>the user is created, but you are not handling it properly. there is no handling of a success case (fulfilled promise), only a rejected one. also, when you're trying to write to the database when an error occurs, that means the user is not authenticated, which means that if you haven't changed your firebase security rules, you won't be able to write. (the default firebase security rules prevents non-authenticated users from reading/writing to your database)</p> <p>this line:</p> <p><code>firebase.auth().createUserWithEmailAndPassword(email,password) .catch(function(error, userData) { ...</code></p> <p>should be changed to this:</p> <p><code> firebase.auth().createUserWithEmailAndPassword(email, password) .then(userData =&gt; { // success - do stuff with userData }) .catch(error =&gt; { // do stuff with error })</code></p> <p>mind that when an error occurs, you won't have access to <code>userData</code>, just the errors. </p> <p>Hope this helps! </p>
Python. Best way to match dictionary value if condition true <p>I'm trying to build a parser now part of my code is looks like this:</p> <pre><code> azeri_nums = {k:v for k,v in zip(range(1,10),("bir","iki","uc","dord","beş","altı","yeddi","səkkiz","doqquz"))} russian_nums = {k:v for k,v in zip(range(1,10),("один","два","три","четыре","пять","шесть","семь","восемь","девять"))} </code></pre> <p>Imagine that I should find the digit if roomnum ="одна" Here is how I trying to match this:</p> <pre><code> if roomnum.isalpha(): for key,value in azeri_nums.items(): if value.startswith(roomnum.lower()): roomnum = str(key) break if roomnum.isalpha(): for key,value in russian_nums.items(): if value.startswith(roomnum.lower()): roomnum = str(key) break </code></pre> <p>is there any other method to do that that will work faster, or some best practices for this situation?</p> <p>Thank you in advance!</p> <p>P.S. the reason that this code works that module "re" capture from "одна" only "од" and that is why "один".startswith("од") returns true.</p>
<p>Change your dict to be</p> <pre><code>azeri_nums = {v.lower():k for k,v in zip(range(1,10),("bir","iki","uc","dord","beş","altı","yeddi","səkkiz","doqquz"))} russian_nums = {v.lower():k for k,v in zip(range(1,10),("один","два","три","четыре","пять","шесть","семь","восемь","девять"))} </code></pre> <p>And once you've names mapped to digits, just use:</p> <pre><code>key = None # By default roomnum_lower = roomnum.lower() if roomnum_lower in azeri_nums: key = azeri_nums[roomnum_lower] elif roomnum_lower in russian_nums: key = russian_nums[roomnum_lower] </code></pre> <p>Dictionary is based on keysearch, not valuesearch. The first one is O(1) and allows u to use <code>key in dict</code> when the 2nd one is O(n) and requires looping.</p> <h1>EDIT TO COMMENT:</h1> <p>if you want to map one word to others, create another dict that will handle it.</p> <pre><code> string_map = {'одна': ['один',]} # map single string to many others if u want </code></pre> <p>And then all u need to do is:</p> <pre><code>key = None # By default roomnum_lower = roomnum.lower() if roomnum_lower in azeri_nums: key = azeri_nums[roomnum_lower] elif roomnum_lower in russian_nums: key = russian_nums[roomnum_lower] if key is None: # At this point you know that the single string is not in any dict, # so u start to check if any other string that u assigned to it is in dict for optional_string in string_map.get(roomnum_lower, []): opt_str_low = optional_string.lower() key = azeri_nums.get(opt_str_low, None) key = russian_nums.get(opt_str_low, None) if key is None else key </code></pre>
Variables staying null in vue.js application for shopify <p>I am building up a vue.js application for Shopify's JavaScript Buy SDK, but i am having problems with one variable not being updated. </p> <p>Basically the <code>shopClient</code> variable is updated, but the <code>shopCart</code> stays null for some reason.</p> <pre><code>var vueApp = new Vue({ el: '#shopify-app', created: function() { this.setupShopAndCart(); }, data: { shopCart: null, shopClient: null, }, methods: { setupShopAndCart: function() { this.shopClient = ShopifyBuy.buildClient({ apiKey: 'xxx', domain: 'xxx.myshopify.com', appId: '6' }); if(localStorage.getItem('lastCartId')) { this.shopClient.fetchCart(localStorage.getItem('lastCartId')).then(function(remoteCart) { this.shopCart = remoteCart; cartLineItemCount = this.shopCart.lineItems.length; console.log(this.shopCart.checkoutUrl); console.log("fetching"); }); } else { this.shopClient.createCart().then(function (newCart) { this.shopCart = newCart; localStorage.setItem('lastCartId', this.shopCart.id); cartLineItemCount = 0; console.log(this.shopCart.checkoutUrl); console.log("failing"); }); } }, //setupShop end } }); </code></pre>
<p>You have a problem with scoping. <code>this</code> in the promise isn't the vue instance.</p> <p>try this</p> <pre><code>var vueApp = new Vue({ el: '#shopify-app', created: function() { this.setupShopAndCart(); }, data: { shopCart: null, shopClient: null, }, methods: { setupShopAndCart: function() { var self = this; this.shopClient = ShopifyBuy.buildClient( { apiKey: 'xxx', domain: 'xxx.myshopify.com', appId: '6' } ); if(localStorage.getItem('lastCartId')) { this.shopClient.fetchCart(localStorage.getItem('lastCartId')).then( function(remoteCart) { self.shopCart = remoteCart; cartLineItemCount = self.shopCart.lineItems.length; console.log(self.shopCart.checkoutUrl); console.log("fetching"); } ); } else { this.shopClient.createCart().then( function (newCart) { self.shopCart = newCart; localStorage.setItem('lastCartId', self.shopCart.id); cartLineItemCount = 0; console.log(self.shopCart.checkoutUrl); console.log("failing"); } ); } }, //setupShop end } }); </code></pre> <p>That stores the local vue instance in the self variable that is accessable to the promises allowing you to set the shopCart variable.</p> <p>EDIT: As indicated lambda functions are correct if using ES2015 or newer</p> <pre><code>var vueApp = new Vue({ el: '#shopify-app', created: function() { this.setupShopAndCart(); }, data: { shopCart: null, shopClient: null, }, methods: { setupShopAndCart: function() { this.shopClient = ShopifyBuy.buildClient( { apiKey: 'xxx', domain: 'xxx.myshopify.com', appId: '6' } ); if(localStorage.getItem('lastCartId')) { this.shopClient.fetchCart(localStorage.getItem('lastCartId')).then( (remoteCart) =&gt; { this.shopCart = remoteCart; cartLineItemCount = this.shopCart.lineItems.length; console.log(this.shopCart.checkoutUrl); console.log("fetching"); } ); } else { this.shopClient.createCart().then( (newCart) =&gt; { this.shopCart = newCart; localStorage.setItem('lastCartId', this.shopCart.id); cartLineItemCount = 0; console.log(this.shopCart.checkoutUrl); console.log("failing"); } ); } }, //setupShop end } }); </code></pre>
Firebase / Facebook SDK login - request password <p>Not sure if it's Firebase issue or facebook SDK issue:</p> <p>In my case, there is <strong>one</strong> device with an option to login via Facebook. Once an user logging into his facebook account, he will be asked for his email ans password. In the second time, clicking the "Log in" button will automically log him back without asking anything.</p> <p>But what if another person need to be authenticated and whenever he clicks the log-in button facebook logins automically to the last person? Yeah, it's much faster if it's the same person, but in my case when multiple users need to authenticate in the same device, there is no option to re-assign the facebook credintals and login to another account.</p> <p><strong>So, is there any way to login to multiple accounts from same device without Facebook to auto-login the last authenticated user?</strong></p>
<p>Facebook takes the last logged in user on the Device. The only solution to require a password with Facebook is to open Facebook in the device's browser or Facebook app and logout there.</p>
Negate condition of an if-statement <p>if I want to do sth like:</p> <pre><code>if (!(condition)) { } </code></pre> <p>What is the equivalent expression in Scala? Does it looks like?</p> <pre><code>if (not(condition)) { } </code></pre> <p>For example, in C++, I can do: </p> <pre><code>bool condition = (x &gt; 0) if(!condition){ printf("x is not larger than zero") } </code></pre>
<p>In Scala, you can check <code>if</code> two operands are equal (<code>==</code>) or not (<code>!=</code>) and it returns true if the condition is met, false if not (<code>else</code>).</p> <pre><code>if(x!=0) { // if x is not equal to 0 } else { // if x is equal to 0 } </code></pre> <p>By itself, <code>!</code> is called the Logical NOT Operator. Use it to reverse the logical state of its operand. If a condition is true then Logical NOT operator will make it false.</p> <pre><code>if(!(condition)) { // condition not met } else { // condition met } </code></pre> <p>Where <code>condition</code> can be any logical expression. ie: <code>x==0</code> to make it behave exactly like the first code example above.</p>
Avoid overridding of default message field in logstash <p>I am using logstash to parse my logs. when i am parsing the json (which contains a "message" field) overrides the default message field. I tried using remove_field option of json{ } filter but that didn't work work for me.</p> <p>Here is my filter code: </p> <pre><code>filter { mutate { gsub =&gt; ["message", "\"", "'"] } mutate { gsub =&gt; ["message", ".", "_"] } csv { columns =&gt; ["TIMESTAMP", "HEADERS", "FIELD1", "FIELD2", "FIELD2_TIME", "INTER_FIELD2"] separator =&gt; "|" } mutate { gsub =&gt; ["FIELD1", "'", '"'] } #Removing message field inside FIELD1 json to avoid overriding json { source =&gt; "FIELD1" remove_field =&gt; ["message"] } mutate { gsub =&gt; ["FIELD2", "'", '"'] } json { source =&gt; "FIELD2" remove_field =&gt; ["message"] } } </code></pre> <p>How to avoid overriding of the defaultmessage field ?</p>
<p>Two options come to mind:</p> <ol> <li>move the [message] field out of the way before calling the json{} filter (mutate->rename).</li> <li>use the 'target' param of the json{} filter to put the json data somewhere other than the root of the document.</li> </ol>
Declare two different types of variables with general Scope using an if...else statement? <p>Depending on a condition, I have to declare a new variable that is either a NumericVector or NumericMatrix that later will be used for further processing. I have attempted the following approach:</p> <pre><code>if(condition) { NumericVector var(n_samples); }else{ NumericMatrix var(n_samples, n_column); } if(condition) { #Further code to process var as NumericVector }else{ #Further code to process var as NumericMatrix } return(var) </code></pre> <p>But we all know that <a href="http://stackoverflow.com/questions/8543167/scope-of-variables-in-if-statements">C++ variables go out scope at the end of the conditional</a> and that is exactly what I am getting.</p> <pre><code>Line xxx: var was not declared in this scope </code></pre> <p>I have tried with a pointer without success.</p> <pre><code>Object *var = NULL; if(condition) { var = new NumericVector Object(n_samples); }else{ var = new NumericMatrix Object(n_samples, n_column); } </code></pre> <p>Is there a solution or workaround for this?</p>
<p>This is what a template is for.</p> <pre><code>template&lt;typename var_type&gt; void do_something_with_var(var_type &amp;var) { // The rest of the code that uses var. } // ..... if(condition) { NumericVector var(n_samples); do_something_with_var(var); } else { NumericMatrix var(n_samples, n_column); do_something_with_var(var); } </code></pre> <p>If <code>do_something_with_var()</code> needs to use some additional objects, variables, etc..., from the scope that calls it, just pass them as additional parameters to <code>do_something_with_var()</code>.</p> <p>This will also introduce you to another C++ feature called "template code bloat". If both <code>NumericMatrix</code> and <code>NumericVar</code> derive from the same superclass, like your <code>Object</code>, it would be possible to avoid code bloat by making <code>do_something_with_var()</code> a regular function that takes an <code>Object &amp;</code> parameter, and implement all subclass-specific functionality as virtual functions.</p>
Find longest repeating substring in string? <p>I came across below program which looks perfect. Per me its time complexity is nlogn where n is the length of String.</p> <p>n for storing different strings,nlog for sorting, n for comparison. So time complexity is nlogn. Space complexity is n for storing the storing n substrings</p> <p>My question is can it be further optimized ?</p> <pre><code>public class LRS { // return the longest common prefix of s and t public static String lcp(String s, String t) { int n = Math.min(s.length(), t.length()); for (int i = 0; i &lt; n; i++) { if (s.charAt(i) != t.charAt(i)) return s.substring(0, i); } return s.substring(0, n); } // return the longest repeated string in s public static String lrs(String s) { // form the N suffixes int n = s.length(); String[] suffixes = new String[n]; for (int i = 0; i &lt; n; i++) { suffixes[i] = s.substring(i, n); } // sort them Arrays.sort(suffixes); // find longest repeated substring by comparing adjacent sorted suffixes String lrs = ""; for (int i = 0; i &lt; n-1; i++) { String x = lcp(suffixes[i], suffixes[i+1]); if (x.length() &gt; lrs.length()) lrs = x; } return lrs; } public static void main(String[] args) { String s = "MOMOGTGT"; s = s.replaceAll("\\s+", " "); System.out.println("'" + lrs(s) + "'"); } } </code></pre>
<p>Have a look at this algorithm given in geeksforgeeks, this might be helpful:</p> <pre><code>http://www.geeksforgeeks.org/suffix-tree-application-3-longest-repeated-substring/ </code></pre>
Inner class is not public error when instantiating new inner class <p>I have this class</p> <pre><code>package com.rafael; public class Vehicle { public class InnerVehicle { InnerVehicle() { System.out.println("This is InnerVehicle"); } } } </code></pre> <p>And in the main function</p> <pre><code>import com.rafael.Vehicle; public class VehicleTest { public static void main(String[] args) { Vehicle v = new Vehicle(); Vehicle.InnerVehicle iv = v.new InnerVehicle(); } } </code></pre> <p>But this always gives me that error:</p> <blockquote> <p>java: InnerVehicle() is not public in com.rafael.Vehicle.InnerVehicle; cannot be accessed from outside package</p> </blockquote>
<p>Make the inner class <code>public static</code></p> <p>Otherwise you need an object of your outer class to creat an instance of the inner as Tim Biegeleisen already mentioned</p> <p>And make the constructor of your inner class <code>public</code> too</p> <p>Something like:</p> <pre><code>public class Vehicle { public static class InnerVehicle { public InnerVehicle() { System.out.println("This is InnerVehicle"); } } } </code></pre>
Android: enable/disable app widgets programmatically <p><strong>Question</strong>: Is there a way to enable some of the homescreen widgets that I give out with my app programmatically? For example, having a "premium" widget and giving access to it only after payment?</p> <hr> <p>As the Android <a href="https://developer.android.com/guide/topics/appwidgets/index.html" rel="nofollow">docs</a> say, one should add a broadcast receiver in the manifest to tell the system that there is a widget coming with the app:</p> <pre><code>&lt;receiver android:name="ExampleAppWidgetProvider" &gt; &lt;intent-filter&gt; &lt;action android:name="android.appwidget.action.APPWIDGET_UPDATE" /&gt; &lt;/intent-filter&gt; &lt;meta-data android:name="android.appwidget.provider" android:resource="@xml/example_appwidget_info" /&gt; &lt;/receiver&gt; </code></pre> <p>But in theory broadcast receivers can also be added programmatically, so can the widgets be registered later at runtime?</p>
<p>You can have <code>android:enabled="false"</code> on the <code>&lt;receiver&gt;</code> element for the app widget in the manifest, then use <code>PackageManager</code> and <code>setComponentEnabledSetting()</code> to enable it at runtime when the the user does something (e.g., pay up).</p> <p>However, it is possible that this will require a reboot before the home screen realizes that there is a new potential app widget provider.</p>
Building a function of a random variable dynamically in python <p>I have some random variables using <code>scipy.stats</code> as follows:</p> <pre><code>import scipy.stats as st x1 = st.uniform() x2 = st.uniform() </code></pre> <p>Now I would like make another random variable based on previous random variables and make some calculations like <code>var</code> for the new random variable. Assume that I want the new random variable to be something like <code>max(2, x1) + x2</code>. How can I define this dynamically?</p>
<p>Not directly, I think. However, this approach might be of use to you.</p> <p>Assume to begin with that you know either the pdf or the cdf of the function of the random variables of interest. Then you can use rv_continuous in scipy.stats to calculate the variance and other moments of that function using the recipe offered at <a class='doc-link' href="http://stackoverflow.com/documentation/scipy/6873/rv-continuous-for-distribution-with-parameters#t=201610161945055670237">SO doc</a>. (Incidentally, someone doesn't like it for some reason. If you think of improvements, please comment.)</p> <p>Obviously the 'fun' begins here. Usually you would attempt to define the cdf. For any given value of the random variable this is the probability that an expression such as the one you gave is not more than the given value. Thus determining the cdf reduces to solving a (an infinite) collection of inequalities in two variables. Of course there is often a strong pattern that greatly reduces the complexity and difficulty of performing this task.</p>
Xamarin, Android. Exception when opening *.axml files in VS2015 using F#, <p>I receive the following error message when opening layout files in <code>F#</code> project.</p> <p><a href="https://i.stack.imgur.com/ayVoo.png" rel="nofollow"><img src="https://i.stack.imgur.com/ayVoo.png" alt="enter image description here"></a></p> <blockquote> <p>System.NullReferenceException: Object reference not set to an instance of an object. at Xamarin.VisualStudio.Android.MonoAndroidDesignerInterface.VisualStudioCodeModelBridge.get_EnclosingProject() in c:\Users\builder\data\lanes\3822\3b7df6f5\source\xamarinvs\src\Core\VisualStudio.Android\Designer\MonoAndroidDesignerInterface.cs:line 180 at Xamarin.AndroidDesigner.CodeInteractions.CodeModelBridge.d__12.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Xamarin.AndroidDesigner.CodeInteractions.CodeModelBridge.d__27.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Xamarin.AndroidDesigner.DesignerProject.d__175.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Xamarin.AndroidDesigner.DesignerProject.d__139.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Xamarin.AndroidDesigner.AndroidRenderSession.d__105.MoveNext()`</p> </blockquote> <p>Never had this problem before, until I updated Xamarin to the latest version. I've found related bug here <a href="https://bugzilla.xamarin.com/show_bug.cgi?id=44956" rel="nofollow">https://bugzilla.xamarin.com/show_bug.cgi?id=44956</a>, but it says that it's a duplicate of another one which is <a href="https://bugzilla.xamarin.com/show_bug.cgi?id=44797" rel="nofollow">https://bugzilla.xamarin.com/show_bug.cgi?id=44797</a>, but I can't access it.</p>
<p>As mentioned, this appears to be <a href="https://bugzilla.xamarin.com/show_bug.cgi?id=44956" rel="nofollow">public bug report 44956</a>, which is currently under investigation. Bug 44797 was filed as a private issue by the individual reporting it; as such, only the original reporter and the Xamarin team can access it. </p> <p>The private bug has been closed as a duplicate of this public report, so future updates on the status of the bug from the Xamarin team will be made via <a href="https://bugzilla.xamarin.com/show_bug.cgi?id=44956" rel="nofollow">Bug 44956</a>.</p>
Swift time between run function <p>I am nearly new to swift Xcode and I am building an app, when the end user is near a iBeacon hi will get a local push notification.<br>The problem I have is each time he comes near to it(if he got back and forward he will get each time he is near).<br> So I think to limit by time like 5 minuets of some like that.<br> I can not find in Swift how to limit a function to run in a time limit.(like 5 minutes)<br><br> Can some one point me in the correct direction?<br><br> Thanks for the help.<br> I did try to work with a timer but it did not do the job for me.</p>
<p>You Can create a Variable: beaconsHasBeenRecognized to turn to true when the beacon has been recognized, then the next time user goes back and forth, before triggering notification, your code should evaluate it beaconsHasBeenRecognized,its false, otherwise, if it is true, it will not trigger the notification. Then with the timer, at the moment you set beaconsHasBeenRecognized to true, you start a timer to change beaconsHasBeenRecognized to false within the time that you want, like the 5 minutes.</p>
Google Chrome dev tools variable tip bubble too little to see the content <p>I have just now sended the following message to google chrome developer:</p> <p>Chrome version: 54.0.2840.59 m</p> <blockquote> <p>As you know, when debugging a web page with javascript, the Chrome debugger allows to pause the execution of the code on breakpoints. In this moment is possible to move the mouse onto a variable to see what value has in: when the mouse is on the variable chrome code inspector/debugger shows a little tip showing the variable value.</p> <p>The problem is that such little bubble tip sometimes is toooo little and it is not possible to see the content.</p> <p>Please correct its size (make it resizable) to make possible to read its content or it isn't useful.</p> <p>Thanks</p> </blockquote> <p>Anyone else has noticed the same issue? Someone has solved it?</p> <h2>Edits</h2> <p>Before the last update was working perfectly (or at least I didn't see anything wrong in its behavior!), but now the following image shows the issue that sometimes happens:</p> <h2><a href="https://i.stack.imgur.com/LhqbP.png" rel="nofollow"><img src="https://i.stack.imgur.com/LhqbP.png" alt="Example.png"></a></h2> <p>As shown into the above img, part of the bubble tip content is shown, part is hidden, and it is not possible to scroll the bubble tip neither up|down nor left|right: scrollbars are greyed. Sometimes scrollbars don't appear at all.</p>
<p>You can scroll the tool tip as per the animation below:</p> <p><a href="https://i.stack.imgur.com/iRtQg.gif" rel="nofollow"><img src="https://i.stack.imgur.com/iRtQg.gif" alt="Scrollable tool tip"></a></p>
Real - time adjustment of route based on Traffic condition <p>With the similarities of WAZE App.</p> <p>I wonder what API i can possibly use to make an mobile application that will dynamically / automatically adjust its route based on traffic level / condition.</p>
<p>If you are using google maps in android you need to call setTrafficEnabled(true) on your googleMaps object.</p> <p><a href="https://developers.google.com/maps/documentation/javascript/examples/layer-traffic" rel="nofollow">https://developers.google.com/maps/documentation/javascript/examples/layer-traffic</a></p> <p>If you want the raw data it's a little more complicated and almost impractical.</p> <p>You can get the layer from google maps and parse the server response(but it's really hard). You could use Google Enterprise (NOT FREE) <a href="https://enterprise.google.com/maps/products/mapsapi.html" rel="nofollow">https://enterprise.google.com/maps/products/mapsapi.html</a> and it will calculate routes with including traffic data.</p> <p>Or if you want just incidents use bingMaps API <a href="https://msdn.microsoft.com/en-us/library/hh441726.aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/hh441726.aspx</a></p> <p>There might be some other solutions, but they are not free, it's a complex service and people work hard for that information, they will charge for it.</p>
creating a sorted list in database <p>So basically I have a table named <code>contents</code> where users can store their items. Normally here when a user add a new item, The item is added at the end of rows. </p> <p>Something like:</p> <pre><code>|ID | Name | Item | -------------------- |1 | Jack | pen | |2 | Mark | apple | |3 | albert| orange| |4 | Jack | pencil| </code></pre> <p>But the problem with above is that it might take a lot of time when we have a lot of users and items like Jack's first item is at row ID 40 and item #2 is at 1000048 and so which might take a while to search for all the items that belongs to Jack So I was wondering how to sort them up by their Name so it could be something like:</p> <pre><code>|ID | Name | Item | -------------------- |1 | Jack | pen | |2 | Jack | pencil| |3 | Mark | apple | |4 | albert| orange| </code></pre> <p>And if the user added a new item it should be added to the end of his rows list.</p> <p>All replies are much appreciated, Thank:)</p>
<p>Add index(es) for any column (or combination of columns) you want to <em>search</em> for and/or want to <em>order by</em>.</p> <p>Do <em>not</em> reorder the table, nor re-number the ids.</p> <p>If you are talking about 1000 rows, you are unlikely to notice any performance problems even if you don't do proper indexing or normalization. With a million rows, you will notice.</p>
What is the replacement of d3.scale.category10().range() in Version 4 <p>I am using d3 graph library v4, There is a code which using the library d3 version3 not working with version4. Particularly the function is the following </p> <pre><code>d3.scale.category10().range() </code></pre> <p>what could be the replacement for the same in version 4 </p>
<p>To translate the line above to D3 v4, replace it with the following:</p> <pre><code>d3.scaleOrdinal(d3.schemeCategory10).range() </code></pre> <p>See also the <a href="https://github.com/d3/d3-scale/blob/master/README.md#schemeCategory10" rel="nofollow">D3 v4 documentation on scales</a>.</p>
Loop through employee numbers and see if certain date falls within a period <p>Who can help a beginner out. I've added two screenshots to make my story clearer.</p> <p><a href="https://i.stack.imgur.com/vSoTW.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/vSoTW.jpg" alt="Calculation"></a></p> <p><a href="https://i.stack.imgur.com/GNIbT.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/GNIbT.jpg" alt="Projects"></a></p> <p>My excel sheet is two tabs. One is 'calculation' and other is 'project'.</p> <p>What i'd like to know is how to program the following in vba:</p> <p>In the calculation tab there is a employee number in column E. I have to look if that number also is written in the projects tab. If so i need to know if the date of the calculation tab falls within the start and end date in the projects tab. If so then write the info if that row to the empty columns in the calculation tab.</p> <p>Another problem arises when an employee works multiple jobs in the projects tab. I guess there needs to be another loop in here:</p> <p>If the date from calculation tab doesn't fall in the period from start to end in the projects tab, is there another row with the same employee number and maybe it falls within that period.</p> <p>I hope i made my story clear. I know what the steps should be, just not how to program it. I hope someone is able to help me with this.</p>
<p>Since your screenshots appear to be Excel for Windows consider an SQL solution using Windows' JET/ACE Engine (.dll files) as you simply need to join the two worksheets with a <code>WHERE</code> clause for date filter. In this approach you avoid any need for looping and use of arrays/collections. </p> <p>To integrate below, add a new worksheet called <em>RESULTS</em> as SQL queries on workbooks are read-only operations and do not update existing data. A <code>LEFT JOIN</code> is used to keep all records in <em>Calculations</em> regardless of matches in <em>Projects</em> but matched data will populate in empty columns. <em>Results</em> should structurally replicate <em>Calculations</em>. Adjust column names in <code>SELECT</code>, <code>ON</code>, and <code>WHERE</code> clauses as required (as I cannot clearly read column names from screenshots). Finally, a very important item: be sure date columns are formatted as Date type.</p> <pre><code>Dim conn As Object, rst As Object Dim strConnection As String, strSQL As String Dim i As Integer Set conn = CreateObject("ADODB.Connection") Set rst = CreateObject("ADODB.Recordset") ' OPEN DB CONNECTION strConnection = "DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};" _ ' &amp; "DBQ=C:\Path\To\Workbook.xlsx;" conn.Open strConnection ' OPEN QUERY RECRDSET strSQL = "SELECT t1.*, t2.[Project] AS [Which Project], t2.[Customer] As [Which Customer]," _ &amp; " t2.[Start], t2.[End planned], t2.[Hours per week]" _ &amp; " FROM [Calculation$A$3:$D$1048576] t1" _ &amp; " LEFT JOIN [Projects$A$3:$J$1048576] t2" _ &amp; " ON t1.EmployeeNum = t2.EmployeeNum" _ &amp; " WHERE t1.[Date] BETWEEN t2.Start AND t2.[End planned];" rst.Open strSQL, conn ' COLUMNS For i = 1 To rst.Fields.Count Worksheets("RESULTS").Cells(3, i) = rst.Fields(i - 1).Name Next i ' DATA ROWS Worksheets("RESULTS").Range("A4").CopyFromRecordset rst rst.Close conn.Close Set rst = Nothing Set conn = Nothing </code></pre>
Use an enter key to perform a text field function <p>My Code that I tried to use. Please tell me what I have done wrong. I am not very good at JavaScript so, don't judge. </p> <p> </p> <pre><code>&lt;!-- Textfield with Floating Label --&gt; &lt;form action="#"&gt; &lt;div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label"&gt; &lt;input class="mdl-textfield__input" type="text" id="userInput" onkeypress="handle(e)"&gt; &lt;label class="mdl-textfield__label" for="userInput"&gt;Answer Here&lt;/label&gt; &lt;/div&gt; &lt;/form&gt; &lt;script&gt; function handle(e){ if(e.keyCode === 13){ e.preventDefault(); // Ensure it is only this code that rusn var input = document.getElementById("userInput").value; alert(input); } } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>You probably wanted to pass the event, not just <code>e</code></p> <pre><code>&lt;input class="mdl-textfield__input" type="text" id="userInput" onkeypress="handle(event)"&gt; </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form action="#"&gt; &lt;div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label"&gt; &lt;input class="mdl-textfield__input" type="text" id="userInput" onkeypress="handle(event)"&gt; &lt;label class="mdl-textfield__label" for="userInput"&gt;Answer Here&lt;/label&gt; &lt;/div&gt; &lt;/form&gt; &lt;script&gt; function handle(e) { if (e.keyCode === 13) { e.preventDefault(); // Ensure it is only this code that rusn var input = document.getElementById("userInput").value; alert(input); } } &lt;/script&gt;</code></pre> </div> </div> </p> <p>Preferably you'd use <code>addEventListener</code> instead</p> <pre><code>document.getElementById('userInput').addEventListener('keypress', function(e) { if(e.keyCode === 13) { e.preventDefault(); var input = this.value; alert(input); } }); </code></pre>
Can someone explain me this bit of code (from decimal to binary) <p>So this is the code i am trying to understand what is "i" standing for, and how this function works. I know what every line do, but i cant understand how is this going to display, let's say 5 into 0101. Thanks in advance!</p> <pre><code>int decimal_binary(int n) /* Function to convert decimal to binary.*/ { int rem, i=1, binary=0; while (n!=0) { rem=n%2; n/=2; binary+=rem*i; i*=10; } return binary; } </code></pre>
<pre><code>int decimal_binary(int n) /* Function to convert decimal to binary.*/ { int rem, i=1, binary=0; // declaring and initializing variables if you // understand that concept. // Another way to write this would be //int rem; //int i=1; //int binary=0; while (n!=0) //while loop to keep executing until (n not operator =0) { rem=n%2; // rem stores value of n%2 (modulus operator) reminder n/=2;// n=n/2; binary+=rem*i; //binary=binary+(rem*i); i*=10; // i=i*10 } return binary; //Hope you know what this is </code></pre> <p>}</p>
HANA procedure for CONDENSE and SPLIT <p>I am trying to condense and split a string into single rows, e.g. </p> <pre><code>A B C </code></pre> <p>into</p> <pre><code>A B C </code></pre> <p>So far, the below procedure works fine for CALL Z_SPLITROW('A B C'), but not if I have more whitespace between the chars. Any ideas?</p> <pre><code>CREATE PROCEDURE Z_SPLITROW(TEXT nvarchar(100)) AS BEGIN declare _items nvarchar(100) ARRAY; declare _text nvarchar(100); declare _index integer; _text := :TEXT; _index := 1; WHILE LOCATE(:_text,' ') &gt; 0 DO _items[:_index] := SUBSTR_BEFORE(:_text,' '); _text := SUBSTR_AFTER(:_text,' '); _index := :_index + 1; END WHILE; _items[:_index] := :_text; rst = UNNEST(:_items) AS ("items"); SELECT * FROM :rst; END; </code></pre>
<p>To filter out a flexible number of whitespace characters, you can use REPLACE_REGEXPR:</p> <pre><code>select 'A B C' as orig, replace_regexpr ( '[[:space:]]+' IN 'A B C' WITH ' ') as repl from dummy; ORIG | REPL ---------+------- A B C| A B C </code></pre>
Vue.js 1.0 select <p>In my webapp I've a select like this:</p> <pre><code>&lt;select class="Form-group-item" v-model="user.corporation_id"&gt; &lt;option value="" disabled selected&gt;Corporatie&lt;/option&gt; &lt;option v-for="corporation in corporations" v-bind:value="corporation.id"&gt;{{ corporation.name }}&lt;/option&gt; &lt;/select&gt; </code></pre> <p>So I receive <code>user.corporation_id</code> in a json format:</p> <pre><code>corporation_id:2 </code></pre> <p>And I set it on the user object. But when I look into my <code>vue-devtools</code> <code>user.corporation_id</code> is <code>''</code> ??</p> <p>When I remove the entire select from my html</p> <p><code>user.corporation_id = 2</code> !</p> <p>What's wrong here??</p>
<p>Remove 'selected' from the default option</p> <pre><code>&lt;select class="Form-group-item" v-model="user.corporation_id"&gt; &lt;option value="" disabled&gt;Corporatie&lt;/option&gt; &lt;option v-for="corporation in corporations" v-bind:value="corporation.id"&gt;{{ corporation.name }}&lt;/option&gt; &lt;/select&gt; </code></pre> <p>Since you have it as 'selected' it's overriding the value you have set and changing it to ''. </p>
Correct Usage of Entity Framework Generated Classes (DB First Approach) <p>I'm developing my first MVC5 website and it happens this is also the first time I'm using ET.</p> <p>I'm using Database First approach.</p> <p>For example, lets say these are my fields in Users table.</p> <pre><code>| Username | Email | Password | </code></pre> <p>And Entity Frameworks generate me the following class:</p> <pre><code>class Users { public string Username { get; set; } public string Email { get; set; } public string Password { get; set; } } </code></pre> <p>Now lets say I want to create a View for Registration. This registration requires user to confirm his password. Do I expand the existing ET generated class like this?</p> <pre><code>class Users { public string Username { get; set; } public string Email { get; set; } public string Password { get; set; } public string ConfirmPassword { get; set; } } </code></pre> <p>Or do I make an entirely different class myself that will contain all the necessary information separately from ET generated class?</p> <p>Do I make Views using ET generated classes, or do I use my own classes?</p> <p>I've seen ViewModels being mentioned here and there, but it is not very clear to me as to what purpose they serve.</p> <p>As of right now, I'm manually adding extra fields to ET classes, and it works, but I've no idea if I'm doing it wrong or right.</p>
<p>You should not touch your entity framework generated code for such requirement. Instead you need to create a view model to contain fields which you want to get from user when registration. You can create a <code>RegisterViewModel</code>. Then to compare those properties, use <a href="https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.compareattribute(v=vs.110).aspx" rel="nofollow"><code>Compare</code></a> attribute, exactly <strong>like what is used in ASP.NET MVC default project template</strong>. Then in controller, check if model state is valid, create a <code>User</code> entity using posted values an save in db:</p> <p><strong>Model</strong></p> <pre><code>public class RegisterViewModel { [Required] [Display(Name = "User name")] public string UserName { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } </code></pre> <p><strong>Action</strong></p> <pre><code>// POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task&lt;ActionResult&gt; Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new User() { UserName = model.UserName, /*... other fields */ }; // Save user } // If we got this far, something failed, redisplay form return View(model); } </code></pre>
ignored declarative Security in IBM WebShere application server <p>I have a spring MVC rest application that is deployed as a war file to IBM WebSphere application server v 8.5, i want to secure some of the rest api in this application, hence, i used the application web.xml and declare the security role i want, then i enabled the application security from the WAS console, but for some reason my security roles are ignored and i can access all rest API that are supposed to be secured, any help is appreciated.</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"&gt; &lt;servlet&gt; &lt;servlet-name&gt;appServlet&lt;/servlet-name&gt; &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/applicationContext.xml&lt;/param-value&gt; &lt;/init-param&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;appServlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;security-constraint&gt; &lt;web-resource-collection&gt; &lt;web-resource-name&gt;LBS_System&lt;/web-resource-name&gt; &lt;url-pattern&gt;/LBS/*&lt;/url-pattern&gt; &lt;http-method&gt;POST&lt;/http-method&gt; &lt;http-method&gt;PUT&lt;/http-method&gt; &lt;http-method&gt;DELETE&lt;/http-method&gt; &lt;/web-resource-collection&gt; &lt;auth-constraint&gt; &lt;role-name&gt;Administrators&lt;/role-name&gt; &lt;/auth-constraint&gt; &lt;/security-constraint&gt; &lt;login-config&gt; &lt;auth-method&gt;BASIC&lt;/auth-method&gt; &lt;realm-name&gt;defaultWIMFileBasedRealm&lt;/realm-name&gt; &lt;/login-config&gt; &lt;security-role&gt; &lt;role-name&gt;Administrators&lt;/role-name&gt; &lt;/security-role&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;resource-ref&gt; &lt;res-ref-name&gt;jdbc/MoictDB&lt;/res-ref-name&gt; &lt;res-type&gt;javax.sql.DataSource&lt;/res-type&gt; &lt;/resource-ref&gt; &lt;persistence-unit-ref&gt; &lt;persistence-unit-ref-name&gt;persistence/MoICTAppUnit&lt;/persistence-unit-ref-name&gt; &lt;persistence-unit-name&gt;MoICTAppUnit&lt;/persistence-unit-name&gt; &lt;/persistence-unit-ref&gt; &lt;/web-app&gt; </code></pre>
<p>You should not include your context-root (LBS in your case) in the url-pattern. It is relative to your application context-root. The <code>/*</code> pattern protects all urls, but <strong>only in your application</strong>, not others. So if you just want to protect for example rest api, it is usually mapped to some sub path e.g. <code>/LBS/rest/something</code>, in that case you would put <code>/rest/*</code> in the pattern.</p> <p>You should not include context-root in any mappings and url patterns in the web.xml, especially that application might be deployed under different context-root and in that case it would be broken.</p>
static variables in multiple processes (Signals) <p>I have 2 processes running test.c. There is a signal handler in test.c which executes an execlp. In test.c, I have a static variable which needs to be only initialized once, and incremented each time before the execlp call. When either process reaches 99, they exit.</p> <p>Unfortunately, right now, it's not getting incremented, my guess is because there are 2 processes that each have a copy of the static variable. Here is test.c:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;signal.h&gt; #include &lt;unistd.h&gt; static int i = 0; static int foo(int j) { printf("In the foo...\n"); j++; printf("%d\n", j); return j; } void main(int argc, char *argv[]) { int pid, pid2, k; int *h = malloc(sizeof(int)); int g = 0; h = &amp;g; static char s[15]; pid = fork(); if (pid &gt; 0) { sleep(1); } if (pid == 0) { k = foo(*h); sprintf(s, "%d", k); if (k &gt;= 99) { printf("k=99\n"); exit(0); } execlp("./a.out", "forktest", s, NULL); } pid2 = fork(); if (pid2 == 0) { k = foo(*h); sprintf(s, "%d", k); if (k &gt;= 99) { printf("k=99\n"); exit(0); } execlp("./a.out", "forktest", s, NULL); } wait(pid2); wait(pid); } </code></pre> <p>Can anyone please explain why there is an infinite loop? Why isn't the static variable get incremented?</p> <p>Thank you.</p>
<p>Use Interprocess communication concepts (pipe, fifo, shared memory) here, <code>execlp</code> function overwrites memory of current program with new program. So when ever you call <code>execlp</code> gets called your program get refreshed and starts from begining and <code>static int i</code> is always 0.</p> <p>I recommend to use <code>pipe</code> <a href="https://users.cs.cf.ac.uk/Dave.Marshall/C/node23.html" rel="nofollow">Refer this</a>.</p>
java collection result designing <p>I am developing a small utility for collection filtering. I have done the coding for that. What I am doing is iterating the original collection and find the filter matching and if any match is found then add the result to the new collection(result collection). And finally the result collection is stored into the original collection. Is this good idea the collection result to store back to the orginal collection? I need to design this filtering framework in a fluent interface style. Please find the code below.</p>
<p>At first it's really bad practice modify original collection, because you can apply filter only once and you always should keep in mind that your original collection can be changed. It's highway to bugs.</p> <p>Also use Predicate instead of Filter or make Filter implements Predicate, its more flexible and convenient way for filtering.</p> <p>Example:</p> <pre><code>class Filter&lt;T&gt; implements Predicate&lt;T&gt; {} </code></pre> <p>You can create your filter then pass it to filter method easily.</p> <p>Also keep in mind that your utility should be thread safe, better use this approach:</p> <pre><code>public final CollectionMapper&lt;T&gt; filter(Filter&lt;T&gt; filter) { Collection&lt;T&gt; result = new ArrayList&lt;&gt;(); Iterator&lt;T&gt; iterator = orginal.iterator(); while (iterator.hasNext()) { T t = iterator.next(); if (filter.match(t)) { result.add(t); } } return new CollectionMapper&lt;&gt;(result); } </code></pre>
Is AtomicCmpExchange reliable on all platforms? <p>I can't find the implementation of <code>AtomicCmpExchange</code> (seems to be hidden), so I don't know what it does. </p> <p>Is <code>AtomicCmpExchange</code> reliable on all platforms? How is it implemented internally? Does it use something like a critical section?</p> <p>I have this scenario :</p> <p>MainThread:</p> <pre><code>Target := 1; </code></pre> <p>Thread1:</p> <pre><code>x := AtomicCmpExchange(Target, 0, 0); </code></pre> <p>Thread2:</p> <pre><code>Target := 2; </code></pre> <p>Thread3:</p> <pre><code>Target := 3; </code></pre> <p>Will <code>x</code> always be an integer 1, 2 or 3, or could it be something else? I mean, even if the <code>AtomicCmpExchange(Target, 0, 0)</code> failed to exchange the value, does it return a "valid" integer (I mean, not a half-read integer, for exemple if another thread has already started to half write of the value)?</p> <p>I want to avoid using a critical section, I need maximum speed.</p>
<p><code>AtomicCmpExchange</code> is what is known as an <a href="http://docwiki.embarcadero.com/RADStudio/en/Delphi_Intrinsic_Routines" rel="nofollow"><em>intrinsic routine</em>, or a <em>standard function</em></a>. It is intrinsically known to the compiler and may or may not have a visible implementation. For example, <code>Writeln</code> is a standard function, but you won't find a single implementation for it. The compiler breaks it up into multiple calls to lower-level functions in System.pas. Some standard functions, such as <code>Inc()</code> and <code>Dec()</code> don't have any implementation in System.pas. The compiler will generate machine instructions which amount to simple <code>INC</code> or <code>DEC</code> instructions.</p> <p>Like <code>Inc()</code> or <code>Dec()</code>, <code>AtomicCmpExchange()</code> is implemented using whatever code is needed for a given platform. It will generate inline instructions. For x86/x64 it will generate a <code>CMPXCHG</code> instruction (along with whatever setup is necessary to get variables/values into the registers). For ARM it will generate a few more instructions around the <code>LDREX</code> and <code>STREX</code> instructions.</p> <p>So the direct answer to your question is that even calling into assembly code, you cannot get much more efficient than using that standard function along with others such as <code>AtomicIncrement</code>, <code>AtomicDecrement</code>, and <code>AtomicExchange</code>.</p>
MongoDB query and calculating average for nested array elements <p>I have a collection <code>lanes</code> which has documents of following structure. Only the <code>dist</code> and <code>time</code> of new documents changes. I want to calculate average-speeds of all lanes grouped by <code>l_id</code>. </p> <pre><code>{ _id: 1213, ab:[ { l_id: 101, dist: 100, time: 100 }, { l_id: 102, dist: 140, time: 120 }, { l_id: 103, dist: 10, time: 10 } ] } </code></pre> <p>like this : </p> <pre><code>{[ { l_id: 101, avgspeed: 14 }, { l_id: 102, avgspeed: 19 }, { l_id: 103, avgspeed: 9 } ]} </code></pre> <p>How can it be done using mongo aggregate/unwind query?</p> <p>EDIT 1: (how to do it the structure is as follows)</p> <pre><code>{ _id: 1213, ab:[ { l_id: 101, data:[{ dist: 100, time: 100 }] }, { l_id: 102, data:[{ dist: 140, time: 120 }] }, { l_id: 103, data:[{ dist: 10, time: 10 }] } ] } </code></pre>
<pre><code>db.Test2.aggregate([ { $unwind: "$ab" }, { $unwind: "$ab.data" }, { $group:{ _id: "$ab.l_id", avgspeed: {$avg:{$divide:["$ab.data.dist","$ab.data.time"]}} } } ]); </code></pre>
Select a large number of ids from a Hive table <p>I have a large table with format similar to</p> <pre><code>+-----+------+------+ |ID |Cat |date | +-----+------+------+ |12 | A |201602| |14 | B |201601| |19 | A |201608| |12 | F |201605| |11 | G |201603| +-----+------+------+ </code></pre> <p>and I need to select entries based on a list with around 5000 thousand IDs. The straighforward way would be to use the list as a <code>WHERE</code> clause but that would have a really bad performance and probably it even would not work. How can I do this selection?</p>
<p>Using a partitioned table things run fast. Once you partitioned the table add your ids into the where. You can also extract a subtable from the original one selecting all the rows which have their ids between the min and the max of you ids list.</p>
Django dateutil parse is changing the date to today's date <p>I am trying to use Django dateutil.pareser.parse() to change the date '2016:09:24 17:08:45' to '2016-09-24 17:08:45'. But when I use the following code:</p> <pre><code>the_timestamp = self.request.query_params.get('timestamp',0) # = '2016:09:24 17:08:45' the_parsed_timestamp = dateutil.parser.parse(the_timestamp) </code></pre> <p>I get the result the_parsed_timestamp = '2016-10-16 17:08:45'. 2016-10-16 is today's date.</p> <p>Why is dateutil.parser.parse replacing the date with today's date (and leaving the time part alone)?</p>
<p>You have the wrong date format. It should be:</p> <pre><code>2016-09-24 </code></pre> <p>not </p> <pre><code>2016:09:24 </code></pre>
How to call a variable inside main function from another program in python? <p>I have two python files first.py and second.py</p> <p>first.py looks like</p> <pre><code>def main(): #some computation first_variable=computation_result </code></pre> <p>second.py looks like</p> <pre><code>import first def main(): b=getattr(first, first_variable) #computation </code></pre> <p>but I am getting No Attribute error. Is there any way to access a variable inside main() method in first.py through second.py?</p>
<p>You should use function calls and return values instead of this. </p> <p>Return the computation_result from the function in the first file, and then store the result in the b variable in the second file.</p> <p>first.py</p> <pre><code>def main(): # computation return computation_result </code></pre> <p>second.py</p> <pre><code>import first def main(): b = first.main() </code></pre> <p>Other option is to use a global variable in the first file where you will store the value and later reference it.</p>
How do you align text on a Text Field? <p>I made a <code>TextField</code> using Libgdx scene2d and I want the text on the text field to appear on the center, so when the user type a string, the string will start at the center and not at the left. I also tried to set the cursor position but nothing is happening, is it because it's in a table?</p> <pre><code>textField = new TextField("", tfStyle); textField.setCursorPosition(33); table.add(tf); </code></pre>
<p>You can try <code>textField.setAlignment(Align.center);</code>.</p> <blockquote> <p>setAlignment(int alignment)</p> <p>Sets text horizontal alignment (left, center or right).</p> </blockquote>
Typescript : Call instance method <p>I have an interface:</p> <pre><code>export interface ISearchService { search(terms: string): Observable&lt;any&gt;; } </code></pre> <p>I have two services implementing this interface:</p> <p>SearchMaleEmployeeService:</p> <pre><code>@Injectable() export class SearchMaleEmployeeService implements ISearchService { constructor() { } public search(terms: string): Observable&lt;any&gt; { console.log('call: SearchMaleEmployeeService.search ' + terms); } } </code></pre> <p>SearchFemaleEmployeeService:</p> <pre><code>@Injectable() export class SearchFemaleEmployeeService implements ISearchService { constructor() { } public search(terms: string): Observable&lt;any&gt; { console.log('call: SearchFemaleEmployeeService.search ' + terms); } } </code></pre> <p>In my search.component, I would like to call the search method of the service.</p> <p>My search.component:</p> <pre><code>export class SearchComponent { constructor(@Inject('ISearchService') private searchService: ISearchService) { } onSearch(terms: string) { this.searchService.search(terms); } } </code></pre> <p>And finally, in the component which hosts SearchComponent:</p> <pre><code>providers: [ { provide: 'ISearchService', useValue: SearchFemaleEmployeeService} ], </code></pre> <p>When I run the onSearch method in SearchComponent, I got this error:</p> <pre><code>EXCEPTION: Error in ./SearchComponent class SearchComponent - inline template:0:127 caused by: this.searchService.search is not a function </code></pre> <p>I think this is because I'm trying to call a method from a interface, but when I <code>console.log</code> <code>this.searchService</code>, it returns <code>SearchFemaleEmployeeService</code>, that mean that this is the good instance. Why do I have this error?</p>
<p>Because you're using <code>useValue</code></p> <pre><code>{provide: 'ISearchService', useValue: SearchFemaleEmployeeService} </code></pre> <p>which just uses the <em>value you provide</em>, which is a class, which in JS is a function. You should instead use <code>useClass</code>, then Angular will create it for you.</p> <pre><code>{provide: 'ISearchService', useClass: SearchFemaleEmployeeService} </code></pre>
Why do my menu items activate a scroll function? <p>I used the 'Page scroll to id' plugin for Wordpress to set up a one scroll page where the menu items let you scroll through the section. I noticed the animation wasn't working, which had been the case for a few other websites I worked on in the past. Strange enough, unchecking the option 'activate on menu-items' did the trick back then and made the animation work. However, this time is different. I checked the general forum for this plugin on Wordpress.org to troubleshoot this and I later deactivated the plugin to try to make it work with a simple jQuery function. </p> <p>After those attemps I noticed that the menu items were still letting me scroll through the page, even though I removed my function and deactivated the plugin. I cleared my browser cache and installed WP Super Cache to delete any cache from the website itself. Neither of these did the trick.</p> <p>I have no idea what makes the menu items scroll through the page, but it overrides any workaround I attempted to get an animated scroll function. There aren't any plugins installed at this moment. Does anyone know what might be causing this?</p> <p><strong>Edit:</strong> I tried a couple of things: </p> <ul> <li>I replaced the id's and urls of the menu items with something I didn't use before, but the buttons still made me jump, just to be sure it's no caching</li> <li>After that, I checked the database, but couldn't find anything related</li> <li>I did a complete reinstall of WordPress and the database, but left my own parent and child theme of twentysixteen in, the problem remained</li> <li>I downloaded a clean twentysixteen and replaced the parent theme with it, the problem remained</li> <li>Checked all files from the child theme just to be sure, but there's nothing that could cause this</li> </ul> <p>This makes me think there now is a jump/scroll function in either the parent theme or the WP installation itself, which is weird because this shouldn't be standard. (let alone impossible to override)</p>
<p>Could be still stetting #id in the menu, try to check the Menu inside appearance.</p> <p>Other things you can do it's delete the tables of the plug-in in the DB. when you uninstall the plug-in form wp, the tables in the db still exits, it's difficult but cold be that. </p> <p>Also you can check if you have really delete all the jQuery script from all files and founder.</p>
Open file with external Intent/Application <p>After creating a file in the app's <code>fileDirectory</code> I would like to open it with an external app like the Adobe Reader etc. To achive this I tried to use an <code>Intent</code> like in the code below.</p> <pre><code>ContextWrapper cw = new ContextWrapper(getApplicationContext()); java.io.File fileItem = new java.io.File(cw.getFilesDir() + "/sync/arbitraryFileName.extension"); MimeTypeMap myMime = MimeTypeMap.getSingleton(); Intent newIntent = new Intent(Intent.ACTION_VIEW); String fileExtension = StaticHelper.fileExt(((File) item).getFileName()); if (fileExtension != null) { String mimeType = myMime.getMimeTypeFromExtension(fileExtension); String bb = Uri.fromFile(fileItem).toString(); newIntent.setDataAndType(Uri.fromFile(fileItem), mimeType); newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { getApplicationContext().startActivity(newIntent); } catch (ActivityNotFoundException e) { Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show(); } } else { Toast.makeText(getApplicationContext(), "no extension found", Toast.LENGTH_SHORT).show(); } </code></pre> <p>But sadly this code does not work: The apps are always saying that the file does not exist - but in the device's ADB shell I can find the file with exactly the same path which is used in my code. I have already added</p> <pre><code>&lt;uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /&gt; </code></pre> <p>in my code, but it did not help at all.</p>
<p>Third-party apps do not have access to your app's portion of <a href="https://commonsware.com/blog/2014/04/07/storage-situation-internal-storage.html" rel="nofollow">internal storage</a>. Use something like <code>FileProvider</code> <a href="https://commonsware.com/blog/2016/03/16/how-publish-files-via-content-uri.html" rel="nofollow">to make this content available to other apps</a>.</p> <p>Also:</p> <ul> <li><p>Replace all occurrences of <code>getApplicationContext()</code> with <code>this</code> in your code shown above. Only use <code>getApplicationContext()</code> when you know <strong>exactly why</strong> you are using <code>getApplicationContext()</code>.</p></li> <li><p>Get rid of the <code>ContextWrapper</code>, as you do not need it.</p></li> </ul>
Using logical OR operator in condition <p>my code is comparing a strings "text" against two additional strings "redact" and "redact2" and replacing it with "REDACTED" if there is match. </p> <pre><code>puts "Enter your sentense" text = gets.downcase.chomp puts "Enter your 2 words to be reducted" redact = gets.downcase.chomp redact2 = gets.downcase.chomp words = text.split(" ") words.each do |w| if w == redact print "REDACTED " elsif w == redact2 print "REDACTED " else print w + " " end end </code></pre> <p>I was trying to simplify my code by using logical OR in <code>if</code> statement, but the code prints <code>"RETUCTED"</code> for all words. Can someone please explain me why?</p> <pre><code>words.each do |w| if w == redact || redact2 print "REDACTED " else print w + " " end end </code></pre>
<blockquote> <p>Can someone please explain me why?</p> </blockquote> <p>Because <code>==</code> binds stronger, than <code>||</code>.</p> <p>Thus, your statement is actually interpreted as follows:</p> <pre><code>if (w == redact) || redact2 </code></pre> <p>not as you are expecting:</p> <pre><code>if w == (redact || redact2) </code></pre> <p>To solve it you have few options:</p> <ul> <li><code>if w == redact || w == redact2</code></li> <li><code>if [reduct, reduct2].include?(w)</code></li> </ul> <p>If you are keen on saving few more lines, you could have simplified your code to:</p> <pre><code>words.each do |w| print [redact,redact2].include?(w) ? "REDACTED " : w + " " end </code></pre>
Swift: Execution was interrupted, reason: EXC_BAD_INSTRUCTION error <p>When I attempt this in Playground:</p> <pre><code>func StockEvolution(S_0:Double, _ down:Double, _ up:Double, _ totalsteps:Int, _ upsteps:Int) -&gt; Double // function being used in calcCall() { var S_t:Double = S_0 * pow(up, Double(upsteps)) * pow(down, Double(totalsteps - upsteps)) return S_t } func CallPayoff(S:Double, _ K:Double) -&gt; Double // function being used in calcCall() { return max(S - K, 0.0) } func calcCall(S_0:Double, _ down:Double, _ up:Double, _ r:Double, _ steps:Int, _ K:Double) -&gt; Double //calculate Call-Option { var prices = [Double]() var q = 0.6 //risk-neutral probability factor var i = 0 while i &lt; steps { var payOff = CallPayoff(StockEvolution(S_0, down, up, steps, i), K) prices.append(payOff) i += 1 } var n = steps - 1 while n &gt;= 0 { var j = 0 while j &lt;= n { var value = (1 / r) * (prices[j + 1] * q + (1 - q) * prices[j]) prices.removeAtIndex(j) prices.insert(value, atIndex: j) j += 1 } n -= 1 } return prices[0] } </code></pre> <p>By doing this:</p> <pre><code>var checkPrice = calcCall(100, 0.6, 1.5, 1.05, 10, 200) </code></pre> <p>It gives me this error: </p> <p>Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)</p> <p>I can't seem to find the bug in my code. I've tried with different input values but the error still occurs. </p> <p>It would be great if you could have a look at my code and help me to fix this issue. Thanks for your efforts.</p>
<p>The issue is with your nested <code>while</code> loops. The first time you loop through, <code>n</code> is set to <code>9</code>, which means that on the final pass through the nested loop you end up with <code>j == 9</code>, which clearly means <code>j + 1 == 10</code>. But you're trying to get <code>prices[j + 1] == prices[10]</code>, which doesn't exist. Hence the crash.</p> <p>To see this, add the following if statement:</p> <pre><code>if j + 1 &lt; prices.count { let value = (1 / r) * (prices[j + 1] * q + (1 - q) * prices[j]) prices.removeAtIndex(j) prices.insert(value, atIndex: j) } j += 1 </code></pre> <p>You'll no longer get the bad access error. </p> <p>Now, I don't know the problem domain at all, so I can't say <em>why</em> your algorithm was incorrect. As such the answer I've provided may not give you the values you expect. You'll probably have to work out why you're trying to access a non-existent index, and how to work around that.</p> <p>Finally, if I may, some general style points:</p> <ul> <li>You might noticed I swapped the <code>var</code> in the code sample above for a <code>let</code>. Since <code>value</code> is never mutated (instead being redefined at each pass through the loop) it doesn't need to be mutable. Removing mutable state will make it easier to find problems in your code. </li> <li>You've used a lot of while loops with mutable state to track progress through them. These can all be replaced with <code>for...in</code> loops. E.g. the first while can be replaced with <code>for i in 0..&lt;steps</code> without any affecting the code. This again helps cut down on mutable state, and programmer error.</li> </ul> <p>I took the liberty of rewriting your code to make it a bit more "Swifty", while also removing as much mutable state as possible. Here it is:</p> <pre><code>func stockEvolution(s_0: Double, _ down: Double, _ up: Double, _ totalsteps: Int, _ upsteps: Int) -&gt; Double { let s_t: Double = s_0 * pow(up, Double(upsteps)) * pow(down, Double(totalsteps - upsteps)) return s_t } func callPayoff(s: Double, _ k: Double) -&gt; Double { return max(s - k, 0.0) } func calcCall(s_0: Double, _ down: Double, _ up: Double, _ r: Double, _ steps:Int, _ k: Double) -&gt; Double { var prices = Array(0..&lt;steps).map { step in return callPayoff(stockEvolution(s_0, down, up, steps, step), k) } let q = 0.6 //risk-neutral probability factor for n in (0..&lt;steps).reverse() { for j in 0...n where j + 1 &lt; prices.count { let value = (1 / r) * (prices[j + 1] * q + (1 - q) * prices[j]) prices.removeAtIndex(j) prices.insert(value, atIndex: j) } } return prices[0] } let checkPrice = calcCall(100, 0.6, 1.5, 1.05, 10, 200) </code></pre>
Performing specific action when user clicks any HTML element <p>I am creating navigation buttons that will drop down sub-menu when clicked, using checkbox input. Whenever user clicks the label input is checked and menu drop's down, when clicking the label again, it is being collapsed back. </p> <p>But now i need to perform specific action, i am trying to make dropdown menu collapse when any HTML element is clicked, so user doesn't need to click the specific element to collapse menu.</p> <p>HTML &amp; CSS code specifically for dropdown menu:</p> <pre><code>&lt;ul class="down-bar" style="list-style:hidden"&gt; &lt;div class="dropdown"&gt; &lt;input type="checkbox" value="drop" id="drop-1" class="dropper"&gt; &lt;li&gt;&lt;label class="down-nav" id="down-nav-1" for="drop-1" style="text-decoration:none"&gt;Click &lt;b class="caret"&gt; &amp;#9660;&lt;/b&gt;&lt;/label&gt;&lt;/li&gt; &lt;div class="dropdown-menu"&gt; &lt;a href="#"&gt;Link&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS: </p> <pre><code>.dropdown { display: inline-block; float: left; padding-top: 0em; transition: 0.1s ease-in; margin-top: 1.5%; white-space: nowrap; } .dropdown-menu { float: left; display: none; top: 0%; margin-top: 2.2%; width: 8%; min-width: 50px; padding-left: 18px; background-color: rgba(26, 26, 26, 2); box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 99; list-style-type: none; transition: 0.1s ease-in; border-color: black; border-radius: 3px; } .dropdown-menu a { color: white; font-size: 0.9em; padding: 0px 2px 0px 0px; text-decoration: none; display: block; list-style-type: none; white-space: nowrap; left: 0%; margin-left: 0%; } .dropdown-menu a:hover { color: #C90205; } .dropper { display: none; visibility: hidden; } .dropper:checked ~ .dropdown-menu { display: block; z-index: 99; } .dropper:checked ~ li #down-nav-1 { border: solid 3px gray; background-color: gray; margin-top: 1.5%; margin-left: 3%; border-radius: 10px; } </code></pre> <hr> <p>I have tried few examples, such as using full width anchor tag, but then main menu would disappear, i was going to use <code>:active</code> tag to change menu's display back to <code>None</code>. see the <a href="https://jsfiddle.net/bqj6myea/embedded/result/" rel="nofollow">full code</a>. ( remove comment tags for full width example ). </p> <p>So in the conclusion, how could i achieve this without making other elements disappear, do i have some mistake in code? is first example good solution? If so, how? How could i make menu collapse back when user clicks any HTML element? Can this be achieved without use of Javascript?</p>
<p>If you are ok with javascript solution you can use this example:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).click(function(e) { if (! ($('#down-nav-1').is(e.toElement) || $('#drop-1').is(e.toElement))) { $('.dropper').prop('checked', false) } });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.dropdown { display: inline-block; float: left; padding-top: 0em; transition: 0.1s ease-in; margin-top: 1.5%; white-space: nowrap; } .dropdown-menu { float: left; display: none; top: 0%; margin-top: 2.2%; width: 8%; min-width: 50px; padding-left: 18px; background-color: rgba(26, 26, 26, 2); box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 99; list-style-type: none; transition: 0.1s ease-in; border-color: black; border-radius: 3px; } .dropdown-menu a { color: white; font-size: 0.9em; padding: 0px 2px 0px 0px; text-decoration: none; display: block; list-style-type: none; white-space: nowrap; left: 0%; margin-left: 0%; } .dropdown-menu a:hover { color: #C90205; } .dropper { display: none; visibility: hidden; } .dropper:checked ~ .dropdown-menu { display: block; z-index: 99; } .dropper:checked ~ li #down-nav-1 { border: solid 3px gray; background-color: gray; margin-top: 1.5%; margin-left: 3%; border-radius: 10px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;ul class="down-bar" style="list-style:hidden"&gt; &lt;div class="dropdown"&gt; &lt;input type="checkbox" value="drop" id="drop-1" class="dropper"&gt; &lt;li&gt;&lt;label class="down-nav" id="down-nav-1" for="drop-1" style="text-decoration:none"&gt;Click &lt;b class="caret"&gt; &amp;#9660;&lt;/b&gt;&lt;/label&gt;&lt;/li&gt; &lt;div class="dropdown-menu"&gt; &lt;a href="#"&gt;Link&lt;/a&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
Rails Rspec Capybara Selenium JS create not showing after pressing submit <p>I am building a web shop, the functionality is already there, namely: in ONE screen there is a list of products and a list of ordered items. When in a product pressing order, this product then shows up immediately in this list. </p> <p>As you can guess, when wanting to do this with a test, using selenium I see Firefox starting up, I think I even see the button being pressed, but then obviously nothing happens. No item in my order list. </p> <p>Using Rails 5 with an updated capybara and selenium webdriver.</p> <pre class="lang-ruby prettyprint-override"><code> gem 'rspec-rails', '~&gt; 3.5', '&gt;= 3.5.1' gem 'capybara', '~&gt; 2.10', '&gt;= 2.10.1' gem "factory_girl_rails", "~&gt; 4.7" gem 'selenium-webdriver', '~&gt; 3.0' gem 'database_cleaner', '~&gt; 1.5', '&gt;= 1.5.3' gem "email_spec", "~&gt; 1.6.0" </code></pre> <p><strong>creating_order_spec.rb</strong></p> <pre class="lang-ruby prettyprint-override"><code>require 'rails_helper' RSpec.feature 'User can fill his shopping cart', js: true do let!(:category) { FactoryGirl.create(:category, name: 'Honey') } let!(:cheap_product) { FactoryGirl.create(:product, name: 'Honey lolly', price: '0,80', category: category) } let!(:expensive_product) { FactoryGirl.create(:product, name: 'Honeyjar 400ml', price: '3,95', category: category) } before do visit categories_path end scenario 'with different products' do page.find('#product', :text =&gt; 'Propolis lollie').click_button('VOEG TOE AAN MANDJE') page.find('#product', :text =&gt; 'Honingpot 400ml').click_button('VOEG TOE AAN MANDJE') within('#order') do expect(page).to have_content 'Honey lolly' expect(page).to have_content 'Honeyjar 400ml' expect(page).to have_content 0.80 + 3.95 end end end </code></pre> <p><strong>Database_cleaning.rb</strong></p> <pre class="lang-ruby prettyprint-override"><code>RSpec.configure do |config| config.before(:suite) do DatabaseCleaner.clean_with(:truncation) end config.before(:each) do DatabaseCleaner.strategy = :transaction end config.use_transactional_fixtures = false config.before(:each, :js =&gt; true) do DatabaseCleaner.strategy = :truncation end config.before(:each) do DatabaseCleaner.start end config.after(:each) do DatabaseCleaner.clean end end </code></pre> <p>Then I run it and get:</p> <pre class="lang-text prettyprint-override"><code>Failure/Error: expect(page).to have_content 'Honey lolly' expected to find text "Honey lolly" in "Total € 0,00" </code></pre> <p>Which means that nothing has happened to my order, or the total would have been more than € 0,00.</p>
<p>Most likely cause is an error in one of your JS assets that's preventing the behavior you're expecting from being attached. Things can work fine in dev mode when the assets aren't concatenated (so an error in one file doesn't prevent the other files from being processed), but then fail in the test and production environments when an error in one file can prevent the JS concatenated after it from being parsed/processed.</p> <p>Additionally you find 2 (I assume they are different since you're expecting 2 products to be added) elements with id = Product ('#product'). That is invalid html since ids are required to be unique, so could lead to weird issues.</p>
Improving javascript code performance <p>Assume you have a webapp with a 1000000 user logins in an hour.</p> <p>and the following code get executed on each user login :</p> <pre><code>if (DevMode) { // make an Ajax call } else if (RealMode) { // make other Ajax call } else { // Do something else } </code></pre> <p>Assuming that the DevMode login occurs only for 5% of the total user logins, is it more efficient to write the code as following:</p> <pre><code> if (RealMode) { // make an Ajax call } else if (DevMode) { // make other Ajax call } else { // Do something else } </code></pre> <p>Thanks</p>
<p>Assuming that <code>RealMode</code> is the 95% case (you haven't actually said whether it's <code>RealMode</code> or <code>else</code>) then: Well, yes, because you avoid doing a check that will be false 95% of the time.</p> <p>It won't <strong>matter</strong> that it's more efficient, though. Testing a variable for truthiness is really, really, really, really, really fast.</p>
React + Webpack - Invariant Violation Error in simple Hello World component <p>So far I have managed to finally figure out how to configure my webpack.config.js file to handle jsx files. here it is:</p> <pre><code>var HtmlWebpackPlugin = require('html-webpack-plugin'); var HtmlWebpackPluginConfig = new HtmlWebpackPlugin({ template: __dirname + '/app/index.html', filename: 'index.html', inject: 'body' }) module.exports = { entry: [ './app/index.jsx' ], output: { path: __dirname + '/dist', filename: "index_bundle.jsx" }, module: { loaders: [ {test: /\.jsx$/, exclude: /node_modules/, loader: "babel-loader", query: {presets: ['react', 'es2015']}} ] }, resolve: { extensions: ['','.js', '.jsx'] }, plugins: [HtmlWebpackPluginConfig] } </code></pre> <p>And what I am trying to do is render a very simple react component with a react-bootstrap button: </p> <p>HelloWorld.jsx</p> <pre><code>import React from 'react'; import { Button } from 'react-bootstrap'; export default React.createClass({ getInitialState: function() { return { spanish: false } }, handleClick: function() { this.setState({spanish: true}); }, render: function() { const text = this.state.spanish ? 'Hola Mundo!' : 'Hello World'; const buttonText = this.state.spanish ? 'Click Para Cambiar a Inglés' : 'Click to Swith To Spanish'; return ( &lt;div&gt; &lt;h1&gt;{text}&lt;/h1&gt; &lt;Button onClick={this.handleClick}&gt;{buttonText}&lt;/Button&gt; &lt;/div&gt; ) } }) </code></pre> <p>And here is the entry point for the application:</p> <p>index.jsx</p> <pre><code>import React from 'react'; import ReactDOM from 'react-dom'; import { HelloWorld } from './components/HelloWorld'; ReactDOM.render( &lt;HelloWorld /&gt;, document.getElementById('app') ); </code></pre> <p>Here is package.json:</p> <pre><code>{ "name": "soundcloud-player", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "production": "webpack -p", "start": "webpack-dev-server" }, "author": "", "license": "ISC", "dependencies": { "axios": "^0.15.1", "babel-cli": "^6.16.0", "babel-core": "^6.17.0", "babel-preset-es2015": "^6.16.0", "babel-preset-react": "^6.16.0", "ejs": "^2.5.2", "express": "^4.14.0", "react": "^15.3.2", "react-bootstrap": "^0.30.5", "react-dom": "^15.3.2", "react-redux": "^4.4.5", "react-router": "^2.8.1", "redux": "^3.6.0" }, "devDependencies": { "babel-loader": "^6.2.5", "html-webpack-plugin": "^2.22.0", "http-server": "^0.9.0", "webpack": "^1.13.2", "webpack-dev-server": "^1.16.2" } } </code></pre> <p>Now I have two issues happening here, and I have no clue why it's happening: </p> <ol> <li><p>When I go to localhost:8080, I get an invariant violation error and a warning:</p> <p>index_bundle.jsx:1300 Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).</p> <p>Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.</p></li> <li><p>When I remove the 'resolve' part of my webpack.config.js, all of a sudden the project is unable to find my ./components/HelloWorld component and throws a lot of errors</p></li> </ol> <p>For the first issue, I've tried using {} when importing components, but to no avail. The second issue is a mystery to me, as I believe it should fetch all jsx files because i've specified that in the 'test' part of my loaders. Can someone please help me figure out what is wrong with my project? Thank you. </p>
<p>You are getting a bit confused about the different import types in ES6. When you <code>export default</code> a class or variable, you must import it without using braces. For example:</p> <p><strong>A.js</strong></p> <pre><code>class X { } export default X; </code></pre> <p><strong>B.js</strong></p> <pre><code>import X from 'A.js'; </code></pre> <p>On the other hand, if you export something without setting it as default, you must use the braces (e.g. <code>import { X } from 'A.js';</code>, if I hadn't set it as a default export).</p> <p>To understand why this works, it helps to see what happens in ES5 syntax. A default export essentially translates to this:</p> <pre><code>module.exports = MyExportedClass; </code></pre> <p>Then, when you import it, <code>import MyExportedClass from 'A.js';</code> translates to:</p> <pre><code>var MyExportedClass = require('A.js'); </code></pre> <p>Non-default exports are actually named properties in an object:</p> <pre><code>export class X { }; </code></pre> <p>Translates to:</p> <pre><code>module.exports = { X: /* translated class */ } </code></pre> <p>As for your second issue, removing the <code>resolve</code> line will reset it to the default values: <code>["", ".webpack.js", ".web.js", ".js"]</code>. This is specified in the <a href="https://webpack.github.io/docs/configuration.html#resolve-extensions" rel="nofollow">documentation</a>.</p> <p>By removing <code>.jsx</code> from the recognised extensions, Webpack will not look for <code>.jsx</code> files unless you explicitly include the extension.</p>
PDF error - removing overlapped objects <p>I'm hand-rolling a PDF (don't ask why, it's a long story) and I am now trying to define a Form XObject.</p> <p>The page I'm working in is 8.5" x 11", moves the origin to the bottom-left, and converts to 96 dpi, so there's a line right at the top:</p> <pre><code>0.75 0 0 0.75 0 791 cm </code></pre> <p>For testing purposes, I'm just using the sample from the PDF manual:</p> <pre><code>35 0 obj &lt;&lt; /Type/XObject /Subtype/Form /FormType 1 /Name/form1 /BBox [0 0 200 200] /Matrix [1 0 0 1 0 0] /Length 184&gt;&gt; stream 0.5 0.5 0.0 sc 0 0 m 0 200 l 200 200 l 200 0 l f endstream endobj </code></pre> <p>When I draw this object:</p> <pre><code>q 1 0 0 1 8 -1043 cm /form1 Do Q </code></pre> <p>However, I get errors in Adobe Reader, and running the Acrobat PreFlight check tells me:</p> <pre><code>An error was encountered while removing overlapping objects </code></pre> <p>Is there any way to get better details on this error?</p>
<p>Most other readers give better diagnostics than Adobe Acrobat. <code>xpdf</code> for example:</p> <pre><code>Syntax Error (324732): Incorrect number of arguments in 'sc' command Syntax Error (2083): Bad block header in flate stream </code></pre> <p>The <code>sc</code> error can be fixed by inserting a <code>/DeviceRGB cs</code> just before it. The number of arguments depends on the current color space, which presumably, should be RGB, but is currently something else.</p> <p>The <code>Bad block header</code> error indicates that there's something wrong with the binary data at byte offset 2083, which is object <code>4 0 R</code>. Something you'll need to investigate and fix.</p> <p>Also note, that the PDF Specification recommends, an end-of-line marker before the, <code>endstream</code>, which is not present here.</p>
C# Include List<> with object to Json result <p>I have this Models:</p> <p>Agenda</p> <pre><code> public class Agenda { [Key] public int AgendaID { get; set; } public DateTime data { get; set; } public List&lt;Agendamento&gt; agentamentos { get; set; } public string status { get; set; } } </code></pre> <p>Agendamento</p> <pre><code>public class Agendamento { [Key] public int AgendamentoID { get; set; } public Clientes cliente { get; set; } public DateTime data { get; set; } public string botijao { get; set; } public int quantidade { get; set; } public string veiculo { get; set; } public string status { get; set; } } </code></pre> <p>My DAOs:</p> <p>AgendaDAO</p> <pre><code> public class AgendaDAO { private ApplicationDbContext db = new ApplicationDbContext(); public List&lt;Agenda&gt; Listar() { return db.Agenda.Include(a =&gt; a.agentamentos).ToList(); } } </code></pre> <p>AgendamentoDAO</p> <pre><code>public class AgendamentoDAO { private ApplicationDbContext db = new ApplicationDbContext(); public List&lt;Agendamento&gt; Listar() { return db.Agendamentoes.Include(a =&gt; a.cliente).ToList(); } } </code></pre> <p>In my ApiController, I have this methods:</p> <pre><code>public class ApiController : Controller { // GET: Api/ListarAgenda public ActionResult ListarAgenda() { AgendaDAO adao = new AgendaDAO(); return Json(adao.Listar(), JsonRequestBehavior.AllowGet); } // GET: Api/ListarAgendamento public ActionResult ListarAgendamento() { AgendamentoDAO adao = new AgendamentoDAO(); return Json(adao.Listar(), JsonRequestBehavior.AllowGet); } } </code></pre> <p>My Json results:</p> <p>Api/ListarAgenda</p> <pre><code> [ { "AgendaID": 13, "data": "/Date(1476327600000)/", "agentamentos": [], "status": null }, { "AgendaID": 14, "data": "/Date(1476669600000)/", "agentamentos": [], "status": null } ] </code></pre> <p>Api/ListarAgendamento</p> <pre><code> [ { "AgendamentoID": 72, "cliente": { "ClientesID": 1007, "Nome": "Maria Zilda", "CPF": "00124794321", "Telefone": 30198269, "Estado": "PR", "Cidade": "Curitiba", "Rua": "Altevir De Souza Gonçalves", "Numero": 59, "Lat": "-25.3955309", "Long": "-49.2168943" }, "data": "/Date(1476327600000)/", "botijao": "P13", "quantidade": 1, "veiculo": "VW Saveiro ", "status": null }] </code></pre> <p>My problem is: I need to see in my json result from Api/ListarAgenda the agendamentos list with clientes attributes. Something like this:</p> <pre><code>[ { "AgendaID": 13, "data": "/Date(1476327600000)/", "agentamentos": [ { "AgendamentoID": 72, "cliente": { "ClientesID": 1007, "Nome": "Maria Zilda", "CPF": "00124794321", "Telefone": 30198269, "Estado": "PR", "Cidade": "Curitiba", "Rua": "Altevir De Souza Gonçalves", "Numero": 59, "Lat": "-25.3955309", "Long": "-49.2168943" }, "data": "/Date(1476327600000)/", "botijao": "P13", "quantidade": 1, "veiculo": "VW Saveiro ", "status": null }], "status": null } ] </code></pre> <p>"Include" is not working very well. How can I do this?</p>
<p>You are using eager load right? You need to include cliente from each agendamento loaded</p>
Regex to match only numbers in currency <p>I'm trying to get a VB regex to match only the numbers in a currency sequence without additional substitution lines if possible. It needs to look for a number with + on end $ at the start and return what's in the middle, minus any commas.</p> <p>Accordingly</p> <pre><code> $10,000+ match returns 10000 $20,000+ match returns 20000 $30,000+ match returns 30000 $1,000,000+ match returns 1000000 $10,000 (anything without the trailing +) should *not* match </code></pre> <p>I can easily get the match to the value but I can't figure out how to get rid, of the trailing + or the prefix and commas inside.</p>
<p>Your regex is <code>\$(\d+(,?\d+)*)\+</code>. Group 1 is what you are looking for <br/> Check <a href="https://regex101.com/r/HQEMuC/2" rel="nofollow">here</a></p> <p>After retrieving results you should remove commas from it</p>
Select N items directly before a given ID <p>If I have a row for each of the alphanumerically ordered items (ids) below:</p> <pre><code>aa ab ac ba cc cf ff gh h4 ia </code></pre> <p>I would like to select the <strong>3 items directly prior</strong> to <code>cc</code>, which would be <code>ab</code>, <code>ac</code> and <code>ba</code> (in that order). My MySQL query does not pick the items directly prior to <code>cc</code>, but rather from the beginning of the list.</p> <pre><code>SELECT * FROM things WHERE id &lt; 'cc' ORDER BY id LIMIT 3. </code></pre> <p>Again, this query does not work because it does not retrieve the items <strong>directly</strong> before <code>cc</code>. What is the correct approach here?</p>
<p>You are very close:</p> <pre><code>SELECT * FROM things WHERE id &lt; 'cc' ORDER BY id DESC ------------^ LIMIT 3; </code></pre> <p>You need to sort the items in descending order to get the "biggest" ones before <code>'cc'</code>.</p> <p>Also, for three items you want <code>limit 3</code>. I assume the "2" is a typo.</p> <p>If you then want these in alphabetical order, use a subquery and order again:</p> <pre><code>SELECT t.* FROM (SELECT t.* FROM things t WHERE id &lt; 'cc' ORDER BY id DESC LIMIT 3 ) t ORDER BY id ASC; </code></pre>
Schema-less in All layers <p>I have use case where schema of my entities keep on changing again and again. Based on that i have to change/add new business rules which is not scalable for me.</p> <p>I am trying to go schema-less by using JSON documents in <strong>my data , service and ui layer</strong>. </p> <p>I want to avoid creating DAO(Data Access objects), Data Transfer object(for sending objects) , View Model objects that are major problem for me in changing schema and deploy again.</p> <p>Are there any good frameworks from where i can take help in this ..</p>
<p>Have you tried the Java API for JSON Processing? <a href="http://www.oracle.com/technetwork/articles/java/json-1973242.html" rel="nofollow">http://www.oracle.com/technetwork/articles/java/json-1973242.html</a></p> <p><a href="https://jcp.org/en/jsr/detail?id=353" rel="nofollow">https://jcp.org/en/jsr/detail?id=353</a></p>
Evaluate String from database in taglib in Grails <p>I have a taglib method and I fetch an object from database with string expressions to evaluate. From the docs, it should be possible to do sth like this:</p> <pre><code>out &lt;&lt; "&lt;div id=\"${attrs.book.id}\"&gt;" </code></pre> <p>But when I try to do the same for the object fetched from database, the expression between ${} does not get evaluated. I realized that the reason is because I have a String, so I tried to convert it to GString, but without any success.</p> <pre><code>// objectFromDb.content = "&lt;div id=\"${attrs.book.id}\"&gt;" def objectFromDb = fetchObjectFromDb() def gStringExpression = "${objectFromDb.getContent()}" out &lt;&lt; gStringExpression </code></pre> <p>How can I achieve the evaluation of the expression inside the taglib? I want to have different variables for each object, so to use TemplateEngine is not possible as I don't know which variables will be used.</p>
<p>try this</p> <pre><code>def output = "" def objectFromDb = fetchObjectFromDb() def output += objectFromDb.getContent() // use toString() if needed out &lt;&lt; output </code></pre>
WPF DataContext works differently in seemingly identical situations <p>I have the following resources:</p> <pre><code>&lt;Window.Resources&gt; &lt;SolidColorBrush x:Key="b" Color="{Binding B}" /&gt; &lt;my:C x:Key="c" Prop="{Binding Source={StaticResource b}}" /&gt; &lt;my:C x:Key="d" Prop="{Binding A}" /&gt; &lt;Ellipse x:Key="e" Fill="{Binding A}" /&gt; &lt;Ellipse x:Key="f"&gt; &lt;Ellipse.Fill&gt; &lt;SolidColorBrush Color="{Binding B}" /&gt; &lt;/Ellipse.Fill&gt; &lt;/Ellipse&gt; &lt;/Window.Resources&gt; </code></pre> <p>My window has a data context declared like this:</p> <pre><code>&lt;Window ... DataContext="{my:Context}" ...&gt; </code></pre> <p>Custom classes C and Context are defined like this:</p> <pre><code>public class Context : MarkupExtension { public Brush A { get; } = Brushes.Blue; public Color B { get; } = Colors.Red; public override object ProvideValue(IServiceProvider serviceProvider) =&gt; this; } public class C : DependencyObject { public static readonly DependencyProperty PropProperty = DependencyProperty.Register("Prop", typeof(Brush), typeof(C)); public Brush Prop { get { return (Brush)GetValue(PropProperty); } set { SetValue(PropProperty, value); } } } </code></pre> <p>Now, the ways in which I use my data context and binding seem very similar to me, yet if I check my resources with the following code (inside a button click handler)</p> <pre><code>MessageBox.Show("f: " + ((FindResource("f") as Ellipse).Fill?.ToString() ?? "null")); MessageBox.Show("e: " + ((FindResource("e") as Ellipse).Fill?.ToString() ?? "null")); MessageBox.Show("d: " + ((FindResource("d") as C).Prop?.ToString() ?? "null")); MessageBox.Show("c: " + ((FindResource("c") as C).Prop?.ToString() ?? "null")); MessageBox.Show("b: " + (FindResource("b") as SolidColorBrush).Color.ToString()); </code></pre> <p>I get this result:</p> <pre><code>f: #00FFFFFF e: null d: null c: #FFFF0000 b: #FFFF0000 </code></pre> <p>i.e. only the last two are seemingly correct. What could be the reason for this?</p>
<p>Strange.</p> <p>my:C has obviously no DataContext and can therefore not bind directly to anything.</p> <p>Resources with DataContext do not inherit the resources owner's DataContext (Ellipses e and f)</p> <p>SolidColorBrush "b" derive form System.Windows.Freezable which has a protected Field/Property called InheritanceContext which for "b" is set to the MainWindow. I think it has access to the Context.B through this reference and that's why "b" and "c" shows the right color.</p>
C++ Function does not take 2 arguments <p>I'm following a tutorial on creating a video game using C++. And I've got stuck on this step:</p> <pre><code>spriteBg -&gt; setAnchorPoint(0,0); </code></pre> <p>I've got an error of: Function does not take 2 arguments</p> <p>But anchor points are usually two digits pair (x,y) or Vec2::ZERO according with the docs, so what it's wrong with this line?</p> <p>The guy on the tutorial has a red curvy line under the second 0 as well I have that red line under my second zero in setAnchorPoint(0,0), nevertheless he can build the project without errors but I can't due this error of 2 arguments.</p> <p>He is using Visual Studio 2012 and I'm using Visual Studio 2013 for what it's worth. The Project was generated with Cocos2d.</p> <p>This is the whole method.</p> <pre><code>bool HelloWorld::init() { if ( !Layer::init() ) { return false; } auto spriteBg = Sprite::create("images/bg.png"); spriteBg -&gt;setAnchorPoint(0,0); spriteBg -&gt;setPosition(0,0); addChild(spriteBg , 0); return true; } </code></pre> <p>This is the whole error:</p> <pre><code>error C2660: 'cocos2d::Sprite::setAnchorPoint': function does not take 2 arguments </code></pre> <p>So far the same result with 5 approaches:</p> <pre><code>spriteBg -&gt;setAnchorPoint(0,0); spriteBg -&gt;setAnchorPoint({0,0}); spriteBg -&gt;setAnchorPoint(Vec2::ZERO); spriteBg -&gt;setAnchorPoint(Vec2(0,0)); spriteBg -&gt;setAnchorPoint(Point(0,0)); </code></pre> <p>This is the tutorial and this particular step is at 18:27. The tutorial is in Spanish but you clearly can see the guy coding and is just a few lines.</p> <p><a href="https://www.youtube.com/watch?v=v7d3ic_lmGw" rel="nofollow">https://www.youtube.com/watch?v=v7d3ic_lmGw</a></p> <p>Greetings.</p>
<p>Not sure what the problem is without the exact error message, but if you say it takes Vec2::ZERO maybe try:</p> <p><code>spriteBg -> setAnchorPoint(Vec2(0,0));</code></p>
ScrollToTop button displaying at the top when page is refreshed <p>I am trying to get my scrollToTop button to stop showing when at the top</p> <p>I have the button working, as in it fades in when scrolling down, and scrolls to the top when clicked, and then hides, but if I am the top of the page and hit refresh the button displays. Is there a way to prevent this?</p> <p>Here is my code:</p> <pre><code>&lt;a href="#main-image" class="scrollToTop"&gt;&lt;img src="img/up-arrow.png" class="up-arrow"/&gt;&lt;/a&gt; </code></pre> <p>And my JS: </p> <pre><code>$(document).ready(function(){ //Check to see if the window is top if not then display button $(window).scroll(function(){ if ($(this).scrollTop() &gt; 200) { $('.scrollToTop').fadeIn(); } else { $('.scrollToTop').fadeOut(); } }); //Click event to scroll to top $('.scrollToTop').click(function(){ $('html, body').animate({scrollTop : 0},500); return false; }); }); </code></pre> <p>Thanks.</p>
<p>You need to make sure its default setting is that it is not appearing, use CSS.</p> <p>The Javscript will then take care of the rest and override this when needed.</p> <pre><code>.scrollToTop { display:none; } </code></pre>
How would i loop this bit of code so that It will go to the start again? <p>I'm a new to python and i need a bit of help. I just need to know how would i loop this bit of code so that after it says "please try again..." it will then go onto "Do you want to roll or stick". Thanks in advance.</p> <pre><code>Roll = input("Do you want to Roll or Stick?") if Roll in ("Roll" , "roll"): print("Your new numbers are," , +number10 , +number20 , +number30 , +number40 , +number50) if Roll in ("Stick" , "stick"): print("Your numbers are," , +number1 , +number2 , +number3 , +number4 , +number5) else: print("Please try again.") </code></pre>
<p>You can wrap up your code with <a href="https://wiki.python.org/moin/WhileLoop" rel="nofollow"><code>while</code></a> loop:</p> <pre><code>while True: Roll = input("Do you want to Roll or Stick?") if Roll.lower() == 'exit': break ... else: print("Please try again. Type 'exit' to exit.") </code></pre>
How to Subtract fields in filemaker? <p>I have added a field11 total. It has to be the value field10 - field9 - field8 - field7. How to write the code and view result in field11? </p>
<p>Calculations need to be defined using FileMaker's field type = "calculation" under Manage Database, whether the desired result is a number or text or other.</p> <p><a href="http://www.filemaker.com/help/12/fmp/html/create_db.8.17.html" rel="nofollow">http://www.filemaker.com/help/12/fmp/html/create_db.8.17.html</a></p>
Twilio iOS SDK fails with "400 Bad request" on outgoing call <p>Took the source code of example provided <a href="https://www.twilio.com/blog/2015/02/a-swift-adventure-building-basicphone-with-twilioclient.html" rel="nofollow">here</a>, converted to Swift 3 and applied my generated token of an upgraded Twilio account.</p> <p>When trying to make a call, it plays a sound, but then fails with a <code>HTTP/1.0 400 Bad request</code> when trying to access <code>https://matrix.twilio.com/2012-02-09/AC ...</code>.</p> <p>Here's the log after trying to make a call -</p> <pre><code>2016-10-16 18:32:12.955056 MyApp[577:121739] [DEBUG TCDeviceInternal] Inside TCDeviceInternal initWithCapabilityToken, capabilityToken_: (null) 2016-10-16 18:32:12.961112 MyApp[577:121739] [VERBOSE TCDeviceInternal] Inside decodeCapabilityToken:, Header: { alg = HS256; typ = JWT; } 2016-10-16 18:32:12.962305 MyApp[577:121739] [VERBOSE TCDeviceInternal] Inside decodeCapabilityToken:, payload: { exp = 1476635532; iss = ....REMOVED....................; scope = "scope:client:incoming?clientName=TestName scope:client:outgoing?appSid=AP.....REMOVED......&amp;clientName=TestName"; } 2016-10-16 18:32:12.962611 MyApp[577:121739] [VERBOSE TCDeviceInternal] Scope URI: scope:client:incoming?clientName=TestName, inside setCapabilitiesWithCapabilityToken: 2016-10-16 18:32:12.962860 MyApp[577:121739] [VERBOSE TCDeviceInternal] Scope URI: scope:client:outgoing?appSid=AP.............REMOVED.......&amp;clientName=TestName, inside setCapabilitiesWithCapabilityToken: 2016-10-16 18:32:12.963710 MyApp[577:121739] [DEBUG TCConstants] X-Twilio-Client string: {"p":"ios","v":"1.2.7.b99-1015b1f","mobile":{"arch":"unknown type 16777228 subtype 1","product":"iPhone","name":"iPhone8,4","v":"10.0.2"}}, inside TCConstants clientString 2016-10-16 18:32:13.035381 MyApp[577:121739] [VERBOSE Twilio] Inside initWithConfig:, codec: speex/16000/1 -&gt; priority: 255 2016-10-16 18:32:13.035425 MyApp[577:121739] [VERBOSE Twilio] Inside initWithConfig:, codec: speex/8000/1 -&gt; priority: 254 2016-10-16 18:32:13.035457 MyApp[577:121739] [VERBOSE Twilio] Inside initWithConfig:, codec: speex/32000/1 -&gt; priority: 0 2016-10-16 18:32:13.035500 MyApp[577:121739] [VERBOSE Twilio] Inside initWithConfig:, codec: opus/48000/1 -&gt; priority: 0 2016-10-16 18:32:13.035574 MyApp[577:121739] [VERBOSE Twilio] Inside initWithConfig:, codec: PCMU/8000/1 -&gt; priority: 128 2016-10-16 18:32:13.035669 MyApp[577:121739] [VERBOSE Twilio] Inside initWithConfig:, codec: PCMA/8000/1 -&gt; priority: 0 2016-10-16 18:32:13.035843 MyApp[577:121739] [DEBUG Twilio] Inside startStateNotificationsForObject, delegate: &lt;TCDeviceInternal: 0x17018c710&gt; 2016-10-16 18:32:13.036069 MyApp[577:121739] [VERBOSE Twilio] Inside addUserAccount:, Registration URL: sip:TestName@chunderm.gll.twilio.com;transport=tls 2016-10-16 18:32:13.037112 MyApp[577:121739] [DEBUG TwilioReachability] Reachability Flag Status: -R ------- networkStatusForFlags 2016-10-16 18:32:13.037191 MyApp[577:121739] [DEBUG TCDeviceInternal] Internet reachability: 1 2016-10-16 18:32:13.037434 MyApp[577:121739] [DEBUG TCDeviceInternal] Created TCDeviceInternal: &lt;TCDeviceInternal: 0x17018c710&gt; for accountId: 0 2016-10-16 18:32:13.038306 MyApp[577:121739] [DEBUG TCHttpJsonLongPollConnection] Inside TCHTTPJSONLongPollConnection run(), gonna connect to host matrix.twilio.com, port 443 2016-10-16 18:32:13.039266 MyApp[577:121739] [DEBUG TCHttpJsonLongPollConnection] Inside onSocketWillConnect, sock: &lt;TCAsyncSocket 0x17418ddd0 local nowhere remote nowhere has queued 0 reads 0 writes, no current read, no current write, read stream 0x17010d260 not open, write stream 0x1701065d0 not open, not connected&gt;, self: &lt;TCHttpJsonLongPollConnection 0x1740aa9e0 url=https://matrix.twilio.com/2012-02-09/.........REMOVED............../TestName?AccessToken=...............REMOVED......................&amp;feature=publishPresence&amp;feature=presenceEvents connected=0 https=1&gt; 2016-10-16 18:32:13.052355 MyApp[577:121739] [DEBUG TCSoundManager] TCSoundManager: sharedInstance: 0x0 2016-10-16 18:32:13.052423 MyApp[577:121739] [DEBUG TCSoundManager] TCSoundManager init, top 2016-10-16 18:32:13.052461 MyApp[577:121739] [VERBOSE TCSoundManager] TCSoundManager init, starting 2016-10-16 18:32:13.109491 MyApp[577:121739] [DEBUG TCSoundManager] TCSoundManager: player configured 2016-10-16 18:32:13.120029 MyApp[577:121739] [VERBOSE TCSoundManager] TCSoundManager init, done 2016-10-16 18:32:13.120917 MyApp[577:121739] [DEBUG TCSoundManager] TCSoundManager: attempting to play item, (inside TCSoundManager play()) 2016-10-16 18:32:13.121720 MyApp[577:121739] [DEBUG TCSoundManager] Player status: 0, inside observeValueForKeyPath: [2016-10-16 18:32:13.123] Caller.swift:55 DEBUG: Twilio connection created successfully 2016-10-16 18:32:13.136004 MyApp[577:121739] [DEBUG TCSoundManager] Player status: 1, inside observeValueForKeyPath: 2016-10-16 18:32:13.145341 MyApp[577:121739] [DEBUG TCSoundManager] Item status: 1, inside observeValueForKeyPath: 2016-10-16 18:32:13.226409 MyApp[577:121739] [DEBUG TCHttpJsonLongPollConnection] Inside beginning of onSocket:didConnectToHost 2016-10-16 18:32:13.226632 MyApp[577:121739] [DEBUG TCHttpJsonLongPollConnection] Starting TLS with settings: { kCFStreamSSLPeerName = "*.twilio.com"; kCFStreamSSLValidatesCertificateChain = 1; kCFStreamSocketSecurityLevelNegotiatedSSL = kCFStreamPropertySocketSecurityLevel; }, inside onSocket:didConnectToHost: 2016-10-16 18:32:13.227088 MyApp[577:121739] [DEBUG TCEventStream] Inside longPollConnectionDidConnect:, stream &lt;TCEventStream: 0x17427cbc0&gt; connected 2016-10-16 18:32:13.227331 MyApp[577:121739] [DEBUG TCHttpJsonLongPollConnection] REQUEST: URL: https://matrix.twilio.com/2012-02-09/.............REMOVED............/TestName?AccessToken=..........................................REMOVED..................................&amp;feature=publishPresence&amp;feature=presenceEvents GET /2012-02-09/........REMOVED............/ProjectName App?AccessToken=................................REMOVED....................................&amp;feature=publishPresence&amp;feature=pres 2016-10-16 18:32:14.028697 MyApp[577:121739] [DEBUG TCHttpJsonLongPollConnection] Inside beginning of onSocket:didReadData 2016-10-16 18:32:14.028836 MyApp[577:121739] [VERBOSE TCHttpJsonLongPollConnection] Received HTTP/1.0 400 Bad request Cache-Control: no-cache Connection: close Content-Type: text/html , inside onSocket:didReadData 2016-10-16 18:32:14.029065 MyApp[577:121739] [DEBUG TCEventStream] Inside longPollConnection:didReceiveHeaders:, stream &lt;TCEventStream: 0x17427cbc0&gt; got headers 2016-10-16 18:32:14.030074 MyApp[577:121739] [DEBUG TCEventStream] Inside longPollConnection:didFailWithError:, stream &lt;TCEventStream: 0x17427cbc0&gt; disconnected, error Error Domain=com.twilio.client.TCHttpErrorDomain Code=4 "HTTP server returned non-success status" UserInfo={com.twilio.client.TCHttpStatusCodeKey=400, NSLocalizedDescription=HTTP server returned non-success status} 2016-10-16 18:32:15.017604 MyApp[577:121739] [INFO TCSoundManager] TCSoundManager: playerItemDidReachEnd: 7466A900, (inside playerItemDidReachEnd) 2016-10-16 18:32:15.017913 MyApp[577:121739] [DEBUG TCCommandHandler] Inside postCommand:, received command of type TCMakeCallCommand 2016-10-16 18:32:15.018535 MyApp[577:121739] [DEBUG TCSoundManager] Player status: 1, inside observeValueForKeyPath: 2016-10-16 18:32:21.396771 MyApp[577:121739] [DEBUG Twilio] Application is in background 2016-10-16 18:32:21.397023 MyApp[577:121739] Legacy VoIP background mode is deprecated and no longer supported </code></pre> <p>What can be the issue?</p>
<p>If you are writing your own <strong><em>client</em></strong>, you need to set the HTTP Content-Type header to "<em>application/x-www-form-urlencoded</em>" for your requests.</p> <p><code>400 BAD REQUEST</code> means: the data given in the <code>POST</code> or <code>PUT</code> failed validation. Here are details in your code:</p> <pre><code>2016-10-16 18:32:14.030074 MyApp[577:121739] [DEBUG TCEventStream] Inside longPollConnection:didFailWithError:, stream &lt;TCEventStream: 0x17427cbc0&gt; disconnected, error Error Domain=com.twilio.client.TCHttpErrorDomain Code=4 "HTTP server returned non-success status" UserInfo={com.twilio.client.TCHttpStatusCodeKey=400, NSLocalizedDescription=HTTP server returned non-success status} </code></pre> <blockquote> <p>Also you should inspect a <code>response</code> body for details.</p> </blockquote> <p>Here are references: </p> <p><a href="http://stackoverflow.com/questions/18950415/sending-sms-text-message-using-twilio-not-working">Sending SMS text message using twilio not working</a></p> <p><a href="https://www.twilio.com/docs/api/rest/making-calls" rel="nofollow">Twilio: REST API: making calls</a></p> <p>¡Hope this helps!</p>
html5 custom validation not working with angular <p>I am using this below form:</p> <pre><code>&lt;form name="signupForm" id="register-form" ng-submit="addUser(user)" method="POST"&gt; &lt;div class="row"&gt; &lt;input type="email" ng-model="user.email" id="reg_email" class="form-control" placeholder="Email" required pattern="[^@\s]+@[^@\s]+\.[^@\s]+" minlength="5" maxlength="40" required&gt; &lt;input type="password" ng-model="user.password" id="reg_password" class="form-control" placeholder="Password" required='true' minlength="3" maxlength="10" required&gt; &lt;input type="submit" id="reg_submit" class="submit-input grad-btn ln-tr" value="Submit"&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>When there error in form, I'm setting <code>setCustomValidity()</code> on input.</p> <pre><code>auth.signup($scope.userData, successAuth, function (error) { $rootScope.error = error.error; console.log("error: " , $rootScope.error); if($rootScope.error == "user already exists"){ var input = document.getElementById("reg_email"); input.setCustomValidity("$rootScope.error"); } else{ var input = document.getElementById("reg_email"); input.setCustomValidity(""); angular.element('#register-modal').modal('hide'); document.getElementById("register-form").reset(); } }); </code></pre> <p>Well the modal form doesn't close because of <code>setCustomValidity()</code> but I can't the error message I set on the input field.</p> <p><strong>Update:</strong></p> <p>Actually it is showing the error message on second click. why?</p> <p>Error messages activates on second click and even when form is valid it is showing the error message.</p>
<p>I fixed it this way. Hope it helps some one.</p> <pre><code>auth.signup($scope.userData, successAuth, function (error) { $rootScope.error = error.error; if ($rootScope.error == "user already exists") { $scope.signupForm.reg_email.$setValidity("User already exists", false); } }); </code></pre> <p>Html:</p> <pre><code>&lt;form novalidate&gt; &lt;input type="email" ng-model="user.email" id="reg_email" name="reg_email" required&gt; &lt;span ng-show="signupForm.reg_email.$invalid" class="custom-help-block"&gt;User already exists&lt;/span&gt; &lt;/form&gt; </code></pre> <p>css:</p> <pre><code>.custom-help-block{ color: red; margin-left: 5px; font-weight:bold; } </code></pre>
Exclipse JavaFX SceneBuilder GridPane <p>i can't use GridPane in SceneBuilder (eclipse), when i try to insert GridPane in my project, the SceneBuilder quit without prompt any message.</p> <p>and that's what i find in the log file:</p> <h1># A fatal error has been detected by the Java Runtime Environment: # # EXCEPTION_ILLEGAL_INSTRUCTION (0xc000001d) at pc=0x000007fed6a35c01, pid=2184, tid=3708 # # JRE version: Java(TM) SE Runtime Environment (8.0_60-b27) (build 1.8.0_60-b27) # Java VM: Java HotSpot(TM) 64-Bit Server VM (25.60-b23 mixed mode windows-amd64 compressed oops) # Problematic frame: # C [MSVCR120.dll+0x95c01] # # Failed to write core dump. Minidumps are not enabled by default on client versions of Windows</h1>
<p>The problem has been solved by installing SceneBuiled 32bit.</p>
How do you get an INTEGER in a textfile mixed with Strings and Integer? <p>I'm trying to get an <code>int</code> value from a text file. This is my current read file algorithm:</p> <pre><code>if (q) { while ((ch = fgetc(q)) != EOF) { if(ch == ) printf("%c",ch); } } else { printf("Failed to open the file\n"); } </code></pre> <p>Inside my text-file:</p> <pre><code>Occupant's Name: qwe qwe Room Number: 1 Occupant's Category: Superior Double Occupant's Name: h j Room Number: 1 Occupant's Category: Superior Double Occupant's Name: h j Room Number: 1 Occupant's Category: Superior Double </code></pre> <p>I would like to get every room number.</p>
<p>Consider using fgets to read each line and sscanf to parse the line. This sscanf will fail on the lines that do not start with "Room Number:".</p> <pre><code>char line[100] = ""; int room = 0; if (q) { while (( fgets ( line, sizeof line, q))) { if( ( sscanf ( line, "Room Number:%d", &amp;room)) == 1) { printf("room number is %d\n", room); } } } else { printf("Failed to open the file\n"); } </code></pre>
What does +@ mean as a method in ruby <p>I was reading some code and I saw something along the lines of </p> <pre><code>module M def +@ self end end </code></pre> <p>I was surprised that this was legal syntax, yet when I ran <code>ruby -c</code> on the file (to lint) it said it was valid. <code>-@</code> was also a legal method name yet when I tried <code>*@</code> or <code>d@</code> both of those were illegal. I was wondering what <code>+@</code> means and why is it legal?</p>
<p>Ruby contains a few unary operators, including <code>+</code>, <code>-</code>, <code>!</code>, <code>~</code>, <code>&amp;</code> and <code>*</code>. As with other operators you can also redefine these. For <code>~</code> and <code>!</code> you can simply just say <code>def ~</code> and <code>def !</code> as they don't have a binary counterpart (e.g. you cannot say <code>a!b</code>).</p> <p>However for <code>-</code> and <code>+</code> there is both a unary, and a binary version (e.g. <code>a+b</code> and <code>+a</code> are both valid), so if you want to redefine the unary version you have to use <code>def +@</code> and <code>def -@</code>.</p> <p>Also note that there is a unary version of <code>*</code> and <code>&amp;</code> as well, but they have special meanings. For <code>*</code> it is tied to splatting the array, and for <code>&amp;</code> it is tied to converting the object to a proc, so if you want to use them you have to redefine <code>to_a</code> and <code>to_proc</code> respectively.</p> <p>Here is a more complete example showing all kinds of the unary operators:</p> <pre><code>class SmileyString &lt; String def +@ SmileyString.new(self + " :)") end def -@ SmileyString.new(self + " :(") end def ~ SmileyString.new(self + " :~") end def ! SmileyString.new(self + " :!") end def to_proc Proc.new { |a| SmileyString.new(self + " " + a) } end def to_a [SmileyString.new(":("), self] end end a = SmileyString.new("Hello") p +a # =&gt; "Hello :)" p ~a # =&gt; "Hello :~" p *a # =&gt; [":(", "Hello"] p !a # =&gt; "Hello :!" p +~a # =&gt; "Hello :~ :)" p *+!-~a # =&gt; [":(", "Hello :~ :( :! :)"] p %w{:) :(}.map &amp;a # =&gt; ["Hello :)", "Hello :("] </code></pre> <p>In your example the Module just simply defines an unary + operator, with a default value of not doing anything with the object (which is a common behaviour for the unary plus, <code>5</code> and <code>+5</code> usually mean the same thing). Mixing in with any class would mean the class immediately gets support for using the unary plus operator, which would do nothing much.</p> <p>For example:</p> <pre><code>module M def +@ self end end p +"Hello" # =&gt; NoMethodError: undefined method `+@' for "Hello":String class String include M end p +"Hello" # =&gt; "Hello" </code></pre>
Yii2. dektrium/user. Custom controller action redirects to the login page <p><strong>Problem</strong></p> <p>Every custom action redirects back to the login page.</p> <p><strong>My code</strong></p> <p>I've extended my custom controller from the <code>dektrium\user\controllers\RegistrationController</code></p> <p>My <code>web.php</code> </p> <pre><code> 'urlManager' =&gt; [ 'enablePrettyUrl' =&gt; true, 'showScriptName' =&gt; false, 'rules' =&gt; [ ], ], </code></pre> <p>...</p> <pre><code>'modules' =&gt; [ 'user' =&gt; [ 'class' =&gt; 'dektrium\user\Module', 'controllerMap' =&gt; [ 'registration' =&gt; 'app\controllers\user\RegistrationController' ], ], ], </code></pre> <p>Custom controller</p> <pre><code>namespace app\controllers\user; use dektrium\user\controllers\RegistrationController as BaseAdminController; class RegistrationController extends BaseAdminController { public function actionPlan() { echo 'Test'; } } </code></pre> <p>Overrode methods works good, but each custom action (<code>site.com/user/registration/plan</code>) redirects back to the login page.</p>
<p>If you want change the access control rules you should change properly eg: in your site controller add plan to the rules accessible without authenctication</p> <pre><code>class SiteController extends Controller { /** * @inheritdoc */ public function behaviors() { return [ 'access' =&gt; [ 'class' =&gt; AccessControl::className(), 'rules' =&gt; [ [ 'actions' =&gt; ['login','plan', 'error'], 'allow' =&gt; true, ], [ 'actions' =&gt; ['logout', 'index'], 'allow' =&gt; true, 'roles' =&gt; ['@'], ], ], ], 'verbs' =&gt; [ 'class' =&gt; VerbFilter::className(), 'actions' =&gt; [ 'logout' =&gt; ['post'], ], ], ]; } </code></pre> <p>see this for more <a href="http://www.yiiframework.com/doc-2.0/guide-security-authorization.html" rel="nofollow">http://www.yiiframework.com/doc-2.0/guide-security-authorization.html</a></p> <p><a href="http://www.yiiframework.com/doc-2.0/yii-filters-accesscontrol.html" rel="nofollow">http://www.yiiframework.com/doc-2.0/yii-filters-accesscontrol.html</a></p>
Angular2 final version: Injected Service method under unit test returning undefined <p>I am trying to write some unit-tests on a component that got some services injected into it, to load the data from server. Data is loaded in this component on OnInit() method. I am trying that service method returns some dummy data, using spyOn. Following is unit-test setup - </p> <pre><code>let comp: MyComponent; let fixture: ComponentFixture&lt;MyComponent&gt;; let staticDataService: any; let spy: jasmine.Spy; let allCountries: string[]; describe('MyComponent', () =&gt; { beforeEach( async(() =&gt; { TestBed.configureTestingModule({ imports : [ FormsModule, HttpModule ], declarations : [MyComponent], providers: [ StaticDataService ] }) .compileComponents(); })); beforeEach(() =&gt; { fixture = TestBed.createComponent(MyComponent); comp = fixture.componentInstance; staticDataService = fixture.debugElement.injector.get(StaticDataService); allCountries = [] = ["US", "UK"]; spy = spyOn(staticDataService, 'getCountries').and.returnValue(Promise.resolve(allCountries)); }); it('Countries should be set', () =&gt; { expect(comp.allCountries).toEqual(allCountries); }); }); </code></pre> <p>Following is the component class that I am unit-testing - </p> <pre><code>@Component({ moduleId: module.id, selector: 'myeditor', templateUrl: 'my.component.html', styleUrls: ['my.component.css'] }) export class MyComponent implements OnInit { allCountries: string[]; constructor(private _staticDataServices: StaticDataService) {} ngOnInit() { this.getDataFromServer(); } getDataFromServer() { this.allCountries = this._staticDataServices.getCountries(); } </code></pre> <p>I am getting the following error - </p> <pre><code> Chrome 53.0.2785 (Windows 7 0.0.0) MyComponent Countries should be set FAILED [1] Expected undefined to equal [ 'US', 'UK' ]. </code></pre> <p>Under the same unit-tests few other tests are working fine, that are not dependent on injected services. Getting 'undefined' while testing the properties that are set by services. Can someone please help what I am doing wrong here?</p> <p>Thanks</p>
<ol> <li><p>You need to call <code>fixture.detectChanges()</code> for the <code>ngOnInit</code> to be called.</p> <pre><code>fixture = TestBed.createComponent(MyComponent); fixture.detectChanges(); </code></pre></li> <li><p><code>getCountries</code> returns a <code>Promise</code> so you need to <code>then</code> it, otherwise the value of <code>allCountries</code> will just be promise and not the data</p> <pre><code>getDataFromServer() { this._staticDataServices.getCountries().then(data =&gt; { this.countries = data; }); } </code></pre></li> <li><p>Since the promise is asynchronous, you need to use <code>async</code> and wait for the asynchronous task to complete by calling <code>fixture.whenStable()</code></p> <pre><code>import { async } from '@angular/core/testing'; it('...', async(() =&gt; { fixture.whenStable().then(() =&gt; { expect(comp.allCountries).toEqual(allCountries); }) }) </code></pre></li> </ol> <hr> <h2>UDPATE</h2> <p>Without seeing the <code>StaticDataService</code>, I'm guessing you are trying to inject <code>Http</code> into it. This wont work in a test environment without further configuration. What I suggest you do is just make the service a mock</p> <pre><code>staticDataService = { getCountries: jasmine.createSpy('getCountries').and.returnValue(...); } providers: [ { provide: StaticDataService, useValue: staticDataService } ] </code></pre>
Python String Extraction for football results <p>I have the following string:</p> <pre><code>"W-Leicester-3-0-H|W-Hull-2-0-A|L-Arsenal-0-3-A|L-Liverpool-1-2-H|D-Swansea-2-2-A" </code></pre> <p>What I would like to do is manipulate the string above so it returns the results of each game which is the first letter after each "|". In this instance it would be WWLLD.</p> <p>Many thanks in advance, Alan.</p>
<p>Try something like this:</p> <pre><code> string = "W-Leicester-3-0-H|W-Hull-2-0-A|L-Arsenal-0-3-A|L-Liverpool-1-2-H|D-Swansea-2-2-A" result = ''.join([s[0] for s in string.replace('||', '|').split('|')]) </code></pre>
How to display current variable of date to minDate using JQuery <p>I have a php variable for date that was from database that should be put in minDate. </p> <p>Example: </p> <p>Php Code </p> <pre><code>&lt;?php //Example variable in PHP that was from the database $get_frm_database = "2016-10-20"; ?&gt; </code></pre> <p>HTML Form</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; Datepicker: &lt;input type="text" name="" id="datepicker"&gt; &lt;script&gt; $( function() { $( "#datepicker" ).datepicker({ dateFormat: "yy-mm-dd", minDate: "+7D", &lt;----------This should be variable which is $get_frm_database maxDate: "+1M", showAnim: "show", showOn: "button", buttonImage: "date.png", buttonImageOnly: true, buttonText: "Select date" }); } ); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>What I want is that the Php variable should be on minDate. Can someone help and show an example of codes? Thanks in advance.</p>
<p>Try to simply echoing it...</p> <pre><code>minDate: "&lt;?php echo $get_frm_database; ?&gt;", </code></pre>
i can't login to my magento backend <p>I installed magento 2.1.1 on a WAMP Server and the installation was successful. I was able to login to backend of the Magento but everything changed when i installed a theme. According to the documentation of the theme I have to create a new database in <code>phpmyadmin</code> and import a <code>database.sql</code> which came with the theme. </p> <p>After this I have to edit <code>app/etc/env.php</code> and change the following: <code>dbname</code>, <code>username</code> and <code>password</code> with the one I use when creating the database. I followed the procedure and everything worked well but since then I couldn't login to the back-end of the Magento. I have search on the internet for two days now but all posts which I found couldn't resolve my issue so far. </p> <p>Please help me. Thanks </p>
<p>If you have changed your database to another, then the user you originally created won't exist anymore for the Magento install to let you in.</p> <p>In this case, you're best off creating a new admin user.</p> <p>You can do this using the Magento commmand line tool:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;path_to_magento&gt;/bin/magento admin:user:create --admin-user="admin" --admin-password="Password1234" --admin-email="admin@example.com" --admin-firstname="Admin" --admin-lastname="Admin"</code></pre> </div> </div> </p> <p>Depending on your setup, you might need to run:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;path_to_php&gt;php &lt;path_to_magento&gt;/bin/magento admin:user:create --admin-user="admin" --admin-password="Password1234" --admin-email="admin@example.com" --admin-firstname="Admin" --admin-lastname="Admin"</code></pre> </div> </div> </p>
Interpolate without having negative values in python <p>I've been trying to create a smooth line from these values but I can't have negative values in my result. So far all the methods I tried do give negative values. Would love some help.</p> <pre><code>import matplotlib.pyplot as plt from scipy.interpolate import UnivariateSpline import numpy as np y = np.asarray([0,5,80,10,1,10,40,30,80,5,0]) x = np.arange(len(y)) plt.plot(x, y, 'r', ms=5) spl = UnivariateSpline(x, y) xs = np.linspace(0,len(y)-1, 1000) spl.set_smoothing_factor(2) plt.plot(xs, spl(xs), 'g', lw=3) plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/RY5hW.png" rel="nofollow"><img src="https://i.stack.imgur.com/RY5hW.png" alt="enter image description here"></a></p>
<p>Spline fitting is known to overshoot. You seem to be looking for one of the so-called <em>monotonic</em> interpolators. For instance,</p> <pre><code>In [10]: from scipy.interpolate import pchip In [11]: pch = pchip(x, y) </code></pre> <p>produces</p> <pre><code>In [12]: xx = np.linspace(x[0], x[-1], 101) In [13]: plt.plot(x, y, 'ro', label='points') Out[13]: [&lt;matplotlib.lines.Line2D at 0x7fce0a7fe390&gt;] In [14]: plt.plot(xx, pch(xx), 'g-', label='pchip') Out[14]: [&lt;matplotlib.lines.Line2D at 0x7fce0a834b10&gt;] </code></pre> <p><a href="https://i.stack.imgur.com/xuYMR.png"><img src="https://i.stack.imgur.com/xuYMR.png" alt="enter image description here"></a></p>
"Incorrect syntax" when using a common table expression <pre><code>WITH list_dedup (Company, duplicate_count) AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY Company ORDER BY Email) AS 'RowNumber' FROM Travels ) </code></pre> <p><strong>Error</strong>:</p> <blockquote> <p>Msg 102, Level 15, State 1, Line 7<br> Incorrect syntax near ')'.</p> </blockquote>
<p>You are missing a final select for the common table expression (<strong>after</strong> the definition of the CTE):</p> <pre><code>WITH list_dedup (Company,duplicate_count) As ( select *, ROW_NUMBER() OVER (PARTITION BY Company ORDER by Email) As "RowNumber" From Travels ) <b>select * from list_dedup;</b></code></pre> <p>But this will not because the CTE is defined to have <strong>two</strong> columns (through the <code>WITH list_dedup (Company,duplicate_count)</code>) but your select inside the CTE returns <em>at least</em> three columns (company, email, rownumber). You need to either adjust the column definition for the CTE, or leave it out completely:</p> <pre><code>WITH list_dedup As ( select *, ROW_NUMBER() OVER (PARTITION BY Company ORDER by Email) As "RowNumber" From Travels ) select * from list_dedup; </code></pre> <hr> <p>The <code>As "RowNumber"</code> in the inner select also doesn't make sense when the column list is defined, because then the CTE definition defines the column names. Any alias used <em>inside</em> the CTE will not be visible outside of it (<em>if</em> the CTE columns are specified in the <code>with .. (...) as</code> part).</p>
Open another conection in OracleDataReader loop the oracle session not close <p>I have a problem about session not close when make calling another connection under OracleDataReader loop code below</p> <pre><code> private ArrayList GetORA() { ArrayList arr = new ArrayList(); string connectionString = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=xx)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)));User ID=kcdev2usr;Password=password;ENLIST=FALSE;Pooling=true;Max Pool Size=20;"; const string queryString = "select * from MASTER_TABLE"; using (OracleConnection connection = new OracleConnection(connectionString)) { OracleCommand command = new OracleCommand(queryString, connection); connection.Open(); OracleDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection); try { while (reader.Read()) { Master m = new Master(); m.ID = reader["ID"].ToString(); m.obj = GetAnother(reader["SOME"].ToString()); arr.Add(m); } } finally { reader.Close(); } } return arr; } private Object GetAnother(string some) { // Do something string getNextID = PutSome(some); //===== Object obj = null; string connectionString = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=xx)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)));User ID=kcdev2usr;Password=password;ENLIST=FALSE;Pooling=true;Max Pool Size=20;"; const string queryString = "SELECT PAGE_NAME FROM ANOTHER_TABLE WHERE ID=:ID"; using (OracleConnection connection = new OracleConnection(connectionString)) { OracleCommand command = new OracleCommand(queryString, connection); command.Parameters.Add("ID",getNextID); connection.Open(); OracleDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection); try { while (reader.Read()) { obj = CreateObj(dr["PAGE_NAME"].ToString()); } } finally { reader.Close(); } } return obj; } </code></pre> <p><a href="https://i.stack.imgur.com/vZPK5.jpg" rel="nofollow">session is not close</a></p> <p>Then,.. I've try to move the problem method out loop like this</p> <pre><code>private ArrayList GetORA() { ArrayList arr = new ArrayList(); string connectionString = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=xx)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)));User ID=kcdev2usr;Password=password;ENLIST=FALSE;Pooling=true;Max Pool Size=20;"; const string queryString = "select * from MASTER_TABLE"; using (OracleConnection connection = new OracleConnection(connectionString)) { OracleCommand command = new OracleCommand(queryString, connection); connection.Open(); OracleDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection); try { while (reader.Read()) { Master m = new Master(); m.ID = reader["ID"].ToString(); m.Some = reader["SOME"].ToString(); arr.Add(m); } } finally { reader.Close(); } foreach (var item in arr) { item.obj = GetAnother(item.Some); } } return arr; } </code></pre> <p>All oracle session was clean and clear correctly, why?</p> <ul> <li>I thing my code not good to be but I would like to know what difference about ODP.Net manage oracle session.</li> </ul> <hr> <p>ps. I use "Oracle.DataAccess.dll" version 4.121.2.0</p>
<p>IF you want to close session you should finish you call <code>connection.Dispose();</code></p> <p><a href="http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/hol08/dotnet/getstarted-c/getstarted_c_otn.htm" rel="nofollow">http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/hol08/dotnet/getstarted-c/getstarted_c_otn.htm</a></p> <p>But why you want to close session in loop? Open session is expensive operation, and better rule of tombs is reusing one connection in times. And Oracle allow you to use one user/pass to several sessions. May be you should think about it.</p>
Launching activity on condition for loginactivity <p>I want to launch activity after login on 2 condition if user is active in Database entry i want to launch MainActivity.java if user is not active it should launch mobile verification screen i am using volley to make http calls and getting data from server here is my script</p> <p>LoginActivity.java</p> <pre><code>// Now store the user in SQLite String uid = jObj.getString("uid"); JSONObject user = jObj.getJSONObject("user"); String name = user.getString("name"); String email = user.getString("email"); String phone = user.getString("phone"); String status = user.getString("status"); // Inserting row in users table db.addUser(name, email, uid,phone); if(new String(status).equals("active") ) { // Launch main activity Intent intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); finish(); } else{ Intent intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); finish(); } </code></pre>
<p>The problem is you are comparing two strings in a wrong way. You should edit </p> <pre><code>if(new String(status).equals("active") ) </code></pre> <p>to:</p> <pre><code>if(status.contentEquals("active")) </code></pre> <p>and you are done.</p>
Angular application works on Chrome but not Safari <p>My website works fine on Chrome but is broken on Apple Mobile Safari.</p> <p>I have troubleshot the situation and have found that it is the below line of code placed in side of my angular controller that is causing the problem. With out this code everything works fine.</p> <p>The code takes all images on the page and puts them inside of an array. Anything I can do differently to ensure proper compatibility? Thank you!</p> <pre><code>$scope.load_picture_cotent = function () { $scope.pictures = Array.from( document.querySelectorAll ('div.album [style^="background-image"]')).map (el=&gt;el.style.backgroundImage.replace(/url\((.*)\)/,'$1') .replace(/"/g,'') .replace(/thumbnails/,'highresolution')); console.log($scope.pictures); } </code></pre> <p>You can also view the website <a href="http://kiawahislandgetaways.com/codingFun/KarlyPortfolio/route-test/index.html#/home" rel="nofollow">here</a>. </p> <p>Please let me know if you need any more information or would like me to expand my post to include more information.</p>
<p>you are using ECMA 2015 lambda notation, try to wrap this with babel and try it again, did you check the browsers compatibility status with ECMA Script 2015?</p>
SQL Sampling: one element from each bucket <p>Here is a simulation of the basic setup i have: each person can hold multiple possessions.<br> <b>Persons</b> table:</p> <pre><code>id name 1 Carl 2 Sam 3 Tom 4 Jack </code></pre> <p><b>Possessions</b> table:</p> <pre><code>possession personId car 2 shoes 2 shovel 2 tent 3 matches 3 axe 4 </code></pre> <p>I want to generate a random set of possessions belonging to a random set of people, <i>one possession per person</i>.</p> <p>So, in a non-SQL world I would generate a set of N random people and then pick a random possession for each person in the set. But how do I implement that in SQL semantics?</p> <p>I thought of getting a random sample of possessions with some variation of:</p> <pre><code>SELECT * FROM Posessions WHERE 0.01 &gt;= RAND() </code></pre> <p>And then filtering out duplicate persons, but that is no good as it will favor persons with large number of possessions in the end, and I want each person to have equal chance of being selected.</p> <p>Is there a canonical way to solve this?</p> <p>P.S. Person contains ~50000 entities and Possession contains ~2500000 entities, but i only need to perform this sampling once, so it can be somewhat slow.</p>
<p>Why don't you take random set of persons and join to posessions ranked by random. Something like below. Sorry if it contain any spelling error but I don't have DB to check it now:</p> <pre><code> select * from ( (select top 1 percent * from persons order by newid()) a inner join (select p.*, ROW_NUMBER() OVER (partition by personId order by newid()) r from posessions p) b on (a.personId = b.personId) ) where r = 1; </code></pre>
C++ code compiles but doesn't run <p>I am currently writing a Texas Hold'em code in order to learn more about c++ and gain experience. But I recently ran into a problem in which I have no idea what to do.My code compiles just fine without errors but once I make it run and it arrive at a specific function it just stops working (as in I get an error from CodeBlock saying your program has stopped working). I have tried cutting out parts such as loops in the function to see which specific part is the problem but after a couple of days im still at a stop. Here is the function and class that I believe is the problem:</p> <pre><code>class Player{ string name; int bank=100; static string cards[53]; static string final_card[2][6]; static string table_cards[5]; public: void set_name(string a){name=a;} string print_name(){return name;} void card_generator(); string set_cards(int c){return cards[c];} int print_bank(){return bank;} void set_final_card(int i, int max_i); void print_cards(){for(int i=0;i&lt;6;i++){cout&lt;&lt;final_card[0][i]&lt;&lt;endl;}} }; void Player::set_final_card(int i, int max_i){ srand(time(NULL)); int tempV = 17;//create temp cards string tempCards[tempV]; int randNB[tempV]; int check1 = 0, tmp; while (check1==0){ for(int g=0; g&lt;tempV;g++){ tempCards[g]=cards[rand()%53]; check1=1; tmp = g - 1; for(int o=tmp; o!=0; o--){ if (tempCards[g]==tempCards[o]){ check1=0; } } } } int p=0,k; while(p&lt;6){ k=0; final_card[0][k]=tempCards[p]; k++; p++; } while(p&lt;12){ k=0; final_card[1][k]=tempCards[p]; k++; p++; } while(p&lt;17){ k=0; table_cards[k]=tempCards[p]; k++; p++; } } </code></pre> <p>Here is the full code in case I am wrong of the source of the problem:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;stdlib.h&gt; #include &lt;ctime&gt; using namespace std; class Player{ string name; int bank=100; static string cards[53]; static string final_card[2][6]; static string table_cards[5]; public: void set_name(string a){name=a;} string print_name(){return name;} void card_generator(); string set_cards(int c){return cards[c];} int print_bank(){return bank;} void set_final_card(int i, int max_i); void print_cards(){for(int i=0;i&lt;6;i++){cout&lt;&lt;final_card[0][i]&lt;&lt;endl;}} }; string Player::cards[53]; string Player::final_card[2][6]; string Player::table_cards[5]; int main () { int choice1=0, i, max_i, tempV; string username; cout&lt;&lt; "Welcome to Texas Hold'Em!\n1-Play\n2-Quit\n";//menu while((choice1!=1)&amp;&amp;(choice1!=2)){//Makes sure that user enters correct input``` cin&gt;&gt;choice1; if ((choice1!=1)&amp;&amp;(choice1!=2)){ cout&lt;&lt;"Invalid Input!\nTry again!\n"; } } system ("cls"); if (choice1==2){//End Program return 0; } cout&lt;&lt;"How many players?[2-6]"&lt;&lt;endl; while((i!=2)&amp;&amp;(i!=3)&amp;&amp;(i!=4)&amp;&amp;(i!=5)&amp;&amp;(i!=6)){//Makes sure that user enters correct input cin&gt;&gt;i; if ((i!=2)&amp;&amp;(i!=3)&amp;&amp;(i!=4)&amp;&amp;(i!=5)&amp;&amp;(i!=6)){ cout&lt;&lt;"Invalid Input!\nTry again!\n"; } } Player player[i];//creating array of players player[0].card_generator(); max_i = i;//max_i is nb of players i--;//since arrays start at 0 system("cls"); player[0].set_final_card(i,max_i); player[0].print_cards(); if (choice1==1) {//SET NAMES OF ALL PLAYERS for(i=0; i&lt;max_i; i++){ cout&lt;&lt; "Whats your name?\n"; cin&gt;&gt;username; player[i].set_name(username); cout&lt;&lt;"Your name is "&lt;&lt; player[i].print_name()&lt;&lt; " and you have "&lt;&lt; player[i].print_bank()&lt;&lt;"$\n"; tempV=i+1;//used bc arrays start at 0 if(tempV!=max_i){ cout&lt;&lt; "Give PC to player "&lt;&lt; i+2 &lt;&lt;endl; } _sleep(3000); system("cls"); } } return 0; } void Player::set_final_card(int i, int max_i){ srand(time(NULL)); int tempV = 17;//create temp cards string tempCards[tempV]; int randNB[tempV]; int check1 = 0, tmp; while (check1==0){ for(int g=0; g&lt;tempV;g++){ tempCards[g]=cards[rand()%53]; check1=1; tmp = g - 1; for(int o=tmp; o!=0; o--){ if (tempCards[g]==tempCards[o]){ check1=0; } } } } int p=0,k; while(p&lt;6){ k=0; final_card[0][k]=tempCards[p]; k++; p++; } while(p&lt;12){ k=0; final_card[1][k]=tempCards[p]; k++; p++; } while(p&lt;17){ k=0; table_cards[k]=tempCards[p]; k++; p++; } } void Player::card_generator(){ string card_value[13]; card_value[0]="1"; card_value[1]="2"; card_value[2]="3"; card_value[3]="4"; card_value[4]="5"; card_value[5]="6"; card_value[6]="7"; card_value[7]="8"; card_value[8]="9"; card_value[9]="10"; card_value[10]="J"; card_value[11]="Q"; card_value[12]="K"; string card_type[4]; card_type[0]="of hearts"; card_type[1]="of diamonds"; card_type[2]="of clubs"; card_type[3]="of spades"; string card[53]; int x=0; fill_n(card,53,0); for (int j=0;j&lt;4;j++){ for (int q=0;q&lt;13;q++){ card[x]=card_value[q]+" "+card_type[j]; cards[x]=card[x]; x++; } } } </code></pre> <p>If you have any criticism about the code itself even if not directly linked to problem feel free to tell me as I'm doing this to learn :D. Thank you in advance!!</p>
<pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;stdlib.h&gt; #include &lt;ctime&gt; </code></pre> <p>Be consistent in what you do. Including <code>&lt;stdlib.h&gt;</code> and <code>&lt;ctime&gt;</code> looks strange. Either include <code>&lt;cstdlib&gt;</code> and <code>&lt;ctime&gt;</code>, or include <code>&lt;stdlib.h&gt;</code> and <code>&lt;time.h&gt;</code>.</p> <pre><code>using namespace std; </code></pre> <p>Don't do this. This <code>using</code> imports <em>all</em> names from the <code>std</code> namespace, which is several hundreds. Only import those names that you actually need, or, alternatively, write <code>std::time</code> instead of the unqualified <code>time</code>. This makes it perfectly clear that you are referring to the <code>time</code> from the standard library instead of one that you might have defined yourself.</p> <pre><code>class Player{ string name; int bank=100; static string cards[53]; static string final_card[2][6]; static string table_cards[5]; </code></pre> <p>The cards should not be represented as strings, but as a separate data type called <code>Card</code>, with properties like <code>suit</code> and <code>rank</code> and a <code>to_string</code> method.</p> <pre><code> public: void set_name(string a){name=a;} </code></pre> <p>To make your program fast, pass <code>a</code> as <code>const std::string &amp;</code> instead of a simple <code>string</code>. This will prevent some copying of data. You should give a better name to the parameter, e.g. <code>void set_name(const std::string &amp;name) { this.name = name; }</code>.</p> <pre><code> string print_name(){return name;} </code></pre> <p>This method does not print anything, therefore it must not be called <code>print_name</code>.</p> <pre><code> void card_generator(); </code></pre> <p>Methods usually are named with verbs, not with nouns. So <code>generate_cards</code> would be a better name. But what does <code>generate</code> mean here? (I'm not a native English speaker, but would <code>draw_cards</code> describe it accurately?)</p> <pre><code> string set_cards(int c){return cards[c];} </code></pre> <p>A method called <code>set_*</code> usually modifies something. This one doesn't. Why did you name it this way?</p> <pre><code> int print_bank(){return bank;} void set_final_card(int i, int max_i); </code></pre> <p>Give better names to the parameters. From reading only this declaration, I have no idea what <code>i</code> and <code>max_i</code> might mean.</p> <pre><code> void print_cards(){for(int i=0;i&lt;6;i++){cout&lt;&lt;final_card[0][i]&lt;&lt;endl;}} }; string Player::cards[53]; string Player::final_card[2][6]; string Player::table_cards[5]; </code></pre> <p>It looks strange that the cards are stored in the Player class, since no poker player should ever have insight to all 52 cards. And why 53? Is there a joker in your game? These three fields should be moved to a <code>class Table</code>. This allows you to have multiple independent tables, which is nice for a big tournament.</p> <pre><code>int main () { int choice1=0, i, max_i, tempV; string username; cout&lt;&lt; "Welcome to Texas Hold'Em!\n1-Play\n2-Quit\n";//menu while((choice1!=1)&amp;&amp;(choice1!=2)){//Makes sure that user enters correct input``` </code></pre> <p>Before reading the <code>choice1</code> variable, you <em>must</em> initialize it. Since you don't do it, you invoke undefined behavior and everything that the program does after that is unpredictable.</p> <pre><code> cin&gt;&gt;choice1; if ((choice1!=1)&amp;&amp;(choice1!=2)){ cout&lt;&lt;"Invalid Input!\nTry again!\n"; } } system ("cls"); if (choice1==2){//End Program return 0; } cout&lt;&lt;"How many players?[2-6]"&lt;&lt;endl; while((i!=2)&amp;&amp;(i!=3)&amp;&amp;(i!=4)&amp;&amp;(i!=5)&amp;&amp;(i!=6)){//Makes sure that user enters correct input </code></pre> <p>Same here. The user hasn't yet entered anything, so how can you check it?</p> <pre><code> cin&gt;&gt;i; </code></pre> <p>Add error handling for every input by enclosing it in an if clause: <code>if (std::cin &gt;&gt; i) {</code>.</p> <pre><code> if ((i!=2)&amp;&amp;(i!=3)&amp;&amp;(i!=4)&amp;&amp;(i!=5)&amp;&amp;(i!=6)){ cout&lt;&lt;"Invalid Input!\nTry again!\n"; } } Player player[i];//creating array of players </code></pre> <p>Don't use arrays, use a <code>std::vector</code> instead. This allows you to easily extend the table to have 10 players. In the end, there should not be a single <code>6</code> in your program.</p> <pre><code> player[0].card_generator(); max_i = i;//max_i is nb of players </code></pre> <p>Why do you call this variable <code>max_i</code>, when the comment says that <code>max_players</code> would be a better name?</p> <pre><code> i--;//since arrays start at 0 system("cls"); player[0].set_final_card(i,max_i); player[0].print_cards(); if (choice1==1) {//SET NAMES OF ALL PLAYERS for(i=0; i&lt;max_i; i++){ cout&lt;&lt; "Whats your name?\n"; cin&gt;&gt;username; player[i].set_name(username); cout&lt;&lt;"Your name is "&lt;&lt; player[i].print_name()&lt;&lt; " and you have "&lt;&lt; player[i].print_bank()&lt;&lt;"$\n"; tempV=i+1;//used bc arrays start at 0 if(tempV!=max_i){ </code></pre> <p>What does the <code>V</code> in <code>tempV</code> mean?</p> <pre><code> cout&lt;&lt; "Give PC to player "&lt;&lt; i+2 &lt;&lt;endl; } _sleep(3000); system("cls"); } } return 0; } void Player::set_final_card(int i, int max_i){ srand(time(NULL)); int tempV = 17;//create temp cards </code></pre> <p>This 17 is a magic number. It would be better to write it as 5 + 6 * 2, since that makes it much clearer.</p> <pre><code> string tempCards[tempV]; int randNB[tempV]; int check1 = 0, tmp; while (check1==0){ for(int g=0; g&lt;tempV;g++){ tempCards[g]=cards[rand()%53]; </code></pre> <p>The 53 is wrong here. I can only be wrong. When you select from 52 cards with equal probability, it must be <code>% 52</code>.</p> <pre><code> check1=1; tmp = g - 1; for(int o=tmp; o!=0; o--){ if (tempCards[g]==tempCards[o]){ check1=0; } } } } </code></pre>
Exit sudoers view difference on apt-get update <p>I ran apt-get upgrade about 10 minutes ago to upgrade my Ubuntu 16.04 server. I asked me if I would like to keep my current Sudoers file or upgrade to the new one, it also had the option to view the differences between the two, so I decided to view the differences.</p> <p>It then opened up a differences view in what seemed like vi, but I cannot interact with anything apart from page-up/down.</p> <p>I don't want to just close my ssh session because it might break the update in progress.</p> <p>Any advice?</p>
<p>Turns out it's <kbd>ctrl</kbd>+<kbd>q</kbd>+<kbd>t</kbd>.</p> <p>Whoever thought of that is an idiot.</p>
Jquery cloned element is replacing himself <p>I have been getting some issue with cloning element, when I am cloning an element and add it to the DOM it work perfectly but when I am trying to clone a second one its replacing the first added clone, do you know where it could come from ? </p> <pre><code> var clone_count = 1; var add_row = $('.modeloRowBlock-hidden').clone(true) // clone my div that is hidden $('.add-modelo-block').on('click', function() { // binded button to add my div var current_row = add_row.removeClass('modeloRowBlock-hidden hidden').addClass('modeloRowBlock' + ' ' + clone_count++) ; $('.modeloRowBlock-hidden').before(current_row); }); </code></pre> <p>Thanks a lot in advance for your help :).</p> <p>Jonathan.</p> <p>EDIT : My bad I made it work, actually cloned that way for another reason, and re integrated it in the .on and it worked.</p>
<p>You clone your row only once.<br> If you're using before on a single element, it will move the elements.</p> <blockquote> <p>If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved before the target (not cloned):</p> </blockquote> <p>Read more: <a href="http://api.jquery.com/before/" rel="nofollow">http://api.jquery.com/before/</a></p>
How to persist values of delegated fields in rails <p>I currently have the following models:</p> <p><strong>user.rb</strong></p> <pre><code> class User &lt; ApplicationRecord has_one :profile, dependent: :destroy before_create :build_profile end </code></pre> <p><strong>profile.rb</strong></p> <pre><code> class Profile &lt; ApplicationRecord belongs_to :user delegate :name, :email, :name=, :email=, to: :user end </code></pre> <p>For the profile, I have the following controller:</p> <p><strong>profile_controller.rb</strong></p> <pre><code> class ProfileController &lt; ApplicationController before_action :set_user before_action :authenticate_user! def edit @user = current_user @profile = @user.profile end def update @user = current_user @profile = @user.profile if @profile.update(profile_params) redirect_to profile_path(current_user.username) else render :edit end end private def profile_params params.require(:profile).permit(:name, :email, :user_id, :bio, :avatar, :remove_avatar) end end </code></pre> <p>My "Edit Profile" form is as follows:</p> <p><strong>edit.html.haml</strong></p> <pre><code> = simple_form_for @profile do |f| = f.error_notification .form-inputs .row .col-md-6.col-sm-12 = f.input :name, required: true, placeholder: "Name" .col-md-6.col-sm-12 = f.input :email, required: true, placeholder: "Email" = f.input :bio, required: true, hint: "Write a short bio about yourself", placeholder: "PHP Developer developing cool apps in Tokyo." = f.input :avatar, as: :attachment, direct: true, presigned: true .form-actions = f.button :submit, "Update", class: "btn ban-info" </code></pre> <p>I am trying to change the delegated values in the profile form. However, they do not persist to the database. How do I go about doing this?</p> <p>Thanks</p>
<p>Instead of delegate, which is normally reserved for exposing public methods that do not involve persistence, try adding the following line to your profile model:</p> <pre><code>accepts_nested_attributes_for :user #This will allow you to handle user attributes via a profile object </code></pre> <p>Also, in your <code>update</code> action you need to specify the relationship of profiles and users such as:</p> <pre><code>if @user.profile.update_attributes(profile_params) </code></pre>
iOS app crashes after deleting the last cell in section <p>So I've my app crashing everytime I try to delete the last cell of the section.</p> <p>Ex., if my section has 10 rows, I can delete them without any problem but the last one throws the following error:</p> <blockquote> <p>Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections. The number of sections contained in the table view after the update (1) must be equal to the number of sections contained in the table view before the update (3), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted).'</p> </blockquote> <p>I've searched around here and found some ways to fix this problem, but I tried them all and couldn't get this issue fixed, it still crashes and throws the same error.</p> <p>The related parts of my code goes as it follows:</p> <pre><code>override func numberOfSections(in tableView: UITableView) -&gt; Int { if (main_arr.count &gt; 0 &amp;&amp; sub_arr.count &gt; 0) { self.numberOfSections = 3 } else { self.numberOfSections = 2 } return self.numberOfSections } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { if (section == 0) { return 1 } else if (section == 1 &amp;&amp; main_arr.count &gt; 0) { return main_arr.count } else { return sub_arr.count } } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -&gt; Bool { return true } // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { switch indexPath.section { case 1: main_arr.remove(at: indexPath.row) case 2: sub_arr.remove(at: indexPath.row) default: print("default 001") } tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } </code></pre> <p><strong>EDIT 1</strong></p> <p>I tried to handle the global variable, responsible for the numberOfSections so when any of my arrays.count == 0 it will be decreased by 1, but it didn't solved the issue.</p> <p>I do understand completely the error message, like, if I've 3 sections, and I delete the whole content of one of them, I should delete one section and delete it from the datasource as well.</p>
<p>The problem is that <code>numberOfSections</code> returns different values before and after you delete rows, but <strong>you don't delete any sections</strong>. So you should either return a constant value in numberOfSections or call <code>deleteSections</code> in addition to <code>deleteRows</code></p> <p>The main thing to remember is the following:</p> <p><strong>UITableView must always contain the same number of rows and sections as your dataSource.</strong></p> <p>You cannot just return a new value in <code>numberOfSections</code> or <code>numberOfRows</code> dataSource methods. Every change should be compensated with delete/insert rows(sections) method. And vice versa: if you delete/insert to tableView, you <strong>must</strong> return corresponding values in dataSource methods. Just as your exception message states:</p> <blockquote> <p>The number of sections contained in the table view <strong>after the update (1)</strong> must be equal to the number of sections contained in the table view <strong>before the update (3)</strong>, plus or minus the number of sections inserted or deleted <strong>(0 inserted, 0 deleted)</strong>.</p> </blockquote> <p>It's because 3+0≠1. In this case you should have deleted two sections to avoid crash.</p>
User defined fields model in django <p>I want to allow my users to define custom properties.</p> <p>They are managing apartments so each customer manages the apartments in different way. I want to allow them to define some custom properties for they apartments.</p> <pre><code>class Unit(CommonInfo): version = IntegerVersionField( ) number = models.CharField(max_length=30,null=True, blank=True) max_occupants = models.PositiveSmallIntegerField() floor = models.PositiveSmallIntegerField() rooms = models.PositiveSmallIntegerField() is_disabled_access = models.BooleanField(default=False) balcony_quantity = models.PositiveSmallIntegerField() building = models.ForeignKey(Building) recomended_price = models.DecimalField(max_digits=7, decimal_places=2) </code></pre> <p>I want them to be able additional fields to this model. For example - is_breaker is_fuse Number_of</p> <p>Since I cant predict what data they will require. </p> <p>how can I do it?</p>
<p>I would reccomend the following solution:</p> <p>1.Create a "property" Model:</p> <pre><code>class Property(models.Model): property = models.CharField(max_length=140) value = models.CharField(max_length=140) def __str__(self): return self.property </code></pre> <p>2.To your Unit model, add a ManytoMany field with property model:</p> <pre><code>class Unit(models.Model): (...) properties = models.ManyToManyField(Property) </code></pre> <p>3.Add an inline in your admin to view the different Properties:</p> <pre><code>class Unit(admin.ModelAdmin): fields = ('__all__') inlines = ('properties') </code></pre>
statistical summary table in sklearn.linear_model.ridge? <p>In OLS form StatsModels, results.summary shows the summary of regression results (such as AIC, BIC, R-squared, ...). </p> <p>Is there any way to have this summary table in sklearn.linear_model.ridge? </p> <p>I do appreciate if someone guide me. Thank you.</p>
<p>As I know, there is no R(or Statsmodels)-like summary table in sklearn. (Please check <a href="http://stackoverflow.com/a/26326883/3054161">this answer</a>) </p> <p>Instead, if you need it, there is <a href="http://statsmodels.sourceforge.net/devel/generated/statsmodels.regression.linear_model.OLS.fit_regularized.html#statsmodels-regression-linear-model-ols-fit-regularized" rel="nofollow">statsmodels.regression.linear_model.OLS.fit_regularized</a> class. (<code>L1_wt=0</code> for ridge regression.)</p> <p>For now, it seems that <code>model.fit_regularized(~).summary()</code> returns <code>None</code> despite of docstring below. But the object has <code>params</code>, <code>summary()</code> can be used somehow.</p> <blockquote> <p>Returns: A RegressionResults object, of the same type returned by <code>fit</code>.</p> </blockquote> <p><strong>Example.</strong></p> <p>Sample data is not for ridge regression, but I will try anyway.</p> <p>In.</p> <pre><code>import numpy as np import pandas as pd import statsmodels import statsmodels.api as sm import matplotlib.pyplot as plt statsmodels.__version__ </code></pre> <p>Out.</p> <pre><code>'0.8.0rc1' </code></pre> <p>In.</p> <pre><code>data = sm.datasets.ccard.load() print "endog: " + data.endog_name print "exog: " + ', '.join(data.exog_name) data.exog[:5, :] </code></pre> <p>Out.</p> <pre><code>endog: AVGEXP exog: AGE, INCOME, INCOMESQ, OWNRENT Out[2]: array([[ 38. , 4.52 , 20.4304, 1. ], [ 33. , 2.42 , 5.8564, 0. ], [ 34. , 4.5 , 20.25 , 1. ], [ 31. , 2.54 , 6.4516, 0. ], [ 32. , 9.79 , 95.8441, 1. ]]) </code></pre> <p>In.</p> <pre><code>y, X = data.endog, data.exog model = sm.OLS(y, X) results_fu = model.fit() print results_fu.summary() </code></pre> <p>Out.</p> <pre><code> OLS Regression Results ============================================================================== Dep. Variable: y R-squared: 0.543 Model: OLS Adj. R-squared: 0.516 Method: Least Squares F-statistic: 20.22 Date: Wed, 19 Oct 2016 Prob (F-statistic): 5.24e-11 Time: 17:22:48 Log-Likelihood: -507.24 No. Observations: 72 AIC: 1022. Df Residuals: 68 BIC: 1032. Df Model: 4 Covariance Type: nonrobust ============================================================================== coef std err t P&gt;|t| [0.025 0.975] ------------------------------------------------------------------------------ x1 -6.8112 4.551 -1.497 0.139 -15.892 2.270 x2 175.8245 63.743 2.758 0.007 48.628 303.021 x3 -9.7235 6.030 -1.613 0.111 -21.756 2.309 x4 54.7496 80.044 0.684 0.496 -104.977 214.476 ============================================================================== Omnibus: 76.325 Durbin-Watson: 1.692 Prob(Omnibus): 0.000 Jarque-Bera (JB): 649.447 Skew: 3.194 Prob(JB): 9.42e-142 Kurtosis: 16.255 Cond. No. 87.5 ============================================================================== Warnings: [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. </code></pre> <p>In.</p> <pre><code>frames = [] for n in np.arange(0, 0.25, 0.05).tolist(): results_fr = model.fit_regularized(L1_wt=0, alpha=n, start_params=results_fu.params) results_fr_fit = sm.regression.linear_model.OLSResults(model, results_fr.params, model.normalized_cov_params) frames.append(np.append(results_fr.params, results_fr_fit.ssr)) df = pd.DataFrame(frames, columns=data.exog_name + ['ssr*']) df.index=np.arange(0, 0.25, 0.05).tolist() df.index.name = 'alpha*' df.T </code></pre> <p>Out.</p> <p><a href="https://i.stack.imgur.com/fSR9N.png" rel="nofollow"><img src="https://i.stack.imgur.com/fSR9N.png" alt="enter image description here"></a></p> <p>In.</p> <pre><code>%matplotlib inline fig, ax = plt.subplots(1, 2, figsize=(14, 4)) ax[0] = df.iloc[:, :-1].plot(ax=ax[0]) ax[0].set_title('Coefficient') ax[1] = df.iloc[:, -1].plot(ax=ax[1]) ax[1].set_title('SSR') </code></pre> <p>Out.</p> <p><a href="https://i.stack.imgur.com/irutn.png" rel="nofollow"><img src="https://i.stack.imgur.com/irutn.png" alt="enter image description here"></a></p> <p>In.</p> <pre><code>results_fr = model.fit_regularized(L1_wt=0, alpha=0.04, start_params=results_fu.params) final = sm.regression.linear_model.OLSResults(model, results_fr.params, model.normalized_cov_params) print final.summary() </code></pre> <p>Out.</p> <pre><code> OLS Regression Results ============================================================================== Dep. Variable: y R-squared: 0.543 Model: OLS Adj. R-squared: 0.516 Method: Least Squares F-statistic: 20.17 Date: Wed, 19 Oct 2016 Prob (F-statistic): 5.46e-11 Time: 17:22:49 Log-Likelihood: -507.28 No. Observations: 72 AIC: 1023. Df Residuals: 68 BIC: 1032. Df Model: 4 Covariance Type: nonrobust ============================================================================== coef std err t P&gt;|t| [0.025 0.975] ------------------------------------------------------------------------------ x1 -5.6375 4.554 -1.238 0.220 -14.724 3.449 x2 159.1412 63.781 2.495 0.015 31.867 286.415 x3 -8.1360 6.034 -1.348 0.182 -20.176 3.904 x4 44.2597 80.093 0.553 0.582 -115.564 204.083 ============================================================================== Omnibus: 76.819 Durbin-Watson: 1.694 Prob(Omnibus): 0.000 Jarque-Bera (JB): 658.948 Skew: 3.220 Prob(JB): 8.15e-144 Kurtosis: 16.348 Cond. No. 87.5 ============================================================================== Warnings: [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. </code></pre>
Adding custom overlay in map view <p>i'm new to iOS and my goal is to add custom overlay in map view using Swift 3 and MapKit. I've followed this <a href="http://stackoverflow.com/questions/9049790/add-inverted-circle-overlay-to-map-view">Add inverted circle overlay to map view</a>. Here is the code:</p> <pre><code>import UIKit import MapKit class MyMapOverlayRenderer: MKOverlayRenderer { let diameter: Double let fillColor: UIColor init(overlay: MKOverlay, diameter: Double, fillColor: UIColor) { self.diameter = diameter self.fillColor = fillColor super.init(overlay: overlay) } override func draw(_ mapRect: MKMapRect, zoomScale: MKZoomScale, in context: CGContext) { let path = UIBezierPath(rect: CGRect(x: mapRect.origin.x, y: mapRect.origin.y, width: mapRect.size.width, height: mapRect.size.height)) path.usesEvenOddFillRule = true let radiusInMapPoints = diameter * MKMapPointsPerMeterAtLatitude(self.overlay.coordinate.latitude) let radiusSquared = MKMapSize(width: radiusInMapPoints, height: radiusInMapPoints) let regionOrigin = MKMapPointForCoordinate(self.overlay.coordinate) var regionRect = MKMapRect(origin: regionOrigin, size: radiusSquared) regionRect = MKMapRectOffset(regionRect, -radiusInMapPoints / 2, -radiusInMapPoints / 2) regionRect = MKMapRectIntersection(regionRect, MKMapRectWorld) let cornerRadius = CGFloat(regionRect.size.width / Double(2)) let excludePath = UIBezierPath(roundedRect: CGRect(x: regionRect.origin.x, y: regionRect.origin.y, width: regionRect.size.width, height: regionRect.size.height), cornerRadius: cornerRadius) path.append(excludePath) context.setFillColor(fillColor.cgColor) context.addPath(path.cgPath) context.fillPath() } } </code></pre> <p>Eventually the overlay is shown without exclude path (a circle), any suggestions?</p>
<p>Solved it, just added reversing():</p> <pre><code>path.append(excludePath.reversing()) </code></pre> <p>Full function code:</p> <pre><code>override func draw(_ mapRect: MKMapRect, zoomScale: MKZoomScale, in context: CGContext) { let path = UIBezierPath(rect: CGRect(x: mapRect.origin.x, y: mapRect.origin.y, width: mapRect.size.width, height: mapRect.size.height)) path.usesEvenOddFillRule = true let radiusInMapPoints = diameter * MKMapPointsPerMeterAtLatitude(MKMapPointsPerMeterAtLatitude(overlay.coordinate.latitude)) let radiusSquared = MKMapSize(width: radiusInMapPoints, height: radiusInMapPoints) let regionOrigin = MKMapPointForCoordinate(overlay.coordinate) var regionRect = MKMapRect(origin: regionOrigin, size: radiusSquared) regionRect = MKMapRectOffset(regionRect, -radiusInMapPoints / 2, -radiusInMapPoints / 2) regionRect = MKMapRectIntersection(regionRect, MKMapRectWorld) let midX = ( regionOrigin.x + regionRect.origin.x) / 2 let midY = ( regionOrigin.y + regionRect.origin.y) / 2 let cornerRadius = CGFloat(regionRect.size.width / Double(2)) let excludePath = UIBezierPath(roundedRect: CGRect(x: midX, y: midY, width: regionRect.size.width / 2, height: regionRect.size.height / 2), cornerRadius: cornerRadius) path.append(excludePath.reversing()) context.setFillColor(fillColor.cgColor) context.addPath(path.cgPath) context.fillPath() } </code></pre>
Concatenating pandas DataFrames keeping only rows with matching values in a column? <p>I am trying to "merge-concatenate" two pandas DataFrames. Basically, I want to stack the two DataFrames, but only keep the rows from each DataFrame which matching values in the other DataFrame. So for example:</p> <pre><code>data1: +---+------------+-----------+-------+ | | first_name | last_name | class | +---+------------+-----------+-------+ | 0 | Alex | Anderson | 1 | | 1 | Amy | Ackerman | 2 | | 2 | Allen | Ali | 3 | | 3 | Alice | Aoni | 4 | | 4 | Andrew | Andrews | 4 | | 5 | Ayoung | Atiches | 5 | +---+------------+-----------+-------+ data2: +---+------------+-----------+-------+ | | first_name | last_name | class | +---+------------+-----------+-------+ | 0 | Billy | Bonder | 4 | | 1 | Brian | Black | 5 | | 2 | Bran | Balwner | 6 | | 3 | Bryce | Brice | 7 | | 4 | Betty | Btisan | 8 | | 5 | Bruce | Bronson | 8 | +---+------------+-----------+-------+ </code></pre> <p>Then the resulting data frame after performing this operation on <code>data1</code> and <code>data2</code> should look like:</p> <pre><code>result: +---+------------+-----------+-------+ | | first_name | last_name | class | +---+------------+-----------+-------+ | 3 | Alice | Aoni | 4 | | 4 | Andrew | Andrews | 4 | | 5 | Ayoung | Atiches | 5 | | 0 | Billy | Bonder | 4 | | 1 | Brian | Black | 5 | +---+------------+-----------+-------+ </code></pre> <p>Basically, I'm trying to merge the two data sets, and then stack the columns. I can think of a couple ways to do this, but they're all sort of hack-y. I could merge <code>data1</code> and <code>data2</code> and then stack up the columns, or use a map like:</p> <pre><code>map1 = data1['subject_id'].map(lambda x: x in list(data2['subject_id'])) map2 = data2['subject_id'].map(lambda x: x in list(data1['subject_id'])) pd.concat([data1[map1], data2[map2]]) </code></pre> <p>But is there a more elegant solution to this?</p>
<p>How about this?</p> <pre><code>In [335]: cls = np.intersect1d(data1['class'], data2['class']) In [336]: cls Out[336]: array([4, 5], dtype=int64) In [337]: pd.concat([data1.ix[data1['class'].isin(cls)], data2.ix[data2['class'].isin(cls)]]) Out[337]: first_name last_name class 3 Alice Aoni 4 4 Andrew Andrews 4 5 Ayoung Atiches 5 0 Billy Bonder 4 1 Brian Black 5 </code></pre> <p>or:</p> <pre><code>In [338]: data1.ix[data1['class'].isin(cls)].append(data2.ix[data2['class'].isin(cls)]) Out[338]: first_name last_name class 3 Alice Aoni 4 4 Andrew Andrews 4 5 Ayoung Atiches 5 0 Billy Bonder 4 1 Brian Black 5 </code></pre>
Trying to split string with regex <p>I'm trying to split a string in Python using a regex pattern but its not working correctly.</p> <p>Example text:</p> <p><code>"The quick {brown fox} jumped over the {lazy} dog"</code></p> <p>Code:</p> <p><code>"The quick {brown fox} jumped over the {lazy} dog".split(r'({.*?}))</code></p> <p>I'm using a capture group so that the split delimiters are retained in the array.</p> <p>Desired result:</p> <p><code>['The quick', '{brown fox}', 'jumped over the', '{lazy}', 'dog']</code></p> <p>Actual result:</p> <p><code>['The quick {brown fox} jumped over the {lazy} dog']</code></p> <p>As you can see there is clearly not a match as it doesn't split the string. Can anyone let me know where I'm going wrong? Thanks.</p>
<p>You're calling the strings' split method, not re's</p> <pre><code>&gt;&gt;&gt; re.split(r'({.*?})', "The quick {brown fox} jumped over the {lazy} dog") ['The quick ', '{brown fox}', ' jumped over the ', '{lazy}', ' dog'] </code></pre>
Cron to detect low available memory <p>Hello I have a memory leak on my server which I finding it difficult to trace, apparently so is support. They told me I to try and write a cron to detect when my server is low on memory but I have no idea how to do this.</p> <p>I use PHP to build my apps on a VPS server with CentOS6 installed..</p>
<p>Quoting from <a href="https://cookbook.wdt.io/memory.html" rel="nofollow">https://cookbook.wdt.io/memory.html</a>:</p> <blockquote> <p><strong>free</strong> is a standard unix command that displays used and available memory. Used with the options -m it will output the values in megabytes. The last value in the line labeled "-/+ buffers/cache:" shows the total available memory. So we can use grep and awk to get this value and turn it into a number.</p> <p><code>free -m | grep cache: | awk '{ print int($NF) }'</code></p> <p>*/5 * * * * ((`free -m | grep cache: | awk '{ print int($NF) }'` >= 50)) &amp;&amp; curl -sm 30 <a href="http://any_monitoring_url" rel="nofollow">http://any_monitoring_url</a></p> </blockquote> <p>The "curl ... any_monitoring_url" in the above example is pinging an external monitoring system like <a href="https://wdt.io/" rel="nofollow">the one we built (wdt.io)</a> to catch memory leaks and then email / sms / slack you. This step is not strictly necessary. You could do something as simple as <code>touch file_to_check_timestamp</code> or <code>echo "Low Memory!" &gt;&gt; file_to_check_for_low_memory_alerts</code>. The problem is that if memory (or CPU or disk space) get pinned, you could hit <a href="https://en.wikipedia.org/wiki/Deadlock" rel="nofollow">deadlock</a> and the scheduled cron task may not run. Hence the value of a third-party monitor. </p> <p>Also see our articles on cron monitoring <a href="https://cookbook.wdt.io/cpu.html" rel="nofollow">CPU</a> and <a href="https://cookbook.wdt.io/disk_space.html" rel="nofollow">Disk Space</a> and <a href="https://cookbook.wdt.io/" rel="nofollow">other recipes</a>, in case they're of value as well.</p>
Convert all lowercase characters to uppercase and vice-versa <p>I am writing a C program to read characters one-by-one from standard input, convert all upper-case characters to lower-case and all lower-case characters to upper-case, and write the result to standard output. I also want to count how many characters I have read, and how many of those have converted in each direction, and output the totals at the end.</p> <p>eg - Radha Krishna! would become</p> <p>rADHA kRISHNA!</p> <p>Read 15 characters in total, 10 converted to upper-case, 2 to lower-case</p> <p>Here's my code :-</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;ctype.h&gt; int main() { char sentence[100]; int count, ch, i; printf("Enter a sentence \n"); for (i = 0; (sentence[i] = getchar()) != '\n'; i++) { ; } sentence[i] = '\0'; /* shows the number of chars accepted in a sentence */ count = i; for (i = 0; i &lt; count; i++) { ch = islower(sentence[i])? toupper(sentence[i]) : tolower(sentence[i]); putchar(ch); } } </code></pre> <p>It is converting from uppercase to lowercase and vice-versa but i cant figure how to count.</p>
<p>Change the ternary to an if/else clause, and provide counters for each condition.</p> <pre><code>int changedToLower = 0; int changedToUpper = 0; for (i = 0; i &lt; count; i++) { char oldC = sentence[i]; if(islower(sentence[i])) { ch = toupper(sentence[i]) changeToUpper += (ch != oldC)? 1 : 0; } else { ch = tolower(sentence[i]); changeToLower += (ch != oldC)? 1 : 0; } } </code></pre>
Error when clicking AlertDialog to setValue at Firebase database <p>I tried to select an option at AlertDialog but it shows an error. Below is the error:</p> <pre><code>10-17 00:54:44.765 25600-25600/com.example.jingwen.bluetoothlowenergy E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.jingwen.bluetoothlowenergy, PID: 25600 java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255) at java.util.ArrayList.get(ArrayList.java:308) at com.example.jingwen.bluetoothlowenergy.MainActivity$1$1.onClick(MainActivity.java:325) at android.support.v7.app.AlertController$AlertParams$3.onItemClick(AlertController.java:959) at android.widget.AdapterView.performItemClick(AdapterView.java:300) at android.widget.AbsListView.performItemClick(AbsListView.java:1143) at android.widget.AbsListView$PerformClick.run(AbsListView.java:3063) at android.widget.AbsListView$3.run(AbsListView.java:3881) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5237) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707) </code></pre> <p>This is the code where the error occurs, specifically the setValue part to Firebase database : <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>private void alertdialog() { final CharSequence peers[] = new CharSequence[] {"Home", "School", "Children"}; stopScan(); final String uid = firebaseAuth.getCurrentUser().getUid(); if(alert11!=null &amp;&amp; alert11.isShowing()) return; AlertDialog.Builder builder1 = new AlertDialog.Builder(this); builder1.setMessage("Add this device to peer list?"); builder1.setCancelable(true); builder1.setNegativeButton( "Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { AlertDialog.Builder pbuilder = new AlertDialog.Builder(MainActivity.this); pbuilder.setTitle("Set peer as:"); pbuilder.setCancelable(false); pbuilder.setItems(peers, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // the user clicked on option[which] if(which == 0) { databaseRef.child("users").child(uid).child("Peer list").child(mBTDevicesArrayList.get(post).getAddress()).setValue("Home"); Toast.makeText(MainActivity.this,"Set peer as 'Home'",Toast.LENGTH_SHORT).show(); Toast.makeText(MainActivity.this,"Peer list updated!",Toast.LENGTH_SHORT).show(); } if(which == 1) { databaseRef.child("users").child(uid).child("Peer list").child(mBTDevicesArrayList.get(post).getAddress()).setValue("School"); Toast.makeText(MainActivity.this,"Set peer as 'School'",Toast.LENGTH_SHORT).show(); Toast.makeText(MainActivity.this,"Peer list updated!",Toast.LENGTH_SHORT).show(); } if(which == 2) { databaseRef.child("users").child(uid).child("Peer list").child(mBTDevicesArrayList.get(post).getAddress()).setValue("Children"); Toast.makeText(MainActivity.this,"Set peer as 'Children'",Toast.LENGTH_SHORT).show(); Toast.makeText(MainActivity.this,"Peer list updated!",Toast.LENGTH_SHORT).show(); } } }); pbuilder.show(); } });</code></pre> </div> </div> </p> <p>Do tell me if there are more parts of the codes need to be shown.</p>
<p>This likely has nothing to do with Firebase.</p> <p>As far as I can tell, mBTDevicesArrayList (definition and assignment not shown above) is an ArrayList of size zero, and you're passing a value of 1 to its get method,as indicated by the error message "java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0". The line numbers in the stack trace will help you figure out which one of the three instances you're showing.</p>
npm ERR! enoent ENOENT: no such file or directory, open package.json <p>I'm new to Node so bear with me.</p> <p>I have a Node server which requires <code>ws</code> so I install it with:</p> <pre><code>$ npm install ws /private/var/www/html/WebRTC/SVC └─┬ ws@1.1.1 ├── options@0.0.6 └── ultron@1.0.2 npm WARN enoent ENOENT: no such file or directory, open '/private/var/www/html/WebRTC/SVC/package.json' npm WARN SVC No description npm WARN SVC No repository field. npm WARN SVC No README data npm WARN SVC No license field. </code></pre> <p>I then run the server using:</p> <pre><code>$ npm run server.js npm ERR! Darwin 15.6.0 npm ERR! argv "/usr/local/Cellar/node/6.2.2/bin/node" "/usr/local/bin/npm" "run" "server.js" npm ERR! node v6.2.2 npm ERR! npm v3.9.5 npm ERR! path /private/var/www/html/WebRTC/SVC/package.json npm ERR! code ENOENT npm ERR! errno -2 npm ERR! syscall open npm ERR! enoent ENOENT: no such file or directory, open '/private/var/www/html/WebRTC/SVC/package.json' npm ERR! enoent ENOENT: no such file or directory, open '/private/var/www/html/WebRTC/SVC/package.json' npm ERR! enoent This is most likely not a problem with npm itself npm ERR! enoent and is related to npm not being able to find a file. npm ERR! enoent npm ERR! Please include the following file with any support request: npm ERR! /private/var/www/html/WebRTC/SVC/npm-debug.log </code></pre> <p>but am getting errors mentioning no <code>package.json</code>.</p> <p>Looking through <code>npm-debug.log</code> it seems pretty much the same.</p> <p>Can someone shed some light on what <code>enoent</code> is and what sort of <code>package.json</code> file I need.</p> <p>I was expecting this script to run out of the box so a little puzzled.</p>
<p>When you type</p> <pre><code>npm run server.js </code></pre> <p>npm tries to find entry named <code>server.js</code> in the <code>scripts</code> section of your <code>package.json</code> file (see <a href="https://docs.npmjs.com/misc/scripts" rel="nofollow">npm docs on scripts </a> for details).</p> <p><code>package.json</code>, simplified, describes your app's dependencies and environment.</p> <p>As you don't have such file, npm fails with <code>ENOENT</code>, which is an abbreviation for <code>Error NO ENTry</code>. Basically, in your case, you just want to <code>node server.js</code> to run your script.</p>
what is type means <pre><code>STUFF((SELECT distinct ',' + QUOTENAME(c.Error_Code) FROM (SELECT Connection_type, Error_Code, Count FROM (SELECT Connection_Type, error_code, count(*) AS count, row_number() over(partition by Connection_Type order by count(*) desc) as ROWNUM FROM Staging WHERE TransactionDate &gt;= convert(varchar, getdate() -1, 111) AND Status != 'Deliver' GROUP BY Connection_Type, error_code) a WHERE rownum &lt;= 10) c FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') </code></pre> <p>what does "TYPE" means?what is significant of using TYPE</p>
<p>It returns a value typed as XML.</p> <p>A common alternative that does not use this and just returns directly as string is below.</p> <pre><code>SELECT STUFF((SELECT ',' + QUOTENAME(c.Error_Code) FROM (VALUES('FOO &amp; BAR'), ('1 &lt; 4 ') ) c(Error_Code) FOR XML PATH('')), 1, 1, '') </code></pre> <p>But this does not handle XML entitisation correctly and returns </p> <pre><code>[FOO &amp;amp; BAR],[1 &amp;lt; 4 ] </code></pre> <p>Returning the XML datatype and calling <code>.value</code> on it correctly returns </p> <pre><code>[FOO &amp; BAR],[1 &lt; 4 ] </code></pre>
Find Max in List Using the Reduce Function <p>In Torbjörn Lager's 46 python exercises, number 26 is finding the max in a list using the reduce function. I know how to add and multiply using the reduce function but it doesn't make sense to me how you could use it to find the largest number. Does anyone know how to do this?</p>
<p>Write a function that returns the larger of two numbers:</p> <pre><code>def larger(a, b): return a if a &gt; b else b </code></pre> <p>Then use it with <code>reduce</code>:</p> <pre><code>reduce(larger, [1, 2, 3, 4]) </code></pre> <p>Conveniently, Python already has a function like <code>larger</code> that's called <code>max</code>. So this will work:</p> <pre><code>reduce(max, [1, 2, 3, 4]) </code></pre> <p>Of course <code>max</code> will do the whole kaboodle for you without <code>reduce</code>:</p> <pre><code>max([1, 2, 3, 4]) </code></pre> <p>And that's what you'd actually use if you weren't learning to work with <code>reduce</code>. It doesn't use <code>reduce</code> under the hood, though; that's actually a rather inefficient way to do the job.</p>
Call a function continuously after key is pressed in C <p>I want to be able to call my function that moves my propellers (OpenGL work) after I press the 'a' key. Here's what I have set up:</p> <pre><code>switch (key) { case 'a': startShip = 1; while (1 (&amp;&amp; startShip == 1)) { spinPropeller(); } } </code></pre> <p>I get caught in an infinite loop. I've tried using a timer function but I'm not sure how to implement it properly. I want my propellers to spin and not stop until the program is closed.</p> <p>edit: program should close after detecting a 'q' key</p>
<p>Game loops work like this:</p> <pre><code>while (true) { get_input(); // get keyboard, mouse, and joystick input move_items(); // update the player position and all other items in the game, fire weapons, and update game state collision_detection(); // figure out what hit what and update game state render(); // draw your OpenGL scene } </code></pre> <p>To make this happen, your get_input function or equivalent needs to read keyboard state in a non-blocking manner. I think OpenGL or GLUT has a helper function for this, but the implementation will likely be platform specific.</p>
Jekyll syntax highlighting with data variable <p>I'm working on a Jekyll page that shows a list of items with their <em>markdownified-syntax highlighted</em> code. I've a data file with content like this</p> <pre><code># myitems.yaml id: 'someID' updated: 'someDate' items: - item: id: "0001" content: " *This is italicized*, and so is _this_. **This is bold**, and so is __this__. &amp; Use ***italics and bold together*** if you ___have to___. ``` html &lt;script&gt;alert() some content&lt;/script&gt; &lt;p&gt;paragraph&lt;/p&gt; ```" - item: id: "0002" content: "some more content" </code></pre> <p>So the <code>items[].content</code> has markdown+some code to be syntax highlighted.</p> <p>I'm accessing this data in my <code>items.html</code> with liquid as</p> <pre><code>&lt;ul&gt; {% for item in site.data.myitems.items %} &lt;li id="{{item.id}}"&gt; &lt;div&gt;{{ item.content | strip | markdownify}}&lt;/div&gt; &lt;/li&gt; {% endfor %} &lt;/ul&gt; </code></pre> <p>I'm using rouge syntax highlighting. The markdown is parsed properly to html but the html syntax highlighting is not working in the <code>items.html</code> part. Syntax highlighting works properly in post body but not in <code>{% include items.html %}</code></p> <p>The <code>items</code> output i get is: <a href="https://i.stack.imgur.com/5W8OI.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/5W8OI.jpg" alt="output image"></a></p> <pre><code>&lt;em&gt;This is italicized&lt;/em&gt;, and so is &lt;em&gt;this&lt;/em&gt;. &lt;strong&gt;This is bold&lt;/strong&gt;, and so is &lt;strong&gt;this&lt;/strong&gt;. &amp;amp; Use &lt;strong&gt;&lt;em&gt;italics and bold together&lt;/em&gt;&lt;/strong&gt; if you &lt;strong&gt;&lt;em&gt;have to&lt;/em&gt;&lt;/strong&gt;. &lt;code class="highlighter-rouge"&gt;html &amp;lt;script&amp;gt;alert() some content&amp;lt;/script&amp;gt; &amp;lt;p&amp;gt;paragraph&amp;lt;/p&amp;gt;&lt;/code&gt; </code></pre> <p>Any help please?</p>
<p>solved by using the pipe instead of regular string quotes. </p> <pre><code>-item: id:"0001" content: | *This is italicized*, and so is _this_. **This is bold**, and so is __this__. &amp; Use ***italics and bold together*** if you ___have to___. ``` html &lt;script&gt;alert() some content&lt;/script&gt; &lt;p&gt;paragraph&lt;/p&gt; ``` </code></pre>
SQL query that removes a row of data based on 2 columns <p>I have a common table expression query that returns this set of data:</p> <pre><code>Board_Name Method Source TicketCount Percentage IT Services NULL NULL 73 0.7 IT Services Call Call 6929 69.7 IT Services Call CallByReception 4303 43.3 IT Services Call CallBySupport 2626 37.9 IT Services Chat Chat 8 0.1 IT Services EmailConnector EmailConnector 2047 20.6 IT Services Internal Internal 51 0.5 IT Services Portal Portal 829 8.3 </code></pre> <p>In a <code>SELECT</code> statement, I would like to return all of the rows in the above result <strong>EXCEPT</strong> the rows that has the Method value equal to 'Call' and the Source value equal to 'Call'.</p> <p>So the result of the query will be this:</p> <pre><code>Board_Name Method Source TicketCount Percentage IT Services NULL NULL 73 0.7 IT Services Call CallByReception 4303 43.3 IT Services Call CallBySupport 2626 37.9 IT Services Chat Chat 8 0.1 IT Services EmailConnector EmailConnector 2047 20.6 IT Services Internal Internal 51 0.5 IT Services Portal Portal 829 8.3 </code></pre> <p><code>;WITH CTE AS (--select statement returns the above result --details are not important ) SELECT * FROM CTE WHERE --I need to include all of the rows except the row that has the Method and Source columns are equal to 'Call'</code></p> <p>How can I construct the <code>where</code> clause to not include the one row?</p>
<p>One way would be (<a href="http://rextester.com/VGJ55852" rel="nofollow">Demo</a>)</p> <pre><code> WHERE NOT 'Call' = ALL(SELECT ISNULL(Method,'') UNION SELECT ISNULL(Source,'')) </code></pre> <p>Or along similar lines (<a href="http://rextester.com/XTW38001" rel="nofollow">Demo</a>)...</p> <pre><code>WHERE 'Call' &lt;&gt; ANY(SELECT ISNULL(MS,'') FROM (VALUES (Method),(Source)) V(MS)) </code></pre> <p>Or - <a href="http://rextester.com/FOTW78120" rel="nofollow">Demo</a></p> <pre><code>WHERE NOT EXISTS (SELECT 'Call' INTERSECT SELECT Method INTERSECT SELECT Source) </code></pre>
get data from a column then select whole row where the data belongs <p>for example this is my <code>JTable</code>:</p> <blockquote> <p>ID|NAME|AGE</p> <p>001|anna|18</p> <p>002|tony|25</p> </blockquote> <p>now i want that the user will enter the ID, then convert that ID into which row it belongs. now i'm using <code>setRowSelectionInterval()</code> to select the row without really selecting it in the actual row. but i don't know how to get the data from a column, then convert it into a row where it belongs, so i can put in in the <code>setRowSelectionInterval()</code>. thank you for any of your help :)</p>
<p>Write a loop.</p> <ol> <li><p>You can use the <code>getRowCount()</code> method of the table to iterate through each row. </p></li> <li><p>Then you use the <code>getValueAt(...)</code> method to get the value of the ID in the row for the specific column. </p></li> <li><p>When you find a match you use the row index for the <code>setRowSelectionInterval(...)</code> method.</p></li> </ol>
Mirror grouped bars across the x-axis <p>This is cross-posted from the rstats subreddit. I have seen mirrored bars or grouped bars, but not mirrored AND grouped bars. The closest I have gotten is using "stacked," but it doesn't seem to work across the x-axis for negative values, while "dodge" offsets related bars that should be aligned: </p> <p>Example graph:</p> <p><a href="https://i.stack.imgur.com/gJ2IC.png" rel="nofollow"><img src="https://i.stack.imgur.com/gJ2IC.png" alt="enter image description here"></a></p> <p>I need the green and purple bars underneath the pink and blue bars, respectively. Does anyone know if this is possible with this library? Here is what I have been using:</p> <pre><code>Input = " treatment group mean sd T-Above 10 9 0.6414207 T-Above 20 3 0.2940872 T-Above 30 2 0.7539211 T-Above 40 1 0.5011464 T-Above 50 7 0.3358966 T-Below 10 -4 0.3155503 T-Below 20 -8 0.4169761 T-Below 30 -2 0.6381697 T-Below 40 -8 0.7360393 T-Below 50 -1 0.4352037 R-Above 10 30 12.375440 R-Above 20 32 7.122308 R-Above 30 27 5.113855 R-Above 40 22 4.141439 R-Above 50 26 4.145096 R-Below 10 -8 0.5532685 R-Below 20 -5 0.3195736 R-Below 30 -6 0.2738115 R-Below 40 -2 0.3338844 R-Below 50 -4 0.1860820" Data = read.table(textConnection(Input),header=TRUE) limits &lt;- aes(ymax = Data$mean + Data$sd, ymin = Data$mean - Data$sd) p &lt;- ggplot(data = Data, aes(x = factor(group), y = mean, fill = treatment)) Pgraph &lt;- p + geom_bar(stat = "identity", position = position_dodge(0.9),color="#000000") + geom_errorbar(limits, position = position_dodge(0.9), width = 0.25) + labs(x = "x", y = "y") + ggtitle("") + scale_fill_discrete(name = "Treatment") Pgraph + theme( panel.grid.major=element_blank(), panel.grid.minor=element_blank(), panel.background=element_rect(fill="white"), panel.border=element_rect(fill=NA,color="black")) </code></pre> <p>I apologize if I overlooked an existing answer here.</p>
<p>How about this?</p> <pre><code>library(ggplot2) library(tidyr) limits &lt;- aes(ymax = Data$mean + Data$sd, ymin = Data$mean - Data$sd) Data %&gt;% separate(treatment, c("Type", "Pos")) %&gt;% ggplot(aes(x = factor(group), y = mean, group = Type, fill = interaction(Pos, Type))) + geom_bar(stat = "identity", position = position_dodge(0.9), color="#000000") + geom_errorbar(limits, position = position_dodge(0.9), width = 0.25) + labs(x = "x", y = "y") + ggtitle("") + scale_fill_discrete(name = "Treatment", labels = c("R-Above","R-Below", "T-Above", "T-Below")) + theme(panel.grid.major=element_blank(), panel.grid.minor=element_blank(), panel.background=element_rect(fill="white"), panel.border=element_rect(fill=NA,color="black")) </code></pre> <p><a href="https://i.stack.imgur.com/mzqXv.png" rel="nofollow"><img src="https://i.stack.imgur.com/mzqXv.png" alt="enter image description here"></a></p>
Image is not displayed on wp_get_attachment_image_src, instead it returns an array <p>Hi i have a wordpress site and i am trying to display image using <strong>wp_get_attachment_image_src</strong> but it returns only array</p> <p>Below what i have tried with myself</p> <pre><code>`$get_story_image_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ), "size" );` if ( $get_story_image_src ) : ?&gt; &lt;img src="&lt;?php echo $get_story_image_src ; ?&gt;" alt="story_image" /&gt; &lt;?php endif; ?&gt; </code></pre>
<p>Its correct <strong>wp_get_attachment_image_src</strong> always returns array .</p> <p>if you want to display image using this function you need to pass array indexes in the image tag .</p> <p>Try below code :</p> <pre><code>`$get_story_image_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ), "size" );` if ( $get_story_image_src ) : ?&gt; &lt;img src="&lt;?php echo $get_story_image_src[0]; width="&lt;?php echo $get_story_image_src[1]; ?&gt;" height="&lt;?php echo $get_story_image_src[2]; ?&gt;" ?&gt;" alt="story_image" /&gt; &lt;?php endif; ?&gt; </code></pre> <p>Also its good if you read all the parameters of the functions before you used</p> <p>Refer this link - <a href="https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/" rel="nofollow">https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/</a></p>
How to get value of array by using the key from a string <p>I have an array with some keys and I want to get the array values according to the array keys where the keys are in a string.</p> <p>Example:</p> <pre><code>$arr = array( "COV" =&gt; "Comilla Victorians", "RK" =&gt; "Rajshaji Kings" ); $str = "COV-RK"; </code></pre> <p>Now I want to show <code>Comilla Victorians VS Rajshaji Kings</code>.</p> <p>I can do it using some custom looping, But I need some smart coding here and looks your attention. I think there are some ways to make it with array functions that I don't know.</p>
<p>You could try this:-</p> <pre><code>&lt;?php $arr = array( "COV" =&gt; "Comilla Victorians", "RK" =&gt; "Rajshaji Kings" ); $str = "COV-RK"; $values = explode("-", $str); // explode string to get keys actually echo $arr[$values[0]] . " VS " . $arr[$values[1]]; // print desired output </code></pre>
Javascript fill array with intermediate value <p>I'm trying to fill an array with missing intermediate data</p> <p>My data input is like this</p> <blockquote> <p>var data = [[5.23,7],[5.28,7],[5.32,8],[5.35,8]];</p> </blockquote> <p>I wanna fill the array with missing value but I need to respect this rule:</p> <ol> <li>The 1st value on 2d array must be the next sequence number, so 5.23 ... 5.24 ... 5.25 ...</li> <li>The 2nd value on 2d array must be the same element from the i+1 value</li> </ol> <p>So the results in this case would be</p> <blockquote> <p>var data = [[5.23,7],[5.24,7],[5.25,7],[5.26,7],[5.27,7],[5.28,7],[5.29,8],[5.30,8],[5.31,8],[5.32,8],[5.33,8],[5.34,8],[5.35,8]];</p> </blockquote> <p>This little piece of code works, but I don't know how to put in loop and how to write a while loop that pass every time the new length of the array</p> <p>var data = [[5.23,7],[5.28,7],[5.32,8],[5.35,8]];</p> <pre><code>if (data[1][0]-data[0][0] &gt; 0.01) { data.push([data[0][0]+0.01,data[1][1]]); data.sort(function (a, b) { return a[0] - b[0]; }); } else { check the next element } </code></pre> <p>console.log(data);</p> <p>Any idea?</p>
<p><code>Array.prototype.reduce()</code> is sometimes handy to extend the array. May be you can do as follows;</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var data = [[5.23,7],[5.28,7],[5.32,8],[5.35,8]], newData = data.reduce((p,c,i,a) =&gt; i ? p.concat(Array(Math.round(c[0]*100 - a[i-1][0]*100)).fill() .map((_,j) =&gt; [Number((a[i-1][0]+(j+1)/100).toFixed(2)),c[1]])) : [c],[]); console.log(newData); var data = [[1.01,3],[1.04,4],[1.09,5],[1.10,6],[1.15,7]], newData = data.reduce((p,c,i,a) =&gt; i ? p.concat(Array(Math.round(c[0]*100 - a[i-1][0]*100)).fill() .map((_,j) =&gt; [Number((a[i-1][0]+(j+1)/100).toFixed(2)),c[1]])) : [c],[]); console.log(newData);</code></pre> </div> </div> </p>