id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
βŒ€
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
βŒ€
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
βŒ€
last_editor_display_name
stringlengths
2
29
βŒ€
last_editor_user_id
int64
-1
20M
βŒ€
owner_display_name
stringlengths
1
29
βŒ€
owner_user_id
int64
1
20M
βŒ€
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
10,239,771
C Beginner: How to search for particular words in a file (line by line) in C
<p>I need to search for two particular words in a file line by line and if they exist, print "Found!".</p> <p>This is file.txt (has four columns)</p> <pre><code>bill gates 62bill microsoft beyonce knowles 300mill entertainment my name -$9000 student </code></pre> <p>The following is the idea I had but it doesn't seem to work</p> <pre><code>char firstname[]; char lastname[]; char string_0[256]; file = fopen("file.txt","r+"); while((fgets(string_0,256,file)) != NULL) { //scans the line then sets 1st and 2nd word to those variables fscanf(file,"%s %s",&amp;firstname, &amp;lastname); if(strcmp(firstname,"beyonce")==0 &amp;&amp; strcmp(lastname,"knowles")==0){ printf("A match has been found"); } } fclose(file); </code></pre> <p>Please help. Could it be that the pointer is not moving to the next line in the while loop? And if so, how can i fix?</p>
10,239,781
2
2
null
2012-04-20 03:17:21.363 UTC
1
2018-03-19 06:43:48.967 UTC
2012-04-20 08:58:48.103 UTC
null
823,955
null
1,290,768
null
1
5
c|file|while-loop|strcmp
44,463
<p>Instead of calling <code>fscanf</code> on the <code>file</code> after you've already read from it with <code>fgets</code>, you should be calling <code>sscanf</code> on the <code>string_0</code> variable that you are copying the data to in your <code>fgets</code> call.</p>
9,854,411
What goes to RAM, Harddrive, Stack and Heap in C++?
<p>Could someone tell in general what goes to what (Harddrive,RAM, Stack or Heap) at runtime in C++ for these instances : </p> <ul> <li><p>Local/global variables </p></li> <li><p>Classes, Methods and functions</p></li> <li><p>Pointers</p></li> <li><p>Objects</p></li> </ul> <p>And is Stack/Heap both located in physical RAM?</p> <p>I would appreciate if someone could include hardware analogy in the answer. Thanks.</p>
9,854,420
3
4
null
2012-03-24 18:38:08.763 UTC
10
2021-06-20 18:42:47.577 UTC
2021-06-20 18:42:47.577 UTC
null
5,459,839
null
1,261,773
null
1
12
c++|memory|heap-memory|stack-memory
15,069
<p>This is generally <strong>dependent on OS</strong>, but it's generally like so:</p> <p>Everything goes to RAM. The binary resides in the hard-drive, but, when ran, is fully loaded, along with dependent libraries, into RAM.</p> <p>Stack and heap are implementation details, but they also reside in the RAM.</p> <p>Although loaded in RAM, the memory is not directly addressable. The operating system allocates virtual memory for each process. This means that the address <code>0x001</code> is not actually located at <code>0x001</code> in the RAM, but represents an address in virtual address space.</p> <p>EDIT: Clarification to one of op's comments:</p> <p>Are binaries fully or partially loaded at runtime? And, are those binaries only accessed once at runtime or continuisly being read from Harddrive?</p> <p>For example, in MS, if you link against a library, it will be fully loaded at runtime, at the start of the program. If you load it programatically, via <code>LoadLibrary()</code>, it is loaded into memory at the function call, and can be unloaded from memory.</p>
9,820,679
Difference between ScrollView and ListView
<p>Can any one explain the difference between Scroll View and List View? When to use which one? And which one is more efficient?</p>
9,820,809
6
0
null
2012-03-22 10:43:14.557 UTC
17
2016-12-17 10:37:32.777 UTC
2014-12-08 16:44:08.167 UTC
null
2,306,173
null
1,275,683
null
1
43
android|android-listview|android-scrollview
31,482
<p><strong>ScrollView</strong> is used to put different or same child views or layouts and the all can be scrolled.</p> <p><strong>ListView</strong> is used to put same child view or layout as multiple items. All these items are also scrollable.</p> <p>Simply ScrollView is for both homogeneous and heterogeneous collection. ListView is for only homogeneous collection.</p>
8,305,120
Use both Account and User tables with Devise
<p>I'm working with Rails 3.1.0 and Devise 1.4.8, and am new to both.</p> <p>I want to allow multiple users for an account. The first user to sign up creates the account (probably for their company), then that user can add more users. A user is always linked to exactly one account.</p> <p>I have Users and Accounts tables. Abbreviated models:</p> <pre><code>class User &lt; ActiveRecord::Base belongs_to :account devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :lockable, :timeoutable attr_accessible :email, :password, :password_confirmation, :remember_me end class Account &lt; ActiveRecord::Base has_many :users, :dependent =&gt; :destroy attr_accessible :name, :account_type end </code></pre> <p>The question is, when the first user signs up, how do I create both the Account and User?</p> <ul> <li><p>Do I need to modify/override the Devise registrations_controller, something like the answer <a href="https://stackoverflow.com/questions/4655114/custom-devise-controller">here</a>? I couldn't figure out how to create the Account then pass it to Devise for creating the User.</p></li> <li><p>account_id is already in the User model. Should I add account_name and account_type to the User model, and create a new the Account record if account_id is not passed in? In this case, I'm trying to hide Account creation from Devise, but not sure that will work since I still need to prompt for account_name and account_type on the registration page.</p></li> </ul>
8,529,340
3
0
null
2011-11-29 02:29:32.523 UTC
21
2017-01-22 11:21:10.32 UTC
2017-05-23 11:33:15.757 UTC
null
-1
null
550,712
null
1
19
ruby-on-rails|ruby-on-rails-3|authentication|devise
6,198
<p>Finally got this to work using nested attributes. As discussed in the comments on Kenton's answer, that example is reversed. If you want multiple users per account, you have to create the Account first, then the User--even if you only create one user to start with. Then you write your own Accounts controller and view, bypassing the Devise view. The Devise functionality for sending confirmation emails etc. still seems to work if you just create a user directly, i.e. that functionality must be part of automagical stuff in the Devise <em>model</em>; it doesn't require using the Devise controller.</p> <p>Excerpts from the relevant files:</p> <p><strong>Models</strong> in app/models</p> <pre><code>class Account &lt; ActiveRecord::Base has_many :users, :inverse_of =&gt; :account, :dependent =&gt; :destroy accepts_nested_attributes_for :users attr_accessible :name, :users_attributes end class User &lt; ActiveRecord::Base belongs_to :account, :inverse_of =&gt; :users validates :account, :presence =&gt; true devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :lockable, :timeoutable attr_accessible :email, :password, :password_confirmation, :remember_me end </code></pre> <p><strong>spec/models/account_spec.rb</strong> RSpec model test</p> <pre><code>it "should create account AND user through accepts_nested_attributes_for" do @AccountWithUser = { :name =&gt; "Test Account with User", :users_attributes =&gt; [ { :email =&gt; "[email protected]", :password =&gt; "testpass", :password_confirmation =&gt; "testpass" } ] } au = Account.create!(@AccountWithUser) au.id.should_not be_nil au.users[0].id.should_not be_nil au.users[0].account.should == au au.users[0].account_id.should == au.id end </code></pre> <p><strong>config/routes.rb</strong></p> <pre><code> resources :accounts, :only =&gt; [:index, :new, :create, :destroy] </code></pre> <p><strong>controllers/accounts_controller.rb</strong></p> <pre><code>class AccountsController &lt; ApplicationController def new @account = Account.new @account.users.build # build a blank user or the child form won't display end def create @account = Account.new(params[:account]) if @account.save flash[:success] = "Account created" redirect_to accounts_path else render 'new' end end end </code></pre> <p><strong>views/accounts/new.html.erb</strong> view</p> <pre><code>&lt;h2&gt;Create Account&lt;/h2&gt; &lt;%= form_for(@account) do |f| %&gt; &lt;%= render 'shared/error_messages', :object =&gt; f.object %&gt; &lt;div class="field"&gt; &lt;%= f.label :name %&gt;&lt;br /&gt; &lt;%= f.text_field :name %&gt; &lt;/div&gt; &lt;%= f.fields_for :users do |user_form| %&gt; &lt;div class="field"&gt;&lt;%= user_form.label :email %&gt;&lt;br /&gt; &lt;%= user_form.email_field :email %&gt;&lt;/div&gt; &lt;div class="field"&gt;&lt;%= user_form.label :password %&gt;&lt;br /&gt; &lt;%= user_form.password_field :password %&gt;&lt;/div&gt; &lt;div class="field"&gt;&lt;%= user_form.label :password_confirmation %&gt;&lt;br /&gt; &lt;%= user_form.password_field :password_confirmation %&gt;&lt;/div&gt; &lt;% end %&gt; &lt;div class="actions"&gt; &lt;%= f.submit "Create account" %&gt; &lt;/div&gt; &lt;% end %&gt; </code></pre> <p>Rails is quite picky about plural vs. singular. Since we say Account has_many Users:</p> <ul> <li>it expects users_attributes (not user_attributes) in the model and tests</li> <li>it expects an <em>array of</em> hashes for the test, even if there is only one element in the array, hence the [] around the {user attributes}.</li> <li>it expects @account.users.build in the controller. I was not able to get the f.object.build_users syntax to work directly in the view.</li> </ul>
11,488,616
Why is max length of C string literal different from max char[]?
<p><strong>Clarification</strong>: Given that a string literal can be rewritten as a <code>const char[]</code> (see below), imposing a lower max length on literals than on <code>char[]</code>s is just a syntactic inconvenience. Why does the C standard encourage this?</p> <hr> <p>The C89 standard has a translation limit for string literals:</p> <blockquote> <p>509 characters in a character string literal or wide string literal (after concatenation)</p> </blockquote> <p>There isn't a limit for a char arrays; perhaps</p> <blockquote> <p>32767 bytes in an object (in a hosted environment only)</p> </blockquote> <p>applies (I'm not sure what object or hosted environment means), but at any rate it's a much higher limit.</p> <p>My understanding is that a string literal is equivalent to char array containing characters, ie: it's always possible to rewrite something like this:</p> <pre><code>const char* str = "foo"; </code></pre> <p>into this</p> <pre><code>static const char __THE_LITERAL[] = { 'f', 'o', 'o', '\0' }; const char* str = __THE_LITERAL; </code></pre> <p>So why such a hard limit on literals?</p>
11,488,687
3
4
null
2012-07-15 01:10:39.54 UTC
3
2015-05-24 03:13:31.35 UTC
2013-01-18 15:13:46.66 UTC
null
319,698
null
319,698
null
1
20
c|standards
42,886
<p>The limit on string literals is a compile-time requirement; there's a similar limit on the length of a logical source line. A compiler might use a fixed-size data structure to hold source lines and string literals.</p> <p>(C99 increases these particular limits from 509 to 4095 characters.)</p> <p>On the other hand, an object (such as an array of <code>char</code>) can be built at run time. The limits are likely imposed by the target machine architecture, not by the design of the compiler.</p> <p>Note that these are <em>not</em> upper bounds imposed on programs. A compiler is not required to impose any finite limits at all. If a compiler does impose a limit on line length, it must be at least 509 or 4095 characters. (Most actual compilers, I think, don't impose fixed limits; rather they allocate memory dynamically.)</p>
12,031,618
How to make a page unscrollable?
<p>I have a page I'm working on that encompasses a vertical drop-down menu. However, when the menu drops down, it pushes the text below it downwards and off the page. This is expected, but this enables the scroll bar on the side of the page. I was wondering it there was a way to get rid of this. In other words, it shouldn't just not scroll, but never even offer the option to scroll.</p> <p>Thanks!</p>
12,031,635
2
0
null
2012-08-20 02:20:09.193 UTC
1
2018-08-09 16:52:59.62 UTC
2012-12-23 21:45:11.057 UTC
null
1,493,707
null
1,596,801
null
1
21
html|css|scroll
49,157
<p>If you want no scrollbar to appear and no scrolling whatsoever to occur, in the CSS for the <code>div</code> in which you contain said dropdown use</p> <pre><code>overflow: hidden; </code></pre> <p>This will cut off any 'additional content' though; see an example <a href="http://www.w3schools.com/cssref/tryit.asp?filename=trycss_overflow" rel="noreferrer">here</a></p>
3,693,397
Howto get rid of <mvc:annotation-driven />?
<p>Up to now, <code>&lt;mvc:annotation-driven /&gt;</code> has caused plenty of trouble for me, so I would like to get rid of it. Although the <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-config" rel="noreferrer">spring framework docs clearly say what it is supposed to be doing</a>, a listing of tags actually summar <code>&lt;mvc:annotation-driven /&gt;</code> is lacking.</p> <p>So I'm stuck with removing <code>&lt;mvc:annotation-driven /&gt;</code> and now getting the error</p> <blockquote> <p>WARN o.s.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/webapp/trainees] in DispatcherServlet with name 'workoutsensor'</p> </blockquote> <p>for all Urls supposed to be resolved by the controller classes (in this case: <code>./trainees</code>). Any suggestion where I can read more about <code>&lt;mvc:annotation-driven /&gt;</code>? I desperately would like to know what tags exactly are represented by <code>&lt;mvc:annotation-driven /&gt;</code>.</p>
3,694,059
4
0
null
2010-09-12 01:36:11.62 UTC
14
2013-12-23 12:25:10.823 UTC
2010-09-12 11:06:27.48 UTC
null
268,098
null
268,098
null
1
15
java|spring|servlets|spring-mvc
21,231
<p>You can use <code>BeanPostProcessor</code> to customize each bean defined by <code>&lt;mvc:annotation-driven /&gt;</code>. The javadocs now details all beans the tag registers.</p> <p>If you really want to get rid of it, you can look at the source code of <a href="https://fisheye.springsource.org/browse/spring-framework/spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java?hb=true" rel="noreferrer"><code>org.springframework.web.servlet.config.AnnotationDrivenBeanDefinitionParser</code></a></p> <p>And you can see which beans it is defining. I've done this 'exercise' (not for all of them, but for those I need), so here are they:</p> <pre><code>&lt;bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" /&gt; &lt;bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" /&gt; &lt;bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&gt; &lt;property name="webBindingInitializer"&gt; &lt;bean class="com.yourpackage.web.util.CommonWebBindingInitializer" /&gt; &lt;/property&gt; &lt;property name="messageConverters"&gt; &lt;list&gt; &lt;bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" /&gt; &lt;bean class="org.springframework.http.converter.ResourceHttpMessageConverter" /&gt; &lt;bean class="org.springframework.http.converter.StringHttpMessageConverter" /&gt; &lt;bean class="org.springframework.http.converter.feed.AtomFeedHttpMessageConverter" /&gt; &lt;bean class="org.springframework.http.converter.feed.RssChannelHttpMessageConverter" /&gt; &lt;bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /&gt; &lt;bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter" /&gt; &lt;bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" /&gt; &lt;!-- bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" /--&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"&gt; </code></pre> <p>Now, above you see the <code>CommonWebBindingInitializer</code>. You have to create this class, in order to use conversion and validation:</p> <pre><code>public class CommonWebBindingInitializer implements WebBindingInitializer { @Autowired private Validator validator; @Autowired private ConversionService conversionService; @Override public void initBinder(WebDataBinder binder, WebRequest request) { binder.setValidator(validator); binder.setConversionService(conversionService); } } </code></pre> <p>And this works fine for me so far. Feel free to report any problems with it.</p>
3,325,546
How to color a pixel?
<p>I have to create a simple 2D animation without using various primitives for drawing line, circle etc for the purpose. It has to be done by manipulating pixels and implementing one of the algorithms for drawing line, circle etc by coloring pixels.</p> <p>I thought of using Turbo C for the purpose, but I use ubuntu. So I tried using dosbox to install and run turbo C but to no avail. </p> <p>Now my only option is Java. Is it possible to manipulate pixels in Java? I couldn't find myself any good tutorials for the same. It would be great if a sample code for the same can be given.</p>
3,325,623
4
2
null
2010-07-24 14:57:07.19 UTC
5
2021-04-27 20:26:21.72 UTC
2010-07-24 15:04:09.137 UTC
null
383,439
null
383,439
null
1
16
java|graphics|pixel
66,313
<p>The class <a href="https://docs.oracle.com/javase/8/docs/api/java/awt/image/BufferedImage.html" rel="noreferrer"><code>java.awt.BufferedImage</code></a> has a method <code>setRGB(int x, int y, int rgb)</code> which sets the color of an individual pixel. Additionally, you might want to look at <a href="https://docs.oracle.com/javase/8/docs/api/java/awt/Color.html" rel="noreferrer"><code>java.awt.Color</code></a>, especially its <code>getRGB()</code> method, which can convert Colors into integers that you can put into the <code>int rgb</code> parameter of <code>setRGB</code>.</p>
3,329,675
Is there any way to use inline styles to define a:visited link style?
<p>So instead doing it using css:</p> <pre><code>&lt;style type="text/css"&gt; a:visited { color: red; } &lt;/style&gt; </code></pre> <p>Could it be done using inline code. Something like this doesn't work:</p> <pre><code>&lt;a href="http://google.com" style='a:visited:color:red'&gt;Google.com&lt;/a&gt; </code></pre>
3,329,702
6
6
null
2010-07-25 15:05:24.333 UTC
1
2017-09-20 20:57:05.81 UTC
null
null
null
null
401,350
null
1
30
html|css
24,453
<p>You can't do this, the specification (CSS2 here) <a href="http://www.w3.org/TR/CSS2/selector.html#pseudo-elements" rel="noreferrer">covers it briefly here</a>:</p> <blockquote> <p>Neither pseudo-elements nor pseudo-classes appear in the document source or document tree.</p> </blockquote> <p><code>:visited</code> along with the others modifiers are all pseudo-classes, and there was never a standard syntax setup to do what you're trying. Honestly this is the first time I've ever seen it requested, so I don't think it'll be added to the specification anytime soon...sorry that answer sucks, but it is what it is :)</p>
3,467,850
Cross compiling a kernel module
<p>I'm trying to cross compile a helloworld kernel (2.6.x) module for ARM architecture on my intel x86 host.</p> <p>The codesourcery tool chain for ARM is located at: <em>/home/ravi/workspace/hawk/arm-2009q3</em></p> <p>The kernel source is located at :<em>/home/ravi/workspace/hawk/linux-omapl1</em></p> <p>My Makefile:</p> <pre><code>ARCH=arm CROSS_COMPILE=arm-none-linux-gnueabi obj-m := Hello.o KDIR := /home/ravi/workspace/hawk/linux-omapl1 PWD := $(shell pwd) default: $(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules clean: $(MAKE) -C $(KDIR) SUBDIRS=$(PWD) clean </code></pre> <p>When i run <em>make</em>, the .ko produced is that of my host machine which means the makefile is invoking the native compiler instead of the cross compiler.What am I doing wrong? The cross compiler's binaries are in my path.</p>
3,471,679
6
1
null
2010-08-12 12:56:59.34 UTC
15
2017-07-15 18:04:26.703 UTC
2010-08-27 22:08:02.453 UTC
null
17,389
null
319,063
null
1
33
makefile|cross-compiling|embedded-linux|kernel-module|linux-toolchain
81,946
<p>Putting <code>ARCH</code> and <code>CROSS_COMPILE</code> in the Makefile doesn't work. You need to put them on the command line:</p> <pre><code>make ARCH=arm CROSS_COMPILE=arm-none-linux-gnueabi- </code></pre>
3,895,124
SEO title vs alt vs text
<p>Does the title attribute in a link do the job of the real text in the link for SEO? i.e</p> <pre><code>&lt;a href="..." title="Web Design"&gt;Web Design&lt;/a&gt; </code></pre> <p>is it the same as:</p> <pre><code>&lt;a href="..." title="Web Design"&gt;click here&lt;/a&gt; </code></pre> <p>when trying to get a good page rank for keywords like "web design"? is it like alt attribute in an image tag? or is it useless in SEO?</p> <p>is it the same as:</p> <pre><code>&lt;a href="..." alt="Web Design"&gt;click here&lt;/a&gt; </code></pre> <p>what's the difference between all the above?</p> <p>Thank you in advance!</p>
3,895,141
6
1
null
2010-10-09 00:14:10.757 UTC
7
2016-10-29 13:33:25.69 UTC
2010-10-09 00:21:31.22 UTC
null
106,224
null
468,017
null
1
36
html|seo|title|alt
51,018
<p>Alt is not a valid attribute for <code>&lt;a&gt;</code> elements.</p> <ul> <li>Use alt to describe images</li> <li>Use title to describe where the link is going.</li> <li>The textvalue (click here) is the most important part The title attribute gets more and more ignored. Google looks far more on the link text than the title attribute. For google the title tag is like a meta tag which is not important compared to content. </li> <li>Image alt tags are however still very important (especially for image search)</li> <li>The main feature of those tags is to provide usability for your users, not to feed informatino to search engines.</li> </ul>
3,884,829
Ruby: How to group a Ruby array?
<p>I have a Ruby array</p> <pre><code>&gt; list = Request.find_all_by_artist("Metallica").map(&amp;:song) =&gt; ["Nothing else Matters", "Enter sandman", "Enter Sandman", "Master of Puppets", "Master of Puppets", "Master of Puppets"] </code></pre> <p>and I want a list with the counts like this:</p> <pre><code>{"Nothing Else Matters" =&gt; 1, "Enter Sandman" =&gt; 2, "Master of Puppets" =&gt; 3} </code></pre> <p>So ideally I want a hash that will give me the count and notice how I have <code>Enter Sandman</code> and <code>enter sandman</code> so I need it case insensitive. I am pretty sure I can loop through it but is there a cleaner way?</p>
3,884,878
6
0
null
2010-10-07 18:48:55.64 UTC
7
2020-02-21 20:57:42.013 UTC
2016-12-27 09:27:01.407 UTC
null
3,873,012
null
223,367
null
1
53
ruby-on-rails|ruby
65,171
<pre><code>list.group_by(&amp;:capitalize).map {|k,v| [k, v.length]} #=&gt; [["Master of puppets", 3], ["Enter sandman", 2], ["Nothing else matters", 1]] </code></pre> <p>The group by creates a hash from the <code>capitalize</code>d version of an album name to an array containing all the strings in <code>list</code> that match it (e.g. <code>"Enter sandman" =&gt; ["Enter Sandman", "Enter sandman"]</code>). The <code>map</code> then replaces each array with its length, so you get e.g. <code>["Enter sandman", 2]</code> for <code>"Enter sandman"</code>.</p> <p>If you need the result to be a hash, you can call <code>to_h</code> on the result or wrap a <code>Hash[ ]</code> around it.</p>
3,557,260
Should I use pt or px?
<p>What is the difference between <code>pt</code> and <code>px</code> in CSS? Which one should I use and why?</p>
27,559,564
6
1
null
2010-08-24 14:03:21.727 UTC
51
2022-08-09 15:50:20.877 UTC
2014-01-26 09:26:13.707 UTC
null
314,166
null
269,970
null
1
185
css
181,730
<h1><code>px</code> β‰  Pixels</h1> <p>All of these answers seem to be incorrect. Contrary to intuition, in CSS the <code>px</code> <strong>is not pixels</strong>. At least, not in the simple physical sense.</p> <p>Read this article from the <a href="https://en.wikipedia.org/wiki/World_Wide_Web_Consortium" rel="nofollow noreferrer">W3C</a>, <a href="https://www.w3.org/Style/Examples/007/units.en.html" rel="nofollow noreferrer">EM, PX, PT, CM, IN…</a>, about how <code>px</code> is a &quot;magical&quot; unit invented for CSS. The meaning of <code>px</code> varies by hardware and resolution. (That article is fresh, last updated 2014-10.)</p> <p>My own way of thinking about it: <em>1 px is the size of a thin line intended by a designer to be barely visible.</em></p> <p>To quote <a href="https://www.w3.org/Style/Examples/007/units.en.html" rel="nofollow noreferrer">that article</a>:</p> <blockquote> <p>The px unit is the magic unit of CSS. It is not related to the current font and also not related to the absolute units. The px unit is defined to be small but visible, and such that a horizontal 1px wide line can be displayed with sharp edges (no anti-aliasing). What is sharp, small and visible depends on the device and the way it is used: do you hold it close to your eyes, like a mobile phone, at arms length, like a computer monitor, or somewhere in between, like a book? The px is thus not defined as a constant length, but as something that depends on the type of device and its typical use.</p> <p>To get an idea of the appearance of a px, imagine a CRT computer monitor from the 1990s: the smallest dot it can display measures about 1/100th of an inch (0.25mm) or a little more. The px unit got its name from those screen pixels.</p> <p>Nowadays there are devices that could in principle display smaller sharp dots (although you might need a magnifier to see them). But documents from the last century that used px in CSS still look the same, no matter what the device. Printers, especially, can display sharp lines with much smaller details than 1px, but even on printers, a 1px line looks very much the same as it would look on a computer monitor. Devices change, but the px always has the same visual appearance.</p> </blockquote> <p>That article gives some guidance about using <code>pt</code> vs <code>px</code> vs <code>em</code>, to answer this Question.</p>
3,732,790
Android Split string
<p>I have a string called <code>CurrentString</code> and is in the form of something like this <code>"Fruit: they taste good"</code>.<br> I would like to split up the <code>CurrentString</code> using the <code>:</code> as the delimiter.<br>So that way the word <code>"Fruit"</code> will be split into its own string and <code>"they taste good"</code> will be another string.<br>And then i would simply like to use <code>SetText()</code> of 2 different <code>TextViews</code> to display that string. </p> <p>What would be the best way to approach this? </p>
3,732,820
6
2
null
2010-09-17 05:10:02.957 UTC
55
2020-05-05 08:49:06.017 UTC
2014-05-08 07:46:39.653 UTC
null
2,514,879
null
326,423
null
1
246
java|android|string
488,875
<pre><code>String currentString = "Fruit: they taste good"; String[] separated = currentString.split(":"); separated[0]; // this will contain "Fruit" separated[1]; // this will contain " they taste good" </code></pre> <p>You may want to remove the space to the second String:</p> <pre><code>separated[1] = separated[1].trim(); </code></pre> <p>If you want to split the string with a special character like dot(.) you should use escape character \ before the dot</p> <p>Example:</p> <pre><code>String currentString = "Fruit: they taste good.very nice actually"; String[] separated = currentString.split("\\."); separated[0]; // this will contain "Fruit: they taste good" separated[1]; // this will contain "very nice actually" </code></pre> <p>There are other ways to do it. For instance, you can use the <code>StringTokenizer</code> class (from <code>java.util</code>):</p> <pre><code>StringTokenizer tokens = new StringTokenizer(currentString, ":"); String first = tokens.nextToken();// this will contain "Fruit" String second = tokens.nextToken();// this will contain " they taste good" // in the case above I assumed the string has always that syntax (foo: bar) // but you may want to check if there are tokens or not using the hasMoreTokens method </code></pre>
3,267,312
How to collapse categories or recategorize variables?
<p>In R, I have 600,000 categorical variables, each of which is classified as &quot;0&quot;, &quot;1&quot;, or &quot;2&quot;.</p> <p>What I would like to do is collapse &quot;1&quot; and &quot;2&quot; and leave &quot;0&quot; by itself, such that after re-categorizing &quot;0&quot; = &quot;0&quot;; &quot;1&quot; = &quot;1&quot; and &quot;2&quot; = &quot;1&quot;. In the end I only want &quot;0&quot; and &quot;1&quot; as categories for each of the variables.</p> <p>Also, if possible, I would rather not create 600,000 new variables, if I can replace the existing variables with the new values that would be great!</p> <p>What would be the best way to do this?</p>
3,267,379
7
0
null
2010-07-16 17:13:36.783 UTC
4
2021-11-05 18:51:08.173 UTC
2021-11-05 18:51:08.173 UTC
null
466,862
null
394,139
null
1
7
r|categories|collapse
41,258
<p>There is a function <code>recode</code> in package <code>car</code> (Companion to Applied Regression):</p> <pre><code>require("car") recode(x, "c('1','2')='1'; else='0'") </code></pre> <p>or for your case in plain R:</p> <pre><code>&gt; x &lt;- factor(sample(c("0","1","2"), 10, replace=TRUE)) &gt; x [1] 1 1 1 0 1 0 2 0 1 0 Levels: 0 1 2 &gt; factor(pmin(as.numeric(x), 2), labels=c("0","1")) [1] 1 1 1 0 1 0 1 0 1 0 Levels: 0 1 </code></pre> <p><strong>Update:</strong> To recode all categorical columns of a data frame <code>tmp</code> you can use the following</p> <pre><code>recode_fun &lt;- function(x) factor(pmin(as.numeric(x), 2), labels=c("0","1")) require("plyr") catcolwise(recode_fun)(tmp) </code></pre>
3,303,420
Regex to remove all special characters from string?
<p>I'm completely incapable of regular expressions, and so I need some help with a problem that I think would best be solved by using regular expressions.</p> <p>I have list of strings in C#:</p> <pre><code>List&lt;string&gt; lstNames = new List&lt;string&gt;(); lstNames.add("TRA-94:23"); lstNames.add("TRA-42:101"); lstNames.add("TRA-109:AD"); foreach (string n in lstNames) { // logic goes here that somehow uses regex to remove all special characters string regExp = "NO_IDEA"; string tmp = Regex.Replace(n, regExp, ""); } </code></pre> <p>I need to be able to loop over the list and return each item without any special characters. For example, item one would be "TRA9423", item two would be "TRA42101" and item three would be TRA109AD. </p> <p>Is there a regular expression that can accomplish this for me?</p> <p>Also, the list contains more than 4000 items, so I need the search and replace to be efficient and quick if possible.</p> <p>EDIT: I should have specified that any character beside a-z, A-Z and 0-9 is special in my circumstance.</p>
3,303,435
9
3
null
2010-07-21 20:14:19.67 UTC
18
2018-06-19 18:06:06.13 UTC
2017-12-11 20:53:18.91 UTC
null
3,885,376
null
60,758
null
1
72
c#|regex|string
259,043
<p>It really depends on your definition of special characters. I find that a whitelist rather than a blacklist is the best approach in most situations:</p> <pre><code>tmp = Regex.Replace(n, "[^0-9a-zA-Z]+", ""); </code></pre> <p>You should be careful with your current approach because the following two items will be converted to the same string and will therefore be indistinguishable:</p> <pre><code>"TRA-12:123" "TRA-121:23" </code></pre>
8,025,825
Is there a NodeJS plugin for Aptana Studio?
<p>Is there a NodeJS plugin for Aptana Studio?</p> <ul> <li>At least for NodeJS code-assist</li> <li>And perhaps a way to create NodeJS project</li> <li>And local NodeJS debugging</li> </ul>
8,086,372
5
0
null
2011-11-06 07:48:21.28 UTC
6
2020-04-06 09:26:53.253 UTC
null
null
null
null
785,349
null
1
46
node.js|aptana
30,222
<p>We have no NodeJS support currently. If this is something the community is interested in, it'd be helpful to file a feature request and vote it up: <a href="http://jira.appcelerator.org/secure/CreateIssue!default.jspa" rel="noreferrer">http://jira.appcelerator.org/secure/CreateIssue!default.jspa</a></p> <p>Since we are built on eclipse, you should be able to try out the instructions for NodeJS debugging on Eclipse, found here: <a href="https://github.com/joyent/node/wiki/Using-Eclipse-as-Node-Applications-Debugger" rel="noreferrer">https://github.com/joyent/node/wiki/Using-Eclipse-as-Node-Applications-Debugger</a></p> <p>As for special NodeJs projects, there's no notion of that. You would likely just create a normal Web project. We do have the concept of libraries that you can add to a project, wherein you could point to js files/libs for NodeJS. We also has special syntax files for describing JS libraries/APIs so it can be integrated into our content assist. A good example might be the ruble we have for jQuery which contains that file for two versions of the jQuery API. Here's the 1.6.2 version: <a href="https://github.com/aptana/javascript-jquery.ruble/blob/master/support/jquery.1.6.2.sdocml" rel="noreferrer">https://github.com/aptana/javascript-jquery.ruble/blob/master/support/jquery.1.6.2.sdocml</a> The bundle.rb up in the parent directory hooks up the file in the ruble/bundle.</p> <p>My guess is that creating an analogous NodeJS ruble and building up an sdocml (xml) file that described the API would be the easiest way to get started. Sharing that on github and sending it to us would allow for others to contribute as well. There are docs for creating rubles here: <a href="http://wiki.appcelerator.org/display/tis/Creating+a+new+Ruble" rel="noreferrer">http://wiki.appcelerator.org/display/tis/Creating+a+new+Ruble</a></p>
8,072,311
Adding <h:form> causes java.lang.IllegalStateException: Cannot create a session after the response has been committed
<p>I'm facing the following exception in a very simple JSF 2 page after adding <code>&lt;h:form&gt;</code>:</p> <pre><code>java.lang.IllegalStateException: Cannot create a session after the response has been committed at org.apache.catalina.connector.Request.doGetSession(Request.java:2758) at org.apache.catalina.connector.Request.getSession(Request.java:2268) </code></pre> <p>I'm using Mojarra 2.1.3 and PrimeFaces3.0M4, on Tomcat 7.0.22 and JDK 7.</p> <p>The page is a very basic data table:</p> <pre><code>&lt;html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui"&gt; &lt;h:head&gt; &lt;/h:head&gt; &lt;h:body&gt; &lt;h:form&gt; &lt;p:dataTable var="car" value="#{tableBean.cars}"&gt; ...... &lt;/p:dataTable&gt; &lt;/h:form&gt; &lt;/h:body&gt; &lt;/html&gt; </code></pre> <p>The page shows correctly on the browser, but on the console I see the exception. The Exception does disappear if I remove the <code>&lt;h:form&gt;</code>.</p> <p>How is this caused and how can I solve it?</p>
8,072,445
5
0
null
2011-11-09 21:58:07.96 UTC
23
2017-06-16 20:22:41.603 UTC
2015-07-29 11:53:19.787 UTC
null
157,882
null
27,789
null
1
47
forms|session|jsf|jsf-2|illegalstateexception
57,118
<p>This is a known problem and has been reported by yours truly as <a href="http://java.net/jira/browse/JAVASERVERFACES-2215" rel="noreferrer">issue 2215</a>. This will occur when the response buffer has overflowed (due to large content) and the response is been committed before the session is been created. This is result of bit overzealous attempts of Mojarra to postpone "unnecessary" session creation as much as possible (which is at its own a Good Thing though).</p> <p>Until they get it fixed, there are several workarounds:</p> <ol> <li><p>Create a <code>Filter</code> which does <a href="http://download.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getSession%28%29" rel="noreferrer"><code>HttpServletRequest#getSession()</code></a> before <a href="http://download.oracle.com/javaee/6/api/javax/servlet/FilterChain.html#doFilter%28javax.servlet.ServletRequest,%20javax.servlet.ServletResponse%29" rel="noreferrer"><code>FilterChain#doFilter()</code></a>. Advantage: no need to change JSF configuration/code. Disadvantage: when you want to avoid unnecessary session creation yourself as well.</p></li> <li><p>Call <a href="http://download.oracle.com/javaee/6/api/javax/faces/context/ExternalContext.html#getSession%28boolean%29" rel="noreferrer"><code>ExternalContext#getSession()</code></a> with <code>true</code> in bean's (post)constructor or <code>preRenderView</code> listener. Advantage: actually, nothing. Disadvantage: too hacky.</p></li> <li><p>Add a context parameter with name of <code>com.sun.faces.writeStateAtFormEnd</code> and value of <code>false</code> to <code>web.xml</code>. Advantage: unnecessary session creation will be really avoided as opposed to #1 and #2. Disadvantage: response will now be fully buffered in memory until <code>&lt;/h:form&gt;</code> is reached. If your forms are not extremely large, the impact should however be minimal. It would however still fail if your <code>&lt;h:form&gt;</code> starts relatively late in the view. This may be combined with #4.</p></li> <li><p>Add a context parameter with name of <code>javax.faces.FACELETS_BUFFER_SIZE</code> and a value of the Facelets response buffer size in bytes (e.g. <code>65535</code> for 64KB) so that the entire HTML output or at least the <code>&lt;h:form&gt;</code> (see #3) fits in the response buffer. Advantage/disadvantage, see #3.</p></li> <li><p>Add a context parameter with name of <code>javax.faces.STATE_SAVING_METHOD</code> and value of <code>client</code> to <code>web.xml</code>. Advantage: session will not be created at all unless you have session scoped beans. It also immediately solves potential <code>ViewExpiredException</code> cases. Disadvantage: increased network bandwidth usage. If you're using partial state saving, then the impact should however be minimal.</p></li> </ol> <p>As to why the problem disappears when you remove <code>&lt;h:form&gt;</code>, this is because no session needs to be created in order to store the view state.</p> <hr> <p><strong>Update</strong>: this has as per the duplicate <a href="http://java.net/jira/browse/JAVASERVERFACES-2277" rel="noreferrer">issue 2277</a> been fixed since Mojarra 2.1.8. So, you can also just upgrade to at least that version.</p>
7,861,196
Check if a geopoint with latitude and longitude is within a shapefile
<p>How can I check if a geopoint is within the area of a given shapefile? </p> <p>I managed to load a shapefile in python, but can't get any further.</p>
13,433,127
7
0
null
2011-10-22 17:10:39.773 UTC
34
2022-07-15 17:07:34.257 UTC
2018-04-04 21:00:33.797 UTC
null
1,366,410
null
618,737
null
1
27
python|geolocation|geocoding|geospatial|shapefile
47,554
<p>This is an adaptation of yosukesabai's answer.</p> <p>I wanted to ensure that the point I was searching for was in the same projection system as the shapefile, so I've added code for that.</p> <p>I couldn't understand why he was doing a contains test on <code>ply = feat_in.GetGeometryRef()</code> (in my testing things seemed to work just as well without it), so I removed that.</p> <p>I've also improved the commenting to better explain what's going on (as I understand it).</p> <pre><code>#!/usr/bin/python import ogr from IPython import embed import sys drv = ogr.GetDriverByName('ESRI Shapefile') #We will load a shape file ds_in = drv.Open("MN.shp") #Get the contents of the shape file lyr_in = ds_in.GetLayer(0) #Get the shape file's first layer #Put the title of the field you are interested in here idx_reg = lyr_in.GetLayerDefn().GetFieldIndex("P_Loc_Nm") #If the latitude/longitude we're going to use is not in the projection #of the shapefile, then we will get erroneous results. #The following assumes that the latitude longitude is in WGS84 #This is identified by the number "4326", as in "EPSG:4326" #We will create a transformation between this and the shapefile's #project, whatever it may be geo_ref = lyr_in.GetSpatialRef() point_ref=ogr.osr.SpatialReference() point_ref.ImportFromEPSG(4326) ctran=ogr.osr.CoordinateTransformation(point_ref,geo_ref) def check(lon, lat): #Transform incoming longitude/latitude to the shapefile's projection [lon,lat,z]=ctran.TransformPoint(lon,lat) #Create a point pt = ogr.Geometry(ogr.wkbPoint) pt.SetPoint_2D(0, lon, lat) #Set up a spatial filter such that the only features we see when we #loop through "lyr_in" are those which overlap the point defined above lyr_in.SetSpatialFilter(pt) #Loop through the overlapped features and display the field of interest for feat_in in lyr_in: print lon, lat, feat_in.GetFieldAsString(idx_reg) #Take command-line input and do all this check(float(sys.argv[1]),float(sys.argv[2])) #check(-95,47) </code></pre> <p><a href="http://hackmap.blogspot.de/2008/03/ogr-python-projection.html" rel="noreferrer">This site</a>, <a href="http://gissolved.blogspot.de/2009/05/projections-and-transformation-2.html" rel="noreferrer">this site</a>, and <a href="http://geoinformaticstutorial.blogspot.de/2012/10/reprojecting-shapefile-with-gdalogr-and.html" rel="noreferrer">this site</a> were helpful regarding the projection check. <a href="http://spatialreference.org/ref/epsg/wgs-84/" rel="noreferrer">EPSG:4326</a></p>
7,949,956
Why does git diff on Windows warn that the "terminal is not fully functional"?
<p>I'm using <strong>msysgit 1.7.7.1</strong> on Windows. I get an error when using <code>git diff</code>. What is causing this? Is there no diff tool included in msysgit? What should I do?</p> <blockquote> <p>WARNING: terminal is not fully functional</p> </blockquote>
7,950,092
7
3
null
2011-10-31 04:14:07.427 UTC
23
2015-11-25 18:09:37.083 UTC
2012-10-10 03:32:02.547 UTC
null
3,619
null
468,539
null
1
113
windows|git|diff|msysgit
30,323
<p>For Git Bash, this can be fixed by adding the following line to ~/.bashrc:</p> <pre><code>export TERM=cygwin </code></pre> <p>-or-</p> <pre><code>export TERM=msys </code></pre> <p>The first seems to be the original by git for windows, the second a popular known form to "heal" as well.</p> <p>The problem can be caused if some other program (like for example <em>Strawberry Perl</em>) sets the <code>TERM</code> system environment variables.</p> <p><a href="http://code.google.com/p/msysgit/issues/detail?id=184" rel="noreferrer">http://code.google.com/p/msysgit/issues/detail?id=184</a></p>
7,949,564
Object from comprehension in CoffeeScript [dict/hash comprehensions]
<p>is there a way to return an object from a comprehension in coffeescript? something so that i could express this:</p> <pre><code>form_values = () -&gt; ret = {} ret[f.name] = f.value for f in $('input, textarea, select') return ret </code></pre> <p>like this:</p> <pre><code>form_values = () -&gt; f.name, f.value for f in $('input, textarea, select') </code></pre> <p>i'd like to construct a <em>single object</em> (not an array of objects). so if the markup looks something like this:</p> <pre><code>&lt;form name=blah&gt; &lt;input type=text name=blah1 value=111 /&gt; &lt;textarea name=blah2&gt;222&lt;/textarea&gt; &lt;select name=blah3&gt; &lt;option value=333a&gt; &lt;option value=333b&gt; &lt;/select&gt; &lt;/form&gt; </code></pre> <p>the returned object would be something like this:</p> <pre><code>{ blah1: '111', blah2: '222', blah3: '' } </code></pre>
7,949,958
8
1
null
2011-10-31 02:52:44.093 UTC
8
2018-03-30 16:01:26.753 UTC
2012-08-20 13:49:01.783 UTC
null
525,872
null
5,377
null
1
43
coffeescript
7,935
<p>Nope. Comprehensions only return arrays in CoffeeScript. Search the issue tracker for <a href="https://github.com/jashkenas/coffee-script/issues/search?q=object+comprehensions" rel="noreferrer">object comprehensions</a>, and you'll find several proposals, but none were found suitable.</p>
4,315,506
load csv into 2D matrix with numpy for plotting
<p>Given this CSV file:</p> <pre><code>"A","B","C","D","E","F","timestamp" 611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291111964948E12 611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291113113366E12 611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291120650486E12 </code></pre> <p>I simply want to load it as a matrix/ndarray with 3 rows and 7 columns. However, for some reason, all I can get out of numpy is an ndarray with 3 rows (one per line) and no columns.</p> <pre><code>r = np.genfromtxt(fname,delimiter=',',dtype=None, names=True) print r print r.shape [ (611.88243, 9089.5601000000006, 5133.0, 864.07514000000003, 1715.3747599999999, 765.22776999999996, 1291111964948.0) (611.88243, 9089.5601000000006, 5133.0, 864.07514000000003, 1715.3747599999999, 765.22776999999996, 1291113113366.0) (611.88243, 9089.5601000000006, 5133.0, 864.07514000000003, 1715.3747599999999, 765.22776999999996, 1291120650486.0)] (3,) </code></pre> <p>I can manually iterate and hack it into the shape I want, but this seems silly. I just want to load it as a proper matrix so I can slice it across different dimensions and plot it, just like in matlab.</p>
4,315,914
3
0
null
2010-11-30 15:40:22.863 UTC
18
2018-05-05 06:18:23.663 UTC
2014-11-05 15:47:16.277 UTC
null
1,281,433
null
494,572
null
1
86
python|arrays|csv|numpy|reshape
222,732
<p>Pure numpy </p> <pre><code>numpy.loadtxt(open("test.csv", "rb"), delimiter=",", skiprows=1) </code></pre> <p> Check out the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html#numpy.loadtxt" rel="noreferrer">loadtxt</a> documentation. </p> <p>You can also use python's csv module: </p> <pre><code>import csv import numpy reader = csv.reader(open("test.csv", "rb"), delimiter=",") x = list(reader) result = numpy.array(x).astype("float") </code></pre> <p> You will have to convert it to your favorite numeric type. I guess you can write the whole thing in one line:</p> <pre> result = numpy.array(list(csv.reader(open("test.csv", "rb"), delimiter=","))).astype("float") </pre> <p><strong>Added Hint:</strong></p> <p>You could also use <code>pandas.io.parsers.read_csv</code> and get the associated <code>numpy</code> array which can be faster.</p>
4,267,014
How can colored terminal output be disabled for sbt/play?
<p>I would like to disable the color escape codes logged from sbt/play. Is this possible? And if it is, is there a way to do it without making changes to the config - i.e. via a command line switch or system property.</p>
4,269,307
5
1
null
2010-11-24 12:56:14.567 UTC
9
2016-07-02 10:07:41.383 UTC
2014-03-26 19:50:57.95 UTC
null
1,305,344
null
2,269,111
null
1
57
scala|playframework|sbt
13,394
<p>You can simply set the system property <code>sbt.log.noformat</code> to <code>true</code>. If you want to e.g. use SBT inside Vim you can create a script like this:</p> <pre><code>#!/bin/bash java -Dsbt.log.noformat=true $JAVA_OPTS -jar "${HOME}/bin/sbt-launch.jar" "$@" </code></pre>
4,296,108
How do I add a line break for read command?
<pre><code> read -p "Please Enter a Message:" message </code></pre> <p>How can I add a line break after <code>Message:</code>?</p>
4,296,177
7
2
null
2010-11-28 09:08:00.057 UTC
16
2018-06-19 12:09:56.46 UTC
2018-01-12 00:06:04.55 UTC
null
5,780,109
null
170,365
null
1
79
bash|shell|unix
73,480
<p>I like <a href="https://stackoverflow.com/questions/4296108/how-do-i-add-a-line-break-for-read-command/4296147#4296147">Huang F. Lei's answer</a>, but if you don't like the literal line break, this works:</p> <pre><code>read -p "Please Enter a Message: `echo $'\n&gt; '`" message </code></pre> <p>Shows:</p> <pre>Please Enter a Message: > _</pre> <p>...where <code>_</code> is where the cursor ends up. Note that since trailing newlines are usually dropped during command substitution, I've included the <code>&gt;</code> afterward. But actually, your original question doesn't seem to want that prompt bit, so:</p> <pre><code># Get a carriage return into `cr` -- there *has* to be a better way to do this cr=`echo $'\n.'` cr=${cr%.} # Use it read -p "Please Enter a Message: $cr" message </code></pre> <p>Shows</p> <pre>Please Enter a Message: _</pre> <p>There has to be a better way, though.</p>
4,636,610
How to pattern match using regular expression in Scala?
<p>I would like to be able to find a match between the first letter of a word, and one of the letters in a group such as "ABC". In pseudocode, this might look something like:</p> <pre><code>case Process(word) =&gt; word.firstLetter match { case([a-c][A-C]) =&gt; case _ =&gt; } } </code></pre> <p>But how do I grab the first letter in Scala instead of Java? How do I express the regular expression properly? Is it possible to do this within a <a href="http://www.scala-lang.org/node/107" rel="noreferrer">case class</a>?</p>
4,636,670
7
3
null
2011-01-08 22:50:17.047 UTC
47
2020-02-21 11:11:31.463 UTC
2020-02-21 11:11:31.463 UTC
null
372,239
null
505,866
null
1
136
regex|scala
180,912
<p>You can do this because regular expressions define extractors but you need to define the regex pattern first. I don't have access to a Scala REPL to test this but something like this should work.</p> <pre><code>val Pattern = "([a-cA-C])".r word.firstLetter match { case Pattern(c) =&gt; c bound to capture group here case _ =&gt; } </code></pre>
4,120,824
Reversing an Animation
<p>I have an ImageView that gets animated when it is added to a layout. When it is removed, I want to reverse the same animation.</p> <p>Is there a way to reverse an animation in android without recoding it and reversing the parameters?</p>
5,259,995
9
2
null
2010-11-08 02:14:58.02 UTC
13
2021-05-21 11:03:02.947 UTC
2017-02-26 03:49:07.61 UTC
null
360,211
null
2,011
null
1
51
android|animation
41,831
<p>No, sadly you cannot do it with the Animation object. But you can simulate it using an interpolator that will inverse the animation:</p> <pre><code>package com.example.android; import android.view.animation.Interpolator; public class ReverseInterpolator implements Interpolator { @Override public float getInterpolation(float paramFloat) { return Math.abs(paramFloat -1f); } } </code></pre> <p>Then on your animation you can set your new interpolator:</p> <pre><code>myAnimation.setInterpolator(new ReverseInterpolator()); </code></pre>
4,491,199
build maven project with propriatery libraries included
<p>How to create maven pom, which will make project buildable, can I include propriatery jars with my project directly without having to take them from repository? anyone did this before ? </p> <p>EDIT :</p> <p>I don't want to make it runnable by building assembly with dependencies jar, I want it to be buildable. So anyone having this project is able to build it, even if jars are nowhere to be found at any repository.</p>
4,491,343
11
1
null
2010-12-20 15:43:33.953 UTC
16
2020-08-11 12:10:33.873 UTC
2010-12-20 16:30:03.107 UTC
null
260,990
null
282,383
null
1
47
java|maven-2|maven
131,737
<p><strong>1</strong> Either you can include that jar in your classpath of application<br> <strong>2</strong> you can install particular jar file in your maven reopos by</p> <pre><code>mvn install:install-file -Dfile=&lt;path-to-file&gt; -DgroupId=&lt;group-id&gt; \ -DartifactId=&lt;artifact-id&gt; -Dversion=&lt;version&gt; -Dpackaging=&lt;packaging&gt; </code></pre>
4,233,581
Xcode 4 - build output directory
<p>I have problems with setting up/locating my output files in Xcode4 (beta 5). They are placed somewhere in <code>~/Library/Developer/ugly_path/...</code>. I can't even select "show in finder" on my products. It is the same for a simple C project, Foundation tool and even Cocoa bundle. A Debugging works fine.</p> <p>Could you please point me out where and how to set up / build output directories? (I know it sounds dumb, I've been coding in Xcode3 for months, but I can't figure it out in Xcode4 beta).</p> <p>Thanks a lot.</p>
4,282,467
11
0
null
2010-11-20 15:55:02.353 UTC
58
2015-05-14 19:22:26.21 UTC
2015-03-15 12:47:24.66 UTC
null
1,779,477
null
514,497
null
1
217
ide|xcode4
166,004
<p>From the Xcode menu on top, click preferences, select the locations tab, look at the build location option.</p> <p>You have 2 options:</p> <ol> <li>Place build products in derived data location (recommended)</li> <li>Place build products in locations specified by targets</li> </ol> <p>Update: On xcode 4.6.2 you need to click the advanced button on the right side below the derived data text field. Build Location select legacy.</p>
4,519,264
OpenGL ES versus OpenGL
<p>What are the differences between OpenGL ES and OpenGL ?</p>
4,519,294
13
4
null
2010-12-23 13:44:06.643 UTC
22
2021-05-11 19:07:29.73 UTC
2015-07-06 11:13:06.9 UTC
null
459,904
null
459,904
null
1
101
opengl|opengl-es
65,083
<blockquote> <p>Two of the more significant differences between OpenGL ES and OpenGL are the removal of the glBegin ... glEnd calling semantics for primitive rendering (in favor of vertex arrays) and the introduction of fixed-point data types for vertex coordinates and attributes to better support the computational abilities of embedded processors, which often lack an FPU </p> </blockquote> <p>Have a look here: <a href="http://en.wikipedia.org/wiki/OpenGL_ES" rel="noreferrer">OpenGL_ES</a></p>
4,650,246
How to cancel an Dialog themed like Activity when touched outside the window?
<p>I have an activity with a Dialog theme and I would like to close (finish) this activity when someone touches the screen anywhere outside this activity's window ? How can I do this ?</p>
4,651,027
17
2
null
2011-01-10 18:46:23.497 UTC
18
2020-12-29 13:23:03.013 UTC
null
null
null
null
467,780
null
1
50
android|dialog|android-activity|touch
83,423
<p>If there's no API support, you should just use a FrameLayout to fill the screen, and manually build a pop-up. Then you can receive focus anywhere on the screen and show/hide views accordingly.</p>
14,464,945
Add queueing to angulars $http service
<p>I have a very quirky api that can only handle a single request at a time. Therefore, I need to ensure that every time a request is made, it goes into a queue, and that queue is executed one request at a time, until it is empty.</p> <p>Normally, I just use jQuery's built in queue, since the site is already using jQuery. However, I was not sure if I could somehow decorate the $http service, or wrap it in another service that returns one promise at a time, or something else.</p>
14,468,276
6
2
null
2013-01-22 17:52:47.59 UTC
18
2019-03-14 13:46:30.063 UTC
null
null
null
null
960,588
null
1
16
angularjs
23,401
<p>Here is my solution for that: <a href="http://plnkr.co/edit/Tmjw0MCfSbBSgWRhFvcg" rel="noreferrer">http://plnkr.co/edit/Tmjw0MCfSbBSgWRhFvcg</a></p> <p>The idea is: each run of service add request to queue and return promise. When request to $http is finished resolve/refuse returned promise and execute next task from queue if any.</p> <pre class="lang-js prettyprint-override"><code>app.factory('srv', function($q,$http) { var queue=[]; var execNext = function() { var task = queue[0]; $http(task.c).then(function(data) { queue.shift(); task.d.resolve(data); if (queue.length&gt;0) execNext(); }, function(err) { queue.shift(); task.d.reject(err); if (queue.length&gt;0) execNext(); }) ; }; return function(config) { var d = $q.defer(); queue.push({c:config,d:d}); if (queue.length===1) execNext(); return d.promise; }; }); </code></pre> <p>Looks quite simple :)</p>
14,892,125
What is the best practice to determine the execution time of the business relevant code of my junit?
<p>The test execution time which is displayed in eclipse->junit-view depends on the whole test case execution which includes:</p> <ul> <li>Testdata preperation</li> <li>Executing businesslogic</li> <li>assert results</li> </ul> <p>I need a more detailed statement about the execution time of my businesslogic and only my businesslogic. That is what I have done inside my testcase:</p> <pre><code>Date lNow = new Date(); List&lt;Geo&gt; lAllBasisGeo = mGeoEvaluator.evaluateAllGeo(lGeoFixture.getGeo(), lAllGeo); Date lStop = new Date(); System.out.println("Time of execution in seconds:"+((lStop.getTime()-lNow.getTime())/1000)); </code></pre> <p>Well... I think I determine the time in a realy awkward way. Furthermore I dont think that it is necessary to declare two Date variables.</p> <p>I need advice writing that code more efficiently...</p>
14,894,192
4
1
null
2013-02-15 09:57:38.703 UTC
13
2021-10-08 22:44:46.937 UTC
2017-12-17 03:46:52.463 UTC
null
1,033,581
null
1,640,490
null
1
29
java|junit
33,095
<p>in a unit test I would prefer to add a timeout to the Test with a JUnit 4 annotation, to determine whether the test passes (fast enough) or not:</p> <pre><code>@Test(timeout=100)//let the test fail after 100 MilliSeconds public void infinity() { while(true); } </code></pre> <p>To determine the exact Runtime of your business logic I would add the Time statements right before and after your critical Codepath like you did, repeat it several times to get scholastically correct results, and remove the statements again, so slim the code.</p> <pre><code>long start = System.currentTimeMillis(); //execute logic in between long end = System.currentTimeMillis(); System.out.println("DEBUG: Logic A took " + (end - start) + " MilliSeconds"); </code></pre>
14,419,206
What does :-1 mean in python?
<p>I'm trying to port some Python code to C, but I came across this line and I can't figure out what it means:</p> <pre><code>if message.startswith('&lt;stream:stream'): message = message[:-1] + ' /&gt;' </code></pre> <p>I understand that if '<code>message</code> starts with <code>&lt;stream:stream</code> then something needs to be appended. However I can't seem to figure out where it should be appended. I have absolutely no idea what <code>:-1</code> indicates. I did several Google searches with no result.</p> <p>Would somebody be so kind as to explain what this does?</p>
14,419,218
5
9
null
2013-01-19 21:46:34.103 UTC
13
2022-09-08 00:01:06.62 UTC
2022-09-08 00:01:06.62 UTC
null
15,497,888
null
1,178,557
null
1
29
python|syntax
133,977
<p>It is list indexing, it returns all elements <code>[:]</code> except the last one <code>-1</code>. Similar question <a href="https://stackoverflow.com/questions/509211/the-python-slice-notation">here</a> </p> <p>For example, </p> <pre><code>&gt;&gt;&gt; a = [1,2,3,4,5,6] &gt;&gt;&gt; a[:-1] [1, 2, 3, 4, 5] </code></pre> <p>It works like this </p> <p><code>a[start:end]</code></p> <pre><code>&gt;&gt;&gt; a[1:2] [2] </code></pre> <p><code>a[start:]</code></p> <pre><code>&gt;&gt;&gt; a[1:] [2, 3, 4, 5, 6] </code></pre> <p><code>a[:end]</code><br> Your case </p> <pre><code>&gt;&gt;&gt; a = [1,2,3,4,5,6] &gt;&gt;&gt; a[:-1] [1, 2, 3, 4, 5] </code></pre> <p><code>a[:]</code></p> <pre><code>&gt;&gt;&gt; a[:] [1, 2, 3, 4, 5, 6] </code></pre>
14,410,994
Images in browsers performance for background-repeat CSS
<p>Does any one know which is going to be better for a browser loading time between these two options:</p> <pre><code>background-image:url('1by1px.png'); </code></pre> <p>or </p> <pre><code>background-image:url('10by10px.png'); </code></pre> <p>A 1px by 1px semi transparent png repeated for the div. Or a larger one say 10px by 10px.</p> <p>There must be some kind of looping that has to be done to display the repeated image in the browser, and so I wondered if the image which is <code>1px by 1px</code> causes alot of looping to get the image displayed that it may in fact be less speedy than a larger dimensioned image with less looping?</p> <p>Of course the counter argument is image size is smaller for 1by1 compared to 10by10, but doesn't mean its better to be smaller because looping many times might not scale as good as looping a large image size slightly less often.</p> <p>Does any know more about which would be better and how browsers handle situations like this?</p>
14,412,617
2
6
null
2013-01-19 04:08:06.37 UTC
6
2014-05-27 15:51:24.727 UTC
2013-01-20 05:53:49.25 UTC
null
1,076,743
null
1,076,743
null
1
31
html|css|browser
2,903
<p>When not repeating the background image, the time required to render depends on only the final scaled image, not the original one. </p> <p>The image in a file is compressed as PNG format, but after being loaded by browser, it is in RGBA bitmap format (4 bytes for a pixel). When repeating a background, (let say on Intel x86), the native code of browser would use <strong>REP MOVSD</strong> to move the bitmap data from RAM to video memory (this is standard sequence, might be different on various implementations of graphics driver or specific GPU).</p> <p>Assume that the dimensions of the HTML DIV which contains the background would be 100x100. </p> <p>For the only-1 pixel image: the browser programme has to exec <strong>10 thousand 'REP MOVSD'</strong> instructions.</p> <p>For the 10x10 image: with each repeated image, the browser programme has to exec 'REP MOVSD' only 10 times (1 time calling to 'REP MOVSD' can render 1 pixel line (pixel row) of the image). So in this case, the number of 'REP MOVSD' instructions executed would be only 10x100 times (10 times in 1 image, 100 repeated images). This takes totally <strong>1 thousand 'REP MOVSD'</strong>.</p> <p><strong>Therefore, the final background based on the bigger image would be rendered faster</strong>.</p> <p>More notes: <em>The above explanation doesn't mean the performance is exactly 10 times better for the 10x10 image. A 'REP MOVSD' (with CX=9999 for example) is only 1 single CPU instruction but still requires 9999x4 bytes to be transfered through data bus. If using 9999 simple 'MOV's, that much of data still have to go thru' data bus, however, CPU has to execute 9998 instructions more. A more clever browser would create a pre-rendered bitmap for the background with replicated images; so each time it needs to transfer to video memory, it needs just only 100 'REP MOVSD' (100 is the number of pixel rows in the final background, assumed above) instead of 10 thousand or 1 thousand.</em></p>
14,901,508
Maximum concurrent connections to MySQL
<p>I want to set up a MySQL database for a social networking website for my college. </p> <p>My app can have at most 10,000 users. What is the maximum number of concurrent MySQL connections possible? </p>
14,901,541
3
8
null
2013-02-15 18:57:36.207 UTC
18
2020-10-20 22:08:45.74 UTC
2014-07-09 23:51:30.783 UTC
null
472,798
null
2,075,703
null
1
52
mysql|database
107,250
<p>As per the MySQL docs: <a href="http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_max_user_connections">http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_max_user_connections</a></p> <pre><code> maximum range: 4,294,967,295 (e.g. 2**32 - 1) </code></pre> <p>You'd probably run out of memory, file handles, and network sockets, on your server long before you got anywhere close to that limit.</p>
14,436,953
setup cron tab to specific time of during weekdays
<p>I am trying to setup a cron job on a Ubuntu server. We want the cron job to run the script at certain times of the day and on some specific days of the week. For example, we want to setup a cron job that runs the script with the following sequence:</p> <blockquote> <p>Execute the script every 2 minutes from 9 am to 2 pm during the weekdays. </p> </blockquote> <p>This is what I have been able to do so far: </p> <blockquote> <p>*/2 09-14 * * * /path_to_script</p> </blockquote> <p>What should I do for the weekdays?</p>
14,437,008
3
0
null
2013-01-21 10:46:31.54 UTC
8
2015-12-16 17:54:24.723 UTC
2015-09-29 20:58:26.103 UTC
null
652,519
null
315,541
null
1
92
linux|cron
71,198
<p>Same as you did for hours:</p> <pre><code>*/2 09-18 * * 1-5 /path_to_script </code></pre> <p><code>0</code> and <code>7</code> stand for Sunday<br /> <code>6</code> stands for Saturday<br /> so, <code>1-5</code> means from Monday to Friday</p>
2,525,905
How do I display the Django '__all__' form errors in the template?
<p>I have the following form code:</p> <pre><code># forms.py class SomeForm(forms.Form): hello = forms.CharField(max_length=40) world = forms.CharField(max_length=40) def clean(self): raise forms.ValidationError('Something went wrong') # views.py def some_view(request): if request.method == 'POST': form = SomeForm(request.POST) if form.is_valid(): pass else: form = SomeForm() data = { 'form': form } return render_to_response( 'someform.html', data, context_instance=RequestContext(request) ) # someform.html {{ form.hello }} {{ form.hello.errors }} {{ form.world }} {{ form.world.errors }} </code></pre> <p>How can I display the errors from the key <code>__all__</code> at the template level without having to extract it in the view separately? I want to avoid the following:</p> <pre><code> if form.errors.has_key('__all__'): print form.errors['__all__'] </code></pre>
2,525,921
2
0
null
2010-03-26 18:52:20.39 UTC
14
2011-09-11 18:01:08.597 UTC
2011-09-11 18:01:08.597 UTC
null
117,642
null
117,642
null
1
61
django|django-forms
27,946
<pre><code>{{ form.non_field_errors }} </code></pre>
49,949,548
How to set the height of vuetify card
<p>I am attempting to add a card with vue and vuetify that will take up the space in my container using v-flex to create a horizontal card that acts the same way vertically. I have attempted to add a height style of 100%, using fill-height, child-flex, etc but I cannot get the size of the card to fill the container. What is the correct way to adjust the height? </p> <p>ref: <a href="https://vuetifyjs.com/en/components/cards" rel="noreferrer">https://vuetifyjs.com/en/components/cards</a></p> <pre><code>&lt;div id="app"&gt; &lt;v-app id="inspire"&gt; &lt;v-toolbar color="green" dark fixed app&gt; &lt;v-toolbar-title&gt;My Application&lt;/v-toolbar-title&gt; &lt;/v-toolbar&gt; &lt;v-content &gt; &lt;v-container fluid fill-height &gt; &lt;v-layout justify-center align-center &gt; &lt;v-flex text-xs-center &gt; &lt;v-card class="elevation-20" &gt; &lt;v-toolbar dark color="primary"&gt; &lt;v-toolbar-title&gt;I want this to take up the whole space with slight padding&lt;/v-toolbar-title&gt; &lt;v-spacer&gt;&lt;/v-spacer&gt; &lt;/v-toolbar&gt; &lt;v-card-text&gt; &lt;/v-card-text&gt; &lt;/v-card&gt; &lt;/v-flex&gt; &lt;/v-layout&gt; &lt;/v-container&gt; &lt;/v-content&gt; &lt;v-footer color="green" app inset&gt; &lt;span class="white--text"&gt;&amp;copy; 2018&lt;/span&gt; &lt;/v-footer&gt; &lt;/v-app&gt; &lt;/div&gt; </code></pre> <p>example: <a href="https://codepen.io/anon/pen/LmVJKx" rel="noreferrer">https://codepen.io/anon/pen/LmVJKx</a></p>
49,953,110
6
2
null
2018-04-20 20:50:54.277 UTC
3
2020-04-17 10:03:14.063 UTC
null
null
null
null
3,550,676
null
1
20
css|vue.js|vuetify.js
119,962
<p>Vuetify says for <strong>height</strong> props: <em>Manually define the height of the card</em></p> <p>So,in v-card element add height as follow:</p> <pre><code>&lt;v-card height="100%"&gt; </code></pre> <p><a href="https://codepen.io/anon/pen/xjGNWr?&amp;editors=100#anon-login" rel="noreferrer">See it in action</a></p>
42,805,750
Differences Between Dockerfile Instructions in Shell and Exec Form
<p>What is the difference between <em>shell</em> and <em>exec</em> form for</p> <p><code>CMD</code>:</p> <pre><code>CMD python my_script.py arg </code></pre> <p>vs.</p> <pre><code>CMD [&quot;python&quot;, &quot;my_script.py&quot;, &quot;arg&quot;] </code></pre> <p><code>ENTRYPOINT</code>:</p> <pre><code>ENTRYPOINT ./bin/main </code></pre> <p>vs.</p> <pre><code>ENTRYPOINT [&quot;./bin/main&quot;] </code></pre> <p>and <code>RUN</code>:</p> <pre><code>RUN npm start </code></pre> <p>vs.</p> <pre><code>RUN [&quot;npm&quot;, &quot;start&quot;] </code></pre> <p><code>Dockerfile</code> instructions?</p>
42,808,931
2
1
null
2017-03-15 09:30:54.46 UTC
13
2022-09-10 13:43:54.75 UTC
2021-07-03 16:31:48.377 UTC
null
5,963,316
null
742,082
null
1
58
docker|dockerfile
24,875
<p>There are two differences between the shell form and the exec form. According to <a href="https://docs.docker.com/engine/reference/builder/#run" rel="noreferrer">the documentation</a>, the exec form is the preferred form. These are the two differences:</p> <blockquote> <p>The exec form is parsed as a JSON array, which means that you must use double-quotes (β€œ) around words not single-quotes (β€˜).</p> <p>Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell processing does not happen. For example, CMD [ &quot;echo&quot;, &quot;$HOME&quot; ] will not do variable substitution on $HOME. If you want shell processing then either use the shell form or execute a shell directly, for example: CMD [ &quot;sh&quot;, &quot;-c&quot;, &quot;echo $HOME&quot; ]. When using the exec form and executing a shell directly, as in the case for the shell form, it is the shell that is doing the environment variable expansion, not docker.</p> </blockquote> <p>Some additional subtleties here are:</p> <blockquote> <p>The exec form makes it possible to avoid shell string munging, and to RUN commands using a base image that does not contain the specified shell executable.</p> <p>In the shell form you can use a \ (backslash) to continue a single RUN instruction onto the next line.</p> </blockquote> <p>There is also a third form for <a href="https://docs.docker.com/engine/reference/builder/#cmd" rel="noreferrer"><code>CMD</code></a>:</p> <blockquote> <p>CMD [&quot;param1&quot;,&quot;param2&quot;] (as default parameters to ENTRYPOINT)</p> </blockquote> <p>Additionally, the exec form is required for <code>CMD</code> if you are using it as parameters/arguments to <code>ENTRYPOINT</code> that are intended to be overwritten.</p>
22,875,270
Error installing bcrypt with pip on OS X: can't find ffi.h (libffi is installed)
<p>I'm getting this error when trying to install bcrypt with pip. I have libffi installed in a couple places (the Xcode OS X SDK, and from homebrew), but I don't know how to tell pip to look for it. Any suggestions?</p> <pre><code>Downloading/unpacking bcrypt==1.0.2 (from -r requirements.txt (line 41)) Running setup.py egg_info for package bcrypt OS/X: confusion between 'cc' versus 'gcc' (see issue 123) will not use '__thread' in the C code c/_cffi_backend.c:14:10: fatal error: 'ffi.h' file not found #include &lt;ffi.h&gt; ^ 1 error generated. Traceback (most recent call last): File "&lt;string&gt;", line 16, in &lt;module&gt; File "/Users/cody/virtualenvs/analytics/build/bcrypt/setup.py", line 104, in &lt;module&gt; "Programming Language :: Python :: 3.3", File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/core.py", line 112, in setup _setup_distribution = dist = klass(attrs) File "build/bdist.macosx-10.9-intel/egg/setuptools/dist.py", line 239, in __init__ File "build/bdist.macosx-10.9-intel/egg/setuptools/dist.py", line 264, in fetch_build_eggs File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 620, in resolve dist = best[req.key] = env.best_match(req, ws, installer) File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 858, in best_match return self.obtain(req, installer) # try and download/install File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 870, in obtain return installer(requirement) File "build/bdist.macosx-10.9-intel/egg/setuptools/dist.py", line 314, in fetch_build_egg File "build/bdist.macosx-10.9-intel/egg/setuptools/command/easy_install.py", line 593, in easy_install File "build/bdist.macosx-10.9-intel/egg/setuptools/command/easy_install.py", line 623, in install_item File "build/bdist.macosx-10.9-intel/egg/setuptools/command/easy_install.py", line 811, in install_eggs File "build/bdist.macosx-10.9-intel/egg/setuptools/command/easy_install.py", line 1017, in build_and_install File "build/bdist.macosx-10.9-intel/egg/setuptools/command/easy_install.py", line 1005, in run_setup distutils.errors.DistutilsError: Setup script exited with error: command 'cc' failed with exit status 1 Complete output from command python setup.py egg_info: OS/X: confusion between 'cc' versus 'gcc' (see issue 123) will not use '__thread' in the C code c/_cffi_backend.c:14:10: fatal error: 'ffi.h' file not found #include &lt;ffi.h&gt; ^ 1 error generated. Traceback (most recent call last): File "&lt;string&gt;", line 16, in &lt;module&gt; File "/Users/cody/virtualenvs/analytics/build/bcrypt/setup.py", line 104, in &lt;module&gt; "Programming Language :: Python :: 3.3", File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/core.py", line 112, in setup _setup_distribution = dist = klass(attrs) File "build/bdist.macosx-10.9-intel/egg/setuptools/dist.py", line 239, in __init__ File "build/bdist.macosx-10.9-intel/egg/setuptools/dist.py", line 264, in fetch_build_eggs File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 620, in resolve dist = best[req.key] = env.best_match(req, ws, installer) File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 858, in best_match return self.obtain(req, installer) # try and download/install File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 870, in obtain return installer(requirement) File "build/bdist.macosx-10.9-intel/egg/setuptools/dist.py", line 314, in fetch_build_egg File "build/bdist.macosx-10.9-intel/egg/setuptools/command/easy_install.py", line 593, in easy_install File "build/bdist.macosx-10.9-intel/egg/setuptools/command/easy_install.py", line 623, in install_item File "build/bdist.macosx-10.9-intel/egg/setuptools/command/easy_install.py", line 811, in install_eggs File "build/bdist.macosx-10.9-intel/egg/setuptools/command/easy_install.py", line 1017, in build_and_install File "build/bdist.macosx-10.9-intel/egg/setuptools/command/easy_install.py", line 1005, in run_setup distutils.errors.DistutilsError: Setup script exited with error: command 'cc' failed with exit status 1 ---------------------------------------- Command python setup.py egg_info failed with error code 1 in /Users/cody/virtualenvs/analytics/build/bcrypt </code></pre>
25,854,749
4
0
null
2014-04-05 00:51:36.633 UTC
21
2017-04-16 04:14:27.693 UTC
2017-04-16 04:14:27.693 UTC
null
1,033,581
null
1,431,252
null
1
38
python|macos|pip|bcrypt|libffi
25,810
<p>Without using sudo and CFLAGS and CPPFLAGS (unnecessary for pip):</p> <pre><code>$ brew install pkg-config libffi $ export PKG_CONFIG_PATH=/usr/local/Cellar/libffi/3.0.13/lib/pkgconfig/ $ pip install bcrypt </code></pre>
50,606,758
VSCode: How do you autoformat on save?
<p>In Visual Studio Code, how do you automatically format your source code when the file is saved?</p>
50,606,759
4
1
null
2018-05-30 14:05:08.373 UTC
4
2022-02-23 20:37:17.817 UTC
null
null
null
null
10,335
null
1
43
formatting|visual-studio-code|vscode-settings
52,800
<p>Enable &quot;Format On Save&quot; by setting</p> <pre><code>&quot;editor.formatOnSave&quot;: true </code></pre> <p>And since <a href="https://code.visualstudio.com/updates/v1_49#_only-format-modified-text" rel="noreferrer">version <strong>1.49.0</strong></a> <code>editor.formatOnSaveMode</code> has the option <code>modifications</code> that will just format the code <em>you</em> modified. Great when you change someone else code.</p> <p>You can also set it just for one specific language:</p> <pre><code>&quot;[python]&quot;: { &quot;editor.tabSize&quot;: 4, &quot;editor.insertSpaces&quot;: true, &quot;editor.formatOnSave&quot;: true # }, </code></pre> <p>Since version <strong>1.6.1</strong>, Vscode supports &quot;<em>Format On Save</em>&quot;. It will automatically use a relevant installed formatter extension to format the whole document.</p> <p>If you are modifying other users code and your team don't standardize a formatter, a nice option also is <code>&quot;editor.formatOnSaveMode&quot;: &quot;modifications&quot;,</code>. Unfortunately, the excellent black formatter does <a href="https://github.com/psf/black/issues/134" rel="noreferrer">not support this feature</a>.</p>
2,872,089
How can I make Perl and Python print each line of the program being executed?
<p>I know that <code>bash -x script.sh</code> will execute script printing each line before actual execution. How to make Perl and Python interpreters do the same?</p>
2,872,117
3
0
null
2010-05-20 08:28:13.913 UTC
13
2019-07-17 12:40:55.523 UTC
2016-02-09 18:34:33.153 UTC
null
584,940
null
266,720
null
1
44
python|bash|perl|debugging|trace
10,135
<p><a href="http://search.cpan.org/~mjd/Devel-Trace-0.10/Trace.pm" rel="noreferrer">Devel::Trace</a> is the Perl analogue, the <a href="http://docs.python.org/library/trace.html" rel="noreferrer">trace module</a> is Python's.</p>
2,501,861
How can I remove a JPanel from a JFrame?
<p>Recently I asked here <a href="https://stackoverflow.com/questions/2492513/why-i-cannot-add-a-jpanel-to-jframe">how to add a new JPanel to JFrame</a>. The answer helped me to get a working code. But not I have a related question: "How can I remove an old JPanel". I need that because of the following problem.</p> <p>A new JPanel appears appears when I want (either time limit is exceeded or user press the "Submit" button). But in several seconds some element of the old JPanel appears together with the component of the new JPanel. I do not understand why it happens.</p> <p>I thought that it is because I have to other threads which update the window. But the first thread just add the old panel once (so, it should be finished). And in the second thread I have a loop which is broken (so, it also should be finished).</p> <p>Here is my code:</p> <pre><code>private Thread controller = new Thread() { public void run() { // First we set the initial pane (for the selection of partner). SwingUtilities.invokeLater(new Runnable() { public void run() { frame.getContentPane().add(generatePartnerSelectionPanel()); frame.invalidate(); frame.validate(); } }); // Update the pane for the selection of the parnter. for (int i=40; i&gt;0; i=i-1) { final int sec = i; SwingUtilities.invokeLater(new Runnable() { public void run() { timeLeftLabel.setText(sec + " seconds left."); } }); try { Thread.sleep(1000); } catch (InterruptedException e) { } if (partnerSubmitted) { break; } } // For the given user the selection phase is finished (either the time is over or form was submitted). SwingUtilities.invokeLater(new Runnable() { public void run() { frame.getContentPane().add(generateWaitForGamePanel()); frame.invalidate(); frame.validate(); } }); } }; </code></pre>
2,502,033
4
1
null
2010-03-23 16:49:24.503 UTC
3
2018-01-31 11:40:54.993 UTC
2017-05-23 12:10:19.847 UTC
null
-1
null
245,549
null
1
12
java|user-interface|swing|multithreading
85,311
<p>the easiest way to remove a component (panel) from a container (frame) is to keep a reference to it, and then call <code>Container.remove(Component)</code> ie:</p> <pre><code>private Thread controller = new Thread() { public void run() { final Component panel1 = generatePartnerSelectionPanel(); // First we set the initial pane (for the selection of partner). SwingUtilities.invokeLater(new Runnable() { public void run() { frame.getContentPane().add(panel1); frame.invalidate(); frame.validate(); } }); // Update the pane for the selection of the parnter. for (int i=40; i&gt;0; i=i-1) { final int sec = i; SwingUtilities.invokeLater(new Runnable() { public void run() { timeLeftLabel.setText(sec + " seconds left."); } }); try {Thread.sleep(1000);} catch (InterruptedException e) {} if (partnerSubmitted) {break;} } // For the given user the selection phase is finished (either the time is over or form was submitted). SwingUtilities.invokeLater(new Runnable() { public void run() { frame.getContentPane().remove(panel1); frame.getContentPane().add(generateWaitForGamePanel()); frame.invalidate(); frame.validate(); } }); } }; </code></pre> <p>i haven't tested this code but it should work.</p>
3,160,267
How to create an array of enums
<p>I have about 30 different flagged enums that I would like to put into an array for indexing and quick access. Let me also claify that I do not have 1 enum with 30 values but I have 30 enums with differing amounts of values.</p> <p>The goal would be to add them to an array at a specifed index. This way I can write a functions in which I can pass the array index into for setting particuler values of the enum.</p> <p>Updated: Here is an example of what I am wanting to do.</p> <p>enum main( enum1 = 0, enum2 = 1, enumn = n-1 ) - this has indexs which would match the index of the associated enum</p> <p>[flag] enum1(value1=0, value2=1, value3=2, value4=4...)</p> <p>[flag] enum2("")</p> <p>[flag] enum2("")</p> <p>since I am using flagable enums I have a class like the following</p> <pre><code>public static class CEnumWorker { public static enum1 myEnum1 = enum1.value1; public static enum2 myEnum2 = enum2.value1; public static enumN myEnumN = enumN.value1; //I would then have functions that set the flags on the enums. I would like to access the enums through an array or other method so that I do not have to build a large switch statement to know which enum I am wanting to manipulate } </code></pre>
3,160,296
4
4
null
2010-07-01 17:37:15.887 UTC
1
2010-07-01 20:35:48.033 UTC
2010-07-01 19:05:38.643 UTC
null
381,347
null
381,347
null
1
13
c#|arrays|enums
83,480
<p>Since you have 30 different types of enums, you can't create a strongly typed array for them. The best you could do would be an array of System.Enum:</p> <pre><code>Enum[] enums = new Enum[] { enum1.Value1, enum2.Value2, etc }; </code></pre> <p>You would then have to cast when pulling an enum out of the array if you need the strongly typed enum value.</p>
37,644,118
Initializing mysql directory error
<p>I checked this page: <a href="http://dev.mysql.com/doc/refman/5.7/en/mysql-install-db.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.7/en/mysql-install-db.html</a></p> <p><code>mysql_install_db</code> is removed, however, when I use <code>mysqld --initialize</code>. It promotes these errors and warning.</p> <pre><code>[Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details). [ERROR] --initialize specified but the data directory has files in it. Aborting. [ERROR] Aborting </code></pre> <p>The first one can be ignored according to this:<a href="https://stackoverflow.com/questions/15701636/how-to-enable-explicit-defaults-for-timestamp">How to enable explicit_defaults_for_timestamp?</a></p> <p>I don't know how to solve the second problem.</p>
37,646,793
11
0
null
2016-06-05 16:21:02.567 UTC
3
2021-08-16 14:09:26.683 UTC
2017-05-23 11:46:20.177 UTC
null
-1
null
4,873,087
null
1
28
php|mysql
83,445
<p>Pls, read error carefully:</p> <blockquote> <p>[ERROR] --initialize specified but the <strong>data directory has files in it</strong>. Aborting.</p> </blockquote> <p>Your directory is not empty. You have to remove all the contents of it or choose another one.</p>
28,514,120
How to make user's email unique in mongoDB?
<p>I am making a collection of user's data. This will be pretty basic consisting of user's email, user's password (hashed), and an array of strings.</p> <pre><code>{ email: '[email protected]', password: 'password hash', arr: [] } </code></pre> <p>I want to make sure that there can't be two inserts with the same <code>email</code>. I read that the <code>_id</code> of mongoDB is unique by default, and it uses some special data structure for improved performance.</p> <p>How can I make sure that the <code>email</code> remains unique, and if possible can I leverage the performance benefits provided by the <code>_id</code> field ?</p> <p>Edit: I also want to make sure that there are no <code>null</code> values for <code>email</code> and that there are no documents which do not contain the <code>email</code> field.</p>
28,514,316
3
0
null
2015-02-14 09:12:32.37 UTC
3
2020-11-03 08:20:52.033 UTC
2015-02-14 14:11:19.227 UTC
null
1,641,882
null
1,641,882
null
1
24
mongodb|indexing
47,558
<p>You can do it by creating a unique index for your email field.</p> <p><a href="http://docs.mongodb.org/manual/tutorial/create-a-unique-index/" rel="nofollow noreferrer">http://docs.mongodb.org/manual/tutorial/create-a-unique-index/</a></p>
36,446,279
Jenkins HTML Publisher Plugin : allow script permission issue
<p>I'm trying to report my <code>.html</code> file with HTML publisher plugin in Jenkins however,since HTML publisher is updated to version 1.10, can't publish HTML.</p> <p><strong>Error message I'm getting:</strong></p> <pre><code>Blocked script execution in '{mydomain}' because the document's frame is sandboxed and the 'allow-scripts' permission is not set. Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag. </code></pre> <p>I found this doc: <a href="https://wiki.jenkins-ci.org/display/JENKINS/Configuring+Content+Security+Policy" rel="noreferrer">https://wiki.jenkins-ci.org/display/JENKINS/Configuring+Content+Security+Policy</a></p> <p>It tells about CSP.</p> <p><strong>I run Jenkins with arg :</strong> </p> <pre><code>/usr/bin/java -Djava.awt.headless=true -Dhudson.model.DirectoryBrowserSupport.CSP=sandbox allow-scripts; style-src 'unsafe-inline' *;script-src 'unsafe-inline' *; -jar /usr/share/jenkins/jenkins.war --webroot=/var/cache/jenkins/war --httpPort=8080 --ajp13Port=-1 </code></pre> <p>but still got same error above.</p> <p><strong>what i tried args :</strong> </p> <pre><code> 1. -Dhudson.model.DirectoryBrowserSupport.CSP="sandbox; default-src 'self';" 2. -Dhudson.model.DirectoryBrowserSupport.CSP= 3. -Dhudson.model.DirectoryBrowserSupport.CSP="sandbox; default-src *;" 4. -Dhudson.model.DirectoryBrowserSupport.CSP="sandbox allow-scripts; default-src *;" </code></pre> <p><strong>.html is located in :</strong> </p> <pre><code>{mydomain}/job/{job_name}/Doc/index.html </code></pre>
36,446,573
3
0
null
2016-04-06 09:01:40.58 UTC
8
2021-05-13 06:39:44.847 UTC
2016-09-07 04:50:07.6 UTC
null
4,483,015
null
6,165,553
null
1
12
jenkins|content-security-policy
12,241
<p>Can you have a try with a blank CSP option?</p> <pre><code>/usr/bin/java -Djava.awt.headless=true -Dhudson.model.DirectoryBrowserSupport.CSP= -jar /usr/share/jenkins/jenkins.war --webroot=/var/cache/jenkins/war --httpPort=8080 --ajp13Port=-1 </code></pre> <p>On my Jenkins instance, it solved my reporting issues.</p> <p>I know it's not a safe option, but I didn't find another solution :(</p>
36,280,056
Page not found 404 Django media files
<p>I am able to upload the files to media folder( <code>'/peaceroot/www/media/'</code>) that I have set up in <code>settings.py</code> as below</p> <pre><code>MEDIA_ROOT = '/peaceroot/www/media/' MEDIA_URL = '/media/' </code></pre> <p>But through admin I tried to access the uploaded image file</p> <p><a href="http://localhost:8000/media/items/1a39246c-4160-4cb2-a842-12a1ffd72b3b.jpg" rel="noreferrer">http://localhost:8000/media/items/1a39246c-4160-4cb2-a842-12a1ffd72b3b.jpg</a></p> <p>then I am getting 404 error. </p> <p>The file exists at <code>peaceroot/www/media/items/1a39246c-4160-4cb2-a842-12a1ffd72b3b.jpg</code></p>
36,280,131
6
0
null
2016-03-29 09:14:35.87 UTC
12
2021-04-18 19:50:35.273 UTC
2020-07-07 17:55:25.307 UTC
null
4,511,992
null
1,579,374
null
1
52
python|django|http-status-code-404|django-settings|django-media
41,170
<p>Add media url entry in your project urlpatterns:</p> <pre><code>from django.conf.urls.static import static from django.conf import settings ... urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) </code></pre>
38,338,906
NSubstitute - mock throwing an exception in method returning Task
<p>Using <a href="http://nsubstitute.github.io" rel="noreferrer">NSubstitute</a>, how do you mock an exception being thrown in a method returning a Task?</p> <p>Let's say our method signature looks something like this:</p> <pre><code>Task&lt;List&lt;object&gt;&gt; GetAllAsync(); </code></pre> <p>Here's how NSubstitute docs say to mock throwing exceptions for non-void return types. But this doesn't compile :(</p> <pre><code>myService.GetAllAsync().Returns(x =&gt; { throw new Exception(); }); </code></pre> <p>So how do you accomplish this?</p>
50,027,096
4
0
null
2016-07-12 21:07:50.423 UTC
3
2022-09-22 14:13:11.957 UTC
2018-03-07 23:04:33.757 UTC
null
2,874,896
null
674,237
null
1
33
c#|.net|asynchronous|task|nsubstitute
23,728
<p>Actually, the accepted answer mocks a synchronous exception being thrown, that is not the <em>real</em> <code>async</code> behavior. The correct way to mock is:</p> <pre><code>var myService = Substitute.For&lt;IMyService&gt;(); myService.GetAllAsync() .Returns(Task.FromException&lt;List&lt;object&gt;&gt;(new Exception("some error"))); </code></pre> <p>Let's say you had this code and <code>GetAllAsync()</code></p> <pre><code>try { var result = myService.GetAllAsync().Result; return result; } catch (AggregateException ex) { // whatever, do something here } </code></pre> <p>The <code>catch</code> would only be executed with <code>Returns(Task.FromException&gt;()</code>, not with the accepted answer since it synchronously throws the exception.</p>
162,897
Marshal "char *" in C#
<p>Given the following C function in a DLL:</p> <pre><code>char * GetDir(char* path ); </code></pre> <p>How would you P/Invoke this function into C# and marshal the char * properly. .NET seems to know how to do LPCTSTR but when I can't figure out any marshaling that doesn't cause a NotSupportedException to fire when calling this function.</p>
163,573
2
0
null
2008-10-02 15:12:59.627 UTC
8
2008-10-02 17:32:45.233 UTC
null
null
null
Adam Haile
194
null
1
25
.net|pinvoke|marshalling
39,250
<p>OregonGhost's answer is only correct if the char* returned from GetDir is either allocated in HGlobal or LocalAlloc. I can't remember which one but the CLR will assume that any string return type from a PInvoke function was allocated with one or the other. </p> <p>A more robust way is to type the return of GetDir to be IntPtr. Then you can use any of the Marshal.PtrToStringAnsi functions in order to get out a string type. It also gives you th flexibility of freeing the string in the manner of your choosing. </p> <pre><code> [DllImport("your.dll", CharSet = CharSet.Ansi)] IntPtr GetDir(StringBuilder path); </code></pre> <p>Can you give us any other hints as to the behavior of GetDir? Does it modify the input string? How is the value which is returned allocated? If you can provide that I can give a much better answer. </p>
3,071,359
Set a default value to a property
<p>Is it possible to set a default value without the body of a property? Preferably with annotations.</p> <pre><code>[SetTheDefaultValueTo(true)] public bool IsTrue { get; set; } [SetTheDefaultValueTo(false)] public bool IsFalse { get; set; } public void Something() { var isTrue = this.IsTrue; var isFalse = this.IsFalse; } </code></pre>
3,071,455
5
0
null
2010-06-18 16:18:22.91 UTC
4
2020-07-21 07:34:00.587 UTC
2010-06-18 16:28:12.373 UTC
null
340,760
null
340,760
null
1
38
c#|.net
72,073
<p>No, there is no built-in way to set the value of a property with metadata. You could use a factory of some sort that would build instances of a class with reflection and then that could set the default values. But in short, you need to use the constructors (or field setters, which are lifted to the constructor) to set the default values.</p> <p>If you have several overloads for your constructor, you may want to look at <a href="http://www.csharp411.com/constructor-chaining/" rel="noreferrer">constructor chaining</a>.</p> <p>Using C# 6+, you are able to do something like this...</p> <pre><code>public string MyValue { get; set; } = &quot;My Default&quot;; </code></pre> <p>Oh, it gets more fun because people have even requested something like this...</p> <pre><code>// this code won't compile! public string MyValue { private string _myValue; get { return _myValue ?? &quot;My Default&quot;; } set { _myValue = value; } } </code></pre> <p>... the advantage being that you could control the scope of the field to only be accesible in the property code so you don't have to worry about anything else in your class playing with the state without using the getter/setter.</p>
2,941,960
A call to PInvoke function '[...]' has unbalanced the stack
<p>I'm getting this weird error on some stuff I've been using for quite a while. It may be a new thing in Visual Studio 2010 but I'm not sure.<br> I'm trying to call a unamanged function written in C++ from C#.<br> From what I've read on the internet and the error message itself it's got something to do with the fact that the signature in my C# file is not the same as the one from C++ but I really can't see it.<br> First of all this is my unamanged function below: </p> <pre><code>TEngine GCreateEngine(int width,int height,int depth,int deviceType); </code></pre> <p>And here is my function in C#: </p> <pre><code>[DllImport("Engine.dll", EntryPoint = "GCreateEngine", CallingConvention = CallingConvention.StdCall)] public static extern IntPtr CreateEngine(int width,int height,int depth,int device); </code></pre> <p>When I debug into C++ I see all arguments just fine so thus I can only think it's got something to do with transforming from TEngine (which is a pointer to a class named CEngine) to IntPtr. I've used this before in VS2008 with no problem.</p>
2,941,979
5
1
null
2010-05-31 07:19:12.49 UTC
8
2016-10-20 15:18:40.53 UTC
2016-10-20 15:18:01.737 UTC
null
1,015,495
null
342,307
null
1
49
c#|c++|pinvoke|unmanaged|managed
44,759
<p>Maybe the problem lies in the calling convention. Are you sure the unmanaged function was compiled as stdcall and not something else ( i would guess fastcall ) ?</p>
2,859,753
What is the simplest C# function to parse a JSON string into an object?
<p>What is the simplest C# function to parse a JSON string into a object and display it (C# XAML WPF)? (for example object with 2 arrays - arrA and arrB) </p>
2,859,813
5
0
null
2010-05-18 18:01:32.803 UTC
14
2015-09-11 06:40:48.78 UTC
2013-06-28 06:51:12.76 UTC
null
2,071,395
null
434,051
null
1
51
c#|.net|wpf|json
117,475
<pre><code>DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(YourObjectType)); YourObjectType yourObject = (YourObjectType)serializer.ReadObject(jsonStream); </code></pre> <p>You could also use the <code>JavaScriptSerializer</code>, but <code>DataContractJsonSerializer</code> is supposedly better able to handle complex types.</p> <p>Oddly enough JavaScriptSerializer was once deprecated (in 3.5) and then resurrected because of ASP.NET MVC (in 3.5 SP1). That would definitely be enough to shake my confidence and lead me to use <code>DataContractJsonSerializer</code> since it is hard baked for WCF.</p>
2,437,169
What is the total amount of public IPv4 addresses?
<p>Yes, I am needing to know what the total number possible IPs in the public IPv4 space. </p> <p>I'm not sure where to even get a neat list of all the IP address ranges, so could someone point me to a resource to calculate this myself or calculate the total number of IPs for me? </p> <p>Also, by Public IPs I mean not counting reserved or private-range IP addresses.. Only the ones that can be access through the internet. </p>
2,437,185
5
0
null
2010-03-13 03:31:51.67 UTC
12
2020-09-11 11:39:40.67 UTC
null
null
null
null
69,742
null
1
61
ip-address|ipv4
112,754
<p>According to <a href="http://en.wikipedia.org/wiki/Reserved_IP_addresses" rel="noreferrer">Reserved IP addresses</a> there are 588,514,304 reserved addresses and since there are 4,294,967,296 (2^32) IPv4 addressess in total, there are <strong>3,706,452,992</strong> public addresses.</p> <p>And too many <em>addresses</em> in this post.</p>
2,906,925
How do I pass an object from one activity to another on Android?
<p>I need to be able to use one object in multiple activities within my app, and it needs to be the <em>same</em> object. What is the best way to do this? </p> <p>I have tried making the object "public static" so it can be accessed by other activities, but for some reason this just isn't cutting it. Is there another way of doing this?</p>
7,923,530
6
0
null
2010-05-25 17:29:05.243 UTC
43
2017-01-27 16:57:40.643 UTC
2015-11-22 13:35:04.767 UTC
null
63,550
null
339,428
null
1
126
android|object|android-activity
167,340
<p>When you are creating an object of intent, you can take advantage of following two methods for passing objects between two activities.</p> <p><a href="http://developer.android.com/reference/android/os/Bundle.html#putParcelable%28java.lang.String,%20android.os.Parcelable%29" rel="noreferrer">putParcelable</a></p> <p><a href="http://developer.android.com/reference/android/os/Bundle.html#putSerializable%28java.lang.String,%20java.io.Serializable%29" rel="noreferrer">putSerializable</a></p> <p>You can have your class implement either <a href="http://developer.android.com/reference/android/os/Parcelable.html" rel="noreferrer">Parcelable</a> or <a href="http://developer.android.com/reference/java/io/Serializable.html" rel="noreferrer">Serializable</a>. Then you can pass around your custom classes across activities. I have found this very useful.</p> <p>Here is a small snippet of code I am using</p> <pre><code>CustomListing currentListing = new CustomListing(); Intent i = new Intent(); Bundle b = new Bundle(); b.putParcelable(Constants.CUSTOM_LISTING, currentListing); i.putExtras(b); i.setClass(this, SearchDetailsActivity.class); startActivity(i); </code></pre> <p>And in newly started activity code will be something like this...</p> <pre><code>Bundle b = this.getIntent().getExtras(); if (b != null) mCurrentListing = b.getParcelable(Constants.CUSTOM_LISTING); </code></pre>
2,779,251
How can I convert JSON to a HashMap using Gson?
<p>I'm requesting data from a server which returns data in the JSON format. Casting a HashMap into JSON when making the request wasn't hard at all but the other way seems to be a little tricky. The JSON response looks like this:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;header&quot; : { &quot;alerts&quot; : [ { &quot;AlertID&quot; : &quot;2&quot;, &quot;TSExpires&quot; : null, &quot;Target&quot; : &quot;1&quot;, &quot;Text&quot; : &quot;woot&quot;, &quot;Type&quot; : &quot;1&quot; }, { &quot;AlertID&quot; : &quot;3&quot;, &quot;TSExpires&quot; : null, &quot;Target&quot; : &quot;1&quot;, &quot;Text&quot; : &quot;woot&quot;, &quot;Type&quot; : &quot;1&quot; } ], &quot;session&quot; : &quot;0bc8d0835f93ac3ebbf11560b2c5be9a&quot; }, &quot;result&quot; : &quot;4be26bc400d3c&quot; } </code></pre> <p>What way would be easiest to access this data? I'm using the GSON module.</p>
15,943,171
16
1
null
2010-05-06 07:29:34.93 UTC
87
2022-03-27 17:52:02.75 UTC
2021-05-10 16:37:55.257 UTC
null
6,715,736
null
304,151
null
1
311
java|json|dictionary|hashmap|gson
371,900
<p>Here you go:</p> <pre><code>import java.lang.reflect.Type; import com.google.gson.reflect.TypeToken; Type type = new TypeToken&lt;Map&lt;String, String&gt;&gt;(){}.getType(); Map&lt;String, String&gt; myMap = gson.fromJson("{'k1':'apple','k2':'orange'}", type); </code></pre>
3,142,495
Deserialize JSON into C# dynamic object?
<p>Is there a way to deserialize JSON content into a C# dynamic type? It would be nice to skip creating a bunch of classes in order to use the <code>DataContractJsonSerializer</code>.</p>
3,806,407
32
5
null
2010-06-29 16:04:01.637 UTC
346
2022-08-04 03:53:26.49 UTC
2021-08-13 19:42:46.377 UTC
null
3,739,391
null
6,133
null
1
1,135
c#|.net|json|serialization|dynamic
1,009,910
<p>If you are happy to have a dependency upon the <code>System.Web.Helpers</code> assembly, then you can use the <a href="http://msdn.microsoft.com/en-us/library/system.web.helpers.json(v=vs.111).aspx" rel="noreferrer"><code>Json</code></a> class:</p> <pre><code>dynamic data = Json.Decode(json); </code></pre> <p>It is included with the MVC framework as an <a href="https://stackoverflow.com/q/8037895/24874">additional download</a> to the .NET 4 framework. Be sure to give Vlad an upvote if that's helpful! However if you cannot assume the client environment includes this DLL, then read on.</p> <hr> <p>An alternative deserialisation approach is suggested <a href="http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx" rel="noreferrer">here</a>. I modified the code slightly to fix a bug and suit my coding style. All you need is this code and a reference to <code>System.Web.Extensions</code> from your project:</p> <pre><code>using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Dynamic; using System.Linq; using System.Text; using System.Web.Script.Serialization; public sealed class DynamicJsonConverter : JavaScriptConverter { public override object Deserialize(IDictionary&lt;string, object&gt; dictionary, Type type, JavaScriptSerializer serializer) { if (dictionary == null) throw new ArgumentNullException("dictionary"); return type == typeof(object) ? new DynamicJsonObject(dictionary) : null; } public override IDictionary&lt;string, object&gt; Serialize(object obj, JavaScriptSerializer serializer) { throw new NotImplementedException(); } public override IEnumerable&lt;Type&gt; SupportedTypes { get { return new ReadOnlyCollection&lt;Type&gt;(new List&lt;Type&gt;(new[] { typeof(object) })); } } #region Nested type: DynamicJsonObject private sealed class DynamicJsonObject : DynamicObject { private readonly IDictionary&lt;string, object&gt; _dictionary; public DynamicJsonObject(IDictionary&lt;string, object&gt; dictionary) { if (dictionary == null) throw new ArgumentNullException("dictionary"); _dictionary = dictionary; } public override string ToString() { var sb = new StringBuilder("{"); ToString(sb); return sb.ToString(); } private void ToString(StringBuilder sb) { var firstInDictionary = true; foreach (var pair in _dictionary) { if (!firstInDictionary) sb.Append(","); firstInDictionary = false; var value = pair.Value; var name = pair.Key; if (value is string) { sb.AppendFormat("{0}:\"{1}\"", name, value); } else if (value is IDictionary&lt;string, object&gt;) { new DynamicJsonObject((IDictionary&lt;string, object&gt;)value).ToString(sb); } else if (value is ArrayList) { sb.Append(name + ":["); var firstInArray = true; foreach (var arrayValue in (ArrayList)value) { if (!firstInArray) sb.Append(","); firstInArray = false; if (arrayValue is IDictionary&lt;string, object&gt;) new DynamicJsonObject((IDictionary&lt;string, object&gt;)arrayValue).ToString(sb); else if (arrayValue is string) sb.AppendFormat("\"{0}\"", arrayValue); else sb.AppendFormat("{0}", arrayValue); } sb.Append("]"); } else { sb.AppendFormat("{0}:{1}", name, value); } } sb.Append("}"); } public override bool TryGetMember(GetMemberBinder binder, out object result) { if (!_dictionary.TryGetValue(binder.Name, out result)) { // return null to avoid exception. caller can check for null this way... result = null; return true; } result = WrapResultObject(result); return true; } public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) { if (indexes.Length == 1 &amp;&amp; indexes[0] != null) { if (!_dictionary.TryGetValue(indexes[0].ToString(), out result)) { // return null to avoid exception. caller can check for null this way... result = null; return true; } result = WrapResultObject(result); return true; } return base.TryGetIndex(binder, indexes, out result); } private static object WrapResultObject(object result) { var dictionary = result as IDictionary&lt;string, object&gt;; if (dictionary != null) return new DynamicJsonObject(dictionary); var arrayList = result as ArrayList; if (arrayList != null &amp;&amp; arrayList.Count &gt; 0) { return arrayList[0] is IDictionary&lt;string, object&gt; ? new List&lt;object&gt;(arrayList.Cast&lt;IDictionary&lt;string, object&gt;&gt;().Select(x =&gt; new DynamicJsonObject(x))) : new List&lt;object&gt;(arrayList.Cast&lt;object&gt;()); } return result; } } #endregion } </code></pre> <p>You can use it like this:</p> <pre><code>string json = ...; var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new[] { new DynamicJsonConverter() }); dynamic obj = serializer.Deserialize(json, typeof(object)); </code></pre> <p>So, given a JSON string:</p> <pre><code>{ "Items":[ { "Name":"Apple", "Price":12.3 }, { "Name":"Grape", "Price":3.21 } ], "Date":"21/11/2010" } </code></pre> <p>The following code will work at runtime:</p> <pre><code>dynamic data = serializer.Deserialize(json, typeof(object)); data.Date; // "21/11/2010" data.Items.Count; // 2 data.Items[0].Name; // "Apple" data.Items[0].Price; // 12.3 (as a decimal) data.Items[1].Name; // "Grape" data.Items[1].Price; // 3.21 (as a decimal) </code></pre>
45,696,761
Create a reusable FormGroup
<p>I am aware of creating custom <em>controls</em> as components, but I can't figure out how to create custom <em>groups</em>.</p> <p>The same we can do this by <a href="https://angular.io/api/forms/ControlValueAccessor" rel="noreferrer">implementing <code>ControlValueAccessor</code></a> and using a custom component like <code>&lt;my-cmp formControlName="foo"&gt;&lt;/my-cmp&gt;</code>, how can we achieve this effect for <a href="https://angular.io/api/forms/FormGroup" rel="noreferrer">a <strong>group</strong></a>?</p> <pre><code>&lt;my-cmp formGroupName="aGroup"&gt;&lt;/my-cmp&gt; </code></pre> <p>Two very common use-cases would be (a) separting a long form into steps, each step in a separate component and (b) encapsulating a group of fields which appear across multiple forms, such as address (group of country, state, city, address, building number) or date of birth (year, month, date).</p> <hr> <h1>Example usage (not actual working code)</h1> <p>Parent has the following form built with <a href="https://angular.io/api/forms/FormBuilder" rel="noreferrer"><code>FormBuilder</code></a>:</p> <pre><code>// parent model form = this.fb.group({ username: '', fullName: '', password: '', address: this.fb.group({ country: '', state: '', city: '', street: '', building: '', }) }) </code></pre> <p>Parent template (inaccessible and non-semantic for brevity):</p> <pre><code>&lt;!-- parent template --&gt; &lt;form [groupName]="form"&gt; &lt;input formControlName="username"&gt; &lt;input formControlName="fullName"&gt; &lt;input formControlName="password"&gt; &lt;address-form-group formGroup="address"&gt;&lt;/address-form-group&gt; &lt;/form&gt; </code></pre> <p>Now this <code>AddressFormGroupComponent</code> knows how to handle a group which has these specific controls inside of it.</p> <pre><code>&lt;!-- child template --&gt; &lt;input formControlName="country"&gt; &lt;input formControlName="state"&gt; &lt;input formControlName="city"&gt; &lt;input formControlName="street"&gt; &lt;input formControlName="building"&gt; </code></pre>
46,025,197
2
0
null
2017-08-15 16:01:41.713 UTC
17
2019-04-11 18:59:21.007 UTC
null
null
null
null
2,131,286
null
1
33
angular|angular-forms
18,896
<p>The piece I was missing was mentioned in <a href="https://stackoverflow.com/a/45736211/2131286">rusev's answer</a>, and that is <strong>injecting the <a href="https://angular.io/api/forms/ControlContainer" rel="noreferrer"><code>ControlContainer</code></a></strong>.</p> <p>Turns out that if you place <code>formGroupName</code> on a component, and if that component injects <code>ControlContainer</code>, you get a reference to the container which contains that form. It's easy from here.</p> <p>We create a sub-form component.</p> <pre><code>@Component({ selector: 'sub-form', template: ` &lt;ng-container [formGroup]="controlContainer.control"&gt; &lt;input type=text formControlName=foo&gt; &lt;input type=text formControlName=bar&gt; &lt;/ng-container&gt; `, }) export class SubFormComponent { constructor(public controlContainer: ControlContainer) { } } </code></pre> <p>Notice how we need a wrapper for the inputs. We don't want a form because this will already be inside a form. So we use an <code>ng-container</code>. This will be striped away from the final DOM so there's no unnecessary element.</p> <p>Now we can just use this component.</p> <pre><code>@Component({ selector: 'my-app', template: ` &lt;form [formGroup]=form&gt; &lt;sub-form formGroupName=group&gt;&lt;/sub-form&gt; &lt;input type=text formControlName=baz&gt; &lt;/form&gt; `, }) export class AppComponent { form = this.fb.group({ group: this.fb.group({ foo: 'foo', bar: 'bar', }), baz: 'baz', }) constructor(private fb: FormBuilder) {} } </code></pre> <p>You can see a <a href="https://stackblitz.com/edit/so-45696761?file=app/app.component.ts" rel="noreferrer">live <strong>demo</strong> on StackBlitz</a>.</p> <hr> <p>This is an improvement over rusev's answer in a few aspects:</p> <ul> <li>no custom <code>groupName</code> input; instead we use the <code>formGroupName</code> provided by Angular</li> <li>no need for <code>@SkipSelf</code> decorator, since we're <em>not</em> injecting the parent control, but the one we need</li> <li>no awkward <code>group.control.get(groupName)</code> which is going to the parent in order to grab itself.</li> </ul>
10,390,989
Python program that finds most frequent word in a .txt file, Must print word and its count
<p>As of right now, I have a function to replace the countChars function,</p> <pre><code>def countWords(lines): wordDict = {} for line in lines: wordList = lines.split() for word in wordList: if word in wordDict: wordDict[word] += 1 else: wordDict[word] = 1 return wordDict </code></pre> <p>but when I run the program it spits out this abomination (this is just an example, there's about two pages of words with a huge number count next to it)</p> <pre><code>before 1478 battle-field 1478 as 1478 any 1478 altogether 1478 all 1478 ago 1478 advanced. 1478 add 1478 above 1478 </code></pre> <p>While obviously this means that the code is sound enough to run, I'm not getting what I want out of it. It needs to print how many times each word is in the file (gb.txt, which is the Gettysburg address) Obviously each word that is in the file isn't in there exactly 1478 times..</p> <p>I'm pretty new at programming, so I'm kind of stumped..</p> <pre><code>from __future__ import division inputFileName = 'gb.txt' def readfile(fname): f = open(fname, 'r') s = f.read() f.close() return s.lower() def countChars(t): charDict = {} for char in t: if char in charDict: charDict[char] += 1 else: charDict[char] = 1 return charDict def findMostCommon(charDict): mostFreq = '' mostFreqCount = 0 for k in charDict: if charDict[k] &gt; mostFreqCount: mostFreqCount = charDict[k] mostFreq = k return mostFreq def printCounts(charDict): for k in charDict: #First, handle some chars that don't show up very well when they print if k == '\n': print '\\n', charDict[k] #newline elif k == ' ': print 'space', charDict[k] elif k == '\t': print '\\t', charDict[k] #tab else: print k, charDict[k] #Normal character - print it with its count def printAlphabetically(charDict): keyList = charDict.keys() keyList.sort() for k in keyList: #First, handle some chars that don't show up very well when they print if k == '\n': print '\\n', charDict[k] #newline elif k == ' ': print 'space', charDict[k] elif k == '\t': print '\\t', charDict[k] #tab else: print k, charDict[k] #Normal character - print it with its count def printByFreq(charDict): aList = [] for k in charDict: aList.append([charDict[k], k]) aList.sort() #Sort into ascending order aList.reverse() #Put in descending order for item in aList: #First, handle some chars that don't show up very well when they print if item[1] == '\n': print '\\n', item[0] #newline elif item[1] == ' ': print 'space', item[0] elif item[1] == '\t': print '\\t', item[0] #tab else: print item[1], item[0] #Normal character - print it with its count def main(): text = readfile(inputFileName) charCounts = countChars(text) mostCommon = findMostCommon(charCounts) #print mostCommon + ':', charCounts[mostCommon] #printCounts(charCounts) #printAlphabetically(charCounts) printByFreq(charCounts) main() </code></pre>
10,398,709
6
0
null
2012-04-30 21:42:53.633 UTC
15
2020-04-05 07:36:33.483 UTC
null
null
null
null
1,364,718
null
1
15
python
77,609
<p>If you need to count a number of words in a passage, then it is better to use regex.</p> <p>Let's start with a simple example:</p> <pre><code>import re my_string = "Wow! Is this true? Really!?!? This is crazy!" words = re.findall(r'\w+', my_string) #This finds words in the document </code></pre> <p>Result:</p> <pre><code>&gt;&gt;&gt; words ['Wow', 'Is', 'this', 'true', 'Really', 'This', 'is', 'crazy'] </code></pre> <p>Note that "Is" and "is" are two different words. My guess is that you want the to count them the same, so we can just capitalize all the words, and then count them.</p> <pre><code>from collections import Counter cap_words = [word.upper() for word in words] #capitalizes all the words word_counts = Counter(cap_words) #counts the number each time a word appears </code></pre> <p>Result:</p> <pre><code>&gt;&gt;&gt; word_counts Counter({'THIS': 2, 'IS': 2, 'CRAZY': 1, 'WOW': 1, 'TRUE': 1, 'REALLY': 1}) </code></pre> <p>Are you good up to here?</p> <p>Now we need to do exactly the same thing we did above just this time we are reading a file.</p> <pre><code>import re from collections import Counter with open('your_file.txt') as f: passage = f.read() words = re.findall(r'\w+', passage) cap_words = [word.upper() for word in words] word_counts = Counter(cap_words) </code></pre>
10,842,829
Will An Associated Object Be Released Automatically?
<p>Note: This other question seems relevant but it's not: <a href="https://stackoverflow.com/questions/6039309">When does an associated object get released?</a></p> <p>I'm adding a second description to a <code>UIView</code> instance as follows:</p> <pre><code>- (void) setSecondDescription:(UIView*)view description2:(NSString*)description2 { objc_setAssociatedObject (view,&amp;key,description2,OBJC_ASSOCIATION_RETAIN); } - (NSString*) secondDescription:(UIView*)view { return (id)objc_getAssociatedObject(view, &amp;key); } </code></pre> <p>If the <code>UIView</code> deallocs, will the associated description 2 get dealloced? Is there any way to get this to happen automatically?</p>
10,843,510
4
0
null
2012-06-01 00:04:14.277 UTC
21
2015-11-30 06:27:53.467 UTC
2017-05-23 11:47:26.357 UTC
null
-1
null
8,047
null
1
18
objective-c|ios
7,198
<p>If you want to actually <strong>see</strong> the description of the entire dealloc timeline, look at WWDC 2011, Session 322, 36:22. However, here's the basic rundown (I wanted to remember it, so this is an actual comment in a piece of my code).</p> <p>Note, that the associated objects are released at the end of the life cycle.</p> <pre><code>// General Information // We take advantage of the documented Deallocation Timeline (WWDC 2011, Session 322, 36:22). // 1. -release to zero // * Object is now deallocating and will die. // * New __weak references are not allowed, and will get nil. // * [self dealloc] is called // 2. Subclass -dealloc // * bottom-most subclass -dealloc is called // * Non-ARC code manually releases iVars // * Walk the super-class chain calling -dealloc // 3. NSObject -dealloc // * Simply calls the ObjC runtime object_dispose() // 4. object_dispose() // * Call destructors for C++ iVars // * Call -release for ARC iVars // * Erase associated references // * Erase __weak references // * Call free() </code></pre>
10,826,064
How can I create a calc mixin to pass as an expression to generate tags?
<p>I am working on a sass stylesheet in which I wish to use the <code>calc</code> element to dynamically size some content. As the <code>calc</code> element has not been standardized, I need to target <code>calc()</code>, <code>-moz-calc()</code>, and <code>-webkit-calc()</code>.</p> <p>Is there a way for me to create a mixin or function that I can pass an expression to so that it will generate the required tags that can then be set as a <code>width</code> or <code>height</code>?</p>
10,826,424
4
0
null
2012-05-31 00:38:10.023 UTC
13
2017-11-23 12:34:42.33 UTC
2016-12-22 15:52:45.337 UTC
null
2,756,409
null
897,794
null
1
41
css|sass
43,305
<p>It would be a basic <a href="http://sass-lang.com/tutorial.html" rel="noreferrer">mixin with an argument</a>, thankfully the expressions are not browser-specific within the supported scope:</p> <pre class="lang-html prettyprint-override"><code>@mixin calc($property, $expression) { #{$property}: -webkit-calc(#{$expression}); #{$property}: calc(#{$expression}); } .test { @include calc(width, "25% - 1em"); } </code></pre> <p>Will render as</p> <pre class="lang-html prettyprint-override"><code>.test { width: -webkit-calc(25% - 1em); width: calc(25% - 1em); } </code></pre> <p>You may want to include a "default" value for when calc is not supported.</p>
5,829,413
WPF MVVM - How to Show a view from MainWindowViewModel upon Clicking on button
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/2108949/the-best-approach-to-create-new-window-in-wpf-using-mvvm">The best approach to create new window in WPF using MVVM</a> </p> </blockquote> <p>Hello Friends,</p> <p>I have two view <strong>MainWindowView</strong> and <strong>AddCustomerView</strong>. I have menu containing buttons in MainwindowView.xmal. </p> <p>How could i popup <strong>AddCustomerView from MainWindowViewModel by clicking on button.</strong></p> <p>My App.xmal.cs for Startup code is..</p> <pre><code>base.OnStartup(e); MainWindow window = new MainWindow(); var viewModel = new MainWindowViewModel(); window.DataContext = viewModel; window.Show(); </code></pre> <p>What is the code for showing AddCustomerView in buttonexecute code.</p> <pre><code> public void AddNewCustomerWindowExecute() //This is button handler { // How to show AddCustomerView from MainWindowViewModel } </code></pre>
5,829,704
2
0
null
2011-04-29 07:48:11.02 UTC
13
2011-04-29 08:19:51.377 UTC
2017-05-23 12:16:42.117 UTC
null
-1
null
510,435
null
1
5
wpf|mvvm
27,453
<h2>Handle it in the view</h2> <p>Probably the most simple approach.</p> <pre><code>private void AddCustomerView_Click(object sender, RoutedEventArgs e) { AddCustomerView view = new AddCustomerView(data); view.Show(); } </code></pre> <h2>ViewModel exposes an event</h2> <p>This has one drawback: it requires lots of manual coding.</p> <pre><code>public class MainWindowViewModel { public event EventHandler AddCustomerViewShowed; public void AddNewCustomerWindowExecute() { if (AddCustomerViewShowed != null) AddCustomerViewShowed(this, EventArgs.Empty); } } </code></pre> <p>Handle it in the view</p> <pre><code>var viewModel = new MainWindowViewModel(); viewModel.AddCustomerViewShowed += (s, e) =&gt; new AddCustomerView(data).Show(); </code></pre> <h2>Controller that handles all your views</h2> <pre><code>public class Controller : IController { public void AddCustomer() { AddCustomerView view = new AddCustomerView(data); view.Show(); } } public class MainWindowViewModel { IController controler; public MainWindowViewModel(IController controller) { this.controller = controller; } public void AddNewCustomerWindowExecute() { controller.AddCustomer(); } } </code></pre> <h2>Mediator pattern</h2> <p>Some MVVM frameworks (e.g. <a href="http://www.galasoft.ch/mvvm/getstarted/" rel="noreferrer">MVVM Light</a>) use this pattern.</p> <pre><code>public class App // or in the view or somewhere else { public void RegisterMessenger() { Messenger.Default.Register&lt;AddCustomerMessage&gt;(this, ProcessAddCustomerMessage); } private void ProcessAddCustomerMessage(AddCustomerMessage message) { AddCustomerView view = new AddCustomerView(data); view.Show(); } } public class MainWindowViewModel { public void AddNewCustomerWindowExecute() { Messenger.Default.Send(new AddCustomerMessage(...)); } } </code></pre>
5,907,259
Java: to use contains in a ArrayList full of custom object should I override equals or implement Comparable/Comparator?
<p>I have an ArrayList full of these:</p> <pre><code>class TransitionState { Position positionA; Position positionB; int counter; public boolean equals (Object o){ if (o instanceof TransitionState){ TransitionState transitionState= (TransitionState)o; if ((this.positionA.equals(transitionState.positionA)) &amp;&amp;(this.positionB.equals(transitionState.positionB))) { return true; } } return false; } @Override public String toString() { String output = "Position A " + positionA.i+ " "+ positionA.j + " "+ positionA.orientation + " "+ "Position B " + positionB.i + " "+ positionB.j + " "+ positionB.orientation; return output; } } class Position { int i; int j; char orientation; Position() { } void setIJ(int i, int j){ this.i=i; this.j=j; } void setOrientation(char c){ orientation = c; } public boolean equals(Object o){ if(o instanceof Position){ Position p = (Position)o; if((p.i==this.i)&amp;&amp;(p.j==this.j)&amp;&amp;(p.orientation==this.orientation)) { return true; } else return false; } return false; } } //end class Position </code></pre> <p>I query it with this:</p> <pre><code> if(!transitionStatesArray.contains(newTransitionState)){ //if the transition state is new add and enqueue new robot positions transitionStatesArray.add(newTransitionState); //marks as visited </code></pre> <p>I'm finding duplicate elements inside my <code>transitionStatesArray</code>, why is this?</p> <p>I'm using these i,j and orientation values to fill unique values in a matrix, yet here I have a duplicate: </p> <pre><code> S . N * * * . D D E . O * * * . D D N . S * * * . D D S . N * * * . D D </code></pre>
5,907,303
2
0
null
2011-05-06 05:44:11.993 UTC
3
2011-05-06 06:36:36.353 UTC
2011-05-06 05:49:29.15 UTC
null
45,963
null
45,963
null
1
21
java|collections|equals|comparator|comparable
41,596
<p>The <code>List.contains(...)</code> method is defined to use <code>equals(Object)</code> to decide if the argument object is "contained" by the list. So you need to override <code>equals</code> ... assuming that the default implementation is not what you need.</p> <p>However, you need to be aware that <code>List.contains(...)</code> potentially tests the argument against every element in the list. For a long list, that's expensive. Depending on the details of your application, it <em>may be</em> better to use a different collection type (e.g. a <code>HashSet</code>, <code>TreeSet</code> or <code>LinkedHashSet</code>) instead of a <code>List</code>. If you use one of those, your class will need to override <code>hashCode</code> or implement <code>Comparable</code>, or you will need to create a separate <code>Comparator</code> ... depending on what you choose.</p> <hr> <p>(A bit more advice on the alternatives ... since the OP is interested)</p> <p>The performance of <code>contains</code> on a <code>List</code> type like <code>ArrayList</code> or <code>LinkedList</code> is <code>O(N)</code>. The worst-case cost of a <code>contains</code> call is directly proportional to the list length.</p> <p>For a <code>TreeSet</code> the worst-case performance of <code>contains</code> is proportional to <code>log2(N)</code>.</p> <p>For a <code>HashSet</code> or <code>LinkedHashSet</code>, the average performance of <code>contains</code> is a constant, independent of the size of the collection, but the worst-case performance is <code>O(N)</code>. (The worst case performance occurs if you 1) implement a poor <code>hashcode()</code> function that hashes everything to a small number of values, or 2) tweak the "load factor" parameter so that the hash table doesn't automatically resize as it grows.)</p> <p>The downside of using <code>Set</code> classes are:</p> <ul> <li>they are <em>sets</em>; i.e. you cannot put two or more "equal" objects into the collection, and</li> <li>they can't be indexed; e.g. there's no <code>get(pos)</code> method, and</li> <li>some of the <code>Set</code> classes don't even preserve the insertion order.</li> </ul> <p>These issues need to be considered when deciding what collection class to use.</p>
60,689,668
Angular: HttpClientModule import error (could not be resolved to an NgModule class)
<p>I was trying to build a simple app with crud on fake json server</p> <p>but i can't import <strong>HttpClientModule</strong></p> <p>Here is error message from <strong>VS Code</strong> :</p> <pre><code>ERROR in node_modules/@angular/common/http/http.d.ts:2801:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class. This likely means that the library (@angular/common/http) which declares HttpClientModule has not been processed correctly by ngcc, or is not compatible with Angular Ivy. Check if a newer version of the library is available, and update if so. Also consider checking with the library's authors to see if the library is expected to be compatible with Ivy. 2801 export declare class HttpClientModule { </code></pre> <p>Here is <strong>app.module.ts</strong></p> <pre><code>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { EmployeeCreateComponent } from './employee-create/employee-create.component'; import { EmployeeEditComponent } from './employee-edit/employee-edit.component'; import { EmployeeListComponent } from './employee-list/employee-list.component'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [ AppComponent, EmployeeCreateComponent, EmployeeEditComponent, EmployeeListComponent ], imports: [ BrowserModule, HttpClientModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } </code></pre> <p><strong>app.component.ts</strong></p> <pre><code>import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'restTest6'; } </code></pre> <p>note that : I didn't use <strong>HttpClientModule</strong> anywhere else. I imported and did <code>ng serve -o</code> and got error. Please point out what went wrong</p>
60,690,710
9
0
null
2020-03-15 04:11:45.607 UTC
7
2022-04-29 20:59:47.65 UTC
2020-05-18 12:18:56.137 UTC
user12504785
null
user12504785
null
null
1
34
angular|typescript
36,001
<p>I had the same problem, I just run the following command and it worked after without any error.</p> <pre><code>npm cache verify </code></pre> <p>If it does not, try manually deleting the <code>node_modules</code> folder and reinstalling the modules with <code>npm install</code>.</p> <pre><code>rm -rf node_modules npm install </code></pre> <p>On npm &gt; 6, you can also run <code>npm ci</code>, which also deletes the <code>node_modules</code> folder and reinstall packages after.</p> <p><strong>Edit</strong> As other answers suggested, you may need to restart<code>ng serve</code> if the above steps do not work (but they normally do)</p>
33,248,816
Pattern match function against empty map
<p>I'm playing around with pattern match and I found out, that it's not quite easy to pattern match parameters of a method against an empty map. I thought it would go something like this:</p> <pre class="lang-elixir prettyprint-override"><code>defmodule PatternMatch do def modify(%{}) do %{} end def modify(map) do # expensive operation %{ modified: &quot;map&quot; } end end </code></pre> <p>But it seems like the first function clause matches arbitrary maps:</p> <pre class="lang-bash prettyprint-override"><code>iex&gt; PatternMatch.modify(%{a: &quot;map&quot;}) ==&gt; %{} </code></pre> <p>Is there another way to check for empty maps?</p>
33,250,932
3
1
null
2015-10-21 00:01:36.663 UTC
5
2022-07-30 15:38:45.72 UTC
2022-07-30 15:36:19.943 UTC
null
2,301,092
null
1,087,469
null
1
62
pattern-matching|elixir
20,494
<p>It works this way by design, but admittedly it can be a bit confusing at first glance. This feature allows you to destructure maps using pattern matching, without having to specify all keys. For example:</p> <pre class="lang-bash prettyprint-override"><code>iex&gt; %{b: value} = %{a: 1, b: 2, c: 3} %{a: 1, b: 2, c: 3} iex&gt; value 2 </code></pre> <p>Consequently, <code>%{}</code> will match any map. If you want to match an empty map in a function, you have to use a guard clause:</p> <pre class="lang-elixir prettyprint-override"><code>defmodule PatternMatch do def modify(map) when map == %{} do %{} end def modify(map) do # ... end end </code></pre>
52,238,171
How to run multiple tasks in VS Code on build?
<p>Using <code>tasks.json</code> version 2.0.0, I have not been able to make it so that, when I build my application, multiple tasks are run at the same time. I'm using gulp for my SCSS compilation, and running my <code>Compile/minify cms.scss</code> task on its own works fine, so it's not a problem with the task itself, just VS Code's task runner. When I <code>Run Build Task</code> in VS Code, my gulp task is not being run, even though it has <code>&quot;group&quot;: &quot;build&quot;</code> β€” only the <code>dotnet</code> one is.</p> <h3><code>tasks.json</code></h3> <pre class="lang-json prettyprint-override"><code>{ &quot;version&quot;: &quot;2.0.0&quot;, &quot;tasks&quot;: [ { &quot;label&quot;: &quot;build&quot;, &quot;command&quot;: &quot;dotnet&quot;, &quot;type&quot;: &quot;process&quot;, &quot;args&quot;: [ &quot;build&quot;, &quot;${workspaceFolder}/HpsCoreWeb.csproj&quot; ], &quot;problemMatcher&quot;: &quot;$msCompile&quot;, &quot;group&quot;: { &quot;kind&quot;: &quot;build&quot;, &quot;isDefault&quot;: true } }, { &quot;label&quot;: &quot;Compile/minify cms.scss&quot;, &quot;type&quot;: &quot;gulp&quot;, &quot;task&quot;: &quot;cms.scss:cms.min.css&quot;, &quot;problemMatcher&quot;: &quot;$node-sass&quot;, &quot;group&quot;: &quot;build&quot; } ] } </code></pre> <p>According to the <a href="https://code.visualstudio.com/docs/editor/tasks#_custom-tasks" rel="noreferrer">VS Code Tasks documentation</a>:</p> <blockquote> <p><strong>group</strong>: Defines to which group the task belongs. In the example, it belongs to the <code>test</code> group. Tasks that belong to the test group can be executed by running <strong>Run Test Task</strong> from the <strong>Command Palette</strong>.</p> </blockquote> <p>The <code>dotnet build</code> task is succeeding, so shouldn't the other task, which is also part of the <code>build</code> group, be run as well? What am I doing wrong?</p>
52,331,208
4
0
null
2018-09-08 18:22:12.707 UTC
14
2021-05-01 06:18:42.517 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
4,028,303
null
1
38
visual-studio-code|vscode-tasks
31,422
<p>The problem is that &quot;Run Test Task&quot; and &quot;Run Build Task&quot; do not execute all tasks in that specific group. Usually you get a drop down selection so you can choose which task to execute. Since you have specified one of the tasks as default, the selection will be skipped and instead the default task is executed.</p> <p>You can work around that by adding dependencies. Take the following example:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;version&quot;: &quot;2.0.0&quot;, &quot;tasks&quot;: [ { &quot;label&quot;: &quot;Echo 1&quot;, &quot;command&quot;: &quot;echo&quot;, &quot;type&quot;: &quot;shell&quot;, &quot;args&quot;: [ &quot;echo1&quot; ], &quot;group&quot;: { &quot;kind&quot;: &quot;build&quot;, &quot;isDefault&quot;: true }, &quot;dependsOn&quot;:[&quot;Echo 2&quot;] }, { &quot;label&quot;: &quot;Echo 2&quot;, &quot;type&quot;: &quot;shell&quot;, &quot;command&quot;: &quot;echo&quot;, &quot;args&quot;: [ &quot;echo2&quot; ], &quot;group&quot;: &quot;build&quot; } ] } </code></pre> <p>As <code>Echo 1</code> depends on <code>Echo 2</code>, <code>Echo 2</code> will be executed prior to executing <code>Echo 1</code>. Note that the definition is a list, so more than one task can be specified. In that case the tasks are executed in parallel.</p> <p>In your case adding <code>&quot;dependsOn&quot;:[&quot;Compile/minify cms.scss&quot;]</code> to your main build task should execute both tasks.</p>
54,708,788
error: an enum switch case label must be the unqualified name of an enumeration constant
<blockquote> <p>error: an enum switch case label must be the unqualified name of an enumeration constant error: duplicate case label</p> </blockquote> <p>no compiling, help me!</p> <pre><code>public class CardViewStyleSetting extends ThemedSetting { public CardViewStyleSetting(ThemedActivity activity) { super(activity); } public void show() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), getActivity().getDialogStyle()); final View dialogLayout = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_album_card_style, null); TextView dialogTitle = dialogLayout.findViewById(R.id.dialog_card_view_style_title); ((CardView) dialogLayout.findViewById(R.id.dialog_card_view_style)).setCardBackgroundColor(getActivity().getCardBackgroundColor()); dialogTitle.setBackgroundColor(getActivity().getPrimaryColor()); final RadioGroup rGroup = dialogLayout.findViewById(R.id.radio_group_card_view_style); final CheckBox chkShowMediaCount = dialogLayout.findViewById(R.id.show_media_count); final CheckBox chkShowAlbumPath = dialogLayout.findViewById(R.id.show_album_path); RadioButton rCompact = dialogLayout.findViewById(R.id.radio_card_compact); RadioButton rFlat = dialogLayout.findViewById(R.id.radio_card_flat); RadioButton rMaterial = dialogLayout.findViewById(R.id.radio_card_material); chkShowMediaCount.setChecked(Prefs.showMediaCount()); chkShowAlbumPath.setChecked(Prefs.showAlbumPath()); getActivity().themeRadioButton(rCompact); getActivity().themeRadioButton(rFlat); getActivity().themeRadioButton(rMaterial); getActivity().themeCheckBox(chkShowMediaCount); getActivity().themeCheckBox(chkShowAlbumPath); rGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int i) { final View v; switch (i) { case R.id.radio_card_compact: v = LayoutInflater.from(getActivity()).inflate(CardViewStyle.COMPACT.getLayout(), null); v.findViewById(R.id.ll_album_info).setBackgroundColor(ColorPalette.getTransparentColor(getActivity().getBackgroundColor(), 150)); break; case R.id.radio_card_flat: v = LayoutInflater.from(getActivity()).inflate(CardViewStyle.FLAT.getLayout(), null); v.findViewById(R.id.ll_album_info).setBackgroundColor(ColorPalette.getTransparentColor(getActivity().getBackgroundColor(), 150)); break; case R.id.radio_card_material: default: v = LayoutInflater.from(getActivity()).inflate(CardViewStyle.MATERIAL.getLayout(), null); v.findViewById(R.id.ll_album_info).setBackgroundColor(getActivity().getCardBackgroundColor()); break; } ImageView img = v.findViewById(R.id.album_preview); img.setBackgroundColor(getActivity().getPrimaryColor()); Glide.with(getActivity()) .load(R.drawable.donald_header) .into(img); String hexPrimaryColor = ColorPalette.getHexColor(getActivity().getPrimaryColor()); String hexAccentColor = ColorPalette.getHexColor(getActivity().getAccentColor()); if (hexAccentColor.equals(hexPrimaryColor)) hexAccentColor = ColorPalette.getHexColor(ColorPalette.getDarkerColor(getActivity().getAccentColor())); String textColor = getActivity().getBaseTheme().equals(Theme.LIGHT) ? "#2B2B2B" : "#FAFAFA"; String albumPhotoCountHtml = "&lt;b&gt;&lt;font color='" + hexAccentColor + "'&gt;420&lt;/font&gt;&lt;/b&gt;"; ((TextView) v.findViewById(R.id.album_media_count)).setText(StringUtils.html(albumPhotoCountHtml)); ((TextView) v.findViewById(R.id.album_media_label)).setTextColor(getActivity().getTextColor()); ((TextView) v.findViewById(R.id.album_path)).setTextColor(getActivity().getSubTextColor()); v.findViewById(R.id.ll_media_count).setVisibility( chkShowMediaCount.isChecked() ? View.VISIBLE : View.GONE); chkShowMediaCount.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { v.findViewById(R.id.ll_media_count).setVisibility(b ? View.VISIBLE : View.GONE); } }); v.findViewById(R.id.album_path).setVisibility( chkShowAlbumPath.isChecked() ? View.VISIBLE : View.GONE); chkShowAlbumPath.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { v.findViewById(R.id.album_path).setVisibility(b ? View.VISIBLE : View.GONE); } }); ((TextView) v.findViewById(R.id.album_name)).setText(StringUtils.html("&lt;i&gt;&lt;font color='" + textColor + "'&gt;PraiseDuarte&lt;/font&gt;&lt;/i&gt;")); ((TextView) v.findViewById(R.id.album_path)).setText("~/home/PraiseDuarte"); ((CardView) v).setUseCompatPadding(true); ((CardView) v).setRadius(2); ((LinearLayout) dialogLayout.findViewById(R.id.ll_preview_album_card)).removeAllViews(); ((LinearLayout) dialogLayout.findViewById(R.id.ll_preview_album_card)).addView(v); } }); switch (Prefs.getCardStyle()) { case CardViewStyle.COMPACT: rCompact.setChecked(true); break; case CardViewStyle.FLAT: rFlat.setChecked(true); break; case CardViewStyle.MATERIAL: default: rMaterial.setChecked(true); break; } builder.setNegativeButton(getActivity().getString(R.string.cancel).toUpperCase(), null); builder.setPositiveButton(getActivity().getString(R.string.ok_action).toUpperCase(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { CardViewStyle cardViewStyle; switch (rGroup.getCheckedRadioButtonId()) { case R.id.radio_card_material: default: cardViewStyle = CardViewStyle.MATERIAL; break; case R.id.radio_card_flat: cardViewStyle = CardViewStyle.FLAT; break; case R.id.radio_card_compact: cardViewStyle = CardViewStyle.COMPACT; break; } Prefs.setCardStyle(cardViewStyle); Prefs.setShowMediaCount(chkShowMediaCount.isChecked()); Prefs.setShowAlbumPath(chkShowAlbumPath.isChecked()); Toast.makeText(getActivity(), getActivity().getString(R.string.restart_app), Toast.LENGTH_SHORT).show(); } }); builder.setView(dialogLayout); builder.show(); } } </code></pre>
54,708,876
1
0
null
2019-02-15 11:53:08.473 UTC
2
2019-02-15 12:09:26.007 UTC
2019-02-15 12:09:26.007 UTC
null
2,649,012
null
9,802,439
null
1
31
java|android
29,464
<p>As per Java docs</p> <blockquote> <p>The Identifier in a EnumConstant may be used in a name to refer to the enum constant. </p> </blockquote> <p>so we need to use the name only in case of an enum.</p> <p>Change to this</p> <pre><code>switch (Prefs.getCardStyle()) { case COMPACT: rCompact.setChecked(true); break; case FLAT: rFlat.setChecked(true); break; case MATERIAL: default: rMaterial.setChecked(true); break; } </code></pre>
62,161,460
Using filter() with across() to keep all rows of a data frame that include a missing value for any variable
<p>Sometimes I want to view all rows in a data frame that will be dropped if I drop all rows that have a missing value for any variable. In this case, I'm specifically interested in how to do this with <code>dplyr</code> 1.0's <code>across()</code> function used inside of the <code>filter()</code> verb. </p> <p>Here is an example data frame:</p> <pre><code>df &lt;- tribble( ~id, ~x, ~y, 1, 1, 0, 2, 1, 1, 3, NA, 1, 4, 0, 0, 5, 1, NA ) </code></pre> <p>Code for keeping rows that <em>DO NOT</em> include any missing values is provided on the <a href="https://dplyr.tidyverse.org/articles/colwise.html" rel="noreferrer">tidyverse website</a>. Specifically, I can use:</p> <pre><code>df %&gt;% filter( across( .cols = everything(), .fns = ~ !is.na(.x) ) ) </code></pre> <p>Which returns:</p> <pre><code># A tibble: 3 x 3 id x y &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; 1 1 1 0 2 2 1 1 3 4 0 0 </code></pre> <p>However, I can't figure out how to return the opposite -- rows <em>with</em> a missing value in any variable. The result I'm looking for is:</p> <pre><code># A tibble: 2 x 3 id x y &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; 1 3 NA 1 2 5 1 NA </code></pre> <p>My first thought was just to remove the <code>!</code>:</p> <pre><code>df %&gt;% filter( across( .cols = everything(), .fns = ~ is.na(.x) ) ) </code></pre> <p>But, that returns zero rows.</p> <p>Of course, I can get the answer I want with this code if I know all variables that have a missing value ahead of time:</p> <pre><code>df %&gt;% filter(is.na(x) | is.na(y)) </code></pre> <p>But, I'm looking for a solution that doesn't require me to know which variables have a missing value ahead of time. Additionally, I'm aware of how to do this with the <code>filter_all()</code> function: </p> <pre><code>df %&gt;% filter_all(any_vars(is.na(.))) </code></pre> <p>But, the <code>filter_all()</code> function has been superseded by the use of <code>across()</code> in an existing verb. See <a href="https://dplyr.tidyverse.org/articles/colwise.html" rel="noreferrer">https://dplyr.tidyverse.org/articles/colwise.html</a></p> <p>Other unsuccessful attempts I've made are:</p> <pre><code>df %&gt;% filter( across( .cols = everything(), .fns = ~any_vars(is.na(.x)) ) ) df %&gt;% filter( across( .cols = everything(), .fns = ~!!any_vars(is.na(.x)) ) ) df %&gt;% filter( across( .cols = everything(), .fns = ~!!any_vars(is.na(.)) ) ) df %&gt;% filter( across( .cols = everything(), .fns = ~any(is.na(.x)) ) ) df %&gt;% filter( across( .cols = everything(), .fns = ~any(is.na(.)) ) ) </code></pre>
66,136,167
8
0
null
2020-06-02 21:09:41.97 UTC
6
2021-10-22 14:21:30.997 UTC
2021-05-13 14:51:22.34 UTC
null
4,882,822
null
4,882,822
null
1
32
r|dplyr|r4epi
10,042
<p>It's now possible with <code>dplyr</code> 1.0.4. The new <code>if_any()</code> replaces <code>across()</code> for the filtering use-case.</p> <pre class="lang-r prettyprint-override"><code>library(dplyr) df &lt;- tribble(~ id, ~ x, ~ y, 1, 1, 0, 2, 1, 1, 3, NA, 1, 4, 0, 0, 5, 1, NA) df %&gt;% filter(if_any(everything(), is.na)) #&gt; # A tibble: 2 x 3 #&gt; id x y #&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; #&gt; 1 3 NA 1 #&gt; 2 5 1 NA </code></pre> <p><sup>Created on 2021-02-10 by the <a href="https://reprex.tidyverse.org" rel="noreferrer">reprex package</a> (v0.3.0)</sup></p> <p>See here for more details: <a href="https://www.tidyverse.org/blog/2021/02/dplyr-1-0-4-if-any/" rel="noreferrer">https://www.tidyverse.org/blog/2021/02/dplyr-1-0-4-if-any/</a></p>
44,538,472
Cocoapods iOS - [!] Google has been deprecated - How to get rid of the warning?
<p><strong>Steps I did:</strong></p> <ol> <li><p><code>pod repo remove master</code></p></li> <li><p><code>pod setup</code></p></li> <li><p><code>pod update --verbose</code> (Just to check the progress especially when updating the Google SDKs, took so long to finish).</p></li> </ol> <p>And there, I got the warning. In my logs, Google SDKs were updated successfully:</p> <blockquote> <p>-> Installing Google 3.1.0 (was 3.0.3)</p> <p>-> Installing GoogleMaps 2.3.0 (was 2.2.0)</p> </blockquote> <p><strong>Podfile:</strong></p> <pre><code>target 'MyProj' do ... pod 'Google/Analytics' pod 'GoogleMaps' ... target 'MyProjTests' do inherit! :search_paths end post_install do |installer| installer.pods_project.targets.each do |target| target.build_configurations.each do |config| config.build_settings['SWIFT_VERSION'] = '3.0' end end end end </code></pre> <p><a href="https://i.stack.imgur.com/BLwFX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BLwFX.png" alt="enter image description here"></a></p> <p>I would like to know how to get rid of this warning.</p>
44,546,794
2
0
null
2017-06-14 07:40:51.8 UTC
null
2017-06-20 08:12:09.62 UTC
null
null
null
null
3,231,194
null
1
42
ios|cocoapods
11,281
<p>Change <code>pod 'Google/Analytics'</code> to <code>pod 'GoogleAnalytics'</code> removing the slash.</p>
22,604,500
Web Audio Api working with Decibels
<p>I wish to understand how to work with decibels in Web Audio API</p> <p>Here i have an audio buffer connected to a gain node</p> <pre><code>var mybuffer = context.createBufferSource()); mybuffer.buffer = buffer; //an audio buffer var gainNode=context.createGain(); mybuffer.connect(gainNode); gainNode.connect(context.destination); </code></pre> <p>Gain volume is a range from 0(silent) to n where 1 is the default volume but as i know, usually audio is not related to such a range, its volume is measured in decibels (Db) and operations are made in Db too.</p> <p>I have read something interesting in this answer but it's far to be complete for my needs: <a href="https://stackoverflow.com/questions/13734710/is-there-a-way-get-something-like-decibel-levels-from-an-audio-file-and-transfor">Is there a way get something like decibel levels from an audio file and transform that information into a json array?</a></p> <p>I wonder how to determine decibel for an Audio Node, how to edit volume using decibels</p>
22,613,964
1
0
null
2014-03-24 08:40:10.973 UTC
9
2020-09-13 09:32:45.55 UTC
2017-05-23 11:33:13.96 UTC
null
-1
null
187,048
null
1
14
html|audio|html5-audio|web-audio-api
7,789
<p>Decibels are an interesting beast. Decibels aren't really a measure of volume, per se - they're a measure of gain or attentuation, as described in <a href="http://en.wikipedia.org/wiki/Decibel" rel="noreferrer">http://en.wikipedia.org/wiki/Decibel</a>. The number of decibels is ten times the logarithm to base 10 of the ratio of the two power quantities.</p> <p>You <em>can</em> get decibels out of one critical place in the Web Audio API - the RealtimeAnalyser's getFloatFrequencyData returns a float array of attenuation per frequency band, in decibels. It's not technically volume - but it's attenuation from unity (1), which would be a sine wave in that frequency at full volume (-1 to 1).</p> <p>Gain controls are, of course, commonly expressed in decibels, because they're a measure of a ratio - between unity and whatever your volume knob is set to. Think of unity (0 dB, gain=1) as "as loud as your speakers will go".</p> <p>To express a gain in decibels, remember that a gain of 1 (no attenuation, no gain) would equal 0 decibels - because 10^0 = 1. (Actually - it's because 10 ^ (0/10) = 1. Obviously, zero divided by anything is still zero - but remember, these are DECI-bels, there's a factor of ten in there.) The aforementioned Wikipedia article explains this in good depth.</p> <p>To convert between the two - e.g., to set a gain.value when you have decibels, and to get the decibel gain from gain.value - you just need to use the formula</p> <pre><code>decibel_level = 20 * log10( gain.value ); </code></pre> <p>aka</p> <pre><code>gain.value = Math.pow(10, (decibel_level / 20)); </code></pre> <p>Note that base 10 log is a little more complex in Javascript, due to only having access to the natural logarithm, not the base 10 logarithm - but you can get that via</p> <pre><code>function log10(x) { return Math.log(x)/Math.LN10; } </code></pre> <p>(There's a Math.log10() method, but it's experimental and not implemented across all browsers.)</p>
27,282,519
Laravel - Testing what happens after a redirect
<p>I have a controller that after submitting a email, performs a redirect to the home, like this:</p> <pre><code>return Redirect::route('home')-&gt;with("message", "Ok!"); </code></pre> <p>I am writing the tests for it, and I am not sure how to make phpunit to follow the redirect, to test the success message:</p> <pre><code>public function testMessageSucceeds() { $crawler = $this-&gt;client-&gt;request('POST', '/contact', ['email' =&gt; '[email protected]', 'message' =&gt; "lorem ipsum"]); $this-&gt;assertResponseStatus(302); $this-&gt;assertRedirectedToRoute('home'); $message = $crawler-&gt;filter('.success-message'); // Here it fails $this-&gt;assertCount(1, $message); } </code></pre> <p>If I substitute the code on the controller for this, and I remove the first 2 asserts, it works</p> <pre><code>Session::flash('message', 'Ok!'); return $this-&gt;makeView('staticPages.home'); </code></pre> <p>But I would like to use the <code>Redirect::route</code>. Is there a way to make PHPUnit to follow the redirect?</p>
32,502,827
6
0
null
2014-12-03 22:01:19.147 UTC
6
2022-06-11 03:19:27.4 UTC
null
null
null
null
392,684
null
1
32
php|redirect|laravel|phpunit
28,472
<p>You can get PHPUnit to follow redirects with:</p> <p><strong>Laravel >= 5.5.19</strong>:</p> <pre><code>$this-&gt;followingRedirects(); </code></pre> <p><strong>Laravel &lt; 5.4.12</strong>:</p> <pre><code>$this-&gt;followRedirects(); </code></pre> <p><strong>Usage:</strong></p> <pre><code>$response = $this-&gt;followingRedirects() -&gt;post('/login', ['email' =&gt; '[email protected]']) -&gt;assertStatus(200); </code></pre> <p><strong>Note:</strong> This needs to be set explicitly for <strong>each request</strong>.</p> <hr> <p><strong>For versions between these two</strong>:</p> <p>See <a href="https://github.com/laravel/framework/issues/18016#issuecomment-322401713" rel="noreferrer">https://github.com/laravel/framework/issues/18016#issuecomment-322401713</a> for a workaround.</p>
20,999,465
Dynamodb reading and writing units
<p>I've been reading various articles on the Amazon DynamoDB but I'm still a little confused on the reading/writing units on how these are used. For example, using the free version, I have 5 writing units and 10 reading units available per second, each unit representing 1kb of data. But what does this really mean?</p> <p>Does this mean max 10 read requests can be performed per seconds or max 10kb of data can be requested per seconds(regardless of whether there are 10 or 100 requests)? Because this aspect is not clear for me. So if I have 20 users who concurrently access a page on my website(which result in 20 queries being performed to retrieve data), what will happen? Will 10 of them see the the data immediately while the other 10 will see it after 1 second? Or will they all see the data immediately if the data requested (multiplied by 20) is less then 10kb?</p> <p>Also, if the reading units are not enough, and 100 users request concurrently 1kb of data each, does this mean all the requests will require 10 seconds to complete??</p> <p>Also, the pricing is a little confusing as I don't understand if the prices are paid for units reserved or consumed? So for example they say the price is "Write Throughput: $0.00735 per hour for every 10 units of Write Capacity". Does this mean one will pay ($0.00735*24=$0.176) even if no writing requests are made during a day? </p>
21,000,686
4
0
null
2014-01-08 15:14:19.477 UTC
12
2019-10-10 22:04:40.547 UTC
2014-01-08 15:22:44.123 UTC
null
840,488
null
840,488
null
1
30
amazon-dynamodb
13,574
<p>You are correct in that the capacity is tightly bound to the size of the objects being read/written. </p> <h2>Feb 2016 Updates</h2> <p>AWS has updated how they calculate throughput, and the they've increased from 1 KB objects to 4 KB for their calculations. The discussion below is still valid, but certain calculations are different now. </p> <p>Always consult the latest DynamoDB documentation for the latest information and examples on how to calculate throughput. </p> <h2>Older Documentation</h2> <p>From the AWS DynamoDB documentation (as of 1/8/14):</p> <blockquote> <p>Units of Capacity required for writes = Number of item writes per second x item size (rounded up to the nearest KB)</p> <p>Units of Capacity required for reads* = Number of item reads per second x item size (rounded up to the nearest KB)</p> <ul> <li>If you use eventually consistent reads you’ll get twice the throughput in terms of reads per second.</li> </ul> </blockquote> <p>Per your example question, if you want to read 10KB of data per second you'll need 10 Read Units provisioned. It doesn't matter if you make 10 requests for 1 KB of data or if you make a single request for 10 KB of data. You're limited to 10KB/second. </p> <blockquote> <p>Note that the required number of units of Read Capacity is determined by the number of items being read per second, not the number of API calls. For example, if you need to read 500 items per second from your table, and if your items are 1KB or less, then you need 500 units of Read Capacity. <strong>It doesn’t matter if you do 500 individual GetItem calls or 50 BatchGetItem calls that each return 10 items.</strong></p> </blockquote> <p>For your 20 user example, keep in mind that data is rounded up to the nearest KB. So even if your 20 users request 0.5 KB of data, you'll need 20 Read Units to service all of them at once. If you only have 10 read units, then the other 10 requests will be throttled. If you use the Amazon DynamoDB libraries, they have auto-retry logic baked in to try the request again so they should eventually get serviced. </p> <p>For your question about 100 users, some of those requests may simply be throttled and the retry logic may eventually fail (the code will only retry the request so many times before it stops trying) - so you need to be ready to handle those 400 response codes from DynamoDB and react accordingly. <strong>It's very important to monitor your application when you use DynamoDB and ensure you aren't going to be throttled on app critical transactions.</strong></p> <p>Your last question about pricing - you pay hourly for what you reserve. If you reserve 1000 Read Units and your site has absolutely no traffic, then too bad, you'll still pay hourly for those 1000 Read Units.</p> <p>For completeness - keep in mind that throughput is provision PER TABLE. So if you have 3 DynamoDB tables: Users, Photos, Friends then you have to provision capacity for each table, and you need to determine what is appropriate for each table. In this trivial example, perhaps Photos is accessed less frequently in your app so you can provision lower throughput compared to your Users table. </p> <p>Eventually consistent reads are great for cost saving but your app has to be designed to handle it. An eventually consistent read means that if you update data and immediately try to read the new value, you may not get the new value back, it may still return the previous value. Eventually, with enough time, you'll get the new value. You pay less since you aren't guaranteed to read the latest data - but that can be OK if you design appropriately.</p>
32,517,234
Access violation on static initialization
<p>I am working on an application with Visual Studio 2015 on Windows 7. The application has a C# frontend, a C++ CLR wrapper and C++ native code.</p> <p>My application crashes with an access violation while initializing a static variable at function scope with C++ native code. But only on Windows Server 2003 Enterprise SP2 and not on Windows 7 or Windows Server 2012. I know Windows Server 2003 is out of support, but I have to target that platform for a few additional months and Visual Studio 2015 provides a platform toolset to target it.</p> <p>I created a small reproducible example which you find at the end.</p> <p>The crash only happens with all three parts involved (C#, C++ CLR, C++). If I remove any, the crash is gone.</p> <p>The crash only happens with a custom constructor defined. If I remove the constructor, the crash is gone.</p> <p>I am no assembly expert, but for me it looks like the crash is caused by the code which checks if the static initialization is required. The constructor is not even called.</p> <p>My question is: Why does it crash on Windows Server 2003? Am I missing some important project setting?</p> <h1>The error message</h1> <pre class="lang-none prettyprint-override"><code>Unhandled exception at 0x1000167E (Native.dll) in Managed.exe.dmp: 0xC0000005: Access violation reading location 0x00000000. </code></pre> <h1>Visual C# Console Application "Managed.exe"</h1> <h2>Program.cs</h2> <pre class="lang-cs prettyprint-override"><code>// Target framework: .NET Framework 4 // Platform target: x86 using System; namespace Managed { class Program { static void Main(string[] args) { Console.Write("Press enter to start test..."); Console.ReadLine(); Native.Wrapper wrapper = new Native.Wrapper(); Console.WriteLine("Test was successful"); Console.Write("Press enter to exit..."); Console.ReadLine(); } } } </code></pre> <h1>Visual C++ CLR Class Library "Native.dll"</h1> <h2>Wrapper.hpp</h2> <pre class="lang-cpp prettyprint-override"><code>#pragma once namespace Native { public ref class Wrapper { public: Wrapper(); }; // public ref class Wrapper } // namespace Native </code></pre> <h2>Wrapper.cpp</h2> <pre class="lang-cpp prettyprint-override"><code>// Platform Toolset: Visual Studio 2015 - Windows XP (v140_xp) // Common Language Runtime Support: Common Language Runtime Support (/clr) // .NET Target Framework Version: v4.0 // Warning Level: Level4 // Treat Warnings As Errors: Yes (/WX) // Precompiled Header: Not Using Precompiled Headers // SubSystem: Console (/SUBSYSTEM:CONSOLE) // Optimization: Disabled (/Od) #pragma once #include "Wrapper.hpp" #include "Caller.hpp" namespace Native { Wrapper::Wrapper() { Caller* caller = new Caller(); delete caller; } } // namespace Native </code></pre> <h2>Caller.hpp</h2> <pre class="lang-cpp prettyprint-override"><code>#pragma once namespace Native { class Caller { public: Caller(); }; // class Caller } // namespace Native </code></pre> <h2>Caller.cpp</h2> <pre class="lang-cpp prettyprint-override"><code>// Platform Toolset: Visual Studio 2015 - Windows XP (v140_xp) // Common Language Runtime Support: No Common Language RunTime Support // Warning Level: Level4 // Treat Warnings As Errors: Yes (/WX) // Precompiled Header: Not Using Precompiled Headers // SubSystem: Console (/SUBSYSTEM:CONSOLE) // Optimization: Disabled (/Od) #include "Caller.hpp" #include "Singleton.hpp" namespace Native { Caller::Caller() { Singleton::GetInstance()-&gt;DoSomething(); } } // namespace Native </code></pre> <h2>Singleton.hpp</h2> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &lt;iostream&gt; namespace Native { class Singleton { public: Singleton() // !!! remove constructor to prevent crash !!! { } static Singleton* GetInstance() { static Singleton Instance; // !!! crashes here !!! return &amp;Instance; } void DoSomething() { std::wcout &lt;&lt; L"Doing something...\n"; } }; // class Singleton } // namespace Native </code></pre> <h1>The disassembly</h1> <pre class="lang-none prettyprint-override"><code> static Singleton* GetInstance() { 10001650 push ebp 10001651 mov ebp,esp 10001653 push 0FFFFFFFFh 10001655 push 10006A8Ch 1000165A mov eax,dword ptr fs:[00000000h] 10001660 push eax 10001661 mov eax,dword ptr ds:[1001B334h] 10001666 xor eax,ebp 10001668 push eax 10001669 lea eax,[ebp-0Ch] 1000166C mov dword ptr fs:[00000000h],eax static Singleton Instance; 10001672 mov eax,dword ptr ds:[1001B5D0h] 10001677 mov ecx,dword ptr fs:[2Ch] 1000167E mov edx,dword ptr [ecx+eax*4] // !!! access violation here !!! 10001681 mov eax,dword ptr ds:[1001B5A4h] 10001686 cmp eax,dword ptr [edx+4] 1000168C jle Native::Singleton::GetInstance+79h (100016C9h) </code></pre> <h1>The registers</h1> <pre class="lang-none prettyprint-override"><code>EAXΒ =Β 00000000 EBXΒ =Β 00000000 ECXΒ =Β 00000000 EDXΒ =Β 006A0003 ESIΒ =Β 001647C8 EDIΒ =Β 0012F3BC EIPΒ =Β 1000167E ESPΒ =Β 0012F394 EBPΒ =Β 0012F3A4 EFLΒ =Β 00010282 </code></pre> <h1>Edit 1</h1> <p>While debugging locally where the crash does not happen, a few more symbols are visible with the assembly:</p> <pre class="lang-none prettyprint-override"><code> static Singleton* GetInstance() { 0FBD1650 push ebp 0FBD1651 mov ebp,esp 0FBD1653 push 0FFFFFFFFh 0FBD1655 push offset __ehhandler$?GetInstance@Singleton@Native@@SAPAV12@XZ (0FBD86BCh) 0FBD165A mov eax,dword ptr fs:[00000000h] 0FBD1660 push eax 0FBD1661 mov eax,dword ptr [___security_cookie (0FBF03CCh)] 0FBD1666 xor eax,ebp 0FBD1668 push eax 0FBD1669 lea eax,[ebp-0Ch] 0FBD166C mov dword ptr fs:[00000000h],eax static Singleton Instance; 0FBD1672 mov eax,dword ptr [__tls_index (0FBF0668h)] 0FBD1677 mov ecx,dword ptr fs:[2Ch] 0FBD167E mov edx,dword ptr [ecx+eax*4] 0FBD1681 mov eax,dword ptr [TSS0&lt;`template-parameter-2',Native::Singleton::tInstance,Native::Singleton * * const volatile,void,int, ?? &amp;&gt; (0FBF063Ch)] 0FBD1686 cmp eax,dword ptr [edx+4] 0FBD168C jle Native::Singleton::GetInstance+79h (0FBD16C9h) </code></pre> <p>The symbol <code>__tls_index</code> seems to belong to some thread local store (guessed from the name). This matches with <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2660.htm">Magic statics</a> which uses thread local store as a performance optimization in the reference implementation. When crashing, the thread local store returns <code>0</code>.</p> <p>Could this be a bug with the runtime environment on Windows Server 2003 which manages and initializes the thread local store?</p> <h1>Edit 2</h1> <p>Reported as bug through Microsoft Connect: <a href="https://connect.microsoft.com/VisualStudio/feedback/details/1789709/visual-c-2015-runtime-broken-on-windows-server-2003-c-11-magic-statics">Bug report</a></p>
32,776,479
2
0
null
2015-09-11 06:48:21.183 UTC
9
2015-09-25 06:55:20.473 UTC
2015-09-23 06:40:28.073 UTC
null
5,321,479
null
5,321,479
null
1
18
c++|visual-c++|c++-cli
5,698
<p>This is the answer of Microsoft as posted to my <a href="https://connect.microsoft.com/VisualStudio/feedback/details/1789709/visual-c-2015-runtime-broken-on-windows-server-2003-c-11-magic-statics" rel="noreferrer">bug report</a> at Microsoft Connect:</p> <blockquote> <p>Windows Server 2003 and Windows XP have problems with dynamically loading a DLL (via LoadLibrary) that uses thread-local storage, which is what thread-safe statics use internally to provide efficient execution when the static local has already been initialized. As these systems are out of support, it is extremely unlikely for a patch to be created for those systems to add this support as is present in Vista and newer OSes, and we are reluctant to penalize the performance on in-support OSes to provide this functionality to the old out-of-support ones.</p> <p>To work around the issue you can use /Zc:threadSafeInit- to disable the thread-safe initialization code and this will avoid the thread-local variable. Of course by doing so the initialization code reverts back to the VS2013 mode and is not thread-safe, so this option is only viable if you don't rely on the thread-safety of local statics.</p> </blockquote>
5,842,813
How can I only allow shift+enter to return new line in text area?
<p>In a default behavior, the textarea "press" enter will become new line, but I don't want to having a new line, I want the user press <kbd>shift</kbd>+<kbd>enter</kbd>, instead. How can I do so? or... ... can I return the textarea enter event before it actually fire to the text area?</p>
5,842,842
1
0
null
2011-04-30 15:37:00.277 UTC
10
2020-10-28 09:43:29.717 UTC
2020-06-18 07:56:26.787 UTC
null
4,370,109
null
148,978
null
1
46
jquery|textarea|jquery-events
27,945
<pre><code>$(&quot;textarea&quot;).keydown(function(e){ // Enter was pressed without shift key if (e.key == 'Enter' &amp;&amp; !e.shiftKey) { // prevent default behavior e.preventDefault(); } }); </code></pre> <p>Try the <a href="http://jsfiddle.net/Su5ts/" rel="noreferrer">jsFiddle</a>.</p>
25,707,629
Why does Spark job fail with "too many open files"?
<p>I get "too many open files" during the shuffle phase of my Spark job. Why is my job opening so many files? What steps can I take to try to make my job succeed.</p>
25,707,630
3
0
null
2014-09-07 06:17:37.343 UTC
8
2020-06-10 17:56:34.067 UTC
2014-09-07 21:22:02.04 UTC
null
1,305,344
null
1,586,965
null
1
32
apache-spark
27,742
<p><a href="http://apache-spark-user-list.1001560.n3.nabble.com/quot-Too-many-open-files-quot-exception-on-reduceByKey-td2462.html">This has been answered on the spark user list</a>:</p> <blockquote> <p>The best way is definitely just to increase the ulimit if possible, this is sort of an assumption we make in Spark that clusters will be able to move it around. </p> <p>You might be able to hack around this by decreasing the number of reducers [or cores used by each node] but this could have some performance implications for your job. </p> <p>In general if a node in your cluster has C assigned cores and you run a job with X reducers then Spark will open C*X files in parallel and start writing. Shuffle consolidation will help decrease the total number of files created but the number of file handles open at any time doesn't change so it won't help the ulimit problem.</p> <p>-Patrick Wendell</p> </blockquote>
21,268,000
Unmarshaling nested JSON objects
<p>There are <a href="https://stackoverflow.com/questions/20101954/go-json-unmarshal-nested-object-into-string-or-byte">a</a> <a href="https://stackoverflow.com/questions/9452897/how-to-decode-json-with-type-convert-from-string-to-float64-in-golang">few</a> <a href="https://stackoverflow.com/questions/9801312/golang-nested-properties-for-structs-with-unknown-property-names">questions</a> on the <a href="https://stackoverflow.com/questions/16674059/how-to-access-deeply-nested-json-keys-and-values">topic</a> but none of them seem to cover my case, thus I'm creating a new one.</p> <p>I have JSON like the following:</p> <pre><code>{"foo":{ "bar": "1", "baz": "2" }, "more": "text"} </code></pre> <p>Is there a way to unmarshal the nested bar property and assign it directly to a struct property without creating a nested struct?</p> <p>The solution I'm adopting right now is the following:</p> <pre><code>type Foo struct { More String `json:"more"` Foo struct { Bar string `json:"bar"` Baz string `json:"baz"` } `json:"foo"` // FooBar string `json:"foo.bar"` } </code></pre> <p>This is a simplified version, please ignore the verbosity. As you can see, I'd like to be able to parse and assign the value to</p> <pre><code>// FooBar string `json:"foo.bar"` </code></pre> <p>I've seen people using a map, but that's not my case. I basically don't care about the content of <code>foo</code> (which is a large object), except for a few specific elements.</p> <p>What is the correct approach in this case? I'm not looking for weird hacks, thus if this is the way to go, I'm fine with that.</p>
21,268,855
8
1
null
2014-01-21 20:05:58.907 UTC
36
2022-07-14 14:35:54.4 UTC
2020-02-23 20:56:54.357 UTC
null
13,860
null
123,527
null
1
157
json|go
155,110
<blockquote> <p>Is there a way to unmarshal the nested bar property and assign it directly to a struct property without creating a nested struct?</p> </blockquote> <p>No, encoding/json cannot do the trick with ">some>deep>childnode" like encoding/xml can do. Nested structs is the way to go.</p>
21,439,239
Download latest GitHub release
<p>I'd like to have <strong>"Download Latest Version"</strong> button on my website which would represent the link to the latest release (stored at <strong>GitHub Releases</strong>). I tried to create release tag named <em>"latest"</em>, but it became complicated when I tried to load new release (confusion with tag creation date, tag interchanging, etc.). Updating download links on my website manually is also a time-consuming and scrupulous task. I see the only way - redirect all download buttons to some html, which in turn will redirect to the actual latest release.</p> <p>Note that my website is hosted at GitHub Pages (static hosting), so I simply <strong>can't use server-side scripting</strong> to generate links. Any ideas?</p>
22,507,358
9
0
null
2014-01-29 18:13:48.497 UTC
8
2022-02-01 18:10:16.66 UTC
2017-06-02 10:53:18.703 UTC
null
2,004,438
null
2,004,438
null
1
23
github|tags|release
26,277
<p>Github now provides a "Latest release" button on the release page of a project, <strong>after you have created your first release</strong>.</p> <p>In the example you gave, this button links to <a href="https://github.com/reactiveui/ReactiveUI/releases/latest" rel="nofollow">https://github.com/reactiveui/ReactiveUI/releases/latest</a></p>
19,007,281
angular trigger changes with $watch vs ng-change, ng-checked, etc
<p>Currently we could monitor data changes with several ways. We could trigger model changes with <code>$watch</code> and we could add directives to elements and bind some actions to it. </p> <p>It's a little bit confusing in many cases, so I'm curious, which is pro and cons of each variant and when should we use <code>$watch</code> binding, and when directives like <code>ng-change</code>? </p>
19,007,534
4
0
null
2013-09-25 14:09:02.403 UTC
13
2016-06-09 15:46:35.913 UTC
2016-04-12 16:22:43.303 UTC
null
31,532
null
1,888,017
null
1
49
javascript|angularjs|angularjs-directive
46,812
<p>Both <code>$watch</code> and <code>ngChange</code> have totally different usages:</p> <p>Lets say you have a model defined on a scope:</p> <pre><code>$scope.myModel = [ { "foo":"bar" } ]; </code></pre> <p>Now if you want to do something whenever any changes happen to <code>myModel</code> you would use <code>$watch</code>:</p> <pre><code>$scope.$watch("myModel", function(newValue, oldValue){ // do something }); </code></pre> <p><code>ngChange</code> is a directive that would evaluate given expression when user changes the input:</p> <pre><code>&lt;select ng-model="selectedOption" ng-options="option for option in options" ng-change="myModel=selectedOption"&gt;&lt;/select&gt; </code></pre> <p>In short, you would normally bind <code>ngChange</code> to some HTML element. While <code>$watch</code> is for the models.</p>
28,059,029
select option generate value from ajax on change
<p>I have <a href="https://stackoverflow.com/questions/27981674/set-the-option-available-for-select-based-on-another-select-php">here</a> the code and flow of my project i have 3 select here one for continent one for country one for city i get data to populate these select from ajax request it is now working fine i just want to make a bit fancy so i want to have a few function</p> <p>1.When Continent is select the list of country for that continent is listed in the country list when the change happens I want the city to also show the cities of the first entry in the country currently it does not happened what i do is i still need to change the entry in country select to show the list of cities </p> <p>2.Question is do i need to add another ajax request inside the ajax request for continent i am not sure this one is feasible i tried it, it is not working for now</p> <p>Ajax Code</p> <pre><code>$('.continentname').change(function() { var id = $(this).find(':selected')[0].id; //alert(id); $.ajax({ type:'POST', url:'../include/continent.php', data:{'id':id}, success:function(data){ // the next thing you want to do var country= document.getElementById('country'); $(country).empty(); var city = document.getElementById('city'); $(city).empty(); for (var i = 0; i &lt; data.length; i++) { $(country).append('&lt;option id=' + data[i].sysid + ' value=' + data[i].name + '&gt;' + data[i].name + '&lt;/option&gt;'); } } }); }); $('.countryname').change(function() { var id = $(this).find(':selected')[0].id; $.ajax({ type:'POST', url:'../include/country.php', data:{'id':id}, success:function(data){ // the next thing you want to do var city = document.getElementById('city'); $(city).empty(); for (var i = 0; i &lt; data.length; i++) { $(city).append('&lt;option id=' + data[i].sysid + ' value=' + data[i].name + '&gt;' + data[i].name + '&lt;/option&gt;'); } } }); }); </code></pre> <p>From database i put the value into the option select like </p> <pre><code>$("#continent").val(continentid); $("#continent").change(); $("#country").change(); $("#country").val(countryid); $("#city").val(cityid); </code></pre>
28,059,053
2
0
null
2015-01-21 03:14:46.357 UTC
5
2016-09-04 09:40:24.777 UTC
2017-05-23 10:27:26.957 UTC
null
-1
null
4,018,130
null
1
9
javascript|php|jquery|ajax|select
86,212
<p>You can trigger a change event for the country element once it is populated</p> <pre><code>$('.continentname').change(function () { var id = $(this).find(':selected')[0].id; //alert(id); $.ajax({ type: 'POST', url: '../include/continent.php', data: { 'id': id }, success: function (data) { // the next thing you want to do var $country = $('#country'); $country.empty(); $('#city').empty(); for (var i = 0; i &lt; data.length; i++) { $country.append('&lt;option id=' + data[i].sysid + ' value=' + data[i].name + '&gt;' + data[i].name + '&lt;/option&gt;'); } //manually trigger a change event for the contry so that the change handler will get triggered $country.change(); } }); }); $('.countryname').change(function () { var id = $(this).find(':selected')[0].id; $.ajax({ type: 'POST', url: '../include/country.php', data: { 'id': id }, success: function (data) { // the next thing you want to do var $city = $('#city'); $city.empty(); for (var i = 0; i &lt; data.length; i++) { $city.append('&lt;option id=' + data[i].sysid + ' value=' + data[i].name + '&gt;' + data[i].name + '&lt;/option&gt;'); } } }); }); </code></pre>
8,752,141
Add additional data to a Highcharts series for use in formatters
<p>My question is exactly the same as the OP in this question:</p> <p><a href="https://stackoverflow.com/questions/8514457/set-additional-data-to-highcharts-series">Set Additional Data to highcharts series</a></p> <p>But the accepted answer explains how to add additional data to the <em>point</em>, not the series, without saying if it's possible to do with the series or not.</p> <p>I would like to be able to define a series like:</p> <pre><code>series: [ {"hasCustomFlag": true, "name": "s1", "data": [...]}, {"hasCustomFlag": false, "name": "s2", "data": [...]}, ] </code></pre> <p>and be able to use <code>point.series.hasCustomFlag</code> inside of a formatting function. Is this possible?</p> <p>I don't want to put the data on the point level, because that means I'd have to duplicate the data far too many times.</p>
8,758,914
2
0
null
2012-01-06 01:02:51.43 UTC
4
2019-05-24 06:21:32.74 UTC
2017-05-23 11:46:08.607 UTC
null
-1
null
871,914
null
1
28
highcharts
20,403
<p>Yes this is possible, the extra configuration properties is located under the <code>options</code> property (<code>this.series</code> refers to the series instance, not the configuration objects). See the reference <a href="http://www.highcharts.com/docs/chart-concepts/series#2" rel="noreferrer">here</a> and scroll down to properties section.</p> <p>So instead use this line in the formatter:</p> <pre><code>if (this.series.options.hasCustomFlag) { ... } </code></pre> <p>Full example on <a href="https://jsfiddle.net/cvfnoymu/1/" rel="noreferrer">jsfiddle</a></p>
8,791,328
What are the differences between ${} and #{}?
<p>I'm programming in JSF2 and NetBeans creates many pages with <code>#{}</code> that contains an expression. However sometimes on the web I found <code>${}</code> for the same thing!</p> <p>Are there any differences? What are they?</p>
8,791,402
5
0
null
2012-01-09 16:02:47.747 UTC
25
2019-06-06 10:19:18.667 UTC
2019-06-06 10:04:55.37 UTC
null
814,702
null
1,069,061
null
1
82
jsf-2|el
35,297
<ul> <li><code>#{}</code> are for <strong><em>deferred expressions</em></strong> (they are resolved depending on the life cycle of the page) and can be used to read or write from or to a <em>bean</em> or to make a <em>method call</em>.</li> <li><code>${}</code> are expressions for <strong><em>immediate resolution</em></strong>, as soon as they are encountered they are resolved. They are read-only.</li> </ul> <p>You can read more here: <a href="http://docs.oracle.com/javaee/6/tutorial/doc/bnahr.html" rel="noreferrer">http://docs.oracle.com/javaee/6/tutorial/doc/bnahr.html</a></p>
55,389,088
localhost didn't send any data - ERR_EMPTY_RESPONSE
<p>Using VScode to write NodeJS</p> <p>But to check, localhost isn't responding properly, it says "the page didn't send any data. I tried looking everywhere and changed all the possible settings I can.</p> <p>restored chrome settings cleared cache, cleared history, changed port numbers, changed LAN settings.</p> <pre><code> '''' const Joi = require('joi'); const express = require('express'); const app = express(); app.use(express.json); //to take inputs ffrom the browser const courses = [ {id: 1, name: "course 1"}, {id: 2, name: "course 2"}, {id: 3, name: "course 3"}, ]; app.get('/', (req, res) =&gt;{ res.send("Hello world!!"); res.end(); }); app.get('/api/courses/', (req, res) =&gt;{ res.send(courses); res.end(); }); const port = process.env.port || 8080; app.listen(port, ()=&gt; console.log(`Listining on port ${port}..`)); '''' </code></pre> <p>Want to see all the courses printed on the webpage.</p>
55,389,192
4
0
null
2019-03-28 01:59:41.22 UTC
1
2022-01-29 21:33:47.057 UTC
null
null
null
user7665661
null
null
1
6
node.js|google-chrome|express|localhost
47,280
<p>Your <code>courses</code> is an object. You need to send it as string over wire. Send it as json and the browser will be able to parse it.</p> <pre><code>app.get('/api/courses/', (req, res) =&gt; { // change here, your object is stringified to json by express res.json(courses); }); </code></pre> <p>To take input from browser, you'd have to use packages like <code>body-parser</code> and not <code>app.use(express.json)</code></p> <pre><code>var express = require('express') var bodyParser = require('body-parser') var app = express() // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })) // parse application/json app.use(bodyParser.json()) </code></pre>
55,473,907
Can I get inline blame (like GitLens) on Webstorm?
<p>Just moved from VSCode to Webstorm. One of the features I like on vscode was the inline blame that came with GitLens, this allowed me to speak with team members who had written the code, can this be done on Webstorm? (I know I can get the whole blame but I just want inline the last commit)</p>
55,917,374
7
0
null
2019-04-02 11:39:16.447 UTC
4
2022-07-31 06:31:50.863 UTC
2019-07-12 01:25:16.49 UTC
null
397,817
null
9,266,540
null
1
51
webstorm
27,903
<p>UPDATED: corrected name to &quot;GitToolBox&quot; from &quot;Jetbrains Toolbox&quot;</p> <p>This can be achieved through the GitToolBox plugin, it provides the exact same functionality as git lens, finally I found it! This can be toggled from other settings&gt; git toolbox global or git toolbox project (if you only want to configure per project) See screenshot <a href="https://i.stack.imgur.com/mnlPG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mnlPG.png" alt="enter image description here" /></a></p>
48,237,779
Angular Material Table -Border Inside the Table
<p>I am using Angular material table and I want to set border inside the table, Using CSS I was able to set border: <strong>Normal case</strong> [<img src="https://i.stack.imgur.com/JX1BV.png" alt="enter image description here"> <br>but when the content of a particular cell increases border of the neighbor cells don't grow and the table looks pretty bad cell with <strong>extra content</strong> <a href="https://i.stack.imgur.com/6WJgK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6WJgK.png" alt="enter image description here"></a><br> here is the CSS:</p> <pre><code>`.example-container { display: flex; flex-direction: column; max-height: 500px; min-width: 300px; } .mat-table { overflow: auto; max-height: 500px; } .mat-column-name{ border-left: 1px solid grey; min-height: 48px; } .mat-column-weight{ border-left: 1px solid grey; min-height: 48px; .mat-column-symbol{ border-left: 1px solid grey; min-height: 48px; }` </code></pre> <p>HTML` </p> <pre><code>&lt;!--- Note that these columns can be defined in any order. The actual rendered columns are set as a property on the row definition" --&gt; &lt;!-- Position Column --&gt; &lt;ng-container matColumnDef="position"&gt; &lt;mat-header-cell *matHeaderCellDef&gt; No. &lt;/mat-header-cell&gt; &lt;mat-cell *matCellDef="let element"&gt; {{element.position}} &lt;/mat-cell&gt; &lt;/ng-container&gt; &lt;!-- Name Column --&gt; &lt;ng-container matColumnDef="name"&gt; &lt;mat-header-cell *matHeaderCellDef&gt; Name &lt;/mat-header-cell&gt; &lt;mat-cell *matCellDef="let element"&gt; {{element.name}} &lt;/mat-cell&gt; &lt;/ng-container&gt; &lt;!-- Weight Column --&gt; &lt;ng-container matColumnDef="weight"&gt; &lt;mat-header-cell *matHeaderCellDef&gt; Weight &lt;/mat-header-cell&gt; &lt;mat-cell *matCellDef="let element"&gt; {{element.weight}} &lt;/mat-cell&gt; &lt;/ng-container&gt; &lt;!-- Symbol Column --&gt; &lt;ng-container matColumnDef="symbol"&gt; &lt;mat-header-cell *matHeaderCellDef&gt; Symbol &lt;/mat-header-cell&gt; &lt;mat-cell *matCellDef="let element"&gt; {{element.symbol}} &lt;/mat-cell&gt; &lt;/ng-container&gt; &lt;mat-header-row *matHeaderRowDef="displayedColumns"&gt;&lt;/mat-header-row&gt; &lt;mat-row *matRowDef="let row; columns: displayedColumns;"&gt;&lt;/mat-row&gt; </code></pre> <p> `</p>
48,240,783
2
0
null
2018-01-13 07:19:00.65 UTC
7
2018-06-23 17:44:09.357 UTC
2018-06-23 17:44:09.357 UTC
null
5,695,162
null
5,695,162
null
1
7
css|angular|angular-material
42,371
<p><strong>Approach-2:</strong> Eventually, I figured out the solution, since material uses flex-layout we can use CSS <code>align-self: stretch; /* Stretch 'auto'-sized items to fit the container */</code><a href="https://i.stack.imgur.com/7T6gz.png" rel="noreferrer">Result with align-self: stretch</a></p> <p>Here is the updated CSS</p> <pre><code> `.example-container { display: flex; flex-direction: column; flex-basis: 300px; } .mat-table { overflow: auto; max-height: 500px; } .mat-column-name{ border-right: 1px solid grey; align-self: stretch; text-align: center } .mat-column-position{ border-right: 1px solid grey; align-self: stretch; text-align: center; } .mat-column-weight{ border-right: 1px solid grey; align-self: stretch; text-align: center; } .mat-column-symbol{ text-align: center; align-self: stretch; } .mat-column-weight{ align-self: stretch; } ` </code></pre>
386,973
Web Service Authentication using OpenID
<p>I'm going to be developing a REST-ful Web Service for a new public website. The idea behind the web service is to have 3rd parties develop fully functional UIs for the business logic.</p> <p>For security reasons, I'd like to avoid users having to give their passwords for our service to the 3rd party applications. (Perhaps this shouldn't be a big concern?) Instead, I'm looking to implement some sort of login system on our site that provides an auth token to the 3rd party app but keeps the actual password out of their hands.</p> <p>This made me think that OpenID might be a potential solution here. It seems to me that it should work: the actual password is handled by the OpenID provider and so it doesn't rest with the 3rd party app. I think that the trouble would probably lie with the various passthroughs, but that should be manageable.</p> <p>However, there's a surprising lack of Googleable info on this, so I'd like SO's opinion. Has anyone implemented a similar system before? Is it even possible? Is it worth the trouble?</p>
429,774
3
0
null
2008-12-22 18:33:14.613 UTC
9
2016-04-06 15:08:50.51 UTC
null
null
null
Craig Walker
3,488
null
1
16
web-services|openid
8,401
<p>I agree completely that what you want is OAuth; I say that having worked on both OAuth and OpenID systems. I've also been in your boat a few times, having to develop a REST web service api.</p> <p>For a really good ideas on OAuth, and why it is what you want see these attached article:</p> <p>These are must read, there are four parts read them all: <a href="http://hueniverse.com/oauth/guide/" rel="nofollow noreferrer">http://hueniverse.com/oauth/guide/</a></p> <p>the RFC, read after reading above as it can be a little daunting for most: <a href="http://oauth.net/core/1.0" rel="nofollow noreferrer">http://oauth.net/core/1.0</a></p> <p>And then finally maybe some code. I have a couple projects hosted that are using Java/Groovy to do OAuth. One is a plain old OAuth client, the other is a client for specific interactions with NetFlix. <a href="http://www.blueleftistconstructor.com/projects/" rel="nofollow noreferrer">http://www.blueleftistconstructor.com/projects/</a></p> <p>If you are relatively inexperienced with REST (you haven't built a full scale web api yet) I would recommend that you buy (or better get your boss to) "RESTful Web Services" by Richardson &amp; Ruby. It is an O'Reilly book. I can say that it is one of their better books to debut in the past few years.</p> <p>It might also help to look at some RESTful OAuth based APIs. The NetFlix API is a perfect example: <a href="http://developer.netflix.com/docs" rel="nofollow noreferrer">http://developer.netflix.com/docs</a></p> <p>Good luck and happy coding!</p>
836,694
JQuery - Adding change event to dropdown
<p>The underlying HTML for my drop down has a chance of changing and I was trying to set it up using the <code>.live</code> option rather than the <code>.change</code> option. it does not work for me.</p> <p>What I currently have is:</p> <pre><code>$("#ItemsPerPage").change(function(e) { return updatePaging(); }); </code></pre> <p>Unfortuantely, if I update this control via <code>$.ajax</code> it loses the event definition. What I tried, and is not working, is:</p> <pre><code>$("#ItemsPerPage").live("change", function(e) { return updatePaging(); }); </code></pre> <p>Any thoughts?</p>
836,821
3
0
null
2009-05-07 19:54:45.01 UTC
2
2012-09-05 14:16:44.83 UTC
2012-09-05 14:16:44.83 UTC
null
319,403
null
86,555
null
1
17
jquery
60,291
<p>Instead of rebinding the <code>&lt;select&gt;</code> every time, you're better off just swapping its contents (the list of <code>&lt;option&gt;</code> elements) instead.</p> <p>So use this as you already are:</p> <pre><code>$("#ItemsPerPage").change(function(e) { return updatePaging(); }); </code></pre> <p>but when you update it, just swap out its contents ( where <code>newSelectElement</code> is the new <code>&lt;select&gt;</code> element):</p> <pre><code>function updateItemsPerPage( newSelectElement ) { $("#ItemsPerPage").empty().append( newSelectElement.childNodes ); } </code></pre> <p>This way, the binding won't need to be refreshed because the node itself isn't swapped.</p>
558,164
How do you decide between using an Abstract Class and an Interface?
<p>I have been getting deeper into the world of OOP, design patterns, and actionscript 3 and I am still curious how to know when to use an Abstract class (pseudo for AS3 which doesn't support Abstract classes) and an interface. To me both just serve as templates that make sure certain methods are implemented in a given class. Is the difference solely in the fact that Abstract classes require inheritance and an Interface merely extends?</p>
558,173
3
0
null
2009-02-17 18:33:42.697 UTC
14
2022-03-12 05:19:31.62 UTC
2022-03-12 05:19:29.363 UTC
Martinho Fernandes
366,904
Brian Hodge
20,628
null
1
20
actionscript-3|oop|interface|abstract-class
23,249
<p>Use an abstract class if you have some functionality that you want it's subclasses to have. For instance, if you have a set of functions that you want all of the base abstract class's subclasses to have. </p> <p>Use an interface if you just want a general contract on behavior/functionality. If you have a function or object that you want to take in a set of different objects, use an interface. Then you can change out the object that is passed in, without changing the method or object that is taking it.</p> <p>Interfaces are typically loose, compared to Abstract classes. You wouldn't want to use interfaces in a situation where you are constantly writing the same code for all of the interface's methods. Use an abstract class and define each method once.</p> <p>Also, if you are trying to create a specific object inheritance hierarchy, you really wouldn't want to try to do that with just interfaces. </p> <p>Also, again, in some languages you can only have a single base class, and if an object already has a base class, you are going to have to do some refactoring in order to use an abstract base class. This may or may not mean that you might want to use an inteface instead.</p> <p>As @tvanfosson notes, it's not a bad idea to use a lot of interfaces, when you really understand abstract classes and interfaces, it's not really an either/or situation. A particular situation could use both abstract classes and interfaces or neither. I like to use interfaces sometimes simply to restrict what a method or object can access on a passed in parameter object.</p>
570,689
How to serialize a JObject without the formatting?
<p>I have a <code>JObject</code> (I'm using Json.Net) that I constructed with LINQ to JSON (also provided by the same library). When I call the <code>ToString()</code> method on the <code>JObject</code>, it outputs the results as formatted JSON.</p> <p>How do I set the formatting to "none" for this?</p>
572,076
3
0
null
2009-02-20 18:15:53.51 UTC
11
2018-01-31 10:13:47.487 UTC
2015-12-20 00:58:11.747 UTC
null
10,263
null
69,041
null
1
124
json|serialization|json.net
156,193
<p>Call JObject's <code>ToString(Formatting.None)</code> method.</p> <p>Alternatively if you pass the object to the JsonConvert.SerializeObject method it will return the JSON without formatting.</p> <p>Documentation: <a href="http://www.newtonsoft.com/json/help/html/ToString.htm" rel="noreferrer"><strong>Write JSON text with JToken.ToString</strong></a></p>
22,338,080
Undo Redo for Fabric.js
<p>I'm trying to add undo/redo functionality to my Fabric.js canvas. My idea is to have a counter which counts canvas modifications (right now it counts the addition of objects). I have a state array, which pushes the whole canvas as JSON to my array.</p> <p>Then I simply want to recall the states with </p> <pre><code>canvas.loadFromJSON(state[state.length - 1 + ctr], </code></pre> <p>As the user clicks on undo, ctr will reduce by one and load the state out of the array; as the user clicks on redo, ctr will increase by one and load the state out of the array.</p> <p>When I experience this with simple numbers, everything works fine. With the real fabric canvas, I get some troubles --> it doesnt really work. I think this relies on my event handler</p> <pre><code>canvas.on({ 'object:added': countmods }); </code></pre> <p><a href="http://jsfiddle.net/gcollect/czaJS/" rel="noreferrer">jsfiddle</a> is here: </p> <p>here is the working numbers only example (results see console): <a href="http://jsfiddle.net/gcollect/U6T94/" rel="noreferrer">jsFiddle</a></p>
23,226,432
5
0
null
2014-03-11 22:31:57.107 UTC
10
2018-09-17 07:21:47.49 UTC
2018-05-24 17:25:18.58 UTC
null
3,207,478
null
3,207,478
null
1
19
javascript|arrays|fabricjs
14,724
<p>I answered this on my own.</p> <p>See <a href="http://jsfiddle.net/gcollect/b3aMF/" rel="noreferrer">jsfiddle</a>:</p> <p>What I did:</p> <pre><code>if (savehistory === true) { myjson = JSON.stringify(canvas); state.push(myjson); } // this will save the history of all modifications into the state array, if enabled if (mods &lt; state.length) { canvas.clear().renderAll(); canvas.loadFromJSON(state[state.length - 1 - mods - 1]); canvas.renderAll(); mods += 1; } // this will execute the undo and increase a modifications variable so we know where we are currently. Vice versa works the redo function. </code></pre> <p>Would still need an improvement to handle both drawings and objects. But that should be simple.</p>
24,177,503
How does the C preprocessor handle circular dependencies?
<p>I want to know how the <strong>C</strong> preprocessor handles circular dependencies (of #defines). This is my program: </p> <pre><code>#define ONE TWO #define TWO THREE #define THREE ONE int main() { int ONE, TWO, THREE; ONE = 1; TWO = 2; THREE = 3; printf ("ONE, TWO, THREE = %d, %d, %d \n",ONE, TWO, THREE); } </code></pre> <p>Here is the preprocessor output. I'm unable to figure out why the output is as such. I would like to know the various steps a preprocessor takes in this case to give the following output.</p> <pre><code># 1 "check_macro.c" # 1 "&lt;built-in&gt;" # 1 "&lt;command-line&gt;" # 1 "check_macro.c" int main() { int ONE, TWO, THREE; ONE = 1; TWO = 2; THREE = 3; printf ("ONE, TWO, THREE = %d, %d, %d \n",ONE, TWO, THREE); } </code></pre> <p>I'm running this program on linux 3.2.0-49-generic-pae and compiling in gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5).</p>
24,177,658
5
0
null
2014-06-12 06:08:33.79 UTC
8
2016-05-18 18:38:52.513 UTC
2016-05-18 18:38:52.513 UTC
null
4,370,109
null
1,499,497
null
1
65
c|linux|gcc|c-preprocessor
5,027
<p>While a preprocessor macro is being expanded, that macro's name is not expanded. So all three of your symbols are defined as themselves:</p> <pre><code>ONE -&gt; TWO -&gt; THREE -&gt; ONE (not expanded because expansion of ONE is in progress) TWO -&gt; THREE -&gt; ONE -&gt; TWO ( " TWO " ) THREE -&gt; ONE -&gt; TWO -&gt; THREE ( " THREE " ) </code></pre> <p>This behaviour is set by &sect;6.10.3.4 of the C standard (section number from the C11 draft, although as far as I know, the wording and numbering of the section is unchanged since C89). When a macro name is encountered, it is replaced with its definition (and <code>#</code> and <code>##</code> preprocessor operators are dealt with, as well as parameters to function-like macros). Then the result is rescanned for more macros (in the context of the rest of the file):</p> <blockquote> <p>2/ If the name of the macro being replaced is found during this scan of the replacement list (not including the rest of the source file’s preprocessing tokens), it is not replaced. Furthermore, if any nested replacements encounter the name of the macro being replaced, it is not replaced&hellip;</p> </blockquote> <p>The clause goes on to say that any token which is not replaced because of a recursive call is effectively "frozen": it will never be replaced: </p> <blockquote> <p>&hellip; These nonreplaced macro name preprocessing tokens are no longer available for further replacement even if they are later (re)examined in contexts in which that macro name preprocessing token would otherwise have been replaced.</p> </blockquote> <p>The situation which the last sentence refers rarely comes up in practice, but here is the simplest case I could think of:</p> <pre><code>#define two one,two #define a(x) b(x) #define b(x,y) x,y a(two) </code></pre> <p>The result is <code>one, two</code>. <code>two</code> is expanded to <code>one,two</code> during the replacement of <code>a</code>, and the expanded <code>two</code> is marked as completely expanded. Subsequently, <code>b(one,two)</code> is expanded. This is no longer in the context of the replacement of <code>two</code>, but the <code>two</code> which is the second argument of <code>b</code> has been frozen, so it is not expanded again. </p>
41,462,606
Get all files recursively in directories NodejS
<p>I have a little problem with my function. I would like to get all files in many directories. Currently, I can retrieve the files in the file passed in parameters. I would like to retrieve the html files of each folder in the folder passed as a parameter. I will explain if I put in parameter "test" I retrieve the files in "test" but I would like to retrieve "test / 1 / *. Html", "test / 2 / <em>. /</em>.html ": </p> <pre><code>var srcpath2 = path.join('.', 'diapo', result); function getDirectories(srcpath2) { return fs.readdirSync(srcpath2).filter(function (file) { return fs.statSync(path.join(srcpath2, file)).isDirectory(); }); } </code></pre> <p>The result : [1,2,3]</p> <p>thanks !</p>
41,462,807
17
0
null
2017-01-04 11:22:40.887 UTC
17
2022-02-12 11:19:20.643 UTC
null
null
null
user6285277
null
null
1
65
node.js|fs|getfiles
88,031
<p>It looks like the <a href="https://www.npmjs.com/package/glob" rel="noreferrer"><code>glob</code> npm package</a> would help you. Here is an example of how to use it:</p> <p>File hierarchy:</p> <pre><code>test β”œβ”€β”€ one.html └── test-nested └── two.html </code></pre> <p>JS code:</p> <pre><code>const glob = require(&quot;glob&quot;); var getDirectories = function (src, callback) { glob(src + '/**/*', callback); }; getDirectories('test', function (err, res) { if (err) { console.log('Error', err); } else { console.log(res); } }); </code></pre> <p>which displays:</p> <pre><code>[ 'test/one.html', 'test/test-nested', 'test/test-nested/two.html' ] </code></pre>
6,234,711
What are the specific differences between an "emulator" and a "virtual machine"?
<p>I see that they are different things but I really can't tell why. Some people say: "emulators are for games; virtual machines are for operating systems" I don't agree with this answers because there are emulators for platforms other than videogame consoles (AMIGA (?) )</p> <p>Can you help me please?</p>
6,234,760
3
0
null
2011-06-04 04:36:44.57 UTC
39
2022-01-06 17:16:50.427 UTC
2012-06-16 23:54:59.827 UTC
null
246,246
null
778,693
null
1
53
emulation|virtual-machine
61,311
<p>Virtual machines make use of CPU self-virtualization, to whatever extent it exists, to provide a virtualized interface to the real hardware. Emulators emulate hardware without relying on the CPU being able to run code directly and redirect some operations to a hypervisor controlling the virtual container.</p> <p>A specific x86 example might help: <a href="http://bochs.sourceforge.net/" rel="noreferrer">Bochs</a> is an emulator, emulating an entire processor in software even when it's running on a compatible physical processor; <a href="http://qemu.org/" rel="noreferrer">qemu</a> is also an emulator, although with the use of a kernel-side <code>kqemu</code> package it gained some limited virtualization capability when the emulated machine matched the physical hardware β€” but it could not really take advantage of full x86 self-virtualization, so it was a limited hypervisor; <a href="http://www.linux-kvm.org/" rel="noreferrer">kvm</a> is a virtual machine hypervisor.</p> <p>A hypervisor could be said to "emulate" protected access; it doesn't emulate the processor, though, and it would be more correct to say that it <em>mediates</em> protected access.</p> <p>Protected access means things like setting up page tables or reading/writing I/O ports. For the former, a hypervisor validates (and usually modifies, to match the hypervisor's own memory) the page table operation and performs the protected instruction itself; I/O operations are mapped to emulated device hardware instead of emulated CPU.</p> <p>And just to complicate things, <a href="http://www.winehq.org/" rel="noreferrer">Wine</a> is also more a hypervisor/virtual machine (albeit at a higher ABI level) than an emulator (hence "Wine Is Not an Emulator").</p>
5,834,371
Is there any good open-source or freely available Chinese segmentation algorithm available?
<p>As phrased in the question, I'm looking for a free and/or open-source text-segmentation algorithm for Chinese, I do understand it is a very difficult task to solve, as there are many ambiguities involed. I know there's google's API, but well it is rather a black-box, i.e. not many information of what it is doing are passing through.</p>
6,053,420
4
0
null
2011-04-29 15:59:09.85 UTC
25
2015-06-15 07:18:36.437 UTC
2013-01-14 19:15:12.467 UTC
null
422,353
null
281,306
null
1
28
algorithm|open-source|cjk|text-segmentation
10,015
<p>The keyword <code>text-segmentation for Chinese</code> should be <code>δΈ­ζ–‡εˆ†θ―</code> in Chinese. </p> <p><strong>Good and active open-source text-segmentation algorithm</strong> : </p> <ol> <li><strong><a href="http://pangusegment.codeplex.com/">η›˜ε€εˆ†θ―(Pan Gu Segment)</a></strong> : <code>C#</code>, <a href="http://i3.codeplex.com/Project/Download/FileDownload.aspx?ProjectName=pangusegment&amp;DownloadId=79153"><strong><code>Snapshot</code></strong></a></li> <li><strong><a href="http://code.google.com/p/ik-analyzer/">ik-analyzer</a></strong> : <code>Java</code></li> <li><strong><a href="http://ictclas.org/index.html">ICTCLAS</a></strong> : <code>C/C++, Java, C#</code>, <a href="http://ictclas.org/ictclas_demo.html"><strong><code>Demo</code></strong></a></li> <li><strong><a href="http://www.oschina.net/p/nlpbamboo">NlpBamboo</a></strong> : <code>C, PHP, PostgreSQL</code> </li> <li><strong><a href="http://code.google.com/p/httpcws/">HTTPCWS</a></strong> : based on <code>ICTCLAS</code>, <a href="http://blog.s135.com/demo/httpcws/"><strong><code>Demo</code></strong></a></li> <li><strong><a href="http://code.google.com/p/mmseg4j/">mmseg4j</a></strong> : <code>Java</code></li> <li><strong><a href="http://code.google.com/p/fudannlp/">fudannlp</a></strong> : <code>Java</code>, <a href="http://jkx.fudan.edu.cn/nlp/"><strong><code>Demo</code></strong></a></li> <li><strong><a href="http://code.google.com/p/smallseg/">smallseg</a></strong> : <code>Python, Java</code>, <a href="http://smallseg.appspot.com/smallseg"><strong><code>Demo</code></strong></a></li> <li><strong><a href="https://github.com/mountain/nseg">nseg</a></strong> : NodeJS</li> <li><strong><a href="https://code.google.com/p/mini-segmenter/">mini-segmenter</a></strong>: <code>python</code> </li> </ol> <p><strong>Other</strong> </p> <ol> <li><strong>Google Code</strong> : <a href="http://code.google.com/query/#q=%E4%B8%AD%E6%96%87%E5%88%86%E8%AF%8D">http://code.google.com/query/#q=δΈ­ζ–‡εˆ†θ―</a></li> <li><strong><a href="http://www.oschina.net/project/tag/264/segment?sort=view&amp;lang=0&amp;os=0">OSChina (Open Source China)</a></strong></li> </ol> <p><strong>Sample</strong></p> <ol> <li><p><strong><a href="http://www.chromium.org/">Google Chrome (Chromium)</a></strong> : <a href="http://src.chromium.org/viewvc"><code>src</code></a>, <a href="http://src.chromium.org/viewvc/chrome/trunk/deps/third_party/icu38/source/data/brkitr/cc_cedict.txt"><code>cc_cedict.txt (73,145 Chinese words/pharases)</code></a> </p> <ul> <li><p>In <code>text field</code> or <code>textarea</code> of <strong>Google Chrome</strong> with Chinese sentences, press <kbd>Ctrl</kbd>+<kbd>←</kbd> or <kbd>Ctrl</kbd>+<kbd>β†’</kbd></p></li> <li><p><code>Double click</code> on <code>δΈ­ζ–‡εˆ†θ―ζŒ‡ηš„ζ˜―ε°†δΈ€δΈͺζ±‰ε­—εΊεˆ—εˆ‡εˆ†ζˆδΈ€δΈͺδΈ€δΈͺε•η‹¬ηš„θ―</code></p></li> </ul></li> </ol>
5,864,540
Infinite loop with cin when typing string while a number is expected
<p>In the following loop, if we type characters as the <code>cin</code> input instead of numbers which are expected, then it goes into infinite loop. Could anyone please explain to me why this occurs?</p> <p>When we use <code>cin</code>, if the input is not a number, then are there ways to detect this to avoid abovementioned problems?</p> <pre><code>unsigned long ul_x1, ul_x2; while (1) { cin &gt;&gt; ul_x1 &gt;&gt; ul_x2; cout &lt;&lt; "ux_x1 is " &lt;&lt; ul_x1 &lt;&lt; endl &lt;&lt; "ul_x2 is " &lt;&lt; ul_x2 &lt;&lt; endl; } </code></pre>
5,864,560
4
0
null
2011-05-03 02:43:59.91 UTC
21
2018-01-27 19:03:21.263 UTC
2016-09-14 05:09:18.61 UTC
null
492,336
null
735,008
null
1
28
c++|validation|infinite-loop|cin
34,129
<p>Well you always will have an infinite loop, but I know what you really want to know is why cin doesn't keep prompting for input on each loop iteration causing your infinite loop to freerun.</p> <p>The reason is because cin fails in the situation you describe and won't read any more input into those variables. By giving cin bad input, cin gets in the <a href="http://www.cplusplus.com/reference/iostream/ios/fail/">fail state</a> and stops prompting the command line for input causing the loop to free run.</p> <p>For simple validation, you can try to use cin to validate your inputs by checking whether cin is in the fail state. When fail occurs <a href="http://www.cplusplus.com/reference/iostream/ios/clear/">clear the fail</a> state and force the stream to <a href="http://www.cplusplus.com/reference/iostream/istream/ignore/">throw away the bad input</a>. This returns cin to normal operation so you can prompt for more input.</p> <pre><code> if (cin.fail()) { cout &lt;&lt; "ERROR -- You did not enter an integer"; // get rid of failure state cin.clear(); // From Eric's answer (thanks Eric) // discard 'bad' character(s) cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); } </code></pre> <p>For more sophisticated validation, you may wish to read into a string first and do more sophisticated checks on the string to make sure it matches what you expect.</p>
5,668,801
Entity framework code-first null foreign key
<p>I have a <code>User</code> &lt; <code>Country</code> model. A user belongs to a country, but may not belong to any (null foreign key).</p> <p>How do I set this up? When I try to insert a user with a null country, it tells me that it cannot be null.</p> <p>The model is as follows:</p> <pre><code> public class User{ public int CountryId { get; set; } public Country Country { get; set; } } public class Country{ public List&lt;User&gt; Users {get; set;} public int CountryId {get; set;} } </code></pre> <p>Error: <code>A foreign key value cannot be inserted because a corresponding primary key value does not exist. [ Foreign key constraint name = Country_Users ]"}</code></p>
5,668,835
4
3
null
2011-04-14 19:46:27.993 UTC
20
2021-02-15 22:12:15.36 UTC
2011-04-14 20:11:01.933 UTC
null
400,861
null
400,861
null
1
138
entity-framework|mapping|ef-code-first|foreign-key-relationship|entity-framework-4.1
136,782
<p>You must make your foreign key nullable:</p> <pre><code>public class User { public int Id { get; set; } public int? CountryId { get; set; } public virtual Country Country { get; set; } } </code></pre>
1,743,448
Auto-scrolling text box uses more memory than expected
<p>I have an application that logs messages to the screen using a TextBox. The update function uses some Win32 functions to ensure that the box automatically scrolls to the end unless the user is viewing another line. Here is the update function:</p> <pre><code>private bool logToScreen = true; // Constants for extern calls to various scrollbar functions private const int SB_HORZ = 0x0; private const int SB_VERT = 0x1; private const int WM_HSCROLL = 0x114; private const int WM_VSCROLL = 0x115; private const int SB_THUMBPOSITION = 4; private const int SB_BOTTOM = 7; private const int SB_OFFSET = 13; [DllImport("user32.dll")] static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw); [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern int GetScrollPos(IntPtr hWnd, int nBar); [DllImport("user32.dll")] private static extern bool PostMessageA(IntPtr hWnd, int nBar, int wParam, int lParam); [DllImport("user32.dll")] static extern bool GetScrollRange(IntPtr hWnd, int nBar, out int lpMinPos, out int lpMaxPos); private void LogMessages(string text) { if (this.logToScreen) { bool bottomFlag = false; int VSmin; int VSmax; int sbOffset; int savedVpos; // Make sure this is done in the UI thread if (this.txtBoxLogging.InvokeRequired) { this.txtBoxLogging.Invoke(new TextBoxLoggerDelegate(LogMessages), new object[] { text }); } else { // Win32 magic to keep the textbox scrolling to the newest append to the textbox unless // the user has moved the scrollbox up sbOffset = (int)((this.txtBoxLogging.ClientSize.Height - SystemInformation.HorizontalScrollBarHeight) / (this.txtBoxLogging.Font.Height)); savedVpos = GetScrollPos(this.txtBoxLogging.Handle, SB_VERT); GetScrollRange(this.txtBoxLogging.Handle, SB_VERT, out VSmin, out VSmax); if (savedVpos &gt;= (VSmax - sbOffset - 1)) bottomFlag = true; this.txtBoxLogging.AppendText(text + Environment.NewLine); if (bottomFlag) { GetScrollRange(this.txtBoxLogging.Handle, SB_VERT, out VSmin, out VSmax); savedVpos = VSmax - sbOffset; bottomFlag = false; } SetScrollPos(this.txtBoxLogging.Handle, SB_VERT, savedVpos, true); PostMessageA(this.txtBoxLogging.Handle, WM_VSCROLL, SB_THUMBPOSITION + 0x10000 * savedVpos, 0); } } } </code></pre> <p>Now the strange thing is that the text box consumes at least double the memory that I would expect it to. For example, when there are ~1MB of messages in the TextBox, the application can consume up to 6MB of memory (in addition to what it uses when the logToScreen is set to false). The increase is always at least double what I expect, and (as in my example) sometimes more.</p> <p>What is more strange is that using:</p> <pre><code>this.txtBoxLogging.Clear(); for (int i = 0; i &lt; 3; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } </code></pre> <p>Does not free the memory (in fact, it increases slightly).</p> <p>Any idea where the memory is going as I'm logging these messages? I don't believe it has anything to do with the Win32 calls, but I've included it to be thorough.</p> <p>EDIT:</p> <p>The first couple of responses I got were related to how to track a memory leak, so I thought I should share my methodology. I used a combination of WinDbg and perfmon to track the memory use over time (from a couple hours to days). The total number of bytes on all CLR heaps does not increase by more than I expect, but the total number of private bytes steadily increases as more messages are logged. This makes WinDbg less useful, as it's tools (sos) and commands (dumpheap, gcroot, etc.) are based on .NET's managed memory.</p> <p>This is likely why GC.Collect() can not help me, as it is only looking for free memory on the CLR heap. My leak appears to be in un-managed memory.</p>
1,743,478
2
2
null
2009-11-16 16:59:27.62 UTC
10
2011-02-09 04:01:50.61 UTC
2011-02-09 04:01:50.61 UTC
null
76,337
null
131,327
null
1
16
c#|.net|memory|textbox
6,336
<p>How are you determining the memory usage? You'd have to watch the CLR memory usage for your application, not the memory used by the system for the whole application (you can use Perfmon for that). Perhaps you are already using the correct method of monitoring.</p> <p>It seems to me that you are using <code>StringBuilder</code> internally. If so, that would explain the doubling of the memory, because that's the way StringBuilder works internally.</p> <p>The <code>GC.Collect()</code> may not do anything if the references to your objects are still in scope, or if any of your code uses static variables.</p> <hr> <p><em>EDIT:</em><br> I'll leave the above, because it may still be true, but I looked up <code>AppendText</code>'s internals. It does not append (i.e., to a StringBuilder), instead, it sets the <code>SelectedText</code> property, which does not set a string but sends a Win32 message (string is cached on retrieval).</p> <p>Because strings are immutable, this means, for every string, there will be three copies: one in the calling application, one in the "cache" of the base <code>Control</code> and one in the actual Win32 textbox control. Each character is two bytes wide. This means that any 1MB of text, will consume 6MB of memory (I know, this is a bit simplistic, but that's basically what seems happening).</p> <p><em>EDIT 2:</em> not sure if it'll make any change, but you can consider calling <code>SendMessage</code> yourself. But it sure starts to look like you'll need your own scrolling algorithm and your own owner-drawn textbox to get the memory down.</p>
2,153,650
How to start a GET/POST/PUT/DELETE request and judge request type in PHP?
<p>I never see how is <code>PUT/DELETE</code> request sent.</p> <p>How to do it in PHP?</p> <p>I know how to send a GET/POST request with curl:</p> <pre><code>$ch = curl_init(); curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); curl_setopt($ch, CURLOPT_COOKIEFILE,$cookieFile); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_POST, 0); curl_setopt($ch, CURLOPT_TIMEOUT, 4); </code></pre> <p>But how to do <code>PUT</code>/<code>DELETE</code> request?</p>
2,153,670
2
2
null
2010-01-28 10:06:17.927 UTC
10
2021-05-26 09:09:33.043 UTC
2014-11-03 11:18:43.853 UTC
null
3,885,376
null
198,729
null
1
17
php|request
36,874
<p>For <code>DELETE</code> use <code>curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');</code><br /> For <code>PUT</code> use <code>curl_setopt($ch, CURLOPT_PUT, true);</code></p> <p>An alternative that doesn't rely on cURL being installed would be to use <code>file_get_contents</code> with a <a href="http://php.net/manual/de/context.http.php" rel="nofollow noreferrer">custom HTTP stream context</a>.</p> <pre><code>$result = file_get_contents( 'http://example.com/submit.php', false, stream_context_create(array( 'http' =&gt; array( 'method' =&gt; 'DELETE' ) )) ); </code></pre> <p>Check out these two articles on doing REST with PHP</p> <ul> <li><a href="https://web.archive.org/web/20130306123233/https://www.gen-x-design.com/archives/create-a-rest-api-with-php/" rel="nofollow noreferrer">http://www.gen-x-design.com/archives/create-a-rest-api-with-php/</a></li> <li><a href="https://web.archive.org/web/20130306123233/http://www.gen-x-design.com/archives/making-restful-requests-in-php/" rel="nofollow noreferrer">http://www.gen-x-design.com/archives/making-restful-requests-in-php/</a></li> </ul>
5,978,482
.NET 4 Caching Support
<p>I understand the .NET 4 Framework has caching support built into it. Does anyone have any experience with this, or could provide good resources to learn more about this?</p> <p>I am referring to the caching of objects (entities primarily) in memory, and probably the use of System.Runtime.Caching.</p>
5,978,646
5
4
null
2011-05-12 13:10:28.81 UTC
6
2016-06-29 16:23:47.187 UTC
2011-05-12 13:52:46.583 UTC
null
418,384
null
418,384
null
1
32
c#|.net|caching
40,956
<p>I assume you are getting at <a href="http://msdn.microsoft.com/en-us/library/dd997357.aspx" rel="nofollow noreferrer">this</a>, <a href="http://msdn.microsoft.com/en-us/library/system.runtime.caching.aspx" rel="nofollow noreferrer"><code>System.Runtime.Caching</code></a>, similar to the <code>System.Web.Caching</code> and in a more general namespace.</p> <p>See <a href="http://deanhume.com/Home/BlogPost/object-caching----net-4/37" rel="nofollow noreferrer">http://deanhume.com/Home/BlogPost/object-caching----net-4/37</a></p> <p>and on the stack,</p> <p><a href="https://stackoverflow.com/questions/2889812/is-there-some-sort-of-cachedependency-in-system-runtime-caching">is-there-some-sort-of-cachedependency-in-system-runtime-caching</a> and,</p> <p><a href="https://stackoverflow.com/questions/3157340/performance-of-system-runtime-caching">performance-of-system-runtime-caching</a>.</p> <p>Could be useful.</p>
6,208,700
Why doesn't "case" with "when > 2" work?
<p>Why is this not working?</p> <pre><code>case ARGV.length when 0 abort "Error 1" when &gt; 2 abort "Error 2" end </code></pre>
6,208,810
5
0
null
2011-06-01 23:00:02.457 UTC
4
2022-01-14 12:06:15.607 UTC
2011-06-02 00:51:01.673 UTC
null
314,166
null
504,715
null
1
35
ruby
21,295
<p>An <code>if</code> statement would probably be more fitting for your code, since you don't have a definitive range/value, but rather just a greater-than:</p> <pre><code>if ARGV.length == 0 abort "Error 1" elsif ARGV.length &gt; 2 abort "Error 2" end </code></pre>
5,943,249
Python argparse and controlling/overriding the exit status code
<p>Apart from tinkering with the <code>argparse</code> source, is there any way to control the exit status code should there be a problem when <code>parse_args()</code> is called, for example, a missing required switch?</p>
5,943,381
8
0
null
2011-05-09 22:29:20.107 UTC
16
2021-01-20 19:02:01.65 UTC
null
null
null
null
419
null
1
58
python|argparse
51,352
<p>I'm not aware of any mechanism to specify an exit code on a per-argument basis. You can catch the <code>SystemExit</code> exception raised on <code>.parse_args()</code> but I'm not sure how you would then ascertain what <em>specifically</em> caused the error.</p> <p><strong>EDIT:</strong> For anyone coming to this looking for a practical solution, the following is the situation:</p> <ul> <li><code>ArgumentError()</code> is raised appropriately when arg parsing fails. It is passed the argument instance and a message</li> <li><code>ArgumentError()</code> does <em>not</em> store the argument as an instance attribute, despite being passed (which would be convenient)</li> <li>It is possible to re-raise the <code>ArgumentError</code> exception by subclassing <code>ArgumentParser</code>, overriding .error() and getting hold of the exception from sys.exc_info()</li> </ul> <p>All that means the following code - whilst ugly - allows us to catch the ArgumentError exception, get hold of the offending argument and error message, and do as we see fit:</p> <pre><code>import argparse import sys class ArgumentParser(argparse.ArgumentParser): def _get_action_from_name(self, name): """Given a name, get the Action instance registered with this parser. If only it were made available in the ArgumentError object. It is passed as it's first arg... """ container = self._actions if name is None: return None for action in container: if '/'.join(action.option_strings) == name: return action elif action.metavar == name: return action elif action.dest == name: return action def error(self, message): exc = sys.exc_info()[1] if exc: exc.argument = self._get_action_from_name(exc.argument_name) raise exc super(ArgumentParser, self).error(message) ## usage: parser = ArgumentParser() parser.add_argument('--foo', type=int) try: parser.parse_args(['--foo=d']) except argparse.ArgumentError, exc: print exc.message, '\n', exc.argument </code></pre> <p>Not tested in any useful way. The usual don't-blame-me-if-it-breaks indemnity applies.</p>