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
783,974
How to implement SOLID principles into an existing project
<p>I apologize for the subjectiveness of this question, but I am a little stuck and I would appreciate some guidance and advice from anyone who's had to deal with this issue before:</p> <p>I have (what's become) a very large RESTful API project written in C# 2.0 and some of my classes have become monstrous. My main API class is an example of this -- with several dozen members and methods (probably approaching hundreds). As you can imagine, it's becoming a small nightmare, not only to maintain this code but even just <strong>navigating</strong> the code has become a chore.</p> <p>I am reasonably new to the SOLID principles, and I am massive fan of design patterns (but I am still at that stage where I can <strong>implement</strong> them, but not quite enough to know when to <strong>use</strong> them - in situations where its not so obvious).</p> <p>I need to break my classes down in size, but I am at a loss of how best to go about doing it. Can my fellow StackOverflow'ers please suggest ways that they have taken existing code monoliths and cut them down to size?</p>
784,035
5
0
null
2009-04-23 23:28:09.733 UTC
20
2021-12-11 15:31:27.037 UTC
2013-04-21 13:01:57.057 UTC
null
682,095
null
11,194
null
1
22
c#|design-patterns|solid-principles
5,745
<p><strong>Single Responsibility Principle</strong> - A class should have only one reason to change. If you have a monolithic class, then it probably has more than one reason to change. Simply define your one reason to change, and be as granular <em>as reasonable</em>. I would suggest to start &quot;large&quot;. Refactor one third of the code out into another class. Once you have that, then start over with your new class. Going straight from one class to 20 is too daunting.</p> <p><strong>Open/Closed Principle</strong> - A class should be open for extension, but closed for change. Where reasonable, mark your members and methods as virtual or abstract. Each item should be relatively small in nature, and give you some base functionality or definition of behavior. However, if you need to change the functionality later, you will be able to <em>add</em> code, rather than <em>change</em> code to introduce new/different functionality.</p> <p><strong>Liskov Substitution Principle</strong> - A class should be substitutable for its base class. The key here, in my opinion, is do to inheritance correctly. If you have a huge case statement, or two pages of if statements that check the derived type of the object, then your violating this principle and need to rethink your approach.</p> <p><strong>Interface Segregation Principle</strong> - In my mind, this principle closely resembles the Single Responsibility principle. It just applies specifically to a high level (or mature) class/interface. One way to use this principle in a large class is to make your class implement an <em>empty</em> interface. Next, change all of the types that use your class to be the type of the interface. This will break your code. However, it will point out exactly how you are consuming your class. If you have three instances that each use their own subset of methods and properties, then you now know that you need three different interfaces. Each interface represents a collective set of functionality, and one reason to change.</p> <p><strong>Dependency Inversion Principle</strong> - The parent / child allegory made me understand this. Think of a parent class. It defines behavior, but isn't concerned with the dirty details. It's dependable. A child class, however, is all about the details, and can't be depended upon because it changes often. You always want to depend upon the parent, responsible classes, and never the other way around. If you have a parent class depending upon a child class, you'll get unexpected behavior when you change something. In my mind, this is the same mindset of SOA. A service contract defines inputs, outputs, and behavior, with no details.</p> <p>Of course, my opinions and understandings may be incomplete or wrong. I would suggest learning from people who have mastered these principles, like Uncle Bob. A good starting point for me was his book, <a href="https://rads.stackoverflow.com/amzn/click/com/0131857258" rel="nofollow noreferrer" rel="nofollow noreferrer">Agile Principles, Patterns, and Practices in C#</a>. Another good resource was <a href="http://www.hanselman.com/blog/HanselminutesPodcast145SOLIDPrinciplesWithUncleBobRobertCMartin.aspx" rel="nofollow noreferrer">Uncle Bob on Hanselminutes</a>.</p> <p>Of course, as <a href="https://blog.stackoverflow.com/2009/02/podcast-41/">Joel and Jeff pointed out</a>, these are principles, not rules. They are to be tools to help guide you, not the law of the land.</p> <p><strong>EDIT:</strong></p> <p>I just found these <a href="http://www.dimecasts.net/Casts/ByTag/SOLID%20Principle" rel="nofollow noreferrer">SOLID screencasts</a> which look really interesting. Each one is approximately 10-15 minutes long.</p>
885,156
What's wrong with var x = new Array();
<p>In JSLint, it warns that</p> <pre><code>var x = new Array(); </code></pre> <p>(That's not a real variable name) should be</p> <pre><code>var result = []; </code></pre> <p>What is wrong with the 1st syntax? What's the reasoning behind the suggestion?</p>
885,196
5
1
null
2009-05-19 21:38:29.077 UTC
8
2013-01-21 20:25:35.723 UTC
2009-05-19 22:29:32.797 UTC
null
21,574
null
21,574
null
1
41
javascript|jslint
19,444
<p><a href="https://stackoverflow.com/questions/383402/is-javascript-s-new-keyword-considered-harmful">Crockford doesn't like <code>new</code></a>. Therefore, <a href="http://www.jslint.com/lint.html#new" rel="nofollow noreferrer">JSLint expects you to avoid it</a> when possible. And creating a new array object is possible without using <code>new</code>....</p>
313,778
generate dependencies for a makefile for a project in C/C++
<p>I have a project that has a makefile with broken dependencies. Is there any best known way to generate a list of dependencies for the project that I can use in the makefile, other than examining each source file by hand or with a hand written perl script?</p>
313,787
5
0
null
2008-11-24 09:49:58.677 UTC
24
2019-02-23 03:41:02 UTC
null
null
null
Nathan Fellman
1,084
null
1
42
c++|c|makefile|dependencies
56,610
<p><a href="https://make.mad-scientist.net/papers/advanced-auto-dependency-generation/#combine" rel="noreferrer">GNU make</a>'s documentation provides a good solution.</p> <p>Absolutely. <code>g++ -MM &lt;your file&gt;</code> will generate a GMake compatible list of dependencies. I use something like this:</p> <pre><code># Add .d to Make's recognized suffixes. SUFFIXES += .d #We don't need to clean up when we're making these targets NODEPS:=clean tags svn #Find all the C++ files in the src/ directory SOURCES:=$(shell find src/ -name "*.cpp") #These are the dependency files, which make will clean up after it creates them DEPFILES:=$(patsubst %.cpp,%.d,$(SOURCES)) #Don't create dependencies when we're cleaning, for instance ifeq (0, $(words $(findstring $(MAKECMDGOALS), $(NODEPS)))) #Chances are, these files don't exist. GMake will create them and #clean up automatically afterwards -include $(DEPFILES) endif #This is the rule for creating the dependency files src/%.d: src/%.cpp $(CXX) $(CXXFLAGS) -MM -MT '$(patsubst src/%.cpp,obj/%.o,$&lt;)' $&lt; -MF $@ #This rule does the compilation obj/%.o: src/%.cpp src/%.d src/%.h @$(MKDIR) $(dir $@) $(CXX) $(CXXFLAGS) -o $@ -c $&lt; </code></pre> <p><strong>Note:</strong> <code>$(CXX)</code>/<code>gcc</code> command must be <a href="https://stackoverflow.com/questions/14109724/makefile-missing-separator">preceded with a hard tab</a></p> <p>What this will do is automatically generate the dependencies for each file that has changed, and compile them according to whatever rule you have in place. This allows me to just dump new files into the <code>src/</code> directory, and have them compiled automatically, dependencies and all.</p>
1,003,613
How to make a div 100% of page (not screen) height?
<p>I'm trying to use CSS to create a 'greyed out' effect on my page while a loading box is displayed in the foreground while the application is working. I've done this by creating a 100% height/width, translucent black div which has its visibility toggled on/off via javascript. I thought this would be simple enough; however, when the page content expands to the point that the screen scrolls, scrolling to the foot of the page reveals a portion which is not greyed out. In other words, the 100% in the div's height seems to be applying to the browser viewport size, not the actual page size. How can I make the div expand to cover the whole of the page's content? I've tried using JQuery .css('height', '100%') before toggling it's visibility on but this doesn't change anything.</p> <p>This is the CSS of the div in question:</p> <pre><code>div.screenMask { position: absolute; left: 0px; top: 0px; width: 100%; height: 100%; z-index: 1000; background-color: #000000; opacity: 0.7; filter: alpha(opacity=70); visibility: hidden; } </code></pre> <p>Thanks.</p>
1,003,652
5
1
null
2009-06-16 19:56:54.113 UTC
11
2016-03-23 09:48:29.987 UTC
null
null
null
null
69,285
null
1
57
html|css
78,279
<p>If you change <code>position: absolute</code> to <code>position: fixed</code> it will work in all browsers except IE6. This fixes the div to the viewport, so it doesn't move out of view when scrolling.</p> <p>You can use <code>$(document).height()</code> in jQuery to make it work in IE6 too. E.g.</p> <pre><code>$('.screenMask').height($(document).height()); </code></pre> <p>That would obviously fix it for all the other browsers too, but I prefer not using JavaScript if I can avoid it. You'd need to do the same thing for the width too, actually, in case there's any horizontal scrolling.</p> <p>There are <a href="http://www.google.com/search?q=%22fixed+positioning%22+ie6" rel="noreferrer">plenty of hacks around to make fixed positioning work in IE6</a> too, but they tend to either impose some other limitations on your CSS, or use JavaScript, so they're likely not worth the trouble.</p> <p>Also, I presume you have only one of these masks, so I'd suggest using an ID for it instead of a class.</p>
165,650
How to add a Tooltip to a "td" with jquery?
<p>I need to add a tooltip/alt to a "td" element inside of my tables with jquery.</p> <p>Can someone help me out?</p> <p>I tried:</p> <pre><code>var tTip ="Hello world"; $(this).attr("onmouseover", tip(tTip)); </code></pre> <p>where I have verified that I am using the "td" as "this".</p> <p>**Edit:**I am able to capture the "td" element through using the "alert" command and it worked. So for some reason the "tip" function doesn't work. Anyone know why this would be?</p>
165,668
6
0
null
2008-10-03 04:00:48.593 UTC
1
2016-02-21 15:03:34.203 UTC
2016-02-21 15:03:34.203 UTC
Scott
1,479,535
Scott
7,644
null
1
8
jquery|html
50,041
<p>you might want to have a look at <a href="http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/" rel="noreferrer">http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/</a></p>
631,695
Why am I getting a Hibernate LazyInitializationException in this Spring MVC web application when the data displays correctly?
<p>I am attempting to create a web application using Spring MVC, with Hibernate as its ORM layer. However, due to my inexperience with both frameworks I'm struggling.</p> <p>The following code will properly display all the records I am looking for but still throw a stack trace into my logs. I'm having trouble finding thorough documentation concerning integrating Hibernate and SpringMVC (I've looked on springsource.org and read various articles on the interweb). Could anyone point out what I could be doing wrong here?</p> <p>Please note that I have spent a few trying to track down answers on the internet for this, including looking at <a href="https://stackoverflow.com/questions/345705/hibernate-lazyinitializationexception-could-not-initialize-proxy">this</a> SO question. Which was unfortunately no help.</p> <p>I should also note that the ORM part of this application has been used and tested in a stand alone Java application without problems. So I believe the integration of Spring MVC and Hibernate is causing the issue.</p> <p>Here is the stack trace (truncated) with the famous lazy initialization issue;</p> <pre><code>2009-03-10 12:14:50,353 [http-8084-6] ERROR org.hibernate.LazyInitializationException.&lt;init&gt;(LazyInitializationException.java:19) - could not initialize proxy - no Session org.hibernate.LazyInitializationException: could not initialize proxy - no Session at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:57) at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:111) at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.invoke(CGLIBLazyInitializer.java:150) at com.generic.orm.generated.SearchRule$$EnhancerByCGLIB$$92abaed6.toString(&lt;generated&gt;) at java.lang.String.valueOf(String.java:2827) at java.lang.StringBuffer.append(StringBuffer.java:219) at org.apache.commons.lang.builder.ToStringStyle.appendDetail(ToStringStyle.java:578) at org.apache.commons.lang.builder.ToStringStyle.appendInternal(ToStringStyle.java:542) at org.apache.commons.lang.builder.ToStringStyle.append(ToStringStyle.java:428) at org.apache.commons.lang.builder.ToStringBuilder.append(ToStringBuilder.java:840) at org.apache.commons.lang.builder.ReflectionToStringBuilder.appendFieldsIn(ReflectionToStringBuilder.java:606) ..... </code></pre> <p>Here is a code from my web page controller;</p> <pre><code>private List&lt;Report&gt; getReports() { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); List&lt;Report&gt; reports = session.createCriteria(Report.class).list(); Hibernate.initialize(reports); session.getTransaction().commit(); return reports; } </code></pre> <p>Which is employed on the web page using this display html;</p> <pre><code>&lt;table border="1"&gt; &lt;c:forEach items="${model.reports}" var="report"&gt; &lt;tr&gt; &lt;td&gt;&lt;c:out value="${report.id}"/&gt;&lt;/td&gt; &lt;td&gt;&lt;c:out value="${report.username}"/&gt;&lt;/td&gt; &lt;td&gt;&lt;c:out value="${report.thresholdMet}"/&gt;&lt;/td&gt; &lt;td&gt;&lt;c:out value="${report.results}"/&gt;&lt;/td&gt; &lt;td&gt;&lt;c:out value="${report.searchRule.name}"/&gt;&lt;/td&gt; &lt;td&gt;&lt;c:out value="${report.uuid}"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/c:forEach&gt; &lt;/table&gt; </code></pre> <p>Note: That I added report.searchRule.name to test if I could get at the objects within the report object. It displays fine.</p> <p>And in my applicationContext.xml;</p> <pre><code>&lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"&gt; &lt;property name="configLocation"&gt; &lt;value&gt;classpath:hibernate.cfg.xml&lt;/value&gt; &lt;/property&gt; &lt;property name="hibernateProperties"&gt; &lt;props&gt; &lt;prop key="hibernate.dialect"&gt;${hibernate.dialect}&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;/bean&gt; </code></pre> <p>Here are the ORM mappings, just in case;</p> <p>The hibernate.cfg.xml (as requested)</p> <pre><code>&lt;hibernate-configuration&gt; &lt;session-factory&gt; &lt;property name="hibernate.connection.driver_class"&gt;com.microsoft.sqlserver.jdbc.SQLServerDriver&lt;/property&gt; &lt;property name="hibernate.connection.url"&gt;jdbc:sqlserver://&lt;removed&gt;&lt;/property&gt; &lt;property name="hibernate.connection.username"&gt;&lt;removed&gt;&lt;/property&gt; &lt;property name="hibernate.connection.password"&gt;&lt;removed&gt;&lt;/property&gt; &lt;property name="hibernate.current_session_context_class"&gt;thread&lt;/property&gt; &lt;property name="hibernate.show_sql"&gt;false&lt;/property&gt; &lt;mapping resource="com/generic/orm/generated/Report.hbm.xml"/&gt; &lt;mapping resource="com/generic/orm/generated/FieldRule.hbm.xml"/&gt; &lt;mapping resource="com/generic/orm/generated/Reconciliation.hbm.xml"/&gt; &lt;mapping resource="com/generic/orm/generated/SearchRule.hbm.xml"/&gt; &lt;mapping resource="com/generic/orm/generated/IndexTemplate.hbm.xml"/&gt; &lt;mapping resource="com/generic/orm/generated/Field.hbm.xml"/&gt; &lt;mapping resource="com/generic/orm/generated/ErrorCode.hbm.xml"/&gt; &lt;/session-factory&gt; &lt;/hibernate-configuration&gt; </code></pre> <p>From report.hbm.xml</p> <pre><code>&lt;hibernate-mapping&gt; &lt;class name="com.generic.orm.generated.Report" table="Report" schema="dbo" catalog="CoolRecon"&gt; &lt;id name="id" type="int"&gt; &lt;column name="ID" /&gt; &lt;generator class="native" /&gt; &lt;/id&gt; &lt;timestamp name="timeStamp" column="TimeStamp" /&gt; &lt;many-to-one name="searchRule" class="com.generic.orm.generated.SearchRule" fetch="select"&gt; &lt;column name="SearchRuleName" length="50" not-null="true" /&gt; &lt;/many-to-one&gt; &lt;many-to-one name="errorCode" class="com.generic.orm.generated.ErrorCode" fetch="select"&gt; &lt;column name="ErrorCodeId" /&gt; &lt;/many-to-one&gt; &lt;many-to-one name="reconciliation" class="com.generic.orm.generated.Reconciliation" fetch="select"&gt; &lt;column name="ReconciliationName" length="100" /&gt; &lt;/many-to-one&gt; &lt;property name="username" type="string"&gt; &lt;column name="Username" length="50" /&gt; &lt;/property&gt; &lt;property name="supersheetDate" type="timestamp"&gt; &lt;column name="SupersheetDate" length="23" not-null="true" /&gt; &lt;/property&gt; &lt;property name="milliSecondsTaken" type="long"&gt; &lt;column name="MilliSecondsTaken" not-null="true" /&gt; &lt;/property&gt; &lt;property name="thresholdMet" type="boolean"&gt; &lt;column name="ThresholdMet" not-null="true" /&gt; &lt;/property&gt; &lt;property name="results" type="int"&gt; &lt;column name="Results" not-null="true" /&gt; &lt;/property&gt; &lt;property name="exception" type="string"&gt; &lt;column name="Exception" length="750" /&gt; &lt;/property&gt; &lt;property name="uuid" type="string"&gt; &lt;column name="UUID" length="36" not-null="true" /&gt; &lt;/property&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; </code></pre>
632,455
6
4
null
2009-03-10 18:39:42.803 UTC
6
2015-01-16 12:41:47.67 UTC
2017-05-23 12:14:46.883 UTC
nemo
-1
nemo
20,774
null
1
11
java|hibernate|spring|web-applications|netbeans
51,397
<p>I am just guessing but from the stack trace it seems that toString is being called on SearchRule. Does SearchRule have any child objects that may not have been loaded? If SearchRule.toString was trying to get the value for an uninitialised child object that could result in the LazyInitializationException.</p>
1,246,749
sql server express connection string
<p>Is there a difference between sql server connection string and the express vesion?!</p>
1,246,763
6
0
null
2009-08-07 20:06:06.703 UTC
3
2012-01-02 07:04:04.103 UTC
2009-08-07 20:09:52.093 UTC
null
23,199
null
108,963
null
1
14
sql-server|asp.net-3.5
47,906
<p>By default (though I don't recommend it<sup>1</sup>), Sql Express is installed as a <a href="http://msdn.microsoft.com/en-us/library/ms165614(SQL.90).aspx" rel="noreferrer">named instance</a>. That means you must connect like <code>Server=servername.com\SQLEXPRESS</code> as opposed to just <code>Server=servername.com</code>.</p> <p>As always, <a href="http://connectionstrings.com/sql-server-2008" rel="noreferrer">connectionstrings.com</a> has the goodies.</p> <p><sup>1</sup> I don't recommend named instances because they <a href="http://support.microsoft.com/kb/265808" rel="noreferrer">run on a different port</a>, which makes firewalling a PITA. Also, it makes little sense to me to run more than 1 MSSQL Server on a computer when you could just host multiple databases instead - so I'm not really sure what the point is.</p>
926,594
Installing a plain plugin jar in Eclipse 3.5
<p>Since Eclipse 3.5 there seems to be no option to have drop a plugin jar ( not a feature ) in the Eclipse base directory and have it picked up at next startup.</p> <p>Is there any possiblity to have plain plugins jars installed in Eclipse 3.5?</p>
926,949
6
0
null
2009-05-29 15:27:27.187 UTC
14
2020-05-20 10:30:14.64 UTC
null
null
null
null
112,671
null
1
57
eclipse
114,867
<p>Since the advent of p2, you should be using the <a href="http://wiki.eclipse.org/Equinox_p2_Getting_Started#Dropins" rel="noreferrer">dropins directory</a> instead.</p> <blockquote> <p>To be completely clear create "plugins" under "/dropins" and make sure to restart eclipse with the "-clean" option.</p> </blockquote>
444,251
How to store a list in a db column
<p>I would like to store an object <strong>FOO</strong> in a database. Lets say FOO contains three integers and a list of "<em>Fruits</em>".</p> <p>The list can have any length, the only thing I know is that the all the fruits allowed are stored in another table.</p> <p>Can I store the fruit list in a column? </p>
444,268
6
0
null
2009-01-14 19:04:50.117 UTC
32
2014-02-19 20:35:11.24 UTC
null
null
null
Stumproot
17,413
null
1
68
sql|database
39,436
<p>In a normalized relational database, such a situation is unacceptable. You should have a junction table that stores one row for each distinct ID of the FOO object and the ID of the Fruit. Existence of such a row means the fruit is in that list for the FOO.</p> <pre><code>CREATE TABLE FOO ( id int primary key not null, int1 int, int2 int, int3 int ) CREATE TABLE Fruits ( id int primary key not null, name varchar(30) ) CREATE TABLE FOOFruits ( FruitID int references Fruits (ID), FooID int references FOO(id), constraint pk_FooFruits primary key (FruitID, FooID) ) </code></pre> <p>To add Apple fruit to the list of a specific FOO object with ID=5, you would:</p> <pre><code>INSERT FOOFruits(FooID, FruitID) SELECT 5, ID FROM Fruits WHERE name = 'Apple' </code></pre>
274,149
Repeat table headers in print mode
<p>Is it possible in CSS using a property inside an @page to say that table headers (th) should be repeated on every page if the table spreads over multiple pages?</p>
274,161
6
0
null
2008-11-08 01:12:35.757 UTC
30
2021-08-20 17:40:28.54 UTC
2016-09-14 17:34:43.457 UTC
Alessandro Vernet
4,370,109
Alessandro Vernet
5,295
null
1
128
css|css-tables
181,596
<p>This is what the <a href="http://htmlhelp.com/reference/html40/tables/thead.html" rel="noreferrer">THEAD</a> element is for. Official docs <a href="http://www.w3.org/TR/html4/struct/tables.html#edef-THEAD" rel="noreferrer">here</a>.</p>
68,982,181
Issue: Audit usage of navigator.userAgent, navigator.appVersion, and navigator.platform
<p>I started a new project in vue.js. I added navbar. At one point, I noticed issue in the console:</p> <pre><code>Audit usage of navigator.userAgent, navigator.appVersion, and navigator.platform </code></pre> <p><a href="https://i.stack.imgur.com/82nIq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/82nIq.png" alt="enter image description here" /></a></p> <p>I don't understand this, because I don't use any navigator in the project.</p> <p>Why am I seeing this issue? How can I change it?</p>
70,084,891
2
3
null
2021-08-30 09:58:34.133 UTC
3
2022-02-09 00:16:29.463 UTC
2021-09-14 08:33:20.183 UTC
null
14,748,677
null
14,748,677
null
1
12
css|vue.js|console|extend
60,667
<p>The reason one sees the message is well explained in the description of the very same message (audit).</p> <p>The real question is who/what is the source of it. There is a hint to the file <code>extended-css.js</code>.</p> <p>Here is an example with another file (as I do not have the <code>extended-css.js</code>): <a href="https://i.stack.imgur.com/YxytF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YxytF.png" alt="enter image description here" /></a></p> <p>Right click on the file and then choose <code>Open in new tab</code>.</p> <p><a href="https://i.stack.imgur.com/vOX6p.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vOX6p.png" alt="enter image description here" /></a></p> <p>So there you can see that the reason for the audit message is the <code>hook.js</code> file from the Vue.js devtools extension.</p> <p>In your case it would be another extension or library you are using - direct or indirect (for example a part of <code>vuetify</code>, etc.).</p> <p>From there you have 3 choices:</p> <ol> <li>ignore it</li> <li>wait for the authors of the library to fix the issue and update it</li> <li>disable the extension/remove the library causing it.</li> </ol>
30,821,356
"Multiple definition", "first defined here" errors
<p>I have 3 projects: <em>Server</em>, <em>Client</em> and <em>Commons</em>. Making header &amp; source pairs in <em>Commons</em> doesn't cause any problems and I can access the functions freely from both <em>Server</em> and <em>Client</em>.</p> <p>However, for some reason making additional source/header files within <em>Server</em> or <em>Client</em> project always causes <code>multiple definition of (...)</code> and <code>first defined here</code> errors.</p> <p>Example:</p> <p><strong>commands.h</strong> (in root dir of the <em>Client</em> project)</p> <pre><code>#ifndef COMMANDS_H_ #define COMMANDS_H_ #include "commands.c" void f123(); #endif /* COMMANDS_H_ */ </code></pre> <p><strong>commands.c</strong> (in root dir of the <em>Client</em> project)</p> <pre><code>void f123(){ } </code></pre> <p><strong>main.c</strong> (in root dir of the <em>Client</em> project)</p> <pre><code>#include "commands.h" int main(int argc, char** argv){ } </code></pre> <p>Errors:</p> <pre><code>make: *** [Client] Error 1 Client first defined here Client multiple definition of `f123' commands.c </code></pre> <p>Cleaning, rebuilding index, rebuilding projects doesn't help. Neither does restarting the computer.</p>
30,821,844
5
2
null
2015-06-13 17:10:45.867 UTC
7
2020-06-08 18:32:19.667 UTC
null
null
null
null
2,903,567
null
1
47
c|eclipse|include|definition|multiple-definition-error
189,627
<p>The problem here is that you are including <code>commands.c</code> in <code>commands.h</code> before the function prototype. Therefore, the C pre-processor inserts the content of <code>commands.c</code> into <code>commands.h</code> before the function prototype. <code>commands.c</code> contains the function definition. As a result, the function definition ends up before than the function declaration causing the error.</p> <p>The content of <code>commands.h</code> after the pre-processor phase looks like this:</p> <pre><code>#ifndef COMMANDS_H_ #define COMMANDS_H_ // function definition void f123(){ } // function declaration void f123(); #endif /* COMMANDS_H_ */ </code></pre> <p>This is an error because you can't declare a function after its definition in C. If you swapped <code>#include "commands.c"</code> and the function declaration the error shouldn't happen because, now, the function prototype comes before the function declaration. </p> <p>However, including a <code>.c</code> file is a <strong>bad practice</strong> and should be avoided. A better solution for this problem would be to include <code>commands.h</code> in <code>commands.c</code> and link the compiled version of command to the main file. For example:</p> <p><strong>commands.h</strong></p> <pre><code>#ifndef COMMANDS_H_ #define COMMANDS_H_ void f123(); // function declaration #endif </code></pre> <p><strong>commands.c</strong></p> <pre><code>#include "commands.h" void f123(){} // function definition </code></pre>
31,189,123
docker-machine behind corporate proxy
<p>I am trying to use docker-machine to create an instance on a private cloud (Openstack) that is behind a corporate http proxy. </p> <p>Is it possible to tell docker-machine to use the proxy or do I need to have a glance image that is already pre-configure with the http_proxy env variable?</p>
39,734,908
5
2
null
2015-07-02 15:47:35.053 UTC
20
2019-07-24 20:42:12.3 UTC
2019-06-11 17:02:51.293 UTC
null
474,034
null
3,612,251
null
1
32
docker|docker-machine
26,066
<p>As previously mentioned, you can edit the file at</p> <pre><code>$HOME\.docker\machine\machines\default\config.json </code></pre> <p>and set the HTTP_PROXY, HTTPS_PROXY and NO_PROXY variables (or delete them):</p> <pre><code> "HostOptions": { "Driver": "", ... "EngineOptions": { ... "Env": [ "HTTP_PROXY=http://10.121.8.110:8080", "HTTPS_PROXY=http://10.121.8.110:8080", "NO_PROXY=192.168.23.4" ], </code></pre> <p>After the file has edited, you only have to execute:</p> <pre><code>docker-machine provision </code></pre>
13,491,852
set column width using jQuery
<p>I have html table with format </p> <pre><code>&lt;div id="divOutputWindow"&gt; &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;/* Set Width 10 Px */ &lt;/td&gt; &lt;td&gt;/* Set Width 20 Px */ &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; /* Same for all tr */ &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; </code></pre> <p>i.e. first td has width 10 px next td 15 px next td 20 px...likewise</p> <p>What i Tried is</p> <pre><code>$('#divOutputWindow').find('table').$('tbody &gt; tr &gt; td').css('width', '10px'); </code></pre>
13,493,279
7
0
null
2012-11-21 11:03:16.417 UTC
null
2012-11-21 12:41:59.19 UTC
null
null
null
null
1,169,180
null
1
4
jquery
49,035
<ul> <li>Loop trough each <code>&lt;td&gt;</code> inner your <code>#divOutputWindow</code>.</li> <li>Use <code>.each();</code> for that, in the loop you can acces the current DOM-object by <code>$(this)</code>.</li> <li>Define a minimum and a stepsize, use <code>$(this).index();</code> for counting.</li> <li>Then use the <code>.css('attr','value');</code> command to manipulate your current <code>&lt;td&gt;</code>. It's a setter of the css attribute. Don't forget to put <code>"px"</code> at the end.</li> </ul> <p>The Code:</p> <pre><code>$('#divOutputWindow td').each(function() { var min = 10; // Define a minimum var step = 5 * $(this).index(); // Define Step(your step is 5 here) $(this).css('width', (min + step) + "px"); // css attribute of your &lt;td&gt; width:15px; i.e. }); </code></pre> <p>Did it work? </p> <p><em><strong>Edit: i saw that @billyonecan already posted something similar, test both examples, mine works (i tested it)</em></strong></p>
37,771,434
mac - pip install pymssql error
<p>I use Mac (OS X 10.11.5). I want to install module <code>pymssql</code> for python. In <code>Terminal.app</code>, I input <code>sudo -H pip install pymssql</code>, <code>pip install pymssql</code>, <code>sudo pip install pymssql</code> . But error occur.</p> <blockquote> <p>The directory <code>/Users/janghyunsoo/Library/Caches/pip/http</code> or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing <code>pip</code> with <code>sudo</code>, you may want <code>sudo</code>'s <code>-H</code> flag.</p> <p>The directory <code>/Users/janghyunsoo/Library/Caches/pip</code> or its parent directory is not owned by the current user and caching wheels has been disabled. Check the permissions and owner of that directory. If executing <code>pip</code> with <code>sudo</code>, you may want <code>sudo</code>'s <code>-H</code> flag.</p> </blockquote> <pre><code>Collecting pymssql Downloading pymssql-2.1.2.tar.gz (898kB) 100% |████████████████████████████████| 901kB 955kB/s Installing collected packages: pymssql Running setup.py install for pymssql ... error Complete output from command /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python -u -c &quot;import setuptools, tokenize;__file__='/private/tmp/pip-build-KA5ksi/pymssql/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))&quot; install --record /tmp/pip-A3wRBy-record/install-record.txt --single-version-externally-managed --compile: setup.py: platform.system() =&gt; 'Darwin' setup.py: platform.architecture() =&gt; ('64bit', '') setup.py: platform.libc_ver() =&gt; ('', '') setup.py: Detected Darwin/Mac OS X. You can install FreeTDS with Homebrew or MacPorts, or by downloading and compiling it yourself. Homebrew (http://brew.sh/) -------------------------- brew install freetds MacPorts (http://www.macports.org/) ----------------------------------- sudo port install freetds setup.py: Not using bundled FreeTDS setup.py: include_dirs = ['/usr/local/include', '/opt/local/include', '/opt/local/include/freetds'] setup.py: library_dirs = ['/usr/local/lib', '/opt/local/lib'] running install running build running build_ext building '_mssql' extension creating build creating build/temp.macosx-10.6-intel-2.7 /usr/bin/clang -fno-strict-aliasing -fno-common -dynamic -arch i386 -arch x86_64 -g -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/usr/local/include -I/opt/local/include -I/opt/local/include/freetds -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _mssql.c -o build/temp.macosx-10.6-intel-2.7/_mssql.o -DMSDBLIB _mssql.c:18924:15: error: use of undeclared identifier 'DBVERSION_80' __pyx_r = DBVERSION_80; ^ 1 error generated. error: command '/usr/bin/clang' failed with exit status 1 ---------------------------------------- Command &quot;/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python -u -c &quot;import setuptools, tokenize;__file__='/private/tmp/pip-build-KA5ksi/pymssql/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))&quot; install --record /tmp/pip-A3wRBy-record/install-record.txt --single-version-externally-managed --compile&quot; failed with error code 1 in /private/tmp/pip-build-KA5ksi/pymssql/ </code></pre>
38,002,724
7
2
null
2016-06-12 06:38:34.283 UTC
11
2022-09-15 18:39:42.073 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
6,455,358
null
1
33
python|macos|python-2.7|pymssql
24,560
<p>I was able to work around this by reverting to an older version of FreeTDS through Homebrew before running the pip install.</p> <pre><code>brew unlink freetds; brew install homebrew/versions/freetds091 </code></pre> <p>The solution was found by andrewmwhite at: <a href="https://github.com/pymssql/pymssql/issues/432" rel="noreferrer">https://github.com/pymssql/pymssql/issues/432</a></p>
21,260,602
How to reject a promise from inside then function
<p>This is probably a silly question, but mid promise chain, how do you reject a promise from inside one of the then functions? For example:</p> <pre><code>someActionThatReturnsAPromise() .then(function(resource) { return modifyResource(resource) }) .then(function(modifiedResource) { if (!isValid(modifiedResource)) { var validationError = getValidationError(modifiedResource); // fail promise with validationError } }) .catch(function() { // oh noes }); </code></pre> <p>There's no longer a reference to the original resolve/reject function or the PromiseResolver. Am I just supposed to add <code>return Promise.reject(validationError);</code> ?</p>
21,262,065
1
3
null
2014-01-21 14:16:02.897 UTC
13
2014-01-21 15:17:32.48 UTC
null
null
null
null
656,677
null
1
97
javascript|promise
54,527
<blockquote> <p>Am I just supposed to add <code>return Promise.reject(validationError);</code>?</p> </blockquote> <p>Yes. However, <a href="https://stackoverflow.com/questions/10843297/throwing-an-error-in-jquerys-deferred-object">it's that complicated</a> only in jQuery, with a <a href="http://promisesaplus.com/">Promise/A+</a>-compliant library you also could simply</p> <pre><code>throw validationError; </code></pre> <p>So your code would then look like</p> <pre><code>someActionThatReturnsAPromise() .then(modifyResource) .then(function(modifiedResource) { if (!isValid(modifiedResource)) throw getValidationError(modifiedResource); // else ! return modifiedResource; }) .catch(function() { // oh noes }); </code></pre>
17,729,853
Replace value for a selected cell in pandas DataFrame without using index
<p>this is a rather similar question to <a href="https://stackoverflow.com/questions/13842088/set-value-for-particular-cell-in-pandas-dataframe" title="Set value for particular cell in pandas DataFrame">this question</a> but with one key difference: I'm selecting the data I want to change not by its index but by some criteria.</p> <p>If the criteria I apply return a single row, I'd expect to be able to set the value of a certain column in that row in an easy way, but my first attempt doesn't work:</p> <pre><code>&gt;&gt;&gt; d = pd.DataFrame({'year':[2008,2008,2008,2008,2009,2009,2009,2009], ... 'flavour':['strawberry','strawberry','banana','banana', ... 'strawberry','strawberry','banana','banana'], ... 'day':['sat','sun','sat','sun','sat','sun','sat','sun'], ... 'sales':[10,12,22,23,11,13,23,24]}) &gt;&gt;&gt; d day flavour sales year 0 sat strawberry 10 2008 1 sun strawberry 12 2008 2 sat banana 22 2008 3 sun banana 23 2008 4 sat strawberry 11 2009 5 sun strawberry 13 2009 6 sat banana 23 2009 7 sun banana 24 2009 &gt;&gt;&gt; d[d.sales==24] day flavour sales year 7 sun banana 24 2009 &gt;&gt;&gt; d[d.sales==24].sales = 100 &gt;&gt;&gt; d day flavour sales year 0 sat strawberry 10 2008 1 sun strawberry 12 2008 2 sat banana 22 2008 3 sun banana 23 2008 4 sat strawberry 11 2009 5 sun strawberry 13 2009 6 sat banana 23 2009 7 sun banana 24 2009 </code></pre> <p>So rather than setting 2009 Sunday's Banana sales to 100, nothing happens! What's the nicest way to do this? Ideally the solution should use the row number, as you normally don't know that in advance!</p>
17,729,985
3
0
null
2013-07-18 17:08:17.71 UTC
33
2021-10-23 06:42:08.417 UTC
2019-06-11 21:41:35.477 UTC
null
2,662,901
null
2,071,807
null
1
58
python|pandas|dataframe
110,804
<p>Many ways to do that </p> <h3>1</h3> <pre><code>In [7]: d.sales[d.sales==24] = 100 In [8]: d Out[8]: day flavour sales year 0 sat strawberry 10 2008 1 sun strawberry 12 2008 2 sat banana 22 2008 3 sun banana 23 2008 4 sat strawberry 11 2009 5 sun strawberry 13 2009 6 sat banana 23 2009 7 sun banana 100 2009 </code></pre> <h3>2</h3> <pre><code>In [26]: d.loc[d.sales == 12, 'sales'] = 99 In [27]: d Out[27]: day flavour sales year 0 sat strawberry 10 2008 1 sun strawberry 99 2008 2 sat banana 22 2008 3 sun banana 23 2008 4 sat strawberry 11 2009 5 sun strawberry 13 2009 6 sat banana 23 2009 7 sun banana 100 2009 </code></pre> <h3>3</h3> <pre><code>In [28]: d.sales = d.sales.replace(23, 24) In [29]: d Out[29]: day flavour sales year 0 sat strawberry 10 2008 1 sun strawberry 99 2008 2 sat banana 22 2008 3 sun banana 24 2008 4 sat strawberry 11 2009 5 sun strawberry 13 2009 6 sat banana 24 2009 7 sun banana 100 2009 </code></pre>
17,748,993
Jenkins: build one job after another with some delay
<p>I have 2 jobs in Jenkins: QA and Dev. In Dev job I checked "Build after other projects are built" option and set project name = QA so that QA job will be built after Dev job is built. But in my particular situation I need that QA job started building in 5 mins after Dev job is built. How can I do it? maybe I can add some build step with some data to add this delay ?</p> <p>TIA, Anna</p>
17,750,344
4
2
null
2013-07-19 14:43:54.933 UTC
6
2019-11-25 07:16:08.373 UTC
2013-07-19 15:03:52.303 UTC
null
2,205,225
null
2,205,225
null
1
31
jenkins
46,857
<p>There is a <a href="http://jenkins-ci.org/content/quiet-period-feature">"Quiet Period"</a> option in the Advanced Project Options available. You can enter a value of 300 (its in seconds) to delay the start of the job by 5 mins.</p>
23,445,936
Numpy random choice of tuples
<p>I'm having trouble to create an array of random choices, where a choice is a tuple. </p> <p>I get the error: <code>a must be 1-dimensional</code></p> <p>Here is an example:</p> <pre><code>choices = ((0,0,0),(255,255,255)) numpy.random.choice(choices,4) </code></pre> <p>Is there any other way to do this?</p> <p>Expected result:</p> <p>a numpy array consiting of 4 elements randomly picked from the choices tuple.</p> <pre><code>((0,0,0),(0,0,0),(255,255,255),(255,255,255)) </code></pre>
23,446,047
3
2
null
2014-05-03 14:49:54.56 UTC
1
2019-03-05 13:13:20.477 UTC
2014-05-03 15:07:56.197 UTC
null
2,096,752
null
673,760
null
1
34
python|numpy|random
18,862
<p>Use <code>choice</code> to choose the 1dim <em>indices</em> into the array, then index it.</p> <p>In the example you provided, only the <strong>number</strong> of possible choices affects the nature of the choice, not the actual values (0, 255). Choosing indices is the 1dim problem <code>choice</code> knows how to handle.</p> <pre><code>choices = numpy.array([[0,0,0],[255,255,255]]) idx = numpy.random.choice(len(choices),4) choices[idx] </code></pre>
23,279,208
Calculate d from n, e, p, q in RSA?
<p>Not sure if this is the correct place to ask a cryptography question, but here goes.</p> <p>I am trying to work out "d" in RSA, I have worked out p, q, e, n and ø(n);</p> <pre><code>p = 79, q = 113, e = 2621 n = pq ø(n) = (p-1)(q-1) n = 79 x 113 = 8927 ø(n) = 78 x 112 = 8736 e = 2621 d = ??? </code></pre> <p>I cant seem to find d, I know that d is meant to be a value that.. ed mod ø(n) = 1. Any help will be appreciated</p> <p>As an example would be e = 17, d = 2753, ø(n) = 3120</p> <pre><code>17 * 2753 mod 3120 = 1 </code></pre>
23,281,286
3
3
null
2014-04-24 20:33:27.197 UTC
2
2022-06-08 21:34:37.33 UTC
2019-09-24 00:28:56.34 UTC
null
608,639
null
3,423,572
null
1
16
encryption|cryptography|rsa|public-key-encryption
40,746
<p>You are looking for the modular inverse of <em>e</em> (mod <em>n</em>), which can be computed using the extended Euclidean algorithm:</p> <pre><code>function inverse(x, m) a, b, u := 0, m, 1 while x &gt; 0 q := b // x # integer division x, a, b, u := b % x, u, x, a - q * u if b == 1 return a % m error "must be coprime" </code></pre> <p>Thus, in your examples, <code>inverse(17, 3120)</code> = 2753 and <code>inverse(2621, 8736)</code> = 4373. If you don't want to implement the algorithm, you can ask <a href="http://www.wolframalpha.com/input/?i=inverse+of+17+modulo+3120">Wolfram|Alpha</a> for the answer.</p>
1,400,198
Is there a way to restrict access to an ASMX Webservice, i.e. the asmx page and its WSDL?
<p>I have a C# .net webservice that I need to restrict access to. I already require my consumers to use a username and password to call the service. But, is there a way to restrict access to the actual asmx page and the WSDL? I would need to restrict access to the webservice by username/password and IP address. If a user did not have the correct credentials, I would not want them to know what webmethods exist in the webservice.</p> <p>Can this be done though IIS? I know that I can restrict IP addresses through IIS, but can I also use usernames/passwords?</p> <p>Is there any other way to do this outside of IIS, maybe using C#.net?</p>
1,621,108
6
0
null
2009-09-09 14:48:07.477 UTC
16
2016-07-07 14:40:06.743 UTC
2009-10-21 20:34:58.71 UTC
null
76,337
null
47,191
null
1
16
web-services|security|iis|asmx
25,170
<p>Well, since it's ASMX you have the entire ASP.NET runtime stack at your disposal.</p> <h2>Step #1 - managing the resource through .config</h2> <p>Apply a <code>&lt;location&gt;</code> tag for the resources you want secured. Assuming it's a single ASMX file you can simply do the following in your web.config:</p> <pre><code>&lt;location path="MyWebService.asmx"&gt; &lt;system.web&gt; &lt;!-- resource specific options will go here --&gt; &lt;/system.web&gt; &lt;/location&gt; </code></pre> <h2>Step #2 - authenticating your users</h2> <p>You need to decide how you're actually going to authenticate users. There are several ways to do this and several authentication standards you could leverage. You need to pick the approach that's the right fit for you.</p> <p>If you're on an intranet and are using Windows authentication I would highly suggest leveraging that because it's truly the simplest option to get setup. However, if your services are being accessed over the internet then Windows authenticatio is not really an option and you need to choose from a web standard. The simplest of those is <a href="http://en.wikipedia.org/wiki/Basic_access_authentication" rel="noreferrer">Basic Authentication</a>, but you should <em>only</em> use this over SSL since the username/password are not encrypted (only base64 encoded). The next step up from that is <a href="http://en.wikipedia.org/wiki/Digest_access_authentication" rel="noreferrer">Digest authentication</a> which doesn't require SSL because the username/password are sent using an MD5 hash. For the ultimate you can go with <a href="http://en.wikipedia.org/wiki/SSL3" rel="noreferrer">SSL v3</a> where you issue a specific client certificate to each user of your API.</p> <p>Now, which option you select for security dictates what else needs to be done. If you choose Windows security, it's as easy as adding the following element to the <code>&lt;system.web&gt;</code> element we started with in Step #1:</p> <pre><code>&lt;authentication mode="Windows" /&gt; </code></pre> <p>The remainder of the security protocols are going to require a little more work. ASP.NET doesn't provide intrinsic support for Basic, Digest or SSL v3. Technically you can leverage IIS to do this type of authentication for you, but it's always going to map to a Windows user. If that's an option for you, then simply leave the <code>&lt;authentication mode="Windows" /&gt;</code> element and configure IIS accordingly. If, however, that is not an option, either because you simply have no control over IIS/ActiveDirectory or you need to authenticate against a custom user database, then that means that you need to hook up a custom HttpModule to provide support for these security protocols.</p> <h2>Step #3 - securing the resource</h2> <p>The simplest approach to securing the resource is to basically say: "don't let anyone who hasn't successfully authenticated in some way into this resource". This is done using the following authorization configuration:</p> <pre><code>&lt;authorization&gt; &lt;deny users="?" /&gt; &lt;/authorization&gt; </code></pre> <p>If you wanted to only allow <em>certain</em> users you could change to do the following instead:</p> <pre><code>&lt;authorization&gt; &lt;deny users="*" /&gt; &lt;allow users="jdoe, msmith" /&gt; &lt;/authorization&gt; </code></pre> <p>Another approach is to define roles (groups) and simply lock the resource down to a special role which you put the users who you want to access the resource into. </p> <pre><code>&lt;authorization&gt; &lt;deny users="*" /&gt; &lt;allow roles="My Service Users" /&gt; &lt;/authorization&gt; </code></pre> <p>This maps well to Windows authentication because you can just setup a Windows group and let your MIS team manage which users are in that group using ActiveDirectory. However, the feature also works just fine for non-Windows authentication assuming the security implementation you've used exposes roles via its IPrincipal implementation.</p>
2,102,251
trapping a MySql warning
<p>In my python script I would like to trap a "Data truncated for column 'xxx'" warning durnig my query using MySql.</p> <p>I saw some posts suggesting the code below, but it doesn' work.</p> <p>Do you know if some specific module must be imported or if some option/flag should be called before using this code?</p> <p>Thanks all</p> <p>Afeg</p> <pre><code>import MySQLdb try: cursor.execute(some_statement) # code steps always here: No Warning is trapped # by the code below except MySQLdb.Warning, e: # handle warnings, if the cursor you're using raises them except Warning, e: # handle warnings, if the cursor you're using raises them </code></pre>
2,102,315
7
0
null
2010-01-20 14:59:39.597 UTC
16
2016-03-28 21:24:04.397 UTC
null
null
null
null
245,416
null
1
37
python|mysql
23,765
<p>Warnings are just that: warnings. They get reported to (usually) stderr, but nothing else is done. You can't catch them like exceptions because they aren't being raised.</p> <p>You can, however, configure what to <em>do</em> with warnings, and turn them off or turn them into exceptions, using the <code>warnings</code> module. For instance, <code>warnings.filterwarnings('error', category=MySQLdb.Warning)</code> to turn <code>MySQLdb.Warning warnings</code> into exceptions (in which case they would be caught using your try/except) or <code>'ignore'</code> to not show them at all. You can (and probably should) have more fine-grained filters than just the category.</p>
1,578,169
How can I read XMP data from a JPG with PHP?
<p>PHP has built in support for reading EXIF and IPTC metadata, but I can't find any way to read XMP?</p>
1,578,326
9
0
null
2009-10-16 13:50:40.66 UTC
16
2021-08-23 10:37:33.54 UTC
2009-10-16 14:04:49.023 UTC
null
18,333
null
18,333
null
1
15
php|metadata|jpeg|xmp
28,029
<p>XMP data is literally embedded into the image file so can extract it with PHP's string-functions from the image file itself.</p> <p>The following demonstrates this procedure (I'm using <a href="http://php.net/manual/book.simplexml.php" rel="noreferrer">SimpleXML</a> but every other XML API or even simple and clever string parsing may give you equal results):</p> <pre><code>$content = file_get_contents($image); $xmp_data_start = strpos($content, '&lt;x:xmpmeta'); $xmp_data_end = strpos($content, '&lt;/x:xmpmeta&gt;'); $xmp_length = $xmp_data_end - $xmp_data_start; $xmp_data = substr($content, $xmp_data_start, $xmp_length + 12); $xmp = simplexml_load_string($xmp_data); </code></pre> <p>Just two remarks:</p> <ul> <li>XMP makes heavy use of XML namespaces, so you'll have to keep an eye on that when parsing the XMP data with some XML tools.</li> <li>considering the possible size of image files, you'll perhaps not be able to use <a href="http://php.net/manual/function.file-get-contents.php" rel="noreferrer"><code>file_get_contents()</code></a> as this function loads the whole image into memory. Using <a href="http://php.net/manual/function.fopen.php" rel="noreferrer"><code>fopen()</code></a> to open a file stream resource and checking chunks of data for the key-sequences <code>&lt;x:xmpmeta</code> and <code>&lt;/x:xmpmeta&gt;</code> will significantly reduce the memory footprint.</li> </ul>
1,503,100
Get latitude/longitude from address
<p>How can I get latitude and longitude from a full address (street, city, etc.) input by the user, using the iPhone SDK 3.x?</p>
3,005,652
9
0
null
2009-10-01 10:19:30.01 UTC
23
2019-06-04 16:06:07.22 UTC
2011-10-22 21:24:14.033 UTC
null
603,977
null
182,416
null
1
17
ios|maps|geocoding
35,555
<p>Here's an updated, more compact, version of unforgiven's code, which uses the latest v3 API:</p> <pre><code>- (CLLocationCoordinate2D) geoCodeUsingAddress:(NSString *)address { double latitude = 0, longitude = 0; NSString *esc_addr = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSString *req = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?sensor=false&amp;address=%@", esc_addr]; NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL]; if (result) { NSScanner *scanner = [NSScanner scannerWithString:result]; if ([scanner scanUpToString:@"\"lat\" :" intoString:nil] &amp;&amp; [scanner scanString:@"\"lat\" :" intoString:nil]) { [scanner scanDouble:&amp;latitude]; if ([scanner scanUpToString:@"\"lng\" :" intoString:nil] &amp;&amp; [scanner scanString:@"\"lng\" :" intoString:nil]) { [scanner scanDouble:&amp;longitude]; } } } CLLocationCoordinate2D center; center.latitude = latitude; center.longitude = longitude; return center; } </code></pre> <p>It makes the assumption that the coordinates for "location" come first, e.g. before those for "viewport", because it just takes the first coords it finds under the "lng" and "lat" keys. Feel free to use a proper JSON scanner (e.g. SBJSON) if you are worried about this simple scanning technique used here.</p>
1,899,772
Most robust method for showing Icon next to text
<p>There are different ways to show graphics in a page next to text. I need to include a graphic/icon that indicates a new tab will be opened.</p> <p>I know it's possible to do using at least these different methods:</p> <ul> <li>Unicode character from default fonts</li> <li>Unicode character from CSS loaded fonts</li> <li>Inline SVG</li> <li>Inline PNG</li> </ul> <p>Please suggest a method to do this, and explain why or why not it's robust on different browsers and operating systems.</p>
1,899,886
17
2
null
2009-12-14 09:00:36.73 UTC
25
2022-01-26 00:12:46.29 UTC
2022-01-26 00:12:46.29 UTC
null
86,375
null
156,446
null
1
106
svg|unicode|png|href
79,758
<p>There's no such a thing as an established standard icon.</p> <p>For example, the icon you chose is similar to the one used in wikipedia to mark links pointing to external websites (not belonging to wikipedia). You may however use it across your websites, and thus establish a convention within your own pages. Just make sure you do so consistently: ALL links marked with that icon MUST open to a new page, and ALL links not marked with it should open in the same page. You may improve accessibility, provided that you have a stable user base, who will have the chance to get used to your conventions. If your site is visited mostly by one-time visitors, then you'd be just adding visual clutter.</p>
33,822,121
React-Native run-android command issue
<p>When starting android project with React-Native it is giving this error:</p> <blockquote> <p>React-Native Command run-android unrecognized.Did you mean to run this inside a react-native project?</p> </blockquote>
35,648,026
11
4
null
2015-11-20 08:31:22.087 UTC
5
2022-04-07 11:50:52.47 UTC
2015-11-20 09:37:29 UTC
null
909,742
null
5,582,285
null
1
11
android|react-native
54,071
<p>You can try to do <code>npm install</code> before <code>react-native run-android</code></p>
46,272,309
Upload multiple images to firebase storage
<p>i build a chat application using firebase and i want to send multiple image to firebase storage.</p> <p>using this library</p> <p>compile 'com.github.darsh2:MultipleImageSelect:3474549'</p> <p>At the top</p> <pre><code>private StorageReference storageRef; private FirebaseApp app; private FirebaseStorage storage; </code></pre> <p>onCreate()Method</p> <pre><code>app = FirebaseApp.getInstance(); storage =FirebaseStorage.getInstance(app); </code></pre> <p>button click action</p> <pre><code> Gallary.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ChatActivity.this, AlbumSelectActivity.class); intent.putExtra(Constants.INTENT_EXTRA_LIMIT, 10); startActivityForResult(intent, Constants.REQUEST_CODE); pwindo1.dismiss(); } }); </code></pre> <p>Activity result</p> <pre><code> if (requestCode == Constants.REQUEST_CODE &amp;&amp; resultCode == RESULT_OK) { ArrayList&lt;Image&gt; images = data.getParcelableArrayListExtra(Constants.INTENT_EXTRA_IMAGES); Uri uri = Uri.parse(String.valueOf(images)); storageRef = storage.getReference("photos"); final StorageReference photoRef = storageRef.child(uri.getLastPathSegment()); photoRef.putFile(uri) .addOnSuccessListener(this, new OnSuccessListener&lt;UploadTask.TaskSnapshot&gt;() { public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { Uri downloadUrl = taskSnapshot.getDownloadUrl(); String content = downloadUrl.toString(); if (content.length() &gt; 0) { editWriteMessage.setText(""); Message newMessage = new Message(); newMessage.text = content; newMessage.idSender = StaticConfig.UID; newMessage.idReceiver = roomId; newMessage.timestamp = System.currentTimeMillis(); FirebaseDatabase.getInstance().getReference().child("message/" + roomId).push().setValue(newMessage); } } }); } </code></pre>
46,292,224
4
4
null
2017-09-18 05:44:44.877 UTC
10
2022-07-21 11:31:51.067 UTC
2019-02-08 04:57:03.677 UTC
null
7,772,630
null
7,772,630
null
1
5
android|firebase|firebase-storage
24,500
<p>It is working fine.</p> <pre><code> if (requestCode == Constants.REQUEST_CODE &amp;&amp; resultCode == RESULT_OK) { ArrayList&lt;Image&gt; images = data.getParcelableArrayListExtra(Constants.INTENT_EXTRA_IMAGES); Uri[] uri=new Uri[images.size()]; for (int i =0 ; i &lt; images.size(); i++) { uri[i] = Uri.parse("file://"+images.get(i).path); storageRef = storage.getReference("photos"); final StorageReference ref = storageRef.child(uri[i].getLastPathSegment()); ref.putFile(uri[i]) .addOnSuccessListener(this, new OnSuccessListener&lt;UploadTask.TaskSnapshot&gt;() { public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { Uri downloadUrl = taskSnapshot.getDownloadUrl(); String content = downloadUrl.toString(); if (content.length() &gt; 0) { editWriteMessage.setText(""); Message newMessage = new Message(); newMessage.text = content; newMessage.idSender = StaticConfig.UID; newMessage.idReceiver = roomId; newMessage.timestamp = System.currentTimeMillis(); FirebaseDatabase.getInstance().getReference().child("message/" + roomId).push().setValue(newMessage); } } }); } } </code></pre>
18,021,082
Could not connect to the database Network error IOException: Connection refused: connect
<p>I am running a SQL Server Express 10.50.4000.0 on my machine. I have enabled on the TCP/IP and made sure the port is set to 1433. I have added an exception in my firewall for 1433. The server service is running. I have tried localhost and the computer name and both give the same error. When i try localhost\SQLEXPRESS or [USER-PC]\SQLEXPRESS I received an error saying it could not find the database. </p> <pre><code>String driverName = "net.sourceforge.jtds.jdbc.Driver"; Class.forName(driverName); String serverName = "localhost"; String instanceName = "ALLEN-PC\\SQLEXPRESS"; String serverPort = "1433"; String database = serverName +":" + serverPort+"/"+instanceName; String url = "jdbc:jtds:sqlserver://" + database; String username = "sa"; String password = "password"; connection = DriverManager.getConnection(url, username, password); </code></pre> <p>I receive the error:</p> <pre><code>Could not connect to the database Network error IOException: Connection refused: connect </code></pre> <p>with no additional context to investigate. </p>
18,025,689
5
6
null
2013-08-02 15:44:20.697 UTC
1
2021-12-16 12:44:37.71 UTC
2013-08-02 16:47:18.763 UTC
null
2,646,440
null
2,646,440
null
1
7
java|sql-server
67,700
<p>Your connection string needs to be in this format. Found here: <a href="http://msdn.microsoft.com/en-us/library/ms378428(v=sql.110).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms378428(v=sql.110).aspx</a></p> <pre><code>jdbc:jtds:sqlserver://&lt;yourDBServerIPAddress&gt;\SQLEXPRESS:1433;databaseName=AdventureWorks;user=sa;password=*****; </code></pre>
17,785,592
Difference between JSON.stringify and JSON.parse
<p>I have been confused over when to use these two parsing methods.</p> <p>After I echo my json_encoded data and retrieve it back via ajax, I often run into confusion about when I should use <strong>JSON.stringify</strong> and <strong>JSON.parse</strong>.</p> <p>I get <code>[object,object]</code> in my <em>console.log</em> when parsed and a JavaScript object when stringified.</p> <pre><code>$.ajax({ url: "demo_test.txt", success: function(data) { console.log(JSON.stringify(data)) /* OR */ console.log(JSON.parse(data)) //this is what I am unsure about? } }); </code></pre>
17,785,623
18
1
null
2013-07-22 10:47:48.023 UTC
200
2022-06-09 04:57:03.563 UTC
2016-01-04 21:02:27.967 UTC
null
403,404
null
2,463,734
null
1
482
javascript|json
507,219
<p><code>JSON.stringify</code> turns a JavaScript object into JSON text and stores that JSON text in a string, eg:</p> <pre><code>var my_object = { key_1: "some text", key_2: true, key_3: 5 }; var object_as_string = JSON.stringify(my_object); // "{"key_1":"some text","key_2":true,"key_3":5}" typeof(object_as_string); // "string" </code></pre> <p><code>JSON.parse</code> turns a string of JSON text into a JavaScript object, eg:</p> <pre><code>var object_as_string_as_object = JSON.parse(object_as_string); // {key_1: "some text", key_2: true, key_3: 5} typeof(object_as_string_as_object); // "object" </code></pre>
17,975,120
Access Denied for User 'root'@'localhost' (using password: YES) - No Privileges?
<p>I am continuously receiving this error.</p> <p>I am using mySQL Workbench and from what I am finding is that root's schema privileges are null. There are no privileges at all.</p> <p>I am having troubles across platforms that my server is used for and this has been all of a sudden issue.</p> <p><strong>root@127.0.0.1</strong> apparently has a lot of access but I am logged in as that, but it just assigns to localhost anyways - localhost has no privileges. </p> <p>I have done a few things like <code>FLUSH HOSTS</code>, <code>FLUSH PRIVILEGES</code>, etc but have found no success from that or the internet.</p> <p>How can I get root its access back? I find this frustrating because when I look around people expect you to "have access" but I don't have access so I can't go into command line or anything and <code>GRANT</code> myself anything.</p> <p>When running <code>SHOW GRANTS FOR root</code> this is what I get in return:</p> <blockquote> <p>Error Code: 1141. There is no such grant defined for user 'root' on host '%'</p> </blockquote>
17,976,151
26
8
null
2013-07-31 15:54:05.287 UTC
64
2022-07-20 06:04:16.06 UTC
2019-07-23 09:40:57.04 UTC
null
306,028
null
2,585,340
null
1
194
mysql|root|mysql-workbench|workbench
1,181,434
<p>Use <a href="http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html" rel="noreferrer">the instructions for resetting the root password</a> - but instead of resetting the root password, we'll going to forcefully INSERT a record into the mysql.user table </p> <p>In the init file, use this instead</p> <pre><code>INSERT INTO mysql.user (Host, User, Password) VALUES ('%', 'root', password('YOURPASSWORD')); GRANT ALL ON *.* TO 'root'@'%' WITH GRANT OPTION; </code></pre>
6,584,100
How do I get a TextBox to fill a resizable column?
<p>I'm trying to get a TextBox to fill the available space in a resizable column. The TextBox is part of a user control:</p> <pre><code>&lt;UserControl x:Class="TextBoxLayout.FieldControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="Auto"/&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Label Grid.Column="0"&gt;Name&lt;/Label&gt; &lt;TextBox Grid.Column="1"/&gt; &lt;/Grid&gt; &lt;/UserControl&gt; </code></pre> <p>This user control is in a window with a vertical splitter:</p> <pre><code>&lt;Window x:Class="TextBoxLayout.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TextBoxLayout" Title="Text box layout" Height="400" Width="600"&gt; &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition MinWidth="100"/&gt; &lt;ColumnDefinition Width="Auto"/&gt; &lt;ColumnDefinition MinWidth="100"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="Auto"/&gt; &lt;RowDefinition/&gt; &lt;/Grid.RowDefinitions&gt; &lt;local:FieldControl Grid.Column="0" Grid.Row="0" MaxWidth="200" HorizontalAlignment="Left"/&gt; &lt;TextBlock Grid.Column="0" Grid.Row="1" Text="Testing"/&gt; &lt;GridSplitter Grid.Column="1" Grid.Row="0" Grid.RowSpan="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="3"/&gt; &lt;TextBlock Grid.Column="2" Grid.Row="0" Grid.RowSpan="2" Text="Testing"/&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>The problem is the TexTBox appears to be very narrow - what I'd want it to do is fill the left column and resize with the splitter. How do I do that?</p>
6,584,370
3
1
null
2011-07-05 14:13:35.743 UTC
5
2018-11-26 11:22:36.54 UTC
null
null
null
null
181,622
null
1
22
wpf|textbox|stretch|splitter
48,921
<p>Use HorizontalAlignment="Stretch" instead of "Left" for FieldControl. Remove MaxWidth if required. Use TextAlignment to align text.</p>
35,895,730
Spring boot devtools - Static content reloading does not work in IntelliJ
<p>When building my first Spring Boot app, I discovered that I need to restart my app every time I make a change to a Javascript file in /resources/static/some-file.js</p> <p>This is very time consuming.</p> <p>When I move the files to the /webapps/ folder, it works as expected, but the files are not packaged in a JAR. The docs mention this, so I cannot continue this way.</p> <p>I read all about <code>spring-boot-devtools</code>, and have installed it in my POM, but the hotswapping doesn't seam to be working. I still need to restart the entire app to see a Javascript or CSS file change.</p> <p>When the app starts, I can see the line <code>LiveReload server is running on port 35729</code>, so <code>spring-boot-devtools</code> must be doing something...</p> <p>What would be the steps to further investigate what is going wrong?</p> <p>My guess is that when IntelliJ runs the app, the files are copied, so when I make a change, I'm actually changing the original files and not the ones used by the running app.</p> <p>PS: I'm using Maven, IntelliJ IDEA 15 and Spring Boot 1.3.3 with the embedded Tomcat server. I'm not sure what command IntelliJ runs to start the app. The IDE is handling this "automatically". Perhaps I need to change my run configuration?</p>
35,895,848
7
5
null
2016-03-09 15:25:41.017 UTC
24
2022-01-09 11:07:48.003 UTC
2016-03-09 16:30:43.763 UTC
null
672,859
null
495,815
null
1
30
java|spring|intellij-idea|spring-boot
27,536
<p>You need to turn on a couple of features in IntelliJ to make this work.</p> <p>First, there's a project specific setting which you would need to apply on any project you want to use devtools in. Go to Preferences > Compiler and enable "Make project automatically."</p> <p>The next setting is an IDEA registry setting that applies to all projects. </p> <ul> <li>In macOS (OSX), press <code>Shift+Command+A</code> (<code>Shift+Ctrl+A</code> in Windows) </li> <li>Type "Registry" in the search box that appears, and select the registry to open it.</li> <li>Lookup <strong>compiler.automake.allow.when.app.running</strong> and enable it.</li> </ul> <p>After that, restart your app. You will notice that the project keeps rebuilding with every change you make. When you check out the result in the browser, you will see both static files and code have been updated.</p>
23,693,562
How to copy all of the files from one directory to another in a bash script
<p>I want to copy all of the files from a subdirectory into another directory without copying the original folder. In a terminal I would just do this:</p> <pre><code>cp -r dir1/* dir2 </code></pre> <p>and then dir2 will contain all of the files from dir1 without containing dir1 itself. I am trying to replicate this in a bash script and I am getting an error. Here is my bash code:</p> <pre><code>cp -r $pck_dir"/*" $TAR_DIR"/pck/" </code></pre> <p>I get this error:</p> <pre><code>cp: cannot stat ‘./mailman/lists/mailman/*’: No such file or directory </code></pre> <p>This is strange because I can verify that the directory in question exists. I believe bash is complaining about the '*' but I am not sure why. Can someone enlighten me as to what I am doing wrong?</p>
23,693,721
2
3
null
2014-05-16 06:00:29.75 UTC
null
2014-05-16 17:36:49.847 UTC
null
null
null
null
3,361,761
null
1
13
linux|bash
61,052
<p>Expanding on devnull's comment:</p> <ul> <li><p>Quotes of <em>any kind</em> around a wildcard, like <code>*</code>, will prevent the shell from expanding the wildcard. Thus, you should only write <code>"/*"</code> if you want a slash followed by a literal star.</p></li> <li><p>An unquoted variable will be subject to word splitting. So, if pck_dir had the value <code>my dir</code>, then <code>$pck_dir"/*"</code> would be expanded to two words <code>my</code> and <code>dir/*</code> and both words would be passed to <code>cp</code> as separate arguments. Unless you want word splitting, shell variables should always be in double quotes.</p></li> </ul> <p>Thus, to get what you want, use:</p> <pre><code>cp -r "$pck_dir"/* "$TAR_DIR/pck/" </code></pre>
23,598,748
Error while creating bean: Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError
<p>I am facing the following error when I try to create bean using Application Context for the circle class! Circle class implements the <code>Shape</code> interface which contains a method <code>draw()</code>.</p> <p><strong>Configuration:</strong></p> <p>I am learning spring and have setup a Java Project in eclipse with all the required jars (Spring and Apache commons logging). I have the spring.xml in my classpath in the src folder. Have also tried downloading the latest jars (Spring 4.0.4 release, previously worked with 4.0.0) but now is not working. Cannot think of any solution to fix this.</p> <p>Error:</p> <pre><code>May 11, 2014 6:20:50 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@90832e: startup date [Sun May 11 18:20:50 EDT 2014]; root of context hierarchy May 11, 2014 6:20:50 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [spring.xml] Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor': Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1076) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1021) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:88) at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:609) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464) at org.springframework.context.support.ClassPathXmlApplicationContext.&lt;init&gt;(ClassPathXmlApplicationContext.java:139) at org.springframework.context.support.ClassPathXmlApplicationContext.&lt;init&gt;(ClassPathXmlApplicationContext.java:83) at com.springApplication.DrawingApplication.main(DrawingApplication.java:16) Caused by: java.lang.ExceptionInInitializerError at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1071) ... 13 more Caused by: java.lang.NullPointerException at org.springframework.beans.PropertyEditorRegistrySupport.&lt;clinit&gt;(PropertyEditorRegistrySupport.java:92) ... 14 more </code></pre> <p>DrawingApplication.java</p> <pre><code>package com.springApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class DrawingApplication { public static void main(String[] args) { //The beanFactory reads from an XML file //BeanFactory context = new XmlBeanFactory(new FileSystemResource("spring.xml")); //Application Context provides -- Event notification and more than Bean Factory ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); //Here we pass the id of the bean from the XML given in the above line Shape shape = (Shape)context.getBean("circle"); //Calling the draw method through object local object created using Spring shape.draw(); } } </code></pre> <p>Circle.java</p> <pre><code>package com.springApplication; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; public class Circle implements Shape{ private Point center; public Point getCenter() { return center; } @Autowired @Qualifier("circleRelated") public void setCenter(Point center) { this.center = center; } @Override public void draw() { System.out.println("Drawing a Circle"); System.out.println("Center Point is: (" + center.getX() + ", " + center.getY() + ")"); } } </code></pre> <p>Point.java</p> <pre><code>package com.springApplication; public class Point { private int x; private int y; public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } } </code></pre> <p>spring.xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt; &lt;bean id="pointA" class="com.springApplication.Point"&gt; &lt;qualifier value="circleRelated" /&gt; &lt;property name="x" value="0"/&gt; &lt;property name="y" value="0"/&gt; &lt;/bean&gt; &lt;bean id="PointB" class="com.springApplication.Point"&gt; &lt;property name="x" value="0"/&gt; &lt;property name="y" value="20"/&gt; &lt;/bean&gt; &lt;bean id="PointC" class="com.springApplication.Point"&gt; &lt;property name="x" value="-20"/&gt; &lt;property name="y" value="0"/&gt; &lt;/bean&gt; &lt;bean id="circle" class="com.springApplication.Circle"&gt; &lt;/bean&gt; &lt;!-- &lt;bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" /&gt; --&gt; &lt;context:annotation-config/&gt; &lt;/beans&gt; </code></pre> <p>Please let me know if anything else is needed. Someone please help !</p> <p>Sorry about the wrong placing!!</p> <p>@Andrei Stefan<br> List of Jars ---------<br> commons-logging-1.1.3<br> spring-aop-4.0.4.RELEASE<br> spring-aop-4.0.4.RELEASE-javadoc<br> spring-aop-4.0.4.RELEASE-sources<br> spring-aspects-4.0.4.RELEASE<br> spring-aspects-4.0.4.RELEASE-javadoc<br> spring-aspects-4.0.4.RELEASE-sources<br> spring-beans-4.0.4.RELEASE<br> spring-beans-4.0.4.RELEASE-javadoc<br> spring-beans-4.0.4.RELEASE-sources<br> spring-build-src-4.0.4.RELEASE<br> spring-context-4.0.4.RELEASE<br> spring-context-4.0.4.RELEASE-javadoc<br> spring-context-4.0.4.RELEASE-sources<br> spring-context-support-4.0.4.RELEASE<br> spring-context-support-4.0.4.RELEASE-javadoc<br> spring-context-support-4.0.4.RELEASE-sources<br> spring-core-4.0.4.RELEASE<br> spring-core-4.0.4.RELEASE-javadoc<br> spring-core-4.0.4.RELEASE-sources<br> spring-expression-4.0.4.RELEASE<br> spring-expression-4.0.4.RELEASE-javadoc<br> spring-expression-4.0.4.RELEASE-sources<br> spring-framework-bom-4.0.4.RELEASE<br> spring-framework-bom-4.0.4.RELEASE-javadoc<br> spring-framework-bom-4.0.4.RELEASE-sources<br> spring-instrument-4.0.4.RELEASE<br> spring-instrument-4.0.4.RELEASE-javadoc<br> spring-instrument-4.0.4.RELEASE-sources<br> spring-instrument-tomcat-4.0.4.RELEASE<br> spring-instrument-tomcat-4.0.4.RELEASE-javadoc<br> spring-instrument-tomcat-4.0.4.RELEASE-sources<br> spring-jdbc-4.0.4.RELEASE<br> spring-jdbc-4.0.4.RELEASE-javadoc<br> spring-jdbc-4.0.4.RELEASE-sources<br> spring-jms-4.0.4.RELEASE<br> spring-jms-4.0.4.RELEASE-javadoc<br> spring-jms-4.0.4.RELEASE-sources<br> spring-messaging-4.0.4.RELEASE<br> spring-messaging-4.0.4.RELEASE-javadoc<br> spring-messaging-4.0.4.RELEASE-sources<br> spring-orm-4.0.4.RELEASE<br> spring-orm-4.0.4.RELEASE-javadoc<br> spring-orm-4.0.4.RELEASE-sources<br> spring-oxm-4.0.4.RELEASE<br> spring-oxm-4.0.4.RELEASE-javadoc<br> spring-oxm-4.0.4.RELEASE-sources<br> spring-test-4.0.4.RELEASE<br> spring-test-4.0.4.RELEASE-javadoc<br> spring-test-4.0.4.RELEASE-sources<br> spring-tx-4.0.4.RELEASE<br> spring-tx-4.0.4.RELEASE-javadoc<br> spring-tx-4.0.4.RELEASE-sources<br> spring-web-4.0.4.RELEASE<br> spring-web-4.0.4.RELEASE-javadoc<br> spring-web-4.0.4.RELEASE-sources<br> spring-webmvc-4.0.4.RELEASE<br> spring-webmvc-4.0.4.RELEASE-javadoc<br> spring-webmvc-4.0.4.RELEASE-sources<br> spring-webmvc-portlet-4.0.4.RELEASE<br> spring-webmvc-portlet-4.0.4.RELEASE-javadoc<br> spring-webmvc-portlet-4.0.4.RELEASE-sources<br> spring-websocket-4.0.4.RELEASE<br> spring-websocket-4.0.4.RELEASE-javadoc<br> spring-websocket-4.0.4.RELEASE-sources<br></p> <p>All of these plus other default system libraries are referenced. </p>
23,634,282
1
3
null
2014-05-11 22:45:34.077 UTC
2
2014-05-13 18:18:02.69 UTC
2014-05-13 18:18:02.69 UTC
null
3,626,602
null
3,626,602
null
1
3
java|spring
53,204
<p>The problem occurs because </p> <pre><code>PropertyEditorRegistrySupport.class.getClassLoader() </code></pre> <p>is <code>null</code>. According to JavaDoc, this happens if the class <code>PropertyEditorRegistrySupport</code> has been loaded by the bootstrap class loader instead of the system class loader:</p> <blockquote> <p>Some implementations may use null to represent the bootstrap class loader. <strong>This method will return null in such implementations if this class was loaded by the bootstrap class loader.</strong> </p> </blockquote> <p>Perhaps your Spring libraries are on the endorsed class path?</p>
15,520,404
How to call a powershell function within the script from Start-Job?
<p>I saw <a href="https://stackoverflow.com/questions/7162090/how-do-i-start-a-job-of-a-function-i-just-defined">this question</a> and <a href="https://stackoverflow.com/questions/12293701/function-not-recognized-in-start-job">this question</a> but couldn't find solution to my problem.</p> <p>So here is the situation: I have two functions DoWork and DisplayMessage in a script (.ps1) file. Here is the code: </p> <pre><code>### START OF SCRIPT ### function DoWork { $event = Register-EngineEvent -SourceIdentifier NewMessage -Action { DisplayMessage($event.MessageData) } $scriptBlock = { Register-EngineEvent -SourceIdentifier NewMessage -Forward $message = "Starting work" $null = New-Event -SourceIdentifier NewMessage -MessageData $message ### DO SOME WORK HERE ### $message = "Ending work" $null = New-Event -SourceIdentifier NewMessage -MessageData $message Unregister-Event -SourceIdentifier NewMessage } DisplayMessage("Processing Starts") $array = @(1,2,3) foreach ($a in $array) { Start-Job -Name "DoActualWork" $ScriptBlock -ArgumentList $array | Out-Null } #$jobs = Get-Job -Name "DoActualWork" While (Get-Job -Name "DoActualWork" | where { $_.State -eq "Running" } ) { Start-Sleep 1 } DisplayMessage("Processing Ends") Get-Job -Name "DoActualWork" | Receive-Job } function DisplayMessage([string]$message) { Write-Host $message -ForegroundColor Red } DoWork ### END OF SCRIPT ### </code></pre> <p>I am creating 3 background jobs (using $array with 3 elements) and using event to pass messages from background jobs to the host. I would expect the powershell host to display "Processing Starts" and "Processing Ends" 1 time and "Starting work" and "Ending work" 3 times each. But instead I am not getting "Starting work"/"Ending work" displayed in console.</p> <p>Event is also treated as a job in powershell, so when I do Get-Job, I can see following error associated with the event job:</p> <blockquote> <p>{The term 'DisplayMessage' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.}</p> </blockquote> <p>My question: How can we reuse (or reference) a function (DisplayMessage in my case) defined in the same script from where I am calling Start-Job? Is it possible? I know we can use -InitializationScript to pass functions/modules to Start-Job, but I do not want to write DisplayMessage function twice, one in script and another in InitializationScript.</p>
15,520,715
3
0
null
2013-03-20 10:02:09.18 UTC
1
2019-07-12 17:06:19.58 UTC
2017-05-23 11:54:24.817 UTC
null
-1
null
1,095,246
null
1
11
powershell|start-job
70,917
<p>Background jobs are run in a seperate process, so the jobs you create with <code>Start-Job</code> can not interact with functions unless you include them in the <code>$scriptblock</code>.</p> <p>Even if you included the function in the <code>$scripblock</code>, <code>Write-Host</code> would not output it's content to the console until you used <code>Get-Job | Receive-Job</code> to recieve the jobs result.</p> <p><strong>EDIT</strong> The problem is that your <code>DisplayMessage</code> function is in a local script-scope while your eventhandler runs in a different parent scope(like global which is the session scope), so it can't find your function. If you create the function in the global scope and call it from the global scope, it will work. </p> <p>I've modified your script to do this now. I've also modified to scriptblock and unregistered the events when the script is done so you won't get 10x messages when you run the script multiple times :-)</p> <p>Untitled1.ps1</p> <pre><code>function DoWork { $event = Register-EngineEvent -SourceIdentifier NewMessage -Action { global:DisplayMessage $event.MessageData } $scriptBlock = { Register-EngineEvent -SourceIdentifier NewMessage -Forward $message = "Starting work $args" $null = New-Event -SourceIdentifier NewMessage -MessageData $message ### DO SOME WORK HERE ### $message = "Ending work $args" $null = New-Event -SourceIdentifier NewMessage -MessageData $message Unregister-Event -SourceIdentifier NewMessage } DisplayMessage("Processing Starts") $array = @(1,2,3) foreach ($a in $array) { Start-Job -Name "DoActualWork" $ScriptBlock -ArgumentList $a | Out-Null } #$jobs = Get-Job -Name "DoActualWork" While (Get-Job -Name "DoActualWork" | where { $_.State -eq "Running" } ) { Start-Sleep 1 } DisplayMessage("Processing Ends") #Get-Job -Name "DoActualWork" | Receive-Job } function global:DisplayMessage([string]$message) { Write-Host $message -ForegroundColor Red } DoWork Get-EventSubscriber | Unregister-Event </code></pre> <p>Test</p> <pre><code>PS &gt; .\Untitled1.ps1 Processing Starts Starting work 1 Starting work 2 Ending work 1 Ending work 2 Starting work 3 Ending work 3 Processing Ends </code></pre>
19,013,725
Linux Mint - adding environment variables permanently
<p>I was trying to modify the ~/.profile file to add a line to the PATH variable. I added this line:</p> <pre><code>PATH=$PATH:/home/paul/avatar-gf-1.0-ea/glassfish4/bin/ </code></pre> <p>at the end. I restarted the terminal, but it still did not identify commands in that directory. Does anyone know what I am doing wrong?</p>
19,013,849
5
2
null
2013-09-25 19:38:13.063 UTC
6
2020-06-04 18:20:37.063 UTC
null
null
null
null
7,385,447
null
1
16
linux|bash|environment-variables|linux-mint
50,646
<p>Try this in the ~/.pam_environment in your home folder. If it does not exist then create it:</p> <pre><code>PATH DEFAULT=${PATH}:/home/paul/avatar-gf-1.0-ea/glassfish4/bin/ </code></pre> <p>You will need to log in and out.</p>
40,303,182
Why don't C++ compilers optimize this conditional boolean assignment as an unconditional assignment?
<p>Consider the following function:</p> <pre><code>void func(bool&amp; flag) { if(!flag) flag=true; } </code></pre> <p>It seems to me that if flag has a valid boolean value, this would be equivalent to unconditional setting it to <code>true</code>, like this:</p> <pre><code>void func(bool&amp; flag) { flag=true; } </code></pre> <p>Yet neither gcc nor clang optimize it this way — both generate the following at <code>-O3</code> optimization level:</p> <pre><code>_Z4funcRb: .LFB0: .cfi_startproc cmp BYTE PTR [rdi], 0 jne .L1 mov BYTE PTR [rdi], 1 .L1: rep ret </code></pre> <p>My question is: is it just that the code is too special-case to care to optimize, or are there any good reasons why such optimization would be undesired, given that <code>flag</code> is not a reference to <code>volatile</code>? It seems the only reason which might be is that <code>flag</code> could somehow have a non-<code>true</code>-or-<code>false</code> value without undefined behavior at the point of reading it, but I'm not sure whether this is possible.</p>
40,303,296
3
3
null
2016-10-28 10:29:20.427 UTC
17
2016-10-28 22:20:29.493 UTC
2016-10-28 22:20:29.493 UTC
null
1,157,100
null
673,852
null
1
117
c++|optimization
7,846
<p>This may negatively impact the performance of the program due to <a href="https://en.wikipedia.org/wiki/Cache_coherence" rel="nofollow noreferrer">cache coherence</a> considerations. Writing to <code>flag</code> each time <code>func()</code> is called would dirty the containing cache line. This will happen regardless of the fact that the value being written exactly matches the bits found at the destination address before the write.</p> <hr> <p><strong>EDIT</strong></p> <p><a href="https://stackoverflow.com/users/743382/hvd">hvd</a> has provided another <a href="https://stackoverflow.com/a/40303540/6394138">good reason</a> that prevents such an optimization. It is a more compelling argument against the proposed optimization, since it may result in undefined behavior, whereas my (original) answer only addressed performance aspects.</p> <p>After a little more reflection, I can propose one more example why compilers should be strongly banned - unless they can prove that the transformation is safe for a particular context - from introducing the unconditional write. Consider this code:</p> <pre><code>const bool foo = true; int main() { func(const_cast&lt;bool&amp;&gt;(foo)); } </code></pre> <p>With an unconditional write in <code>func()</code> this definitely triggers undefined behavior (writing to read-only memory will terminate the program, even if the effect of the write would otherwise be a no-op).</p>
34,365,369
GoogleService failed to initialize
<p>I am using google Maps in my android application. I have created the key and added necessary permissions in manifest file. But soon I start the application I get this message in debugger:</p> <blockquote> <p>GoogleService failed to initialize, status: 10, Missing an expected resource: 'R.string.google_app_id' for initializing Google services. Possible causes are missing google-services.json or com.google.gms.google-services gradle plugin.</p> </blockquote> <p>I am not sure whats wrong. The Map is working fine and I can use it without any issues. My gradle file has this entry:</p> <blockquote> <p>compile 'com.google.android.gms:play-services:8.4.0'</p> </blockquote> <p>What is it complaining about and how do I alleviate it?</p>
34,388,626
11
6
null
2015-12-18 23:18:18.69 UTC
36
2018-10-05 19:11:05.157 UTC
2016-01-07 14:40:43.21 UTC
null
445,131
null
623,401
null
1
113
android|google-maps|android-mapview|android-maps-v2
100,820
<p>You need to place the configuration file (<code>google-services.json</code>) generated by <a href="https://developers.google.com/mobile/add?platform=android" rel="noreferrer">developer.google.com</a>, as mentioned in the 2nd step of the official docs <a href="https://developers.google.com/identity/sign-in/android/start?hl=en" rel="noreferrer">here</a></p> <p>The process is simple</p> <ol> <li>You can select your project or create a new one.</li> <li><p>Then after selecting desired services (in this case the maps service), you can generate the configuration file.</p> <blockquote> <p>For people who have migrated to the Firebase projects they can get the same by going to <a href="https://console.firebase.google.com/" rel="noreferrer">Firebase Console</a>, selecting your project and under settings you will find the configuration file.</p> </blockquote></li> <li><p>Then as quoted in step 3 of the official docs <a href="https://developers.google.com/identity/sign-in/android/start?hl=en" rel="noreferrer">here</a></p> <blockquote> <p>Copy the <code>google-services.json</code> file you just downloaded into the app/ or mobile/ directory of your Android</p> </blockquote></li> </ol> <p><strong>P.S : For people downvoting this answer, please do leave a comment as to why you are down voting it.</strong></p>
51,403,071
Create jre from OpenJDK Windows
<p>We are switching from Oracle JDK/JRE to OpenJDK. Now I found only the JDK but I want to have a JRE as well from OpenJDK. This is for installing our application on the clients without the need of having the full JDK.</p> <p>Is there a way to create a JRE package from the OpenJDK for Windows X64?</p>
56,807,371
12
5
null
2018-07-18 13:18:16.99 UTC
11
2022-06-09 06:11:39.6 UTC
2018-07-18 13:39:42.357 UTC
null
5,156,999
null
2,448,399
null
1
40
java
42,780
<p>Inspired by the article <a href="https://medium.com/azulsystems/using-jlink-to-build-java-runtimes-for-non-modular-applications-9568c5e70ef4" rel="noreferrer">Using jlink to Build Java Runtimes for non-Modular Applications</a> I used the commands:</p> <ol> <li><code>java --list-modules</code> to get a list of all openjdk modules available</li> <li><code>jlink --no-header-files --no-man-pages --compress=2 --add-modules &lt;module-list from step 1&gt; --output java-runtime</code> to create a compact jre.</li> </ol> <p>For OpendJDK 12 this is the command I ended up with: </p> <p><code>jlink --no-header-files --no-man-pages --compress=2 --add-modules java.base,java.compiler,java.datatransfer,java.desktop,java.instrument,java.logging,java.management,java.management.rmi,java.naming,java.net.http,java.prefs,java.rmi,java.scripting,java.se,java.security.jgss,java.security.sasl,java.smartcardio,java.sql,java.sql.rowset,java.transaction.xa,java.xml,java.xml.crypto,jdk.accessibility,jdk.aot,jdk.attach,jdk.charsets,jdk.compiler,jdk.crypto.cryptoki,jdk.crypto.ec,jdk.crypto.mscapi,jdk.dynalink,jdk.editpad,jdk.hotspot.agent,jdk.httpserver,jdk.internal.ed,jdk.internal.jvmstat,jdk.internal.le,jdk.internal.opt,jdk.internal.vm.ci,jdk.internal.vm.compiler,jdk.internal.vm.compiler.management,jdk.jartool,jdk.javadoc,jdk.jcmd,jdk.jconsole,jdk.jdeps,jdk.jdi,jdk.jdwp.agent,jdk.jfr,jdk.jlink,jdk.jshell,jdk.jsobject,jdk.jstatd,jdk.localedata,jdk.management,jdk.management.agent,jdk.management.jfr,jdk.naming.dns,jdk.naming.rmi,jdk.net,jdk.pack,jdk.rmic,jdk.scripting.nashorn,jdk.scripting.nashorn.shell,jdk.sctp,jdk.security.auth,jdk.security.jgss,jdk.unsupported,jdk.unsupported.desktop,jdk.xml.dom,jdk.zipfs --output java-runtime</code></p>
5,576,901
sqlplus spooling: How to get rid of first, empty line?
<p>I'm doing the following spooling statement:</p> <pre><code>SET VERIFY OFF SET FEEDBACK OFF SET HEADING OFF SET TRIMSPOOL ON SET TERM OFF SPOOL &amp;pathRelations START scripts/relations.sql &amp;parent SPOOL OFF SET TERM ON </code></pre> <p>The <code>scripts/relations.sql</code> file contains a simple <code>select</code> statement.</p> <p>Unfortunately, the spooled file contains an empty line as the first one in the file. This line causes trouble in our framework.</p> <p>Of course I could get rid of these line through <code>sed</code> but ain't there a way to suppress its creation in the first place?</p>
7,719,778
2
0
null
2011-04-07 06:27:36.553 UTC
4
2019-12-26 05:28:22.737 UTC
null
null
null
user321068
null
null
1
23
sql|sqlplus|spool|fixed-length-file
46,091
<p><code>SET NEWPAGE NONE</code> is the correct answer.</p> <p><code>SET NEWPAGE 0</code> will cause a page feed, which is not what the OP wants.</p>
113,427
How to clear the scrollback in the screen command?
<p>I use the <code>screen</code> command for command-line multitasking in Linux and I set my scrollback buffer length to a very large value. Is there a key combination to clear the buffer for a certain tab when I don't want it sitting there anymore?</p>
113,473
7
1
null
2008-09-22 06:18:09.163 UTC
10
2022-05-06 11:53:25.137 UTC
2011-11-09 20:27:13.583 UTC
Harley
496,830
Liu Chang
null
null
1
35
linux|command-line|gnu-screen
30,763
<p><a href="http://osdir.com/ml/gnu.screen.user/2006-01/msg00029.html" rel="noreferrer">This thread</a> has the following suggestion:</p> <blockquote> <p>In the window whose scrollback you want to delete, set the scrollback to zero, then return it to its normal value (in your case, 15000).</p> <p>If you want, you can bind this to a key:</p> <p>bind / eval "scrollback 0" "scrollback 15000"</p> </blockquote> <p>You can issue the <code>scrollback 0</code> command from the session as well, after typing <code>C-a :</code>. HTH.</p>
1,038,435
SQL conditional SELECT
<p>I would like to create a stored procedure with parameters that indicate which fields should be selected.</p> <p>E.g. I would like to pass two parameters "selectField1" and "selectField2" each as bools.</p> <p>Then I want something like</p> <pre><code>SELECT if (selectField1 = true) Field1 ELSE do not select Field1 if (selectField2 = true) Field2 ELSE do not select Field2 FROM Table </code></pre> <p>Thanks Karl</p>
1,038,505
7
0
null
2009-06-24 13:41:53.607 UTC
16
2013-05-13 20:58:52.917 UTC
2009-06-24 13:44:11.59 UTC
null
122,428
null
115,391
null
1
37
sql|select|conditional
149,355
<p>Sounds like they want the ability to return only allowed fields, which means the number of fields returned also has to be dynamic. This will work with 2 variables. Anything more than that will be getting confusing. </p> <pre><code>IF (selectField1 = true AND selectField2 = true) BEGIN SELECT Field1, Field2 FROM Table END ELSE IF (selectField1 = true) BEGIN SELECT Field1 FROM Table END ELSE IF (selectField2 = true) BEGIN SELECT Field2 FROM Table END </code></pre> <p>Dynamic SQL will help with multiples. This examples is assuming atleast 1 column is true.</p> <pre><code>DECLARE @sql varchar(MAX) SET @sql = 'SELECT ' IF (selectField1 = true) BEGIN SET @sql = @sql + 'Field1, ' END IF (selectField2 = true) BEGIN SET @sql = @sql + 'Field2, ' END ... -- DROP ', ' @sql = SUBSTRING(@sql, 1, LEN(@sql)-2) SET @sql = @sql + ' FROM Table' EXEC(@sql) </code></pre>
383,977
Viewing more than 10,000 files on a FTP file server?
<p>I've queued up over 10,000 files to be uploaded to a UNIX based FTP server using a freeware (Windows based) FTP client which as far as i can see has finished without error.</p> <p>Now, when i view the remote directory (using the Windows software) the output is truncated to 10,000 filenames. This ever occurs when i use the Windows command line FTP tool. Is there a way i can see more than this limit using another piece of software? I just need to confirm all files where indeed uploaded.</p> <p>Any ideas?</p> <p>Any information regarding this limit is very welcome.</p>
383,989
8
2
null
2008-12-21 01:26:14.42 UTC
4
2012-09-28 19:49:21.487 UTC
null
null
null
Gary Willoughby
13,227
null
1
16
file|ftp|limit
42,012
<p>Please provide more information like specific OS and version. Also please list the names and versions of the ftp clients that you are using when you experience the problem.</p> <p>A lot of files in a single directory can cause many programs to have problems. I would recommend reducing the number of files in a folder, by putting them in several folders. </p> <p>The FTP client that you are using probably has an option to look at the raw log and you should be able to use that to determine if it's a problem with the server or your client. The clients could be using a slightly different method to retrieve the list of files. </p> <p>The story is in the logs. </p>
479,923
Is C# a single dispatch or multiple dispatch language?
<p>I'm trying to understand what single and multiple dispatch are, exactly.</p> <p>I just read this:<br> <a href="http://en.wikipedia.org/wiki/Multiple_dispatch" rel="noreferrer">http://en.wikipedia.org/wiki/Multiple_dispatch</a></p> <p>And from that definition is seems to me that C# and VB.Net are multiple-dispatch, even though the choice of which overload to call is made at compile-time.</p> <p>Am I correct here, or am I missing something? Thanks!</p>
483,649
8
0
null
2009-01-26 14:17:39.843 UTC
11
2020-01-19 08:30:39.623 UTC
2013-08-18 14:10:28.22 UTC
Dan Dyer
221,800
Daniel Magliola
3,314
null
1
30
c#|programming-languages|multiple-dispatch|single-dispatch
10,701
<p>OK, I understood the subtle difference where function overloading is different from multiple-dispatch.</p> <p>Basically, the difference is whether which method to call is chosen at run-time or compile-time. Now, I know everybody's said this, but without a clear example this sounds VERY obvious, given that C# is statically typed and multiple-dispatch languages (apparently to me, at least) seem to be dynamically typed. Up to now, with just that definition multiple-dispatch and function overloading sounded exactly the same to me.</p> <p>The case where this makes a real difference is when you have 2 overloads of a method which differ on the type of a parameter, but the 2 types are polymorphic, and you call with a reference declared as the higher type, which has an object of the lower type... (If someone can think of a better way to express this, please feel free to edit this answer)</p> <p>Example:</p> <pre><code>int CaptureSpaceShip(IRebelAllianceShip ship) {} int CaptureSpaceShip(XWing ship) {} void Main() { IRebelAllianceShip theShip = new XWing(); CaptureSpaceShip(theShip); } </code></pre> <p>XWing obviously implements IRebelAllianceShip. In this case, the first method will be called, whereas if C# implemented multiple-dispatch, the second method would be called.</p> <p>Sorry about the doc rehash... This seems to me the clearest way to explain this difference, rather than just reading the definitions for each dispatch method.</p> <p>For a more formal explanation: <a href="http://en.wikipedia.org/wiki/Double_dispatch#Double_dispatch_is_more_than_function_overloading" rel="noreferrer" title="http://en.wikipedia.org/wiki/Double_dispatch#Double_dispatch_is_more_than_function_overloading">http://en.wikipedia.org/wiki/Double_dispatch#Double_dispatch_is_more_than_function_overloading</a></p>
428,634
Advantages of Cache vs Session
<p>What is the difference between storing a datatable in Session vs Cache? What are the advantages and disadvantages?</p> <p>So, if it is a simple search page which returns result in a datatable and binds it to a gridview. If user 'a' searches and user 'b' searches, is it better to store it in Session since each user would most likely have different results or can I still store each of their searches in Cache or does that not make sense since there is only one cache. I guess basically what I am trying to say is that would the Cache be overwritten.</p>
428,684
8
4
null
2009-01-09 16:06:11.837 UTC
22
2019-10-22 07:55:21.797 UTC
2015-08-30 17:57:19.307 UTC
Martin Clarke
1,996,435
Xaisoft
33,690
null
1
72
c#|asp.net|session|caching|viewstate
79,581
<p>One important difference is, that items in the cache can expire (will be removed from cache) after a specified amount of time. Items put into a session will stay there, until the session ends.</p> <p>ASP.NET can also remove items from cache when the amount of available memory gets small.</p> <p>Another difference: the session state can be kept external (state server, SQL server) and shared between several instances of your web app (for load balancing). This is not the case with the cache.</p> <p>Besides of these differences (as others have noted): session is per user/session while cache is per application.</p>
1,184,997
Enabling tabs in xcode? Or lessening the pain of not having them?
<p>I am currently using xcode and I find it's lack of tabs quite disturbing.</p> <p>I currently use command-shift-d to search through all the files, or ctrl-1 to open the history of files that were recently opened.</p> <p>It works but I find it less effective than just tabbing through the few files i am currently working on.</p> <p>Is there any way, third party or not, to enable some sort of tabbed organization? If not, is there any other way to quickly navigate through a subset of files?</p>
5,257,206
8
2
null
2009-07-26 16:49:02.557 UTC
11
2017-01-23 08:51:44.537 UTC
null
null
null
null
2,011
null
1
76
objective-c|xcode|macos|ide
38,865
<p>XCode 4 now supports tabs. You can enable by selecting "View / Show Tab Bar" menu.</p>
292,965
What is a UUID?
<p>Well, what is one?</p>
292,989
8
5
null
2008-11-15 19:43:27.53 UTC
22
2020-06-03 18:24:58.667 UTC
2009-08-12 18:30:08.437 UTC
chakrit
1,431
doctor smith
null
null
1
94
uuid|glossary|acronym
53,392
<p>It's an identification number that will uniquely identify something. The idea being that id number will be <em>universally</em> unique. Thus, no two things should have the same uuid. In fact, if you were to generate 10 trillion uuids, there would be something along the lines of a .00000006 chance of two uuids being the same.</p>
588,040
window.onload vs document.onload
<p>Which is more widely supported: <code>window.onload</code> or <code>document.onload</code>?</p>
588,048
9
2
null
2009-02-25 21:45:11.487 UTC
271
2021-11-07 21:49:38.013 UTC
2020-05-11 08:59:59.06 UTC
null
860,099
Chris Ballance
1,551
null
1
846
javascript|event-handling|dom-events
2,300,885
<h2>When do they fire?</h2> <p><a href="https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onload" rel="noreferrer"><code>window.onload</code></a></p> <ul> <li>By default, it is fired when the entire page loads, <strong>including</strong> its content (images, CSS, scripts, etc.).</li> </ul> <p>In some browsers it now takes over the role of <code>document.onload</code> and fires when the DOM is ready as well.</p> <p><code>document.onload</code></p> <ul> <li>It is called when the DOM is ready which can be <strong>prior</strong> to images and other external content is loaded.</li> </ul> <h2>How well are they supported?</h2> <p><code>window.onload</code> appears to be the most widely supported. In fact, some of the most modern browsers have in a sense replaced <code>document.onload</code> with <code>window.onload</code>.</p> <p>Browser support issues are most likely the reason why many people are starting to use libraries such as <a href="http://jquery.com/" rel="noreferrer">jQuery</a> to handle the checking for the document being ready, like so:</p> <pre><code>$(document).ready(function() { /* code here */ }); $(function() { /* code here */ }); </code></pre> <hr> <p>For the purpose of history. <code>window.onload</code> vs <code>body.onload</code>:</p> <blockquote> <p>A similar question was asked on <a href="http://www.codingforums.com/archive/index.php/t-106229.html" rel="noreferrer">codingforums</a> a while back regarding the usage of <code>window.onload</code> over <code>body.onload</code>. The result seemed to be that you should use <code>window.onload</code> because it is good to separate your structure from the action.</p> </blockquote>
337,739
How to log something in Rails in an independent log file?
<p>In rails I want to log some information in a different log file and not the standard development.log or production.log. I want to do this logging from a model class.</p>
337,971
9
0
null
2008-12-03 16:24:12.327 UTC
56
2017-05-25 03:00:43.117 UTC
null
null
null
akshat
29,653
null
1
165
ruby-on-rails|logging
84,504
<p>You can create a Logger object yourself from inside any model. Just pass the file name to the constructor and use the object like the usual Rails <code>logger</code>:</p> <pre><code>class User &lt; ActiveRecord::Base def my_logger @@my_logger ||= Logger.new("#{Rails.root}/log/my.log") end def before_save my_logger.info("Creating user with name #{self.name}") end end </code></pre> <p>Here I used a class attribute to memoize the logger. This way it won't be created for every single User object that gets created, but you aren't required to do that. Remember also that you can inject the <code>my_logger</code> method directly into the <code>ActiveRecord::Base</code> class (or into some superclass of your own if you don't like to monkey patch too much) to share the code between your app's models.</p>
137,043
Can emacs re-indent a big blob of HTML for me?
<p>When editing HTML in emacs, is there a way to automatically pretty-format a blob of markup, changing something like this:</p> <pre><code> &lt;table&gt; &lt;tr&gt; &lt;td&gt;blah&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt; </code></pre> <p>...into this:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt; blah &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre>
144,938
10
1
null
2008-09-26 00:10:55.923 UTC
33
2016-09-11 21:22:58.187 UTC
2008-09-26 02:27:06.487 UTC
raldi
7,598
raldi
7,598
null
1
72
html|emacs
32,174
<p>By default, when you visit a <code>.html</code> file in Emacs (22 or 23), it will put you in <code>html-mode</code>. That is probably not what you want. You probably want <code>nxml-mode</code>, which is seriously fancy. <code>nxml-mode</code> seems to only come with Emacs 23, although you can download it for earlier versions of emacs from the <a href="http://www.thaiopensource.com/nxml-mode/" rel="noreferrer">nXML web site</a>. There is also a Debian and Ubuntu package named <code>nxml-mode</code>. You can enter <code>nxml-mode</code> with:</p> <pre><code>M-x nxml-mode </code></pre> <p>You can view nxml mode documentation with:</p> <pre><code>C-h i g (nxml-mode) RET </code></pre> <p>All that being said, you will probably have to use something like <a href="http://tidy.sourceforge.net/" rel="noreferrer">Tidy</a> to re-format your xhtml example. <code>nxml-mode</code> will get you from</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;blah&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt; &lt;/body&gt; </code></pre> <p>to</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;blah&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>but I don't see a more general facility to do line breaks on certain xml tags as you want. Note that <code>C-j</code> will insert a new line with proper indentation, so you may be able to do a quick macro or hack up a <code>defun</code> that will do your tables.</p>
605,920
Reasons for why a WinForms label does not want to be transparent?
<p>Why can't I set the BackColor of a Label to Transparent? I have done it before, but now it just don't want to...</p> <p>I created a new UserControl, added a progressbar and a label to it. When I set the BackColor of the label to transparent it is still gray =/ Why is this?</p> <p>What I wanted was to have the label on top of the progressbar so that its text was "in" the progressbar...</p>
605,944
11
2
null
2009-03-03 10:46:54.683 UTC
9
2021-01-12 19:37:34.97 UTC
2009-10-05 17:32:47.573 UTC
null
76,337
Svish
39,321
null
1
29
c#|winforms|transparency
31,131
<p>WinForms doesn't really support transparent controls, but you can make a transparent control yourself. <a href="https://stackoverflow.com/questions/373913/setting-the-parent-of-a-usercontrol-prevents-it-from-being-transparent/373961#373961">See my answer here</a>.</p> <p>In your case you should probably subclass the progress bar and override the OnPaint method to draw a text on the progress bar. </p>
833,227
What's the easiest way to get a user's full name on a Linux/POSIX system?
<p>I could grep through /etc/passwd but that seems onerous. 'finger' isn't installed and I'd like to avoid that dependency. This is for a program so it would be nice if there was some command that let you just access user info.</p>
833,256
11
0
null
2009-05-07 06:55:27.287 UTC
11
2021-10-05 06:50:48.947 UTC
2011-11-18 16:52:57.62 UTC
null
70,157
null
83,898
null
1
43
database|linux|shell|posix|user-accounts
60,167
<p>You don't specify a programming language, so I'll assume you want to use the shell; here's <strong>an answer for Posix shells</strong>.</p> <p>Two steps to this: get the appropriate record, then get the field you want from that record.</p> <p>First, getting the account record is done by <strong>querying the <code>passwd</code> table</strong>:</p> <pre><code>$ user_name=foo $ user_record="$(getent passwd $user_name)" $ echo "$user_record" foo:x:1023:1025:Fred Nurk,,,:/home/foo:/bin/bash </code></pre> <p>For hysterical raisins, the full name of the user is recorded in a field called the <strong><a href="http://en.wikipedia.org/wiki/Gecos_field" rel="noreferrer">“GECOS” field</a></strong>; to complicate matters, this field often has its own structure with the <strong>full name as just one of several optional sub-fields</strong>. So anything that wants to get the full name from the account record needs to parse both these levels.</p> <pre><code>$ user_record="$(getent passwd $user_name)" $ user_gecos_field="$(echo "$user_record" | cut -d ':' -f 5)" $ user_full_name="$(echo "$user_gecos_field" | cut -d ',' -f 1)" $ echo "$user_full_name" Fred Nurk </code></pre> <p>Your <strong>programming language probably has a library function</strong> to do this in fewer steps. In C, you'd use the ‘getpwnam’ function and then parse the GECOS field.</p>
261,455
Using backticks around field names
<p>After reading a couple of answers and comments on some SQL questions here, and also hearing that a friend of mine works at a place which has a policy which bans them, I'm wondering if there's anything wrong with using backticks around field names in MySQL.</p> <p>That is:</p> <pre><code>SELECT `id`, `name`, `anotherfield` ... -- vs -- SELECT id, name, anotherfield ... </code></pre>
261,476
11
4
null
2008-11-04 10:30:20.077 UTC
48
2019-01-24 17:17:48.073 UTC
2017-01-06 14:02:14.013 UTC
null
2,360,798
nickf
9,021
null
1
181
mysql|backticks
104,038
<p>Using backticks permits you to use alternative characters. In query writing it's not such a problem, but if one assumes you can just use backticks, I would assume it lets you get away with ridiculous stuff like</p> <pre><code>SELECT `id`, `my name`, `another field` , `field,with,comma` </code></pre> <p>Which does of course generate badly named tables. </p> <p>If you're just being concise I don't see a problem with it, you'll note if you run your query as such</p> <pre><code>EXPLAIN EXTENDED Select foo,bar,baz </code></pre> <p>The generated warning that comes back will have back-ticks <strong>and</strong> fully qualified table names. So if you're using query generation features and automated re-writing of queries, backticks would make anything parsing your code less confused. </p> <p>I think however, instead of mandating whether or not you can use backticks, they should have a standard for names. It solves more 'real' problems. </p>
651,702
String.Replace(char, char) method in C#
<p>How do I replace <code>\n</code> with empty space?</p> <p>I get an empty literal error if I do this:</p> <pre><code>string temp = mystring.Replace('\n', ''); </code></pre>
651,723
12
2
null
2009-03-16 18:56:49.433 UTC
null
2015-12-01 16:04:38.01 UTC
2015-11-25 15:34:07.237 UTC
null
63,550
gnomixa
57,997
null
1
72
c#|string
133,134
<p><code>String.Replace('\n', '')</code> doesn't work because <code>''</code> is not a valid character literal.</p> <p>If you use the String.Replace(string, string) override, it should work.</p> <pre><code>string temp = mystring.Replace("\n", ""); </code></pre>
234,365
Is TCHAR still relevant?
<p>I'm new to Windows programming and after reading the Petzold book I wonder: </p> <p>is it still good practice to use the <code>TCHAR</code> type and the <code>_T()</code> function to declare strings or if I should just use the <code>wchar_t</code> and <code>L""</code> strings in new code?</p> <p>I will target only Windows 2000 and up and my code will be <a href="http://en.wikipedia.org/wiki/Internationalization_and_localization" rel="noreferrer">i18n</a> from the start up.</p>
234,505
12
0
null
2008-10-24 16:55:50.77 UTC
25
2020-05-07 21:18:23.413 UTC
2010-03-07 13:37:26.933 UTC
null
63,550
F&#225;bio
9,458
null
1
88
c++|c|windows|unicode|wchar-t
42,798
<p>I would still use the TCHAR syntax if I was doing a new project today. There's not much practical difference between using it and the WCHAR syntax, and I prefer code which is explicit in what the character type is. Since most API functions and helper objects take/use TCHAR types (e.g.: CString), it just makes sense to use it. Plus it gives you flexibility if you decide to use the code in an ASCII app at some point, or if Windows ever evolves to Unicode32, etc.</p> <p>If you decide to go the WCHAR route, I would be explicit about it. That is, use CStringW instead of CString, and casting macros when converting to TCHAR (eg: CW2CT).</p> <p>That's my opinion, anyway.</p>
203,844
jQuery Validation plugin: disable validation for specified submit buttons
<p>I have a form with multiple fields that I'm validating (some with methods added for custom validation) with Jörn Zaeffere's excellent jQuery Validation plugin. How do you circumvent validation with specified submit controls (in other words, fire validation with some submit inputs, but do not fire validation with others)? This would be similar to ValidationGroups with standard ASP.NET validator controls.</p> <p>My situation:</p> <p>It's with ASP.NET WebForms, but you can ignore that if you wish. However, I am using the validation more as a "recommendation": in other words, when the form is submitted, validation fires but instead of a "required" message displaying, a "recommendation" shows that says something along the line of "you missed the following fields.... do you wish to proceed anyways?" At that point in the error container there's another submit button now visible that can be pressed which would ignore the validation and submit anyways. How to circumvent the forms .validate() for this button control and still post?</p> <p>The Buy and Sell a House sample at <a href="http://jquery.bassistance.de/validate/demo/multipart/" rel="noreferrer">http://jquery.bassistance.de/validate/demo/multipart/</a> allows for this in order to hit the previous links, but it does so through creating custom methods and adding it to the validator. I would prefer to not have to create custom methods duplicating functionality already in the validation plugin.</p> <p>The following is a shortened version of the immediately applicable script that I've got right now:</p> <pre><code>var container = $("#&lt;%= Form.ClientID %&gt; div.validationSuggestion"); $('#&lt;%= Form.ClientID %&gt;').validate({ errorContainer: container, errorLabelContainer: $("ul",container), rules: { &lt;%= YesNo.UniqueID %&gt;: { required: true }, &lt;%= ShortText.UniqueID %&gt;: { required: true } // etc. }, messages: { &lt;%= YesNo.UniqueID %&gt;: 'A message.', &lt;%= ShortText.UniqueID %&gt;: 'Another message.' // etc. }, highlight: function(element, errorClass) { $(element).addClass(errorClass); $(element.form).find("label[for=" + element.id + "]").addClass(errorClass); $(element.form).find("label[for=" + element.id + "]").removeClass("valid"); }, unhighlight: function(element, errorClass) { $(element).removeClass(errorClass); $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass); $(element.form).find("label[for=" + element.id + "]").addClass("valid"); }, wrapper: 'li' }); </code></pre>
203,989
12
1
null
2008-10-15 06:14:55.76 UTC
45
2020-07-21 08:58:50.017 UTC
2016-05-03 22:57:34.587 UTC
ovalsquare
594,235
ovalsquare
9,344
null
1
171
jquery|jquery-validate
181,623
<p>You can add a CSS class of <code>cancel</code> to a submit button to suppress the validation</p> <p>e.g</p> <pre><code>&lt;input class="cancel" type="submit" value="Save" /&gt; </code></pre> <p>See the jQuery Validator documentation of this feature here: <a href="https://jqueryvalidation.org/reference#link-skipping-validation-on-submit" rel="noreferrer">Skipping validation on submit</a></p> <hr> <p><strong>EDIT</strong>:</p> <p>The above technique has been deprecated and replaced with the <code>formnovalidate</code> attribute.</p> <pre><code>&lt;input formnovalidate="formnovalidate" type="submit" value="Save" /&gt; </code></pre>
1,007,481
How to replace whitespaces with underscore?
<p>I want to replace whitespace with underscore in a string to create nice URLs. So that for example:</p> <pre><code>&quot;This should be connected&quot; </code></pre> <p>Should become</p> <pre><code>&quot;This_should_be_connected&quot; </code></pre> <p>I am using Python with Django. Can this be solved using regular expressions?</p>
1,007,499
14
1
null
2009-06-17 14:41:36.94 UTC
54
2021-11-28 09:07:40.967 UTC
2021-11-28 09:07:40.967 UTC
null
6,045,800
null
74,660
null
1
285
python|string
452,700
<p>You don't need regular expressions. Python has a built-in string method that does what you need:</p> <pre><code>mystring.replace(" ", "_") </code></pre>
3,452
SQL Client for Mac OS X that works with MS SQL Server
<p>How can I connect to a remote SQL server using Mac OS X? I don't really need a GUI, but it would be nice to have for the color coding and resultset grid. I'd rather not have to use a VM.</p> <p>Is there a SQL client for Mac OS X that works with MS SQL Server?</p>
34,153
25
11
2011-01-21 07:02:48.517 UTC
2008-08-06 14:25:17.457 UTC
194
2018-11-05 11:44:52.22 UTC
2016-11-29 16:16:09.797 UTC
Nigel Campbell
1,676,152
null
437
null
1
481
sql-server|macos
688,744
<p>Let's work together on a canonical answer.</p> <h3>Native Apps</h3> <ul> <li><a href="http://www.macsqlclient.com/" rel="noreferrer">SQLPro for MSSQL</a></li> <li><a href="http://www.navicat.com/products/navicat-for-sqlserver" rel="noreferrer">Navicat</a></li> <li><a href="http://www.valentina-db.com/en/valentina-studio-overview" rel="noreferrer">Valentina Studio</a></li> <li><a href="https://tableplus.io" rel="noreferrer">TablePlus</a></li> </ul> <h3>Java-Based</h3> <ul> <li><a href="http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html" rel="noreferrer">Oracle SQL Developer</a> (free)</li> <li><a href="http://squirrel-sql.sourceforge.net/" rel="noreferrer">SQuirrel SQL</a> (free, open source)</li> <li><a href="http://razorsql.com/" rel="noreferrer">Razor SQL</a></li> <li><a href="http://www.dbvis.com/" rel="noreferrer">DB Visualizer</a></li> <li><a href="http://dbeaver.jkiss.org/" rel="noreferrer">DBeaver</a> (free, open source)</li> <li><a href="http://www.sql-workbench.net" rel="noreferrer">SQL Workbench/J</a> (free, open source)</li> <li><a href="https://www.jetbrains.com/datagrip/" rel="noreferrer">JetBrains DataGrip</a></li> <li><a href="http://www.metabase.com/" rel="noreferrer">Metabase</a> (free, open source)</li> <li><a href="https://netbeans.org" rel="noreferrer">Netbeans</a> (free, open source, full development environment)</li> </ul> <h3>Electron-Based</h3> <ul> <li><a href="https://docs.microsoft.com/en-us/sql/linux/sql-server-linux-develop-use-vscode" rel="noreferrer">Visual Studio Code with mssql extension</a></li> <li><a href="https://docs.microsoft.com/en-us/sql/azure-data-studio/what-is" rel="noreferrer">Azure Data Studio</a></li> <li><a href="https://sqlectron.github.io" rel="noreferrer">SQLectron</a></li> </ul> <p>(TODO: Add others mentioned below)</p>
886,955
How do I break out of nested loops in Java?
<p>I've got a nested loop construct like this:</p> <pre><code>for (Type type : types) { for (Type t : types2) { if (some condition) { // Do something and break... break; // Breaks out of the inner loop } } } </code></pre> <p>Now how can I break out of both loops? I've looked at similar questions, but none concerns Java specifically. I couldn't apply these solutions because most used gotos.</p> <p>I don't want to put the inner loop in a different method.</p> <p>I don't want to return the loops. When breaking I'm finished with the execution of the loop block.</p>
886,979
36
0
null
2009-05-20 09:07:43.643 UTC
436
2021-12-06 06:35:30.897 UTC
2021-12-06 06:35:30.897 UTC
null
6,444,297
null
15,108
null
1
2,004
java|loops|nested-loops
1,331,657
<p>Like other answerers, I'd definitely <em>prefer</em> to put the loops in a different method, at which point you can just return to stop iterating completely. This answer just shows how the requirements in the question can be met.</p> <p>You can use <code>break</code> with a label for the outer loop. For example:</p> <pre><code>public class Test { public static void main(String[] args) { outerloop: for (int i=0; i &lt; 5; i++) { for (int j=0; j &lt; 5; j++) { if (i * j &gt; 6) { System.out.println("Breaking"); break outerloop; } System.out.println(i + " " + j); } } System.out.println("Done"); } } </code></pre> <p>This prints:</p> <pre><code>0 0 0 1 0 2 0 3 0 4 1 0 1 1 1 2 1 3 1 4 2 0 2 1 2 2 2 3 Breaking Done </code></pre>
450,799
Shell command to sum integers, one per line?
<p>I am looking for a command that will accept (as input) multiple lines of text, each line containing a single integer, and output the sum of these integers.</p> <p>As a bit of background, I have a log file which includes timing measurements. Through grepping for the relevant lines and a bit of <code>sed</code> reformatting I can list all of the timings in that file. I would like to work out the total. I can pipe this intermediate output to any command in order to do the final sum. I have always used <code>expr</code> in the past, but unless it runs in RPN mode I do not think it is going to cope with this (and even then it would be tricky).</p> <p>How can I get the summation of integers?</p>
450,821
45
2
2013-10-02 18:41:50.33 UTC
2009-01-16 15:42:03.5 UTC
286
2022-06-23 23:21:44.51 UTC
2019-11-25 07:57:38.937 UTC
J.F. Sebastian
4,021,802
dtsazza
45,664
null
1
1,025
shell
684,625
<p>Bit of awk should do it? </p> <pre><code>awk '{s+=$1} END {print s}' mydatafile </code></pre> <p>Note: some versions of awk have some odd behaviours if you are going to be adding anything exceeding 2^31 (2147483647). See comments for more background. One suggestion is to use <code>printf</code> rather than <code>print</code>:</p> <pre><code>awk '{s+=$1} END {printf "%.0f", s}' mydatafile </code></pre>
7,007,032
What is the difference between static, internal and public constructors?
<p>What is the difference between static, internal and public constructors? Why do we need to create all of them together?</p> <pre><code> static xyz() { } public xyz() { } internal xyz() { } </code></pre>
7,007,072
5
1
null
2011-08-10 07:06:57.957 UTC
2
2018-12-07 16:28:19.653 UTC
2011-08-10 07:15:54.823 UTC
null
64,976
null
865,053
null
1
28
c#|static|constructor|access-modifiers
28,726
<p>The <code>static</code> constructor will be called the first time an object of the type is instantiated or a static method is called. And will only run once</p> <p>The <code>public</code> constructor is accessible to all other types</p> <p>The <code>internal</code> constructor is only accessible to types in the same assembly</p> <p>On top of these three there's also <code>protected</code> which is only accessible to types derived from the enclosing type</p> <p>and <code>protected internal</code> which is only accessible to types in the same assembly or those that derives from the enclosing type</p> <p>and <code>private</code> which is only accessible from the type itself and any nested types</p>
6,751,463
Iterate over lines in a file in parallel (Scala)?
<p>I know about the parallel collections in Scala. They are handy! However, I would like to iterate over the lines of a file that is too large for memory in parallel. I could create threads and set up a lock over a Scanner, for example, but it would be great if I could run code such as:</p> <pre><code>Source.fromFile(path).getLines.par foreach { line =&gt; </code></pre> <p>Unfortunately, however</p> <pre><code>error: value par is not a member of Iterator[String] </code></pre> <p>What is the easiest way to accomplish some parallelism here? For now, I will read in somes lines and handle them in parallel.</p>
6,753,544
5
4
null
2011-07-19 17:34:06.44 UTC
16
2017-06-09 10:36:48.27 UTC
null
null
null
null
568,393
null
1
35
scala|concurrency|parallel-processing
8,444
<p>You could use grouping to easily slice the iterator into chunks you can load into memory and then process in parallel.</p> <pre><code>val chunkSize = 128 * 1024 val iterator = Source.fromFile(path).getLines.grouped(chunkSize) iterator.foreach { lines =&gt; lines.par.foreach { line =&gt; process(line) } } </code></pre> <p>In my opinion, something like this is the simplest way to do it.</p>
6,715,095
How to SUM and SUBTRACT using SQL?
<p>I am using MySQL and I have two tables:</p> <p><code>master_table</code></p> <ul> <li>ORDERNO </li> <li>ITEM</li> <li>QTY</li> </ul> <p><code>stock_bal</code> </p> <ul> <li>ITEM </li> <li>BAL_QTY</li> </ul> <p>Master table has duplicate <code>ORDERNO</code> and <code>ITEM</code> values. I have get total <code>QTY</code> using SQL 'GROUP BY' clause.</p> <p>I need to deduct/subtract <code>BAL_QTY</code> from SUM of <code>ITEM</code> (master_table). I've got SUM <code>QTY</code> value using query (actually there are many rows).</p>
6,715,121
6
0
null
2011-07-16 03:23:56.997 UTC
10
2020-01-16 17:21:31.07 UTC
2012-10-22 14:37:21.733 UTC
null
489,560
null
847,415
null
1
42
mysql|sql|aggregate-functions
498,115
<p>I think this is what you're looking for. <code>NEW_BAL</code> is the sum of <code>QTY</code>s subtracted from the balance:</p> <pre><code>SELECT master_table.ORDERNO, master_table.ITEM, SUM(master_table.QTY), stock_bal.BAL_QTY, (stock_bal.BAL_QTY - SUM(master_table.QTY)) AS NEW_BAL FROM master_table INNER JOIN stock_bal ON master_bal.ITEM = stock_bal.ITEM GROUP BY master_table.ORDERNO, master_table.ITEM </code></pre> <p>If you want to update the item balance with the new balance, use the following:</p> <pre><code>UPDATE stock_bal SET BAL_QTY = BAL_QTY - (SELECT SUM(QTY) FROM master_table GROUP BY master_table.ORDERNO, master_table.ITEM) </code></pre> <p>This assumes you posted the subtraction backward; it subtracts the quantities in the order from the balance, which makes the most sense without knowing more about your tables. Just swap those two to change it if I was wrong:</p> <pre><code>(SUM(master_table.QTY) - stock_bal.BAL_QTY) AS NEW_BAL </code></pre>
6,825,713
HTML5: W3C vs WHATWG. Which gives the most authoritative spec?
<p>I'm in halfway trough an html parser and found html5 defined <strong>explicitly</strong> the rules of thumb for parsing <em>ill formed html</em>. <em>(And I used to infer them from DTDs, sigh)</em></p> <p>I love that fact, but I know well that html5 isn't finalized yet (also I wonder if it ever will) and that it isn't developed by the W3C, but by the WHATWG.</p> <p>Searching for the spec I need I'm presented with:</p> <ul> <li>8.2 section of the <strong>W3C</strong> <em>TR</em><br> <a href="http://www.w3.org/TR/html5/syntax.html#parsing" rel="noreferrer">http://www.w3.org/TR/html5/syntax.html#parsing</a></li> </ul> <p>or</p> <ul> <li>11.2 section of the <strong>WHATWG</strong> <em>web-apps/current-work</em><br> <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html" rel="noreferrer">http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html</a></li> </ul> <p>If it wasn't for the section numbers I would induce those are simply the same. But the different numbering makes me wonder. <em>Which version is, supposedly, the most authoritative?</em></p> <p>WHATWG seems to have more sections, and to have been <em>added to</em> since W3C uploaded its candidate recommendation.</p> <p>Will W3C update to the WHATWG version?<br> Or will they stick to their current candidate until it gets to the official recommendation status?</p> <p><strong>Which html5 spec are we poor devils supposed to follow, when in doubt?</strong></p>
6,826,506
6
3
null
2011-07-26 05:38:48.223 UTC
19
2022-05-04 16:12:50.337 UTC
2014-10-30 01:46:24.45 UTC
null
169,922
null
169,922
null
1
68
html|html-parsing|w3c
14,974
<p>It depends on who you ask. Really. The politics of this are ugly. And to make matters worse, the specifications aren't fully stable yet. I would have thought that the two specifications would be largely the same in their parsing sections since <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/introduction.html#how-do-the-whatwg-and-w3c-specifications-differ?" rel="noreferrer">section 1.1.1</a> which lists the differences does not mention parsing. But then I did a web diff and I saw that there are subtle differences in the text. I would say that if you are actually implementing the specification to talk to the players involved about any differences you see between the specs, using the public mailing lists. Anyway, I am sorry I can't give you a clear cut answer.</p>
6,697,147
JSON - Iterate through JSONArray
<p>I have a JSON file with some arrays in it. I want to iterate through the file arrays and get their elements and their values.</p> <p><strong>This is how my file looks like:</strong></p> <pre><code>{ &quot;JObjects&quot;: { &quot;JArray1&quot;: [ { &quot;A&quot;: &quot;a&quot;, &quot;B&quot;: &quot;b&quot;, &quot;C&quot;: &quot;c&quot; }, { &quot;A&quot;: &quot;a1&quot;, &quot;B&quot;: &quot;b2&quot;, &quot;C&quot;: &quot;c3&quot;, &quot;D&quot;: &quot;d4&quot; &quot;E&quot;: &quot;e5&quot; }, { &quot;A&quot;: &quot;aa&quot;, &quot;B&quot;: &quot;bb&quot;, &quot;C&quot;: &quot;cc&quot;, &quot;D&quot;: &quot;dd&quot; } ] } } </code></pre> <p><strong>This is how far I have come:</strong></p> <pre><code>JSONObject object = new JSONObject(&quot;json-file.json&quot;); JSONObject getObject = object.getJSONObject(&quot;JObjects&quot;); JSONArray getArray = getObject.getJSONArray(&quot;JArray1&quot;); for(int i = 0; i &lt; getArray.length(); i++) { JSONObject objects = getArray.getJSONArray(i); //Iterate through the elements of the array i. //Get thier value. //Get the value for the first element and the value for the last element. } </code></pre> <p>Is it possible to do something like this?</p> <p>The reason I want to do it like this is because the arrays in the file have a different number of elements.</p>
6,697,385
6
2
null
2011-07-14 17:01:29.943 UTC
27
2021-09-06 13:19:20.817 UTC
2021-08-12 16:59:08.333 UTC
null
12,363,493
null
776,679
null
1
79
java|json
370,205
<p>Change</p> <pre><code>JSONObject objects = getArray.getJSONArray(i); </code></pre> <p>to</p> <pre><code>JSONObject objects = getArray.getJSONObject(i); </code></pre> <p>or to</p> <pre><code>JSONObject objects = getArray.optJSONObject(i); </code></pre> <p>depending on which JSON-to/from-Java library you're using. (It looks like <code>getJSONObject</code> will work for you.)</p> <p>Then, to access the string elements in the "objects" <code>JSONObject</code>, get them out by element name.</p> <pre><code>String a = objects.get("A"); </code></pre> <p>If you need the names of the elements in the <code>JSONObject</code>, you can use the static utility method <code>JSONObject.getNames(JSONObject)</code> to do so.</p> <pre><code>String[] elementNames = JSONObject.getNames(objects); </code></pre> <blockquote> <p>"Get the value for the first element and the value for the last element."</p> </blockquote> <p>If "element" is referring to the component in the array, note that the first component is at index 0, and the last component is at index <code>getArray.length() - 1</code>.</p> <hr> <blockquote> <p>I want to iterate though the objects in the array and get thier component and thier value. In my example the first object has 3 components, the scond has 5 and the third has 4 components. I want iterate though each of them and get thier component name and value.</p> </blockquote> <p>The following code does exactly that.</p> <pre><code>import org.json.JSONArray; import org.json.JSONObject; public class Foo { public static void main(String[] args) throws Exception { String jsonInput = "{\"JObjects\":{\"JArray1\":[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\"},{\"A\":\"a1\",\"B\":\"b2\",\"C\":\"c3\",\"D\":\"d4\",\"E\":\"e5\"},{\"A\":\"aa\",\"B\":\"bb\",\"C\":\"cc\",\"D\":\"dd\"}]}}"; // "I want to iterate though the objects in the array..." JSONObject outerObject = new JSONObject(jsonInput); JSONObject innerObject = outerObject.getJSONObject("JObjects"); JSONArray jsonArray = innerObject.getJSONArray("JArray1"); for (int i = 0, size = jsonArray.length(); i &lt; size; i++) { JSONObject objectInArray = jsonArray.getJSONObject(i); // "...and get thier component and thier value." String[] elementNames = JSONObject.getNames(objectInArray); System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", elementNames.length); for (String elementName : elementNames) { String value = objectInArray.getString(elementName); System.out.printf("name=%s, value=%s\n", elementName, value); } System.out.println(); } } } /* OUTPUT: 3 ELEMENTS IN CURRENT OBJECT: name=A, value=a name=B, value=b name=C, value=c 5 ELEMENTS IN CURRENT OBJECT: name=D, value=d4 name=E, value=e5 name=A, value=a1 name=B, value=b2 name=C, value=c3 4 ELEMENTS IN CURRENT OBJECT: name=D, value=dd name=A, value=aa name=B, value=bb name=C, value=cc */ </code></pre>
42,203,169
How to implement XUnit descriptive Assert message?
<p><strong>Context</strong></p> <p>in XUnit github I found this: <a href="https://github.com/xunit/xunit/issues/350" rel="noreferrer">Add Assert.Equal(expected, actual, message) overload #350</a> <em>(so a developer ask for a non existing overload see below)</em></p> <p>Quote from the answer:</p> <blockquote> <p>We are a believer in self-documenting code; that includes your assertions.</p> </blockquote> <p><em>(so the XUnit team rejects it)</em></p> <p>OK, I got it. I also believe the self documenting code. Still I can not find out this use case:</p> <p><strong>Sample</strong></p> <pre><code>// Arrange // Create some external soap service client and its wrapper classes // Act // client.SomeMethod(); // Assert // Sorry, soap service's interface, behaviour and design is *given* // So I have to check if there is no Error, and // conveniently if there is, then I would like to see it in the assertion message Assert.Equal(0, client.ErrorMessage.Length); // Means no error // I would like to have the same result what would be the following *N*U*n*i*t* assert: // Assert.AreEqual(0, client.ErrorMessage.Length, client.ErrorMessage); // Means no error </code></pre> <p><strong>Question</strong></p> <p>How can I implement a descriptive assert message in this case in XUnit which still has no such an overload?</p>
42,204,780
4
7
null
2017-02-13 11:39:19.387 UTC
7
2022-09-17 11:15:59.493 UTC
2017-02-13 13:12:42.48 UTC
null
5,233,410
null
1,157,814
null
1
56
c#|unit-testing|xunit|assertions|xunit2
37,373
<p>Use the suggestions provided at the link. Like <a href="http://www.fluentassertions.com/" rel="noreferrer">fluent assertions</a> or create your own assertion that wraps the <code>Assert.True or Assert.False</code> which were left with their message overloads. It was mentioned further down </p> <p><a href="https://github.com/xunit/xunit/issues/350#issuecomment-199982253" rel="noreferrer">Quote</a></p> <blockquote> <p>You can provide messages to Assert.True and .False. If you simply cannot live without messages (and refuse to use a different assertion), you could always fall back to:</p> <pre><code>Assert.True(number == 2, "This is my message"); </code></pre> </blockquote> <p><a href="https://github.com/xunit/xunit/issues/350#issuecomment-78211410" rel="noreferrer">Quote:</a></p> <blockquote> <p>If you really want to have messages you could add <a href="http://www.fluentassertions.com/" rel="noreferrer">Fluent Assertions</a> or maybe <a href="https://github.com/xbehave/xbehave.net/wiki/Writing-scenarios" rel="noreferrer">xbehave</a> to your test projects and use their syntax. Fluent Assertions even throws xunit.net exceptions if it encounters its presence.</p> </blockquote>
38,202,039
JSON properties now lower case on swap from ASP .Net Core 1.0.0-rc2-final to 1.0.0
<p>I've just swapped our project from ASP .Net Core 1.0.0-rc2-final to 1.0.0. Our website and client have stopped working because of the capitalization of JSON properties. For example, this line of JavaScript now fails </p> <pre><code>for (var i = 0; i &lt; collection.Items.length; i++){ </code></pre> <p>because the controller now calls the array "items" instead of "Items". I have made no changes beyond installing the updated packages and editing the project.json file. I have not changed the C# model files which still capitalize their properties.</p> <p>Why have the ASP.Net Core controllers started returning JSON with lower-cased properties? How do I go back to them honoring the case of the property names from the model?</p>
38,202,543
8
2
null
2016-07-05 11:15:00.3 UTC
14
2020-12-03 09:36:22.643 UTC
2020-01-14 20:26:37.703 UTC
null
70,345
null
575,530
null
1
124
c#|asp.net-core|asp.net-core-1.0
63,779
<p>MVC now serializes JSON with camel case names by default</p> <p>Use this code to avoid camel case names by default</p> <pre><code> services.AddMvc() .AddJsonOptions(options =&gt; options.SerializerSettings.ContractResolver = new DefaultContractResolver()); </code></pre> <p>Source: <a href="https://github.com/aspnet/Announcements/issues/194">https://github.com/aspnet/Announcements/issues/194</a></p>
15,932,492
iPad - Parsing an extremely huge json - File (between 50 and 100 mb)
<p>I'm trying to parse an extremely big json-File on an iPad. The filesize will vary between 50 and 100 mb (there is an initial file and there will be one new full set of data every month, which will be downloaded, parsed and saved into coredata)</p> <p>I'm building this app for a company as an Enterprise solution - the json file contains sensitive customerdata and it needs to be saved locally on the ipad so it will work even offline. It worked when the file was below 20mb, but now the set of data became bigger and I really need to parse it. I'm receiving memory warnings during parsing and after the third warning it just crashes. I have several different Core Data entities and I'm just setting all the values coming from the json file (when app is launched for the first time) and after everything is done, I'm doing the <code>[context save]</code>.</p> <p>I was hoping somebody could give me some advice on how to handle such huge files. I was thinking about splitting the json file up to several smaller json files and maybe parsing them in multiple threads, but I don't know if that's the right approach. I guess one big problem is that the whole file is being held in the memory - maybe there's some way of "streaming" it into the memory or something like that?</p> <p>I'm using JSONKit (<a href="https://github.com/johnezang/JSONKit">https://github.com/johnezang/JSONKit</a>) for parsing the file, since I have read that it's the fastest one (maybe there's a slower one which goes easier on memory?). </p> <p>Thanks in advance.</p>
15,932,917
2
7
null
2013-04-10 17:26:34.213 UTC
10
2014-12-08 21:00:50.053 UTC
null
null
null
null
2,139,309
null
1
16
ios|json|ipad|core-data|bigdata
9,406
<p>1) Write your data to a file, then use NSData's <strong>dataWithContentsOfFile:options:error:</strong> and specify the <strong>NSDataReadingMappedAlways</strong> and <strong>NSDataReadingUncached</strong> flags. This will tell the system to use mmap() to reduce the memory footprint, and not to burden the file system cache with blocks of memory (that makes it slower, but much less of a burden to iOS).</p> <p>2) You can use the <a href="https://github.com/gabriel/yajl-objc" rel="noreferrer">YAJL SAX style JSON parser</a> to get objects as they decode.</p> <p>Note: I have not done 2) but have used the techniques embodied in 1).</p> <p>3) I ended up needed such a thing myself, and wrote <a href="https://github.com/dhoerl/SAX-JSON-Parser-ForStreamingData" rel="noreferrer">SAX-JSON-Parser-ForStreamingData</a> that can be tied to any asynchronous downloader (including my own).</p>
15,926,005
How make JUnit print assertion results
<p>How can I get the results of my JUnit assertions to be printed [to standard output]?</p> <p>I have some tests like this:</p> <pre><code>@Test public void test01() { Position p = getPositionAt('a', 1); assertNotNull(&quot;a1 exists&quot;, p); assertNotNull(&quot;figure exists a1&quot;, p.getFigure()); p = getPositionAt('a', 2); assertNotNull(&quot;exists a2&quot;, p); assertNull(&quot;figure exists a2&quot;, p.getFigure()); p = getPositionAt('b', 1); assertNotNull(&quot;exists b1&quot;, p); assertNull(&quot;figure exists b1&quot;, p.getFigure()); } </code></pre> <p>This is the printed output format I am hoping to get:</p> <pre><code>a1 exists -success figure exists a1 -success exists a2 -success figure exists a2 -succcess exists b1 -succcess figure exists b1 -failed </code></pre> <p>Is there way to do this using <code>runners</code> and <code>suites</code>? Or does there exist any <code>assertSuccess()</code>, <code>assertFailed()</code> methods?</p>
15,926,172
4
4
null
2013-04-10 12:35:05.663 UTC
9
2020-06-29 00:31:03.337 UTC
2020-06-29 00:18:58.49 UTC
null
1,357,094
null
1,763,888
null
1
35
java|testing|junit|junit4
85,363
<p>First, you have two issues not one. When an assertion fails, an <code>AssertionError</code> exception is thrown. This prevents any assertion past this point from being checked. To address this you need to use an <a href="http://junit-team.github.io/junit/javadoc/latest/org/junit/rules/ErrorCollector.html" rel="nofollow noreferrer">ErrorCollector</a>.</p> <p>Second, I do not believe there is any way built in to JUnit to do this. However, you could implement your own methods that wrap the assertions:</p> <pre><code>public static void assertNotNull(String description, Object object){ try{ Assert.assertNotNull(description, object); System.out.println(description + " - passed"); }catch(AssertionError e){ System.out.println(description + " - failed"); throw e; } } </code></pre>
15,953,895
Splitting Declaration and Assignment = Good Practice?
<p>Being an avid user of NetBeans, I keep getting suggestions to split my variable declarations and assignments when I introduce a new variable. As a super quick example off the top of my head, let's take this Java line:</p> <pre><code>String someInput = JOptionPane.showInputDialog(null, "- Enter something: "); </code></pre> <p>versus:</p> <pre><code>String someInput; someInput = JOptionPane.showInputDialog(null, "- Enter something: "); </code></pre> <p>NetBeans seems to prefer the latter (I wouldn't know about other IDEs, though). While it clearly works both ways, which would be considered 'good practice', if at all? Or s it purely a matter of personal preference? </p> <p>(Obviously splitting the two means an extra line that you could've just combined into one, but that's beside the point.)</p>
15,953,960
6
12
null
2013-04-11 16:18:09.323 UTC
7
2014-11-23 20:03:55.387 UTC
null
null
null
null
2,128,915
null
1
36
java|variables|variable-assignment|declaration
21,084
<p>There's no reason to split the declaration and the assignment if you're just going to have them on consecutive lines. I'd only split them if the assignment were conditional, or if it needed to go in a separate code block (like a try/catch, or if the assignment goes in a constructor, etc.).</p>
15,767,685
Understanding Heroku server status 143
<p>I'm wondering about Heroku server status and can't find any documentation about this topic.</p> <p>Example: </p> <pre><code>Process exited with status 143 </code></pre> <p>Can anyone explain this example? And where would I find resources for future reference?</p>
15,773,335
7
0
null
2013-04-02 15:11:01.093 UTC
14
2022-08-12 06:56:11.29 UTC
2015-07-03 16:39:51.59 UTC
null
949,598
null
2,213,842
null
1
106
heroku|deployment|server-side
78,718
<p>Exit code 143 means that your process was terminated by a SIGTERM. This is generally sent when you do any commands that require your dynos to restart (config:set, restart, scale down...). </p>
10,366,374
What is the 'pythonic' equivalent to the 'fold' function from functional programming?
<p>What is the most idiomatic way to achieve something like the following, in Haskell:</p> <pre><code>foldl (+) 0 [1,2,3,4,5] --&gt; 15 </code></pre> <p>Or its equivalent in Ruby:</p> <pre><code>[1,2,3,4,5].inject(0) {|m,x| m + x} #&gt; 15 </code></pre> <p>Obviously, Python provides the <code>reduce</code> function, which is an implementation of fold, exactly as above, however, I was told that the 'pythonic' way of programming was to avoid <code>lambda</code> terms and higher-order functions, preferring list-comprehensions where possible. Therefore, is there a preferred way of folding a list, or list-like structure in Python that isn't the <code>reduce</code> function, or is <code>reduce</code> the idiomatic way of achieving this?</p>
10,366,417
8
6
null
2012-04-28 18:30:48.82 UTC
22
2019-09-21 00:30:14.223 UTC
2012-04-28 18:44:17.063 UTC
null
1,219,006
null
413,744
null
1
164
python|list|functional-programming|reduce|fold
130,245
<p>The Pythonic way of summing an array is using <a href="https://docs.python.org/3/library/functions.html#sum" rel="noreferrer"><code>sum</code></a>. For other purposes, you can sometimes use some combination of <a href="https://docs.python.org/3/library/functools.html#functools.reduce" rel="noreferrer"><code>reduce</code></a> (from the <a href="https://docs.python.org/3/howto/functional.html#the-functools-module" rel="noreferrer"><code>functools</code></a> module) and the <a href="https://docs.python.org/3/library/operator.html#module-operator" rel="noreferrer"><code>operator</code></a> module, e.g.:</p> <pre><code>def product(xs): return reduce(operator.mul, xs, 1) </code></pre> <p>Be aware that <code>reduce</code> is actually a <code>foldl</code>, in Haskell terms. There is no special syntax to perform folds, there's no builtin <code>foldr</code>, and actually using <code>reduce</code> with non-associative operators is considered bad style.</p> <p>Using higher-order functions is quite pythonic; it makes good use of Python's principle that everything is an object, including functions and classes. You are right that lambdas are frowned upon by some Pythonistas, but mostly because they tend not to be very readable when they get complex.</p>
33,446,347
No module named 'pymysql'
<p>I'm trying to use PyMySQL on Ubuntu.</p> <p>I've installed <code>pymysql</code> using both <code>pip</code> and <code>pip3</code> but every time I use <code>import pymysql</code>, it returns <code>ImportError: No module named 'pymysql'</code></p> <p>I'm using Ubuntu 15.10 64-bit and Python 3.5.</p> <p>The same .py works on Windows with Python 3.5, but not on Ubuntu.</p>
33,446,502
20
7
null
2015-10-30 23:34:19.49 UTC
7
2022-09-19 02:45:07.36 UTC
2015-10-31 00:42:15.713 UTC
null
530,873
null
4,621,575
null
1
69
python|python-3.x|ubuntu|pymysql
210,243
<p>Sort of already answered this in the comments, but just so this question has an answer, the problem was resolved through running:</p> <pre><code>sudo apt-get install python3-pymysql </code></pre>
40,794,471
ffmpeg throwing "Output file #0 does not contain any stream" when trying to make a slideshow out of images
<p>Im trying to create video streaming using phantomjs that create screenshots from a url then it will pipe the frames to ffmpeg so he can use it to stream the video to an rtmp url . here is what i tried so far :</p> <pre><code>phantomjs runner.js | ffmpeg -f image2pipe -vcodec png -c:a copy -c:v libx264 -f flv rtmp://localhost/mystream </code></pre> <p>and here is the script : </p> <pre><code>var page = require('webpage').create(); page.viewportSize = { width: 640, height: 480 }; page.open('http://www.goodboydigital.com/pixijs/examples/12-2/', function () { setInterval(function() { page.render('/dev/stdout', { format: "png" }); }, 25); }); </code></pre> <p>and this is the output : </p> <pre><code>ffmpeg version 3.0.2 Copyright (c) 2000-2016 the FFmpeg developers built with Apple LLVM version 7.3.0 (clang-703.0.29) configuration: --prefix=/usr/local/Cellar/ffmpeg/3.0.2 --enable-shared --enable-pthreads --enable-gpl --enable-version3 --enable-hardcoded-tables --enable-avresample --cc=clang --host-cflags= --host-ldflags= --enable-opencl --enable-libx264 --enable-libmp3lame --enable-libxvid --enable-vda libavutil 55. 17.103 / 55. 17.103 libavcodec 57. 24.102 / 57. 24.102 libavformat 57. 25.100 / 57. 25.100 libavdevice 57. 0.101 / 57. 0.101 libavfilter 6. 31.100 / 6. 31.100 libavresample 3. 0. 0 / 3. 0. 0 libswscale 4. 0.100 / 4. 0.100 libswresample 2. 0.101 / 2. 0.101 libpostproc 54. 0.100 / 54. 0.100 Output #0, flv, to 'rtmp://localhost/mystream': Output file #0 does not contain any stream </code></pre>
40,801,706
1
8
null
2016-11-24 21:05:10.58 UTC
3
2020-07-27 04:24:36.227 UTC
2016-11-25 09:20:26.767 UTC
null
187,606
null
2,233,585
null
1
28
ffmpeg|phantomjs|video-streaming|rtmp
79,061
<p>Your present command doesn't specify any input, so use</p> <pre><code>phantomjs runner.js | ffmpeg -f image2pipe -i pipe:.png -c:a copy -c:v libx264 -f flv rtmp://localhost/mystream </code></pre> <p>There's no audio input, so setting an audio codec is pointless. If your output needs an audio stream, use</p> <pre><code>phantomjs runner.js | ffmpeg -f image2pipe -i pipe:.png -f lavfi -i anullsrc -c:v libx264 -c:a aac -f flv rtmp://localhost/mystream </code></pre>
22,741,183
Sqoop: Could not load mysql driver exception
<p>I Installed Sqoop in my local machine. Following are the config information.</p> <p>Bash.bashrc:</p> <pre><code>export HADOOP_HOME=/home/hduser/hadoop export HBASE_HOME=/home/hduser/hbase export HIVE_HOME=/home/hduser/hive export HCAT_HOME=/home/hduser/hive/hcatalog export SQOOP_HOME=/home/hduser/sqoop export PATH=$PATH:$HIVE_HOME/bin export PATH=$PATH:$HADOOP_HOME/bin export PATH=$PATH:$HBASE_HOME/bin export PATH=$PATH:$SQOOP_HOME/bin export PATH=$PATH:$HCAT_HOME/bin </code></pre> <p>Hadoop:</p> <pre><code>Version: Hadoop 1.0.3 </code></pre> <p>Hive:</p> <pre><code>Version: hive 0.11.0 </code></pre> <p>Mysql Connector driver</p> <pre><code>version: mysql-connector-java-5.1.29 "The driver is copied to the lib folder of sqoop" </code></pre> <p>Sqoop : </p> <pre><code>version: sqoop 1.4.4 </code></pre> <p>After making all the installation I create a table in mysql named practice_1, But when I run the load command to load data from mysql to hdfs the command throws an exception:</p> <pre><code>ERROR sqoop.Sqoop: Got exception running Sqoop: java.lang.RuntimeException: Could not load db driver class: com.mysql.jdbc.Driver </code></pre> <p>Coud anyone please guide me what can be the possible problem.</p>
22,753,480
7
2
null
2014-03-30 06:53:47 UTC
1
2019-03-28 12:07:15.33 UTC
2014-03-30 07:03:29.093 UTC
null
13,302
null
2,404,193
null
1
5
mysql|hadoop|hive|sqoop
38,809
<p>You need database driver in 'SQOOP' classpath check <a href="http://sqoop.apache.org/docs/1.4.0-incubating/SqoopUserGuide.html#id1763114" rel="noreferrer">this</a> It has wonderful explanation about the 'SQOOP'</p> <p>SQOOP has other options like</p> <blockquote> <p>Ex: --driver com.microsoft.jdbc.sqlserver.SQLServerDriver -libjars=".*jar"</p> </blockquote> <p>from <a href="http://sqoop.apache.org/docs/1.4.0-incubating/SqoopUserGuide.html#id1763114" rel="noreferrer">here</a> </p> <blockquote> <p>You can use Sqoop with any other JDBC-compliant database. First, download the appropriate JDBC driver for the type of database you want to import, and install the .jar file in the $SQOOP_HOME/lib directory on your client machine. (This will be /usr/lib/sqoop/lib if you installed from an RPM or Debian package.) Each driver .jar file also has a specific driver class which defines the entry-point to the driver. For example, MySQL's Connector/J library has a driver class of com.mysql.jdbc.Driver. Refer to your database vendor-specific documentation to determine the main driver class. This class must be provided as an argument to Sqoop with --driver.</p> </blockquote> <p>You may be interested in understanding the difference between connector and driver <a href="https://blogs.apache.org/sqoop/entry/connectors_and_drivers_in_the" rel="noreferrer">here</a> is the article </p>
22,591,499
What are the differences between abstract classes and interfaces in Java 8?
<p>In Java there used to be a subtle but important difference between abstract classes and interfaces: <a href="https://stackoverflow.com/questions/1913098/what-is-the-difference-between-an-interface-and-abstract-class">default implementations</a>. Abstract classes could have them, interfaces could not. Java 8 though introduces default implementations for interfaces, meaning this is no longer the critical difference between an interface and an abstract class.</p> <p>So what is?</p> <p>As best as I can tell, the only remaining difference (besides perhaps some under the hood efficiency stuff) is that abstract classes follow traditional Java single-inheritance, whereas interfaces can have multiple-inheritance (or multiple-implementation if you will). This leads me to another question - </p> <p>How do the new Java 8 interfaces avoid the <a href="http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem" rel="noreferrer">diamond Problem</a>?</p>
22,591,531
5
3
null
2014-03-23 13:25:18.667 UTC
24
2016-11-20 02:45:59.91 UTC
2017-05-23 12:26:10.503 UTC
null
-1
null
1,305,516
null
1
67
java|interface|abstract-class|java-8|diamond-problem
19,644
<p>Interfaces cannot have state associated with them.</p> <p>Abstract classes can have state associated with them.</p> <p>Furthermore, default methods in interfaces need not be implemented. So in this way, it will not break already existing code, as while the interface does receive an update, the implementing class does not need to implement it.<br> As a result you may get suboptimal code, but if you want to have more optimal code, then your job is to override the default implementation.</p> <p>And lastly, in case a diamond problem occurs, then the compiler will warn you, and <em>you</em> will need to choose which interface you want to implement.</p> <p>To show more about the diamond problem, consider the following code:</p> <pre><code>interface A { void method(); } interface B extends A { @Override default void method() { System.out.println("B"); } } interface C extends A { @Override default void method() { System.out.println("C"); } } interface D extends B, C { } </code></pre> <p>Here I get the compiler error on <code>interface D extends B, C</code>, that:</p> <p><code>interface D inherits unrelated defaults for method() form types B and C</code></p> <p>The fix is:</p> <pre><code>interface D extends B, C { @Override default void method() { B.super.method(); } } </code></pre> <p>In case I wanted to inherit the <code>method()</code> from <code>B</code>.<br> The same holds for if <code>D</code> were a <code>class</code>.</p> <p>To show even more about the difference between interfaces and abstract classes in Java 8, consider the following <code>Team</code>:</p> <pre><code>interface Player { } interface Team { void addPlayer(Player player); } </code></pre> <p>You can in theory provide a default implementation of <code>addPlayer</code> such that you can add players to for example a list of players.<br> But wait...?<br> How do I store the list of players?<br> The answer is that you cannot do that in an interface, even if you have default implementations available.</p>
13,649,872
Can I make an svg image button?
<p>Is there any way of making a POST request when an svg image is clicked?</p> <p>My best attempt so far looks like:</p> <pre><code>&lt;form action="/test-button" method="POST"&gt; &lt;input name="Submit" type="submit" value="Submit" /&gt; &lt;svg &gt; &lt;rect width="100" height="100" &gt; &lt;/svg&gt; &lt;/form&gt; </code></pre> <p>Which is a black rectangle with a submit button next to it.</p> <p>I want to allow people to choose between several images, so this may be an ok solution, but is there any way of making an image which, when clicked, will fire off a POST?</p> <p>Extra points for not using javascript.</p>
13,650,140
6
0
null
2012-11-30 17:14:16.873 UTC
7
2022-01-05 04:06:50.283 UTC
null
null
null
null
254,837
null
1
22
html|post|button|svg
45,328
<p>Warning: This is a little hacky, but as far as I know it's 100% legit, and doesn't need javascript.</p> <p>Since the <code>label</code> element can also be used to control it's associated input, you could try something like this:</p> <pre><code>&lt;form action="/test-button" method="POST"&gt; &lt;label&gt; &lt;input type="submit" name="image" value="one"&gt; &lt;svg&gt;&lt;rect width="100" height="100"&gt;&lt;/rect&gt;&lt;/svg&gt; &lt;/label&gt; &lt;label&gt; &lt;input type="submit" name="image" value="two"&gt; &lt;svg&gt;&lt;rect width="100" height="100"&gt;&lt;/rect&gt;&lt;/svg&gt; &lt;/label&gt; &lt;/form&gt; ​ </code></pre> <p>Then hide the submit buttons with CSS. You can put anything in the label that you want.</p> <p>When you click on whatever's in the label, it will trigger the submit button inside it and submit the form, with the button's <code>value</code> in the POST array.</p> <p>There is also an <code>&lt;input type="image"&gt;</code>, but that's for an entirely different purpose (tracking coordinates of where it was clicked).</p>
13,382,609
In SQL Server can you find the first number in a string?
<p>I have a varchar(50) sql server column with data like this:</p> <pre><code>RawData ---------------------------- Washington 40 New Orleans 32 Detroit 27 St. Louis 23 </code></pre> <p>I'm trying to parse out the data so I have something like this:</p> <pre><code>WinningTeam WinningTeamScore LosingTeam LosingTeamScore ----------- ---------------- ---------- --------------- Washington 40 New Orleans 32 Detroit 27 St. Louis 23 </code></pre> <p>I'm stuck. I was going to use charindex to find the first space, however some city names (St. Louis, New York, etc) have spaces in the names. </p> <p>Is there a way to identify the position of the first number in a string?</p> <p>Thanks</p>
13,382,874
5
2
null
2012-11-14 16:11:59.61 UTC
3
2014-11-18 22:46:50.153 UTC
null
null
null
null
110,701
null
1
25
sql-server|string
106,394
<p>You can use the PATINDEX function instead of CHARINDEX, <a href="http://msdn.microsoft.com/library/ms188395.aspx">here</a> lies the documentation ;)</p>
13,538,772
How to replace space with comma using sed?
<p>I would like to replace the empty space between each and every field with comma delimiter.Could someone let me know how can I do this.I tried the below command but it doesn't work.thanks.</p> <pre><code>My command: :%s//,/ 53 51097 310780 1 56 260 1925 1 68 51282 278770 1 77 46903 281485 1 82 475 2600 1 84 433 3395 1 96 212 1545 1 163 373819 1006375 1 204 36917 117195 1 </code></pre>
13,538,795
8
2
null
2012-11-24 06:03:40.107 UTC
5
2019-05-21 19:27:40.437 UTC
2014-06-24 05:59:58.943 UTC
null
1,734,130
null
1,049,893
null
1
32
regex|unix|vim|replace|sed
152,892
<p>If you are talking about <code>sed</code>, this works:</p> <pre><code>sed -e "s/ /,/g" &lt; a.txt </code></pre> <p>In <code>vim</code>, use same regex to replace:</p> <pre><code>s/ /,/g </code></pre>
13,595,610
Gradle nested multi-projects with project compile dependencies
<p>I have an identical problem to this <a href="https://stackoverflow.com/questions/9013597/gradle-multi-module-project-setup">Gradle Multi-Module Project Setup</a> but I have to use project compile dependencies to build and cannot use the library(jar) dependencies solution that was given as a solution in the above question.</p> <pre><code>Root |__ P1 | |_ PP1 | |_ PP2 | |__ P2 |_PP3 |_PP4 </code></pre> <p>PP1, PP2, PP3 and PP4 are sub-projects and each have their own build.gradle files; P1 and P2 also have build.gradle and settings.gradle files. </p> <p>How can I declare PP1 as a compile dependency in PP3's build.gradle file?</p> <pre><code>apply plugin: 'java' dependencies { compile('P1:PP1') //does not work compile group: 'P1', name: 'PP1', version: '0.1' // jar library dependency not an option compile('{ant_target}')? //follow up question - an ant target as a dependency } </code></pre> <p>I'm running Gradle v1.2</p>
13,598,904
1
1
null
2012-11-28 00:14:47.763 UTC
6
2018-03-22 18:18:19.153 UTC
2017-05-23 12:17:40.393 UTC
null
-1
null
1,017,642
null
1
35
build|dependencies|gradle|multi-project
43,531
<p>A build can only have a single <code>settings.gradle</code> file. Assuming <code>settings.gradle</code> is in the root directory and includes projects like so:</p> <pre><code>include "P1:PP1" </code></pre> <p>You can add a compile dependency like so:</p> <pre><code>dependencies { compile(project(":P1:PP1")) } </code></pre> <p>For more information, see the "Multi-Project Builds" chapter in the <a href="http://gradle.org/docs/current/userguide/userguide_single.html#javaMultiProject" rel="noreferrer">Gradle User Guide</a>.</p>
13,576,161
convert openCV image into PIL Image in Python (for use with Zbar library)
<p>I'm trying to use the Zbar library's QR code detection methods on images I extract with OpenCV's camera methods. Normally the QR code detection methods work with images (jpg, png, etc.) on my computer, but I guess the captured frames of OpenCV are different.<br> Is there a way of making the captured frame into a PIL Image?</p> <p>Thank you.</p> <pre><code>from PIL import Image import zbar import cv2.cv as cv capture = cv.CaptureFromCAM(1) imgSize = cv.GetSize(cv.QueryFrame(capture)) img = cv.QueryFrame(capture) #SOMETHING GOES HERE TO TURN FRAME INTO IMAGE img = img.convert('L') width, height = img.size scanner = zbar.ImageScanner() scanner.parse_config('enable') zbar_img = zbar.Image(width, height, 'Y800', img.tostring()) # scan the image for barcodes scanner.scan(zbar_img) for symbol in zbar_img: print symbol.data </code></pre>
18,158,998
4
0
null
2012-11-27 01:39:55.483 UTC
5
2019-04-04 17:46:51.59 UTC
null
null
null
null
1,730,215
null
1
36
python|opencv|python-imaging-library|zbar
51,190
<p>With the python CV2, you can also do this:</p> <pre><code>import Image, cv2 cap = cv2.VideoCapture(0) # says we capture an image from a webcam _,cv2_im = cap.read() cv2_im = cv2.cvtColor(cv2_im,cv2.COLOR_BGR2RGB) pil_im = Image.fromarray(cv2_im) pil_im.show() </code></pre>
39,622,173
Can't run "ssh -X" on MacOS Sierra
<p>I just upgraded to MacOS Sierra, and I realized that I can't seem to run the "ssh -X" command in the Terminal anymore. It used to launch xterm windows, but now it's like I didn't even put the -X option anymore. It was working absolutely fine right before I updated. Other than going from OS X Yosemite to MacOS Sierra, I didn't change anything else in the setup.</p> <p>EDIT:</p> <p>As suggested, this is what I found in the debug logs that might be causing this problem.</p> <pre><code>debug1: No xauth program. Warning: untrusted X11 forwarding setup failed: xauth key data not generated </code></pre>
39,835,138
11
5
null
2016-09-21 16:44:09.317 UTC
21
2022-04-05 02:11:26.003 UTC
2016-09-21 18:02:03.953 UTC
null
5,035,553
null
5,035,553
null
1
42
ssh|terminal|xterm|macos-sierra
96,079
<p>I didn't need to reinstall XQuartz, but, based on Matt Widjaja's answer, I came up with a refinement.</p> <ul> <li><code>sudo vi /etc/ssh/ssh_config</code> (This is ssh client config, not sshd_config) <ul> <li>Under the <code>Host *</code> entry add (or add where appropriate per-host) <ul> <li><strong><code>XAuthLocation /usr/X11/bin/xauth</code> (The location of xauth changed in Sierra)</strong></li> <li><code>ServerAliveInterval 60</code> (Pings the server every 60 seconds to keep your ssh connection alive)</li> <li><code>ForwardX11Timeout 596h</code> (Allows untrusted X11 connections beyond the 20 minute default)</li> </ul></li> </ul></li> </ul> <p>No need to restart ssh, except, of course, existing ssh client connections.</p> <p>It sounds like -Y (trusted X11) would be preferable to untrusted. If you switch over to trusted, the ForwardX11Timeout line can probably be removed.</p> <p>The ServerAliveInterval line is also an optional preference.</p> <p>It may also be possible to make these changes in <code>~/.ssh/config</code> (the user's config file) but the permissions have to be correct.</p> <p>EDIT: I removed ForwardX11 and ForwardX11Trusted. They aren't needed and ForwardX11 is less secure and causes problems for git (or other tools using ssh).</p>
24,374,867
Label and Text differences in JavaFX
<p>What is the difference between javafx.scene.text.Text and javafx.scene.control.Label?</p> <p>The documentation says: </p> <ul> <li>Label is a non-editable text control. </li> <li>The Text class defines a node that displays a text.</li> </ul> <p>But the Label class has a method "setText" and "textProperty", therefore is editable.</p>
24,389,619
3
2
null
2014-06-23 20:35:11.037 UTC
9
2018-07-27 23:15:37.933 UTC
null
null
null
null
2,452,287
null
1
64
java|javafx|fxml
33,671
<p>As Harry Blargle pointed out, "non-editable" means "not editable by the user." So both Label and Text are non-editable.</p> <p>Label and Text have different CSS properties. <a href="http://docs.oracle.com/javase/8/javafx/api/javafx/scene/doc-files/cssref.html#label">Label inherits from Labeled, Control, and Region</a>, which means it inherits a great many styleable properties which Text doesn't have. A Label can have alignment, a graphic, a background, a border, a displayed keyboard mnemonic, built-in wrapping, and can be intelligently clipped with an <a href="http://en.wikipedia.org/wiki/Ellipsis">ellipsis</a> ("…").</p> <p>Text can participate in a <a href="http://docs.oracle.com/javase/8/javafx/api/javafx/scene/text/TextFlow.html">TextFlow</a>. (Technically, Label can also, but it is treated as just another embedded control and is not laid out as text.)</p> <p>In general, if you want to show the purpose of an input control by placing one or more words next to it, and/or you want to allow direct keyboard navigation to an input control, you use a Label. If you want to display text content not associated with input, you use Text.</p>
3,814,126
Display AlertDialog as system overlay window from Service
<p>I have issue with displaying AlertDialog from Service. I am able to display custom layout window using Toast or using WindowManager(TYPE_SYSTEM_ALERT or TYPE_SYSTEM_OVERLAY). But, I do not want to use custom layout, I prefer to use nice AlertDialog GUI directly.</p> <p>Scenario:</p> <ul> <li>Running Service. No active Activity present.</li> <li>On some external event, Service sends Notification</li> <li>When user press Notification, Service is informed via PendingIntent and AlertDialog should be displayed (created with <code>AlertDialog.Builder(this)</code>)</li> </ul> <p>Error:</p> <pre><code>ERROR/AndroidRuntime(1063): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application </code></pre> <p>Searching for the answer lead me to impression that I am trying something that is currently not possible (Android 2.2). Or maybe it is.</p>
3,912,748
2
1
null
2010-09-28 15:04:14.68 UTC
13
2014-09-22 23:36:24.75 UTC
2011-09-27 10:26:43.547 UTC
null
760,489
null
423,823
null
1
15
android
17,600
<p>Solution that matches described scenario has been found.</p> <ul> <li><p>New Activity has been created and started from Service. However, it is activity with translucent background. Such activity does not have line <code>super.setContentView()</code> in <code>onCreate()</code>. More important, to ensure transparency</p> <p>@android:style/Theme.Translucent</p></li> </ul> <p>is entered under Theme tag for this activity in AndroidManifest.xml GUI. So, new line added to the manifest xml is</p> <p><code>android:theme="@android:style/Theme.Translucent"</code></p> <ul> <li><p>In <code>onCreate()</code> actual display of AlertDialog occurs</p></li> <li><p>Press on AlertDialog buttons causes Dialog and Activity closing and sending of the Intent (or use of some other means) to deliver result to the Service.</p></li> <li><p>Be sure that you defined setOnDismissListener() for the Dialog (implementation should call finish() on activity). If you do not do that press on the Back key cancels dialog but leaves you in the current activity which is transparent and looks to user like something is really wrong. </p></li> </ul>
3,698,718
What are Google Test, Death Tests
<p>I saw the documentation of that feature is seem pretty major since it's in Google Test overview features and detailed in:<br /> <a href="https://github.com/google/googletest/blob/master/docs/advanced.md#death-tests" rel="nofollow noreferrer">https://github.com/google/googletest/blob/master/docs/advanced.md#death-tests</a></p> <p>They look like standard <code>assert()</code> but they're part of Google Test, so a xUnit testing framework. Therefore, I wonder what the real usage <em>or advantage</em> of using those <strong>death tests</strong> are.</p>
3,698,752
2
0
null
2010-09-13 08:07:37.58 UTC
4
2021-01-29 09:56:40.293 UTC
2021-01-29 09:56:40.293 UTC
null
5,970,163
null
167,897
null
1
32
c++|testing|googletest
34,676
<p>The assertion is there to confirm that a function would bring about program termination if it were executed in the current process (the details explains that the death test is invoked from a subprocess which allows the tests to continue despite the death). This is useful because some code may guarantee program termination / abortion on failure (e.g. if there was an irrecoverable error), and unit tests should confirm that a function adheres to its documented behavior, regardless of what that might be.</p> <p>The description on the wiki page really explains it best:</p> <blockquote> <p>In many applications, there are assertions that can cause application failure if a condition is not met. These sanity checks, which ensure that the program is in a known good state, are there to fail at the earliest possible time after some program state is corrupted. If the assertion checks the wrong condition, then the program may proceed in an erroneous state, which could lead to memory corruption, security holes, or worse. Hence it is vitally important to test that such assertion statements work as expected.</p> </blockquote>
9,166,400
Convert RGBA PNG to RGB with PIL
<p>I'm using PIL to convert a transparent PNG image uploaded with Django to a JPG file. The output looks broken.</p> <h3>Source file</h3> <p><img src="https://i.stack.imgur.com/I2uNe.png" alt="transparent source file"></p> <h3>Code</h3> <pre><code>Image.open(object.logo.path).save('/tmp/output.jpg', 'JPEG') </code></pre> <p>or</p> <pre><code>Image.open(object.logo.path).convert('RGB').save('/tmp/output.png') </code></pre> <h3>Result</h3> <p>Both ways, the resulting image looks like this:</p> <p><img src="https://i.stack.imgur.com/rmlPz.png" alt="resulting file"></p> <p>Is there a way to fix this? I'd like to have white background where the transparent background used to be.</p> <hr> <h1>Solution</h1> <p>Thanks to the great answers, I've come up with the following function collection:</p> <pre><code>import Image import numpy as np def alpha_to_color(image, color=(255, 255, 255)): """Set all fully transparent pixels of an RGBA image to the specified color. This is a very simple solution that might leave over some ugly edges, due to semi-transparent areas. You should use alpha_composite_with color instead. Source: http://stackoverflow.com/a/9166671/284318 Keyword Arguments: image -- PIL RGBA Image object color -- Tuple r, g, b (default 255, 255, 255) """ x = np.array(image) r, g, b, a = np.rollaxis(x, axis=-1) r[a == 0] = color[0] g[a == 0] = color[1] b[a == 0] = color[2] x = np.dstack([r, g, b, a]) return Image.fromarray(x, 'RGBA') def alpha_composite(front, back): """Alpha composite two RGBA images. Source: http://stackoverflow.com/a/9166671/284318 Keyword Arguments: front -- PIL RGBA Image object back -- PIL RGBA Image object """ front = np.asarray(front) back = np.asarray(back) result = np.empty(front.shape, dtype='float') alpha = np.index_exp[:, :, 3:] rgb = np.index_exp[:, :, :3] falpha = front[alpha] / 255.0 balpha = back[alpha] / 255.0 result[alpha] = falpha + balpha * (1 - falpha) old_setting = np.seterr(invalid='ignore') result[rgb] = (front[rgb] * falpha + back[rgb] * balpha * (1 - falpha)) / result[alpha] np.seterr(**old_setting) result[alpha] *= 255 np.clip(result, 0, 255) # astype('uint8') maps np.nan and np.inf to 0 result = result.astype('uint8') result = Image.fromarray(result, 'RGBA') return result def alpha_composite_with_color(image, color=(255, 255, 255)): """Alpha composite an RGBA image with a single color image of the specified color and the same size as the original image. Keyword Arguments: image -- PIL RGBA Image object color -- Tuple r, g, b (default 255, 255, 255) """ back = Image.new('RGBA', size=image.size, color=color + (255,)) return alpha_composite(image, back) def pure_pil_alpha_to_color_v1(image, color=(255, 255, 255)): """Alpha composite an RGBA Image with a specified color. NOTE: This version is much slower than the alpha_composite_with_color solution. Use it only if numpy is not available. Source: http://stackoverflow.com/a/9168169/284318 Keyword Arguments: image -- PIL RGBA Image object color -- Tuple r, g, b (default 255, 255, 255) """ def blend_value(back, front, a): return (front * a + back * (255 - a)) / 255 def blend_rgba(back, front): result = [blend_value(back[i], front[i], front[3]) for i in (0, 1, 2)] return tuple(result + [255]) im = image.copy() # don't edit the reference directly p = im.load() # load pixel array for y in range(im.size[1]): for x in range(im.size[0]): p[x, y] = blend_rgba(color + (255,), p[x, y]) return im def pure_pil_alpha_to_color_v2(image, color=(255, 255, 255)): """Alpha composite an RGBA Image with a specified color. Simpler, faster version than the solutions above. Source: http://stackoverflow.com/a/9459208/284318 Keyword Arguments: image -- PIL RGBA Image object color -- Tuple r, g, b (default 255, 255, 255) """ image.load() # needed for split() background = Image.new('RGB', image.size, color) background.paste(image, mask=image.split()[3]) # 3 is the alpha channel return background </code></pre> <h2>Performance</h2> <p>The simple non-compositing <code>alpha_to_color</code> function is the fastest solution, but leaves behind ugly borders because it does not handle semi transparent areas.</p> <p>Both the pure PIL and the numpy compositing solutions give great results, but <code>alpha_composite_with_color</code> is much faster (8.93 msec) than <code>pure_pil_alpha_to_color</code> (79.6 msec). <del>If numpy is available on your system, that's the way to go.</del> (Update: The new pure PIL version is the fastest of all mentioned solutions.)</p> <pre><code>$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_to_color(i)" 10 loops, best of 3: 4.67 msec per loop $ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_composite_with_color(i)" 10 loops, best of 3: 8.93 msec per loop $ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color(i)" 10 loops, best of 3: 79.6 msec per loop $ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color_v2(i)" 10 loops, best of 3: 1.1 msec per loop </code></pre>
9,459,208
7
2
null
2012-02-06 19:58:12.33 UTC
60
2022-05-28 06:09:27.29 UTC
2012-02-27 22:32:23.443 UTC
null
284,318
null
284,318
null
1
132
python|png|jpeg|python-imaging-library|rgba
185,270
<p>Here's a version that's much simpler - not sure how performant it is. Heavily based on some django snippet I found while building <code>RGBA -&gt; JPG + BG</code> support for sorl thumbnails. </p> <pre><code>from PIL import Image png = Image.open(object.logo.path) png.load() # required for png.split() background = Image.new("RGB", png.size, (255, 255, 255)) background.paste(png, mask=png.split()[3]) # 3 is the alpha channel background.save('foo.jpg', 'JPEG', quality=80) </code></pre> <p>Result @80%</p> <p><img src="https://i.stack.imgur.com/jaVG7.jpg" alt="enter image description here"></p> <p>Result @ 50%<br> <img src="https://i.stack.imgur.com/9IsAI.jpg" alt="enter image description here"></p>
29,555,839
how to calculate Bubble sort Time Complexity
<p>I was trying to understand the Data Structure and different algorithm, then i got confused to measure the Bubble sort time complexity.</p> <pre><code>for (c = 0; c &lt; ( n - 1 ); c++) { for (d = 0; d &lt; n - c - 1; d++) { if (array[d] &gt; array[d+1]) /* For descending order use &lt; */ { swap = array[d]; array[d] = array[d+1]; array[d+1] = swap; } } } </code></pre> <p>Now every Big O tells Best case O(n), Avg case(n2) and Worst Case(n2).But when i see the code, found in first phase inner loop run n time then in second phase n - 1, and n - 2 and so on. That means in every iteration its value goes down. For example if i have a[] = {4, 2, 9, 5, 3, 6, 11} so the total number of comparison will be - </p> <pre><code>1st Phase - 7 time 2nd phase - 6 time 3rd Phase - 5 time 4th Phase - 4 time 5th Phase - 3 time 6th Phase - 2 time 7th Phase - 1 time </code></pre> <p>so when i calculate the time it looks like = (7 + 6 + 5 + 4 + 3 + 2 + 1) + 7 = 35, but the worst time complexity is n2 as per doc. </p> <p>so can Someone tell me how to calculate the correct value. </p>
29,556,003
7
2
null
2015-04-10 07:37:29.173 UTC
8
2020-11-17 10:23:06.22 UTC
null
null
null
null
1,558,312
null
1
10
algorithm|sorting
82,887
<p>Let's go through the cases for Big O for Bubble Sort</p> <p>Case 1) O(n) (Best case) This time complexity can occur if the array is already sorted, and that means that no swap occurred and only 1 iteration of n elements</p> <p>Case 2) O(n^2) (Worst case) The worst case is if the array is already sorted but in descending order. This means that in the first iteration it would have to look at n elements, then after that it would look n - 1 elements (since the biggest integer is at the end) and so on and so forth till 1 comparison occurs. Big-O = n + n - 1 + n - 2 ... + 1 = (n*(n + 1))/2 = O(n^2)</p> <p>In your example, it may not examine these many elements in each phase as the array is not in descending order.</p>
17,258,778
How to generate a string variable out of a labeled numeric variable (Stata)?
<p>I have a variable <code>state</code> that takes integer values from 11 to 99. It is labeled. </p> <p>How can I create a string variable <code>stateString</code> that would have string values without all those numeric values?</p> <p><code>gen stateString = tostring(state)</code></p> <p>doesn't do the trick. </p>
17,259,745
2
0
null
2013-06-23 08:03:13.54 UTC
2
2021-03-11 12:10:17.683 UTC
2013-06-23 10:19:26.32 UTC
null
1,820,446
null
2,088,905
null
1
5
string|label|stata
46,273
<p><code>tostring</code> isn't a function; it's a command, and in Stata the two are quite distinct. Nothing but guesswork leads to the syntax you tried.</p> <pre><code>tostring state, gen(stateString) </code></pre> <p>should work. But <code>tostring</code> is just a wrapper for the function <code>string()</code> and</p> <pre><code>gen stateString = string(state) </code></pre> <p>should also work to get string variables.</p> <p>But the string values would be &quot;11&quot;, ... &quot;99&quot; and that's the wrong approach. Given the value labels, you are fine with having this variable as numeric.</p> <p>If you really want a string variable, you need <code>decode</code>, not <code>tostring</code>.</p> <pre><code>decode state, gen(stateString) </code></pre> <p>EDIT: The syntax <code>tostring()</code> would only work if <code>tostring()</code> were a function, which is not. The original answer thus explained why the OP's code was wrong, as well as explaining how to do it correctly. I spelled out in this edit how to use <code>decode</code>.</p> <p>EDIT 2021: The function <code>string()</code> still works and is documented as before, but the function name <code>strofreal()</code> is now given prominence.</p>
24,767,184
TcpClient - An existing connection was forcibly closed by the remote host
<p><strong>The Info</strong></p> <p>I have been developing a web http server in c# and decided to add a remote console feature. The console can be used from any location and uses a TcpListener (web server) and a TcpClient (remote console) to send commands and functions through.</p> <p><strong>The Code</strong></p> <p>This is what my server looks like:</p> <pre><code>TcpListener consoleListener = new TcpListener(consolePort); consoleListener.Start(); byte[] bytes = new Byte[256]; string data = null; while (true) { TcpClient client = consoleListener.AcceptTcpClient(); data = null; byte[] msg = { 0 }; int i; while ((i = client.GetStream().Read(bytes, 0, bytes.Length)) != 0) { data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); if (data == "shutdown") { //Server shutdown logic. } //Other commands here... else { msg = Encoding.ASCII.GetBytes("Invalid command. Type 'help' or '?' to get a list of commands."); } client.GetStream().Write(msg, 0, msg.Length); //sends return message to console } client.Close(); //closes connection between client and server after EVERY command. Connection is reopened when a new command is sent. } </code></pre> <p>Note - The server is run on a separate thread to both the webserver and main console application thread.</p> <p>This is my client:</p> <pre><code>public static string Communicate(string text) { try { TcpClient client = new TcpClient(ip, port); //initializes tcpclient (ip and port are correct) byte[] data = System.Text.Encoding.ASCII.GetBytes(text); //converts text to bytes for stream writing NetworkStream stream = client.GetStream(); stream.Write(data, 0, data.Length); Console.WriteLine("Sent data: " + text); data = new Byte[256]; string responseData = String.Empty; //initializes responsData string Int32 bytes = stream.Read(data, 0, data.Length); responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); client.Close(); return responseData; //returns what server writes } catch (Exception ex) { return "An error occured\n" + ex.ToString(); } } </code></pre> <p><strong>The Problem</strong></p> <p>I can send one command to the server with a successful return. However, when I try and send another command, the server throws the error below:</p> <pre><code>System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---&gt; System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) --- End of inner exception stack trace --- at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) at ---.Server.ConsoleListener() in X:\Users\---\Documents\Visual Studio 2013\Projects\---\---\Program.cs:line x </code></pre> <p>I know it is not firewall or administrator elevation problems as I can send one command through successfully. It is only on the second command sent that it throws this error.</p> <p>Here is a screenshot describing the problem: <img src="https://i.stack.imgur.com/omGIQ.png" alt="The remote console and server communication and error reporting."></p> <p>EDIT: By doing a little research, I found that the problem is most likely a result of a small error in my for loop. However, I do not know any way of fixing this as I do not know the exact problem :). Please help me identify it so I can fix it.</p> <p>Thanks again</p>
24,767,583
3
5
null
2014-07-15 20:05:06.923 UTC
2
2019-07-19 11:50:31.747 UTC
null
null
null
null
3,125,916
null
1
5
c#|tcpclient|tcplistener
52,245
<p>It seems that your client closes the connection after one message.</p> <pre><code>responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); client.Close(); return responseData; //returns what server writes </code></pre> <p>If you want to persist the connection you should have a loop on the client similar to the one you have on the server. If you want to establish a new connection every time you should close the stream gracefully on the server and not have a loop like this. You will still need to loop in case the message is longer or you need to specify max length for the command.</p>
24,562,716
How to retry HTTP requests with OkHttp/Retrofit?
<p>I am using Retrofit/OkHttp (1.6) in my Android project. </p> <p>I don't find any request retry mechanism built-in to either of them. On searching more, I read OkHttp seems to have silent-retries. I don't see that happening on any of my connections (HTTP or HTTPS). How to configure retries with okclient ? </p> <p>For now, I am catching exceptions and retrying maintaining a counter variable.</p>
31,733,634
15
5
null
2014-07-03 20:23:05.083 UTC
40
2022-07-28 13:17:09.137 UTC
null
null
null
null
430,720
null
1
93
android|retrofit|okhttp
106,034
<p><strong>For Retrofit 2.x;</strong></p> <p>You can use <a href="https://square.github.io/retrofit/2.x/retrofit/retrofit2/Call.html#clone" rel="nofollow noreferrer">Call.clone()</a> method to clone request and execute it.</p> <p><strong>For Retrofit 1.x;</strong></p> <p>You can use <a href="https://github.com/square/okhttp/wiki/Interceptors" rel="nofollow noreferrer">Interceptors</a>. Create a custom interceptor</p> <pre><code> OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); client.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); client.interceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); // try the request Response response = chain.proceed(request); int tryCount = 0; while (!response.isSuccessful() &amp;&amp; tryCount &lt; 3) { Log.d(&quot;intercept&quot;, &quot;Request is not successful - &quot; + tryCount); tryCount++; // retry the request response.close() response = chain.proceed(request); } // otherwise just pass the original response on return response; } }); </code></pre> <p>And use it while creating RestAdapter.</p> <pre><code>new RestAdapter.Builder() .setEndpoint(API_URL) .setRequestInterceptor(requestInterceptor) .setClient(new OkClient(client)) .build() .create(Adapter.class); </code></pre>
22,310,007
Differences between Git-scm, msysGit & Git for Windows
<p>What is the difference between <code>git-scm</code> (downloaded from <a href="http://git-scm.com" rel="noreferrer">git-scm.com</a>) and msysGit (hosted on <a href="https://code.google.com/p/msysgit/downloads/list" rel="noreferrer">Google Code</a>, <a href="https://github.com/msysgit/msysgit/" rel="noreferrer">Github</a>, and probably others)? They both seem pretty similar, and even though I have git-scm, I have applied fixes specified for msysGit and they seem to work fine.</p> <p>Also, which one, if either, is <code>Git for Windows</code>, and are both called <code>Git Bash</code>, or do both have the <code>Git Bash</code> shell, or only one of the two?</p>
22,310,210
1
3
null
2014-03-10 19:56:34.783 UTC
25
2016-01-11 10:43:39.613 UTC
2016-01-11 10:36:04.153 UTC
null
216,074
null
2,057,814
null
1
81
windows|git|msysgit|git-bash
32,574
<p>The website <a href="http://git-scm.com">git-scm.com</a> is the official website for Git, the version control software. There is no “Git-SCM”, that’s just the URL of the <em>source control management (SCM)</em> software—the name is just <strong>Git</strong>. Originally written for Linux, the original Git software is only available as a source that doesn’t compile easily on Windows.</p> <blockquote> <p>If you are just interested in installing Git on Windows, then you can stop reading here and just download a Windows build <a href="http://git-scm.com/download/win">from the official website</a>.</p> </blockquote> <h3>Git for Windows</h3> <p><a href="http://git-for-windows.github.io/">Git for Windows</a> is the project dedicated to building native builds of Git for Windows. The Windows releases are available for download <a href="http://git-scm.com/download/win">on the official Git website</a>, they come as 32-bit and 64-bit builds.</p> <p>Git for Windows is built on top of MSYS2 (a part of <a href="https://en.wikipedia.org/wiki/MinGW">MinGW</a>) which provides a minimal unix-like shell environment which is used to run all the components of Git which are not written in native code (a lot of Git is written as shell scripts). In order to build Git with MSYS2, the project group has a special “Git for Windows SDK” which is basically the whole build environment needed to build Git on Windows, and comes <a href="https://github.com/git-for-windows/git/wiki/Technical-overview">with everything</a> you need to start working on Git itself.</p> <p>The project maintains its own <a href="https://github.com/git-for-windows/git">fork of Git</a> which is kept up to date with the original Git project but contains a set of patches necessary to build it on Windows. Git for Windows <a href="https://github.com/git-for-windows/git/releases">releases</a> are usually released with a short delay after the official version is released (although versions are sometimes skipped).</p> <h3>msysGit</h3> <p>Prior to Git version 2, the <em>Git for Windows</em> binaries were released by the project called <a href="https://github.com/msysgit">msysGit</a>, which is the predecessor of the <em>Git for Windows</em> project. The project was retired on August 18, 2015 in favor to launch the <em>Git for Windows</em> project with the rebuilt <em>Git for Windows SDK</em> development environment. The new project was mostly started with the same team.</p> <p>While many people thought of <em>msysGit</em> as the name of the Git binaries, that was actually the name of the development environment they created. It was based on MSYS, the older and kind-of outdated version before MSYS2 was started fresh. The bad state of MSYS was one of the reasons why the <em>Git for Windows</em> project was started with a completely revamped build environment.</p> <p>The project essentially released three things: msysGit, Git for Windows, and a portable Git for Windows. The msysGit installer would install and set up the development environment required to build Git on Windows, just like the <em>Git for Windows SDK</em> does now. Git for Windows was an installer that would install Git on a Windows machine, and the portable Git for Windows were just the binaries you wouldn’t have to install. Note that all their releases were released as “preview” builds, meaning that they would not be fully supported releases. Despite that, the project was very mature and the releases were very stable and the de-facto best way to set up Git on Windows.</p> <h3>Git Bash</h3> <p>As mentioned above, a lot of Git is written as shell scripts. In order to execute those scripts, Git for Windows uses <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29">Bash</a> that comes bundled with MSYS2 (so Bash works as an interpreter for it).</p> <p><em>Git Bash</em> commonly refers to the shortcut the <em>Git for Windows</em> installer creates. It launches a full featured console window running Bash, so you can use Git as well as a set of common command line tools or Unix programs (like <code>less</code>, <code>awk</code>, <code>grep</code>, or even the text editor <a href="https://en.wikipedia.org/wiki/Vim_%28text_editor%29"><code>vim</code></a>). Especially for less experienced users, Git Bash is the common way to interact with Git, although you could easily use it from more Windows-centric environments like <a href="https://en.wikipedia.org/wiki/Windows_PowerShell">PowerShell</a>.</p> <p>Starting with Git version 2, Git Bash will by default launch in MinTTY, a <a href="https://en.wikipedia.org/wiki/Terminal_emulator">terminal emulator</a> which comes with MSYS2, making it easily usable even for users not accustomed to a console experience.</p> <p>It’s also useful to know that <em>Git Bash</em> will always work even if you decided not to add any Git executables to your PATH during the setup of <em>Git for Windows</em>. However, my personal recommendation is to add the Git executable (<em>just</em> the Git executable, choosing the option “Use Git from the Windows Command Prompt” during setup) to the PATH. That way, you can work with Git from other shells (cmd.exe or PowerShell), and other programs can access it too (e.g. many libraries or even IDE integrations expect a Git executable in the PATH to interact with Git repositories).</p>
26,773,729
Check if combobox value is empty
<p>I have created a ComboBox with three values. I wanted that a message box opens when no item is selected so I tried this:</p> <pre><code>if (comboBox1.SelectedItem == null) { MessageBox.Show("Please select a value"); return; } </code></pre> <p>That works fine but only if I click into the field in the combobox. When I dont touch it, the program will start without message box. Whats wrong?</p>
26,773,792
7
2
null
2014-11-06 07:15:03.94 UTC
3
2020-12-16 12:14:44.823 UTC
2014-11-06 07:16:20.573 UTC
null
447,156
null
4,197,368
null
1
10
c#|winforms|combobox
78,318
<p><code>if (string.IsNullOrEmpty(comboBox1.Text))</code> or <code>if (comboBox1.SelectedIndex == -1)</code></p>
17,352,104
Multiple JS event handlers on single element
<p>I am working with an existing web app, in the app there are a variety of submit buttons on different forms, some using regular http post, some defining an onClick function, and some binding a js event handler to the button using a class on the element.</p> <p>What I want to do, is bind another event handler to these buttons by just adding a class to the buttons, but what I want to determine is will the new event handler be guaranteed to be executed, or could one of the form submit actions happen before it does meaning my new function isn't hit.</p> <p>The example scenario is I want to add a class to these buttons that bimds them all to a common js function that simply logs usage to some api. Is there a risk that the logging function isn't called because the form submit has navigated away from the page?</p> <p>I've not done loads of js development, and I could test this 100 times over and just get lucky with it firing.</p> <hr> <p>Below is some code I have tested with for one of the examples - again, I'm not asking how to bind multiple events, the question is to about my understanding of the spec and whether execution of all handlers is guaranteed.</p> <pre><code>$(document).ready(function(){ $('.testingBtn').click(function() { window.location.replace("http://stackoverflow.com"); }); $( ".testingBtn" ).click(function(){ alert('submitting!'); }); }); &lt;input class="testingBtn" type="submit" id="submitform" value="Complete Signup" /&gt; </code></pre> <p>As seen above, I can bind the multiple events, and in this example, just directed to another url, but this could be a <code>form.submit()</code> etc. In my testing the alert has always fired first, but am I just getting lucky with the race conditions?</p>
17,352,923
3
6
null
2013-06-27 19:56:58.89 UTC
22
2019-05-23 09:30:51.963 UTC
2019-05-23 09:30:51.963 UTC
null
4,370,109
null
258,813
null
1
34
javascript|jquery|dom-events|jquery-events
83,342
<p>In JS, you don't <em>really</em> have control over what order the event handlers are called, but with careful delegation and well-placed listeners, it is possible.</p> <p>Delegation is one of the most powerful features of the event model. As you may or may not know: in JS, an event is handed to the top of the dom, from where it propagates down to the element onto which the event should be applied. It stands to reason, therefore, that an event listener attached to the global object will call its handler <em>prior</em> to a listener that has been attached to the element itself.</p> <pre><code>window.addEventListener('click',function(e) { e = e || window.event; var target = e.target || e.srcElement; console.log('window noticed you clicked something'); console.log(target);//&lt;-- this is the element that was clicked }, false);//&lt;-- we'll get to the false in a minute </code></pre> <p>It's important to note we actually have access to the event object in the handlers. In this case, we left the event object untouched, so it'll just continue to propagate down to the target, on its way down, it might meet with something like this:</p> <pre><code>document.getElementById('container').addEventListener('click', function(e) { e = e || window.event; var target = e.target || e.srcElement; if (target.tagName.toLowerCase() !== 'a' || target.className.match(/\bclickable\b/)) { return e;//&lt;return the event, unharmed } e.returnValue = false; if (e.preventDefault) { e.preventDefault(); } }, false); </code></pre> <p>Now, this handler will be called after the listener at the window level calls its helper. This time, the event <em>is</em> changed if the clicked element didn't have the <code>clickable</code> class, or the element is a link. The event is canceled, but it lives on, still. The event is still free to propagate further down the dom, so we might encounter something like:</p> <pre><code>document.getElmentById('form3').addEventListener('click',function(e) { e = e || window.event; if (e.returnValue === false || e.isDefaultPrevented) {//this event has been changed already //do stuff, like validation or something, then you could: e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } } }, false); </code></pre> <p>Here, by calling <code>stopPropagation</code>, the event is killed off. It can't propagate further down the dom to its target unless the event was already altered. If not, the event object travels further down the DOM, as if nothing happened.</p> <p>Once it reaches its target node, the event enters its second phase: the bubble phase. Instead of propagating down into the deeps of the DOM, it climbs back up, to the top level (all the way to the global object, where it was dispatched... from whence it came and all that).</p> <p>In the bubble phase, all the same rules apply as in the propagation phase, only the other way around. The event object will encounter the elements that are closest to the target element first, and the global object last.</p> <p><a href="http://www.quirksmode.org/js/events_order.html">There's a lot of handy, and clear diagrams for this here</a>. I can't put it any better than good 'ol quirksmode, so I suggest you read what they have to say there.</p> <p>Bottom line: when dealing with 2 event listeners, attach them both on a different level to sort-of queue them the way you like.</p> <p>If you want to guarantee both are called, only stop the event from propagating in that handler that will be called last.</p> <p>When you've got two listeners, attached to the same element/object for the same event, I've never come across a situation where the listener that was attached first, wasn't also called first.</p> <p>That's it, I'm off to bed, hoping I made sense</p>
17,509,846
Python super() arguments: why not super(obj)?
<p>I am trying to understand when and how to use super() in Python correctly (either 2.7.x or 3.x)</p> <p>on <code>&gt;&gt;&gt; help(super)</code> the interpreter tells me how to call it:</p> <pre><code>class super(object) | super(type) -&gt; unbound super object | super(type, obj) -&gt; bound super object; requires isinstance(obj, type) | super(type, type2) -&gt; bound super object; requires issubclass(type2, type) </code></pre> <p>I understand that in Python3.x it's now possible to juse use super() within a class definition, but I don't understand why <code>super(obj)</code> is not possible. Or <code>super(self)</code> within a class definition. </p> <p>I know there must be a reason for it, but I can't find it. To me those lines are equivalent to <code>super(obj.__class__, obj)</code> or <code>super(self.__class__, self)</code> and those would work right?</p> <p>I would think that just typing <code>super(obj)</code> would be a nice shortcut even in Python 3.x.</p>
17,509,938
2
1
null
2013-07-07 06:36:15.14 UTC
12
2017-04-03 11:39:07.097 UTC
null
null
null
null
1,621,769
null
1
44
python|inheritance|super
15,409
<p>The two-argument form is only needed in Python 2. The reason is that <code>self.__class__</code> always refers to the "leaf" class in the inheritance tree -- that is, the most specific class of the object -- but when you call <code>super</code> you need to tell it which implementation is currently being invoked, so it can invoke the next one in the inheritance tree.</p> <p>Suppose you have:</p> <pre><code>class A(object): def foo(self): pass class B(A): def foo(self): super(self.__class__, self).foo() class C(B): def foo(self): super(self.__class__, self).foo() c = C() </code></pre> <p>Note that <code>c.__class__</code> is <code>C</code>, always. Now think about what happens if you call <code>c.foo()</code>.</p> <p>When you call <code>super(self.__class__, self)</code> in a method of C, it will be like calling <code>super(C, self)</code>, which means "call the version of this method inherited by C". That will call <code>B.foo</code>, which is fine. But when you call <code>super(self.__class__, self)</code> from B, it's still like calling <code>super(C, self)</code>, because it's the same <code>self</code>, so <code>self.__class__</code> is still <code>C</code>. The result is that the call in B will again call <code>B.foo</code> and an infinite recursion occurs.</p> <p>Of course, what you really want is to be able to call <code>super(classThatDefinedTheImplementationThatIsCurrentlyExecuting, self)</code>, and that is effectively what the Python 3 <code>super()</code> does.</p> <p>In Python 3, you can just do <code>super().foo()</code> and it does the right thing. It's not clear to me what you mean about <code>super(self)</code> being a shortcut. In Python 2, it doesn't work for the reason I described above. In Python 3, it would be a "longcut" because you can just use plain <code>super()</code> instead.</p> <p>The <code>super(type)</code> and <code>super(type1, type2)</code> uses might still be needed occasionally in Python 3, but those were always more esoteric usages for unusual situations.</p>
37,133,191
Is there a difference between lambdas declared with and without async
<p>Is there a difference between lambdas <code>() =&gt; DoSomethingAsync()</code> and <code>async () =&gt; await DoSomethingAsync()</code> when both are typed as <code>Func&lt;Task&gt;</code>? Which one should we prefer and when?</p> <p>Here is a simple console app</p> <pre><code>using System; using System.Threading.Tasks; namespace asyncDemo { class Program { static void Main(string[] args) { var demo = new AsyncDemo(); var task = demo.RunTheDemo(); task.Wait(); Console.ReadLine(); } } public class AsyncDemo { public async Task Runner(Func&lt;Task&gt; action) { Console.WriteLine(DateTime.Now.ToLongTimeString() + " Launching the action"); await action(); } private async Task DoSomethingAsync(string suffix) { await Task.Delay(2000); Console.WriteLine(DateTime.Now.ToLongTimeString() + " Done something, " + suffix); } public async Task RunTheDemo() { await Runner(() =&gt; DoSomethingAsync("no await")); await Runner(async () =&gt; await DoSomethingAsync("with await")); } } } </code></pre> <p>The output is:</p> <pre><code>09:31:08 Launching the action 09:31:10 Done something, no await 09:31:10 Launching the action 09:31:12 Done something, with await </code></pre> <p>So in <code>RunTheDemo</code>, both calls to <code>await Runner(someLambda);</code> appear to do the same thing with the same timing characteristics - both have the correct two-second delay.</p> <p>Both lines work, so are they exactly equivalent? What is the difference between the <code>() =&gt; DoSomethingAsync()</code> and <code>async () =&gt; await DoSomethingAsync()</code> constructs? Which one should we prefer and when?</p> <p>This is not the same question as "should I use <code>await</code> in the general case", as here we are dealing with working async code, with lambdas typed as <code>Func&lt;Task&gt;</code> which are correctly awaited inside the consuming method. The question concerns how those lambdas are declared, and what the effects of that declaration are.</p>
37,133,814
3
2
null
2016-05-10 08:34:49.14 UTC
3
2016-05-10 14:10:46.137 UTC
2016-05-10 08:56:11.947 UTC
null
5,599
null
5,599
null
1
30
c#|asynchronous|lambda|async-await
1,507
<blockquote> <p>Is there a difference between lambdas declared with and without async</p> </blockquote> <p>Yes, there's a difference. One is an async lambda and the other is just a task-returning lambda.</p> <p>An async lambda is compiled into a state machine while the other doesn't so an async lambda has different exception semantics as exceptions are encapsulated in the returned task and can't be thrown synchronously.</p> <p>It's exactly the same difference that exists in regular methods. For example between this async method:</p> <pre><code>async Task FooAsync() { await DoSomethingAsync("with await"); } </code></pre> <p>And this task-returning method:</p> <pre><code>Task FooAsync() { return DoSomethingAsync("no await"); } </code></pre> <p>Looking at these methods shows the differences more clearly, but as lambdas are just syntactic sugar and are actually compiled into methods that behave just the same as these.</p> <blockquote> <p>Which one should we prefer and when?</p> </blockquote> <p>This really depends on your taste. Using the async keyword generates a state machine which is less performant than simply returning a task. However, the exception semantics may be surprising in some cases.</p> <p>Take this code for example:</p> <pre><code>Hamster hamster = null; Func&lt;Task&gt; asyncAction = () =&gt; FooAsync(hamster.Name); var task = asyncAction(); try { await task; } catch { // handle } </code></pre> <p>Would the try-catch block handle the <code>NullReferenceException</code> or not?</p> <p>It will not because the exception is thrown synchronously when calling <code>asyncAction</code>. However the exception <strong>will</strong> be handled in this case as it is captured in the returned task and rethrown when that task is awaited.</p> <pre><code>Func&lt;Task&gt; asyncAction = async () =&gt; await FooAsync(hamster.Name); </code></pre> <p>I personally use task-returning lambdas for these one line expression lambdas as they're usually pretty simple. But my team, after a few extremely hurtful bugs, always use the <code>async</code> and <code>await</code> keywords.</p>
18,456,498
How can I change the size of an iframe from inside?
<p>I am developing with jquery and I stumbled with the next problem: I added an IFrame inside the main page and I want to re size them from inside. I tried some ideas but without success.</p> <p>Here is my code:</p> <p>index.html</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Index&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;iframe id=&quot;myframe&quot; src=&quot;frame.html&quot; width=&quot;100px&quot; height=&quot;100px&quot;&gt;&lt;/frame&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>frame.html</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;IFrame&lt;/title&gt; &lt;script&gt; document.width = 500; document.height = 500; &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h2&gt;My IFrame&lt;/h2&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
18,456,714
3
0
null
2013-08-27 03:37:57.767 UTC
9
2021-01-23 18:18:53.84 UTC
2021-01-23 18:18:53.84 UTC
null
1,783,163
null
2,708,544
null
1
30
html|iframe
53,097
<p>When you create an <code>IFRAME</code> the browser automatically adds a <code>'window'</code> object for the IFRAME inside the <code>'window'</code> object of main page.</p> <p>You need to change the size of the <code>IFRAME</code> instead of the size of the document.</p> <p>Try this code:</p> <p>For <code>JavaScript</code>:</p> <pre><code>window.parent.document.getElementById('myframe').width = '500px'; window.parent.document.getElementById('myframe').height = '500px'; </code></pre> <p>And for <code>jQuery</code>:</p> <pre><code>$('#myframe', window.parent.document).width('500px'); $('#myframe', window.parent.document).height('500px'); </code></pre>
31,732,169
Error inflating class android.webkit.WebView happens sporadically in production
<p>my application is on Google Play and it runs fine on most of devices (thousands of users). But in rare cases (fraction of percent of daily active users) I get <code>Error inflating class android.webkit.WebView</code> when I inflate layout for my fragment in <code>onCreateView</code> method. Full stack trace is following:</p> <pre><code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tapmedia.tapito/com.tapmedia.tapito.LockscreenActivity}: android.view.InflateException: Binary XML file line #20: Error inflating class android.webkit.WebView at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2694) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2759) at android.app.ActivityThread.access$900(ActivityThread.java:178) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:145) at android.app.ActivityThread.main(ActivityThread.java:5944) at java.lang.reflect.Method.invoke(Method.java) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194) Caused by: android.view.InflateException: Binary XML file line #20: Error inflating class android.webkit.WebView at android.view.LayoutInflater.createView(LayoutInflater.java:640) at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:55) at android.view.LayoutInflater.onCreateView(LayoutInflater.java:689) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:748) at android.view.LayoutInflater.rInflate(LayoutInflater.java:813) at android.view.LayoutInflater.rInflate(LayoutInflater.java:821) at android.view.LayoutInflater.inflate(LayoutInflater.java:511) at android.view.LayoutInflater.inflate(LayoutInflater.java:415) at com.tapmedia.tapito.WebViewFragment.onCreateView(SourceFile:84) at android.support.v4.app.Fragment.performCreateView(SourceFile:1789) at android.support.v4.app.FragmentManagerImpl.moveToState(SourceFile:924) at android.support.v4.app.FragmentManagerImpl.moveToState(SourceFile:1116) at android.support.v4.app.FragmentManagerImpl.onCreateView(SourceFile:2196) at android.support.v4.app.FragmentActivity.onCreateView(SourceFile:300) at android.support.v7.app.AppCompatDelegateImplV7.callActivityOnCreateView(SourceFile:838) at android.support.v7.app.AppCompatDelegateImplV11.callActivityOnCreateView(SourceFile:34) at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(SourceFile:826) at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(SourceFile:44) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:732) at android.view.LayoutInflater.rInflate(LayoutInflater.java:813) at android.view.LayoutInflater.inflate(LayoutInflater.java:511) at android.view.LayoutInflater.inflate(LayoutInflater.java:415) at android.view.LayoutInflater.inflate(LayoutInflater.java:366) at android.support.v7.app.AppCompatDelegateImplV7.setContentView(SourceFile:249) at android.support.v7.app.AppCompatActivity.setContentView(SourceFile:106) at com.tapmedia.tapito.LockscreenActivity.onCreate(SourceFile:103) at android.app.Activity.performCreate(Activity.java:6289) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2647) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2759) at android.app.ActivityThread.access$900(ActivityThread.java:178) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:145) at android.app.ActivityThread.main(ActivityThread.java:5944) at java.lang.reflect.Method.invoke(Method.java) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Constructor.newInstance(Constructor.java) at java.lang.reflect.Constructor.newInstance(Constructor.java:288) at android.view.LayoutInflater.createView(LayoutInflater.java:614) at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:55) at android.view.LayoutInflater.onCreateView(LayoutInflater.java:689) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:748) at android.view.LayoutInflater.rInflate(LayoutInflater.java:813) at android.view.LayoutInflater.rInflate(LayoutInflater.java:821) at android.view.LayoutInflater.inflate(LayoutInflater.java:511) at android.view.LayoutInflater.inflate(LayoutInflater.java:415) at com.tapmedia.tapito.WebViewFragment.onCreateView(SourceFile:84) at android.support.v4.app.Fragment.performCreateView(SourceFile:1789) at android.support.v4.app.FragmentManagerImpl.moveToState(SourceFile:924) at android.support.v4.app.FragmentManagerImpl.moveToState(SourceFile:1116) at android.support.v4.app.FragmentManagerImpl.onCreateView(SourceFile:2196) at android.support.v4.app.FragmentActivity.onCreateView(SourceFile:300) at android.support.v7.app.AppCompatDelegateImplV7.callActivityOnCreateView(SourceFile:838) at android.support.v7.app.AppCompatDelegateImplV11.callActivityOnCreateView(SourceFile:34) at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(SourceFile:826) at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(SourceFile:44) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:732) at android.view.LayoutInflater.rInflate(LayoutInflater.java:813) at android.view.LayoutInflater.inflate(LayoutInflater.java:511) at android.view.LayoutInflater.inflate(LayoutInflater.java:415) at android.view.LayoutInflater.inflate(LayoutInflater.java:366) at android.support.v7.app.AppCompatDelegateImplV7.setContentView(SourceFile:249) at android.support.v7.app.AppCompatActivity.setContentView(SourceFile:106) at com.tapmedia.tapito.LockscreenActivity.onCreate(SourceFile:103) at android.app.Activity.performCreate(Activity.java:6289) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2647) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2759) at android.app.ActivityThread.access$900(ActivityThread.java:178) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:145) at android.app.ActivityThread.main(ActivityThread.java:5944) at java.lang.reflect.Method.invoke(Method.java) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194) Caused by: android.util.AndroidRuntimeException: android.content.pm.PackageManager$NameNotFoundException: com.google.android.webview at android.webkit.WebViewFactory.getFactoryClass(WebViewFactory.java:161) at android.webkit.WebViewFactory.getProvider(WebViewFactory.java:101) at android.webkit.WebView.getFactory(WebView.java:2193) at android.webkit.WebView.ensureProviderCreated(WebView.java:2188) at android.webkit.WebView.setOverScrollMode(WebView.java:2247) at android.view.View.(View.java:3795) at android.view.View.(View.java:3909) at android.view.ViewGroup.(ViewGroup.java:507) at android.widget.AbsoluteLayout.(AbsoluteLayout.java:55) at android.webkit.WebView.(WebView.java:547) at android.webkit.WebView.(WebView.java:492) at android.webkit.WebView.(WebView.java:475) at android.webkit.WebView.(WebView.java:462) at java.lang.reflect.Constructor.newInstance(Constructor.java) at java.lang.reflect.Constructor.newInstance(Constructor.java:288) at android.view.LayoutInflater.createView(LayoutInflater.java:614) at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:55) at android.view.LayoutInflater.onCreateView(LayoutInflater.java:689) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:748) at android.view.LayoutInflater.rInflate(LayoutInflater.java:813) at android.view.LayoutInflater.rInflate(LayoutInflater.java:821) at android.view.LayoutInflater.inflate(LayoutInflater.java:511) at android.view.LayoutInflater.inflate(LayoutInflater.java:415) at com.tapmedia.tapito.WebViewFragment.onCreateView(SourceFile:84) at android.support.v4.app.Fragment.performCreateView(SourceFile:1789) at android.support.v4.app.FragmentManagerImpl.moveToState(SourceFile:924) at android.support.v4.app.FragmentManagerImpl.moveToState(SourceFile:1116) at android.support.v4.app.FragmentManagerImpl.onCreateView(SourceFile:2196) at android.support.v4.app.FragmentActivity.onCreateView(SourceFile:300) at android.support.v7.app.AppCompatDelegateImplV7.callActivityOnCreateView(SourceFile:838) at android.support.v7.app.AppCompatDelegateImplV11.callActivityOnCreateView(SourceFile:34) at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(SourceFile:826) at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(SourceFile:44) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:732) at android.view.LayoutInflater.rInflate(LayoutInflater.java:813) at android.view.LayoutInflater.inflate(LayoutInflater.java:511) at android.view.LayoutInflater.inflate(LayoutInflater.java:415) at android.view.LayoutInflater.inflate(LayoutInflater.java:366) at android.support.v7.app.AppCompatDelegateImplV7.setContentView(SourceFile:249) at android.support.v7.app.AppCompatActivity.setContentView(SourceFile:106) at com.tapmedia.tapito.LockscreenActivity.onCreate(SourceFile:103) at android.app.Activity.performCreate(Activity.java:6289) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2647) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2759) at android.app.ActivityThread.access$900(ActivityThread.java:178) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:145) at android.app.ActivityThread.main(ActivityThread.java:5944) at java.lang.reflect.Method.invoke(Method.java) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194) Caused by: android.content.pm.PackageManager$NameNotFoundException: com.google.android.webview at android.app.ApplicationPackageManager.getPackageInfo(ApplicationPackageManager.java:137) at android.webkit.WebViewFactory.getFactoryClass(WebViewFactory.java:133) at android.webkit.WebViewFactory.getProvider(WebViewFactory.java:101) at android.webkit.WebView.getFactory(WebView.java:2193) at android.webkit.WebView.ensureProviderCreated(WebView.java:2188) at android.webkit.WebView.setOverScrollMode(WebView.java:2247) at android.view.View.(View.java:3795) at android.view.View.(View.java:3909) at android.view.ViewGroup.(ViewGroup.java:507) at android.widget.AbsoluteLayout.(AbsoluteLayout.java:55) at android.webkit.WebView.(WebView.java:547) at android.webkit.WebView.(WebView.java:492) at android.webkit.WebView.(WebView.java:475) at android.webkit.WebView.(WebView.java:462) at java.lang.reflect.Constructor.newInstance(Constructor.java) at java.lang.reflect.Constructor.newInstance(Constructor.java:288) at android.view.LayoutInflater.createView(LayoutInflater.java:614) at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:55) at android.view.LayoutInflater.onCreateView(LayoutInflater.java:689) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:748) at android.view.LayoutInflater.rInflate(LayoutInflater.java:813) at android.view.LayoutInflater.rInflate(LayoutInflater.java:821) at android.view.LayoutInflater.inflate(LayoutInflater.java:511) at android.view.LayoutInflater.inflate(LayoutInflater.java:415) at com.tapmedia.tapito.WebViewFragment.onCreateView(SourceFile:84) at android.support.v4.app.Fragment.performCreateView(SourceFile:1789) at android.support.v4.app.FragmentManagerImpl.moveToState(SourceFile:924) at android.support.v4.app.FragmentManagerImpl.moveToState(SourceFile:1116) at android.support.v4.app.FragmentManagerImpl.onCreateView(SourceFile:2196) at android.support.v4.app.FragmentActivity.onCreateView(SourceFile:300) at android.support.v7.app.AppCompatDelegateImplV7.callActivityOnCreateView(SourceFile:838) at android.support.v7.app.AppCompatDelegateImplV11.callActivityOnCreateView(SourceFile:34) at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(SourceFile:826) at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(SourceFile:44) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:732) at android.view.LayoutInflater.rInflate(LayoutInflater.java:813) at android.view.LayoutInflater.inflate(LayoutInflater.java:511) at android.view.LayoutInflater.inflate(LayoutInflater.java:415) at android.view.LayoutInflater.inflate(LayoutInflater.java:366) at android.support.v7.app.AppCompatDelegateImplV7.setContentView(SourceFile:249) at android.support.v7.app.AppCompatActivity.setContentView(SourceFile:106) at com.tapmedia.tapito.LockscreenActivity.onCreate(SourceFile:103) at android.app.Activity.performCreate(Activity.java:6289) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2647) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2759) at android.app.ActivityThread.access$900(ActivityThread.java:178) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:145) at android.app.ActivityThread.main(ActivityThread.java:5944) at java.lang.reflect.Method.invoke(Method.java) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194) </code></pre> <p>I don't understand what's wrong. Because this error comes from online reporting tool (Crashlytics/Fabric), I can't tell, whether this happens every time the specific user tries to use the fragment or if the user normally gets the fragment inflated and the error happens only from time to time. WebView widget is part of the system, right? I mean - I can't be missing something in my production APK - like support library or so. Or can I?</p>
31,732,953
5
5
null
2015-07-30 19:12:02.83 UTC
8
2020-06-21 19:14:34.333 UTC
null
null
null
null
1,325,048
null
1
42
android|webview
20,842
<p>If you see these reports from devices running Android Lollipop, please ignore them. This likely happens whenever something launches an activity that uses WebView while the WebView package is in the middle of being updated by Play Store (which can only happen on Lollipop currently). During updates, packages are treated as not installed by the package manager. That is, there is nothing wrong with your app. The time window while the updated package is considered non-existent is typically small, so when the app is relaunched after such a crash, it will start normally.</p>
4,969,133
Database design - articles, blog posts, photos, stories
<p>I'm designing a database for a web site that will have at least 4 different object types represented (articles, blog posts, photos, stories), each of which have different enough data requirements to warrant their own tables. We want users to be able to post comments for any of these types. The data requirements for comments are simple and independent of the type of thing the comment regards (ie just a comment body, and the author's email).</p> <p>I want to avoid the redundancy of creating and managing 4+ separate tables for the comments, so I'd like to be able to hold all comments in one table, possibly specifying the relation via 2 columns: one to designate the parent entity and one for the parent row Id. </p> <p>but I don't understand how, then, I would implement foreign keys, since foreign keys establish a relation between 2 and only 2 tables (right?). </p> <p>So with all that in mind, what would be the best approach?</p>
4,970,646
3
0
null
2011-02-11 12:45:06.93 UTC
28
2020-07-26 19:40:39.083 UTC
2013-04-04 10:22:47.05 UTC
null
558,486
null
613,004
null
1
30
database-design
12,413
<p>Here's one way to implement supertype/subtype tables for your app.</p> <p>First, the supertype table. It contains all the columns common to all subtypes.</p> <pre><code>CREATE TABLE publications ( pub_id INTEGER NOT NULL PRIMARY KEY, pub_type CHAR(1) CHECK (pub_type IN ('A', 'B', 'P', 'S')), pub_url VARCHAR(64) NOT NULL UNIQUE, CONSTRAINT publications_superkey UNIQUE (pub_id, pub_type) ); </code></pre> <p>Next, a couple of subtype tables.</p> <pre><code>CREATE TABLE articles ( pub_id INTEGER NOT NULL, pub_type CHAR(1) DEFAULT 'A' CHECK (pub_type = 'A'), placeholder CHAR(1) NOT NULL, -- placeholder for other attributes of articles PRIMARY KEY (pub_id, pub_type), FOREIGN KEY (pub_id, pub_type) REFERENCES publications (pub_id, pub_type) ); CREATE TABLE stories ( pub_id INTEGER NOT NULL, pub_type CHAR(1) DEFAULT 'S' CHECK (pub_type = 'S'), placeholder CHAR(1) NOT NULL, -- placeholder for other attributes of stories PRIMARY KEY (pub_id, pub_type), FOREIGN KEY (pub_id, pub_type) REFERENCES publications (pub_id, pub_type) ); </code></pre> <p>The CHECK() and FOREIGN KEY constraints in these subtype tables prevent rows from referencing the wrong kind of row in the supertype. It effectively partitions the pub_id values among the subtypes, guaranteeing that any given pub_id can appear in one and only one of the subtype tables. That's why you need either a PRIMARY KEY or NOT NULL UNIQUE constraint on the pair of columns {publications.pub_id, publications.pub_type}.</p> <p>The table for comments is simple. Given that it is to have the same structure for all subtypes, you can reference the supertype.</p> <pre><code>CREATE TABLE comments ( pub_id INTEGER NOT NULL REFERENCES publications (pub_id), comment_timestamp TIMESTAMP NOT NULL DEFAULT now(), commenter_email VARCHAR(10) NOT NULL, -- Only allow people who have -- really short email addresses comment_text VARCHAR(30) NOT NULL, -- Keep 'em short! PRIMARY KEY (pub_id, comment_timestamp, commenter_email) ); </code></pre> <p>Add a little bit of data.</p> <pre><code>INSERT INTO publications VALUES (1,'A', 'url 1 goes here'), (2,'A', 'url 2 goes here'), (3,'S', 'url 3 goes here'); INSERT INTO articles VALUES (1,'A', 'A'), (2,'A', 'B'); INSERT INTO stories VALUES (3,'S', 'A'); INSERT INTO comments VALUES (1, now(), 'a@b.com','You''re stupid'), (1, now(), 'b@c.com', 'You''re stupid, too!'); </code></pre> <p>Now you can create a view to show all articles and resolve the join. You'd do the same for each of the subtypes.</p> <pre><code>CREATE VIEW articles_all AS SELECT P.*, A.placeholder FROM publications P INNER JOIN articles A ON (A.pub_id = P.pub_id) </code></pre> <p>You might prefer names like "published_articles" instead of "articles_all".</p> <p>To select one article and all its comments, you can just <strong>left join</strong> the two tables. (But see below why you probably won't do that.)</p> <pre><code>SELECT A.*, C.* FROM articles_all A LEFT JOIN comments C ON (A.pub_id = C.pub_id) WHERE A.pub_id = 1; </code></pre> <p>You'd probably not actually do that for a web interface, because the dbms would have to return 'n' copies of the article, where 'n' equals the number of comments. But it does make sense to do this in some applications. In applications where it makes sense, you'd use one updatable view for each subtype, and application code would use the updatable views most of the time.</p> <hr> <p>The more common business application of a supertype/subtype involves "Parties" (the supertype), "Organizations" and "Individuals" (the subtypes, informally <em>companies</em> and <em>people</em>. Addresses, like "comments" in the example above, are related to the supertype, because all the subtypes (organizations and individuals) have addresses.</p>
9,410,611
Default value of textbox
<p>How to set value of textbox? </p> <p>I have this 1 textbox, and i want to set the default value is 0 so that when user not entering anythng my calculation still can.</p>
9,410,666
5
3
null
2012-02-23 09:51:00.863 UTC
null
2017-01-30 10:01:43.943 UTC
2012-02-23 10:40:20.87 UTC
null
159,270
null
1,227,357
null
1
6
asp.net|textbox
51,328
<p>This can either be done in the markup (.aspx) like:</p> <pre><code>&lt;asp:TextBox id="txt" runat="server" Text="0" /&gt; </code></pre> <p>Or in the code-behind (.aspx.cs):</p> <pre><code>txt.Text = 0; </code></pre> <p>Or if you're using VB.NET:</p> <pre><code>txt.Text = 0 </code></pre> <hr> <p>However, if you're doing a calculation based on this, you shouldn't rely on there always being a value in the textbox.</p> <p>You could do:</p> <pre><code>Dim txtValue as Integer = 0 If IsNumeric(txt.Text) Then txtValue = txt.Text End If </code></pre>
9,351,423
How do I reduce MySQL's overhead as displayed in phpMyAdmin?
<p>In my MySQL database I see these statistics:</p> <pre><code>Type Usage Data 16,384 Bytes Index 32,768 Bytes Overhead 405,0 MB Effective -424,624,128 Bytes Total 49,152 Bytes </code></pre> <p>When I try the commands <code>check table</code>, <code>ALTER TABLE 'mytable' ENGINE = INNODB</code>, <code>OPTIMIZE TABLE</code>, nothing happens to the overhead.</p> <p>Why does nothing happen, should I worry, and when should I worry? I've seen other questions that state 'to worry when the overhead gets too large'. What is too large?</p>
9,738,414
2
4
null
2012-02-19 17:32:00.43 UTC
9
2016-06-17 07:20:02.207 UTC
2014-03-28 02:46:34.217 UTC
null
74,585
null
675,383
null
1
10
mysql|phpmyadmin
14,326
<p>Overhead in PHPMyAdmin is calculated by 'Data_free' column returned by SHOW TABLE STATUS. It is actually explained in MySQL documentation: <a href="http://dev.mysql.com/doc/refman/5.1/en/show-table-status.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.1/en/show-table-status.html</a></p> <p>Data_free: The number of allocated but unused bytes. </p> <blockquote> <p>Beginning with MySQL 5.1.24, this information is also shown for InnoDB tables (previously, it was in the Comment value). InnoDB tables report the free space of the tablespace to which the table belongs. For a table located in the shared tablespace, this is the free space of the shared tablespace. If you are using multiple tablespaces and the table has its own tablespace, the free space is for only that table. Free space means the number of completely free 1MB extents minus a safety margin. Even if free space displays as 0, it may be possible to insert rows as long as new extents need not be allocated.</p> </blockquote> <p>However for InnoDB this is important "InnoDB tables report the free space of the tablespace to which the table belongs. For a table located in the shared tablespace, this is the free space of the shared tablespace.". So with a typical InnoDB setup ('innondb_file_per_table' is not set) you will get the free space for all tables and not for a single table. That is probably why phpMyAdmin ignores/discards the information or on Optimize table nothing happens.</p> <p>You should read this <a href="https://stackoverflow.com/questions/3927690/howto-clean-a-mysql-innodb-storage-engine/4056261#4056261">post</a> which clearly explains how to optimize a table in innodb.</p>