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
11,042,218
C restore stdout to terminal
<p>I am working with a multi-thread program. </p> <p>First I redirect my stdout to a certain file. No problem there (I used <code>dup2(fd, 1)</code> where <code>fd</code> is the file descriptor for the file). </p> <p>Afterwards, I need to redirect my stdout to the terminal again.</p> <p>My first approach:</p> <pre><code> /*Declaration*/ fpost_t stream_sdout; /*code*/ if ( fgetpos( stdout, &amp;stream_sdout) == -1 ) perror(Error:); </code></pre> <p>It says illegal seek.<br> No idea why this is happening.<br> But if I get this to work, then I only need to use <code>fsetpos(stdout, &amp;stream_stdout)</code> and it should work.</p> <p>My second idea, was to to copy the stdout using <code>dup2(stdout, 4)</code> to the file descriptor table, at position 4. But that ain't working either.</p> <p>How can I switch the standard output back to its original destination (terminal, pipe, file, whatever)?</p>
11,042,581
3
8
null
2012-06-14 22:27:39.123 UTC
13
2018-01-17 07:49:40.557 UTC
2018-01-17 07:49:40.557 UTC
null
212,378
null
1,418,069
null
1
28
c|stdout
40,950
<pre><code>#include &lt;unistd.h&gt; ... int saved_stdout; ... /* Save current stdout for use later */ saved_stdout = dup(1); dup2(my_temporary_stdout_fd, 1); ... do some work on your new stdout ... /* Restore stdout */ dup2(saved_stdout, 1); close(saved_stdout); </code></pre>
11,041,137
What is the difference between variable, parameter and field in JasperReports?
<p>I am a newbie to <em>JasperReports</em>, have been working on some small samples. It seems "Fields", "Parameters" and "Variables" are very commonly used to demonstrate dynamic data and looks much alike. So can I ask what's their difference specifically in <em>JasperReports</em>?</p> <p>I guess variable is something defined within a Jasper report and can dynamically change. Parameter is something taking from external source (Java..etc), field is for entities (database schema, class entity), but I don't think my understand is all right.</p>
11,041,480
3
2
null
2012-06-14 20:50:25.83 UTC
11
2021-11-13 15:04:36.95 UTC
2016-06-18 11:43:11.043 UTC
null
876,298
null
1,233,359
null
1
32
jasper-reports
37,112
<p>From my personal experience with <code>JasperReports</code> i can deduce that you will be using Parameters and Fields the most. Parameters and fields are memory locations or values which you can populate from your code, i.e when you generate the report. </p> <p>What you would usually be doing is populating a parameter map or maps with different settings for your report. I use parameters if i have a summary page or a cover page (the very first in a report) Something like:</p> <pre><code>parameters.put("authorName", author); //where authorName is a parameter you have created in your JRXML template. </code></pre> <p>Next, you might be using some custom <code>"variables"</code> or you might be using variables provided from JasperReports. Some of those useful variables are: PAGE_COUNT and PAGE_NUMBER. They keep track of... report page counts and page numbers. Of course you can have custom variables.</p> <p>Fields are used where data changes frequently. They are quite similar to parameters but with each iteration the data might change. Like, a field might be a list of <code>germanCar</code> objects for one iteration and a list of <code>japaneseCar</code> object for the next. I would use a field to hold the list of <code>Car</code> objects that might change.</p> <p>Bottom line is parameters and fields are quite similar, but fields are populated from the <code>JasperReportDataSource</code> (so they can change frequently as you are populating that datasource), while parameters you would use for cover pages or custom JR settings WHILE generating the report itself. They could be quite confusing.</p> <p>Hope this helps a bit!</p>
11,106,825
How to pass a null parameter with Dapper
<p>I have a stored procedure that has a parameter with no default value, but it can be null. But I can't figure out how to pass null with Dapper. I can do it just fine in ADO.</p> <pre><code>connection.Execute("spLMS_UpdateLMSLCarrier", new { **RouteId = DBNull.Value**, CarrierId = carrierID, UserId = userID, TotalRouteRateCarrierId = totalRouteRateCarrierId }, commandType: CommandType.StoredProcedure); </code></pre> <p>Exception:</p> <pre><code>System.NotSupportedException was caught Message=The member RouteId of type System.DBNull cannot be used as a parameter value Source=Dapper StackTrace: at Dapper.SqlMapper.LookupDbType(Type type, String name) in C:\Dev\dapper-git\Dapper\SqlMapper.cs:line 348 at Dapper.SqlMapper.CreateParamInfoGenerator(Identity identity) in C:\Dev\dapper-git\Dapper\SqlMapper.cs:line 1251 at Dapper.SqlMapper.GetCacheInfo(Identity identity) in C:\Dev\dapper-git\Dapper\SqlMapper.cs:line 908 at Dapper.SqlMapper.Execute(IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Nullable`1 commandTimeout, Nullable`1 commandType) in C:\Dev\dapper-git\Dapper\SqlMapper.cs:line 532 at Rating.Domain.Services.OrderRatingQueueService.UpdateLMSLCarrier(Int32 totalRouteRateCarrierId, Int32 carrierID, Int32 userID) in C:\DevProjects\Component\Main\Source\Rating\Source\Rating.Domain\Services\OrderRatingQueueService.cs:line 52 at Benchmarking.Program.OrderRatingQueue() in C:\DevProjects\Component\Main\Source\Benchmarking\Source\Benchmarking\Program.cs:line 81 at Benchmarking.Program.Main(String[] args) in C:\DevProjects\Component\Main\Source\Benchmarking\Source\Benchmarking\Program.cs:line 28 InnerException: </code></pre> <p>Can't leave the RouteId off, gives me an error that says it's required. Can't use regular null either gives me another error. Can't change the stored procedure, it does not belong to me.</p>
11,106,904
1
1
null
2012-06-19 18:11:15.817 UTC
5
2012-06-19 18:17:38.903 UTC
2012-06-19 18:17:38.903 UTC
null
13,627
user1466918
null
null
1
45
dapper
34,642
<p>I think you should be able to do it by casting <code>null</code> to the appropiate type. Let's assume RouteId is an integer:</p> <pre><code>connection.Execute("spLMS_UpdateLMSLCarrier", new { RouteId = (int?)null, CarrierId = carrierID, UserId = userID, TotalRouteRateCarrierId = totalRouteRateCarrierId }, commandType: CommandType.StoredProcedure); </code></pre> <p>The problem you are encountering when using regular null is likely that the compiler cannot infer the type of <code>RouteId</code> in the anonymous type when just using <code>null</code> without the cast.</p>
11,058,387
How do you add a computed column to a Table?
<p>How can I add a computed column to a table that already exists? S.O. has <a href="https://stackoverflow.com/q/5841876/456188">Computed Column Help - TSQL</a> but no information about adding them.</p>
11,058,389
1
0
null
2012-06-15 21:25:49.573 UTC
3
2014-01-06 15:19:05.647 UTC
2017-05-23 11:54:46.753 UTC
null
-1
null
456,188
null
1
69
tsql|ddl
94,031
<p>The syntax I was looking for is:</p> <pre><code>alter table TABLE_NAME add [column_name] as (**COLUMN-SQL**) </code></pre>
12,981,021
Are there any patterns in GoF?
<p>I'm currently learning for a Design Patterns exam (which will take place tomorrow...). In one of the "test exams" I found the following question: </p> <blockquote> <p>Jim Coplien said during the invited lecture that there is not even one design pattern in the GoF book. What is your opinion about this?</p> </blockquote> <p>Because I wasn't in this particular lecture (it was last semester ;) I have no clue what he could have meant. And I have no evidence that Jim Coplien said it, but I think that doesn't matter.</p> <p><strong>What do you think could he meant with this statement?</strong></p> <p>(I'm not sure if the question is appropriate for this forum, however, I wanted to ask.)</p>
24,664,544
2
4
null
2012-10-19 19:20:09.973 UTC
10
2014-07-11 14:58:28.113 UTC
2014-07-10 07:57:32.687 UTC
null
847,064
null
847,064
null
1
9
design-patterns
2,722
<h1>Patterns: The Notion is Grounded in Alexander's Work</h1> <p>The GoF claims to take its pattern inspiration from Christopher Alexander (as they say in the front matter of the book), who popularized the term in the broader field of design. To Alexander a pattern: is always an element of pattern language; contributes to deep human feeling; and is always geometric in nature. At least some of the GoF patterns fail on at least one of these points, and several fail on all three. Although "pattern" is a neutral English language word, the cultural and historic roots of the GoF work, combined with their invocation of Alexandrian inspiration, leave it subject to judgment by the fundamental criteria of its ancestor, and it comes up lacking. Even though they know, and express that they know, that they diverge some from Alexander, they still choose to use a term that he crafted, researched, and popularized, and I hold them accountable for that. (That said, they are all valued acquaintances; I was close to John Vlissides, whom we lost several years ago, and have had great dialog with Richard Helm and Eric Gamma on the deeper issues behind this. My discussions with Ralph have been less interesting as they stop at the engineering level.)</p> <h2>Historical Roots</h2> <p>Words mean things. The Alexandrian sense of the term "pattern" was not well understood by the GoF (or by the software community as a whole) when they wrote the book, but they built on the vulgar perception of the time, which was grounded in three sources: 1. Erich Gamma's Ph.D thesis; 2. Ralph Johnson's framework work, and 3. the C++ idioms book (you can find this in the GoF book's own explanation of its sources in section 6.3). (Oh, Knuth was also an influence.) I continued to challenge the authors about it but people liked it, and they liked that people liked it, so the momentum continued.</p> <p>Several years later (2 December 2004) one of the GoF would write to me to describe his "aha" experience of finally understanding what Alexander was trying to convey. It was quite a bit different than what underlies the content of the GoF book:</p> <blockquote> <p>Finally grok'ed "generative patterns" and piecemeal growth through a long tortuous route.... Largely through some interesting universal properties of software (scale-free and small-worldness)</p> <p>A bit slow I am sometimes... but got there in the end...</p> </blockquote> <h1>GoF Patterns Address a Problem of Accidental, rather than Essential, Complexity</h1> <p>That people find them useful as they do is, unfortunately, an indictment of modern programming languages. The languages don't have the proper constructs to express the broken symmetry that Alexander holds to be characteristic of patterns, and which are intrinsic to complex design (Nature of Order, p. 187: "<em>...in general, a large symmetry of the simplified neoclassicist type rarely contributes to the life of a thing, because in any complex whole in the world, there are nearly always complex, asymmetrical forces at work—matters of location, and context, and function—which require that symmetry be broken</em>"; op cit., pp. 63-4: "<em>Nature, too, creates beautiful structures which are governed by repeated application of structure-preserving transformations. In this connection, I think it is useful to remark that what I call structure-preserving transformations are very closely related to what has become known as “symmetry breaking” in physics.</em>"). Java in particularly bad about this but so is its ancestor Smalltalk. C++ is rich in features to describe local symmetry-breaking but most people don't really know how to use them. Richard Gabriel – who has also worked closely with Alexander, and who has languages like CLOS and Scheme to his credit — says that he simply doesn't understand the GoF patterns because a properly designed language (like CLOS or Scheme) doesn't need them. I am largely in that same camp.</p> <h2>The Design Movement</h2> <p>There's a lot of design theory behind this that goes back to the Design Movement (Thackara ("Design after Modernism", 1989), Naur, Alexander, Cross ("Developments in Design Methodology," 1984) and other authors in the 1980s). It has always amazed me how little programmers know of this body of literature and how wrong-headed much CS thinking is in light of the obvious findings of the work of the Design Movement at this time. Those of us who founded the pattern discipline (the original 7 of The Hillside Group) back in 1993 were familiar with the major themes of this literature. The PLoP conferences evolved a body of literature that devolved radically from these foundations, being more focused on arcane knowledge than the "quality without a name" that Alexander sought.</p> <h2>Origins of Idioms</h2> <p>The reason I introduced idioms for C++ programmers was to allow them to do object-oriented programming when the language got in their way. Now, we have more powerful approaches like DCI that greatly reduce the need for idioms. Patterns still apply at the domain level — which is in line with Alexander's vision. There have been a few good pattern languages written; e.g., by Hanmer (Patterns for Fault-Tolerant Software, 2007); by Eloranta et al. (Designing Distributed Control Systems, 2014), and the Organisational Patterns which Alexander himself noted met the necessary criteria (Coplien and Harrison, 2004).</p> <h1>The Battle Lost, but the Work Continues</h1> <p>Alexander and I (and Richard Gabriel — read his "Patterns of Software" — and others as well) share disappointment in this early redirection of a term that had been well-established in design before being re-defined by GoF. Yes because they call them Design Patterns, they are Design Patterns — in the context of any discussion about the Design Patterns book by the Gang of Four. In the broader scheme of design theory and architecture, they are not: they are only idioms. Even as the authors themselves say, that's how they started out.</p> <p>There are several efforts afoot to restore Alexander's vision to the software community. The ScrumPLoP® community (<a href="http://scrumplop.org">http://scrumplop.org</a>) takes all the Alexandrian groundings of patterns very seriously. An old-time Alexandrian colleague, Greg Bryant, who used to do the IT stuff for CES, has reached out to me and told me of his work to get Alexander's vision back into software, and we're about to trade notes. I'm sure that Dick Gabriel always has something in mind as well though he and I haven't chatted for a while. In the mean time I continue to work directly with Alexander's colleague, Hiroshi Nakano, who connects Alexander's ideas (which he expressed directly in terms of the Tao te Ching in <em>Timeless</em>) directly into their parallels in Japanese culture. It's a much better fit than to try to shoehorn it into Western culture. That probably explains some of the frustration in being able to understand my claim — though it's not an excuse for a professional working in the knowledge business.</p> <h1>An Exhoratation to the Grumblers</h1> <p>Of course, all of this grounding is a matter of published dialectic and research and is available to anyone willing to take the time to research it. It is not as casual a matter as can be quickly dismissed as it was here. It took me 20 years — and I had direct access to the sources. I can appreciate that it's difficult for the average programmer to dig into these things, but I would suggest doing a bit more research before dismissing a well-researched position out-of-hand, before doing one's homework. It's a StackOverflow thing.</p>
30,737,617
The type javax.servlet.ServletContext and javax.servlet.ServletException cannot be resolved
<p>I'm trying to include Spring Security to my web project, i'm following this tutorial <a href="http://docs.spring.io/spring-security/site/docs/current/guides/html5//helloworld.html" rel="noreferrer">http://docs.spring.io/spring-security/site/docs/current/guides/html5//helloworld.html</a></p> <p>I've done everything in the tutorial with the given maven project and works fine. But when i'm trying to include it to my project a compilation error appear. Specifically when i extends from <code>AbstractSecurityWebApplicationInitializer</code> appear the given error</p> <p><img src="https://i.stack.imgur.com/n24L7.png" alt="Code with the error" /></p> <p><img src="https://i.stack.imgur.com/qeo4f.png" alt="The floating compilation error" /></p> <blockquote> <p>Multiple markers at this line</p> <ul> <li>The type javax.servlet.ServletContext cannot be resolved. It is indirectly referenced from required .class files</li> <li>The type javax.servlet.ServletException cannot be resolved. It is indirectly referenced from required .class files</li> </ul> </blockquote> <p>The POM.xml</p> <pre><code>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;spring.primefaces&lt;/groupId&gt; &lt;artifactId&gt;primefaces.testwebapp&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;name&gt;SpringPrimefacesWebApp&lt;/name&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;source&gt;1.7&lt;/source&gt; &lt;target&gt;1.7&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt; &lt;version&gt;2.3&lt;/version&gt; &lt;configuration&gt; &lt;failOnMissingWebXml&gt;false&lt;/failOnMissingWebXml&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;dependencies&gt; &lt;!-- JSF 2.2 core and implementation --&gt; &lt;dependency&gt; &lt;groupId&gt;com.sun.faces&lt;/groupId&gt; &lt;artifactId&gt;jsf-api&lt;/artifactId&gt; &lt;version&gt;2.2.11&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.sun.faces&lt;/groupId&gt; &lt;artifactId&gt;jsf-impl&lt;/artifactId&gt; &lt;version&gt;2.2.11&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Prime Faces --&gt; &lt;dependency&gt; &lt;groupId&gt;org.primefaces&lt;/groupId&gt; &lt;artifactId&gt;primefaces&lt;/artifactId&gt; &lt;version&gt;5.2&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Spring security --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.security&lt;/groupId&gt; &lt;artifactId&gt;spring-security-web&lt;/artifactId&gt; &lt;version&gt;4.0.1.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.security&lt;/groupId&gt; &lt;artifactId&gt;spring-security-config&lt;/artifactId&gt; &lt;version&gt;4.0.1.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;dependencyManagement&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-framework-bom&lt;/artifactId&gt; &lt;version&gt;4.1.6.RELEASE&lt;/version&gt; &lt;type&gt;pom&lt;/type&gt; &lt;scope&gt;import&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/dependencyManagement&gt; </code></pre> <p>Thanks for the help!</p> <p>Using mvn clean install -U</p> <p><img src="https://i.stack.imgur.com/mfq6u.png" alt="enter image description here" /></p>
30,739,587
5
5
null
2015-06-09 16:20:11.33 UTC
8
2020-01-09 06:42:00.263 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
4,068,310
null
1
35
java|maven|servlets|spring-security
82,891
<p>Just add the <a href="http://docs.oracle.com/javaee/7/api/javax/servlet/package-summary.html"><code>javax.servlet</code> API</a> to the compile time dependencies. You don't need to include it in the build, it's already provided by the target servlet container.</p> <p>Your current pom suggests that you're deploying to a barebones servlet container (<a href="http://tomcat.apache.org">Tomcat</a>, <a href="http://www.eclipse.org/jetty/">Jetty</a>, etc) instead of a full fledged Java EE application server (<a href="http://wildfly.org">WildFly</a>, <a href="http://tomee.apache.org">TomEE</a>, <a href="https://glassfish.java.net/">GlassFish</a>, <a href="http://www-03.ibm.com/software/products/en/appserv-was-liberty-core">Liberty</a>, etc), otherwise you'd have run into classloading-related trouble by providing JSF along with the webapp instead of using the container-provided one. </p> <p>In that case, adding the below dependency should do for a <a href="http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api/3.1.0">Servlet 3.1</a> container like Tomcat 8: </p> <pre class="lang-xml prettyprint-override"><code>&lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt; &lt;version&gt;3.1.0&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <p>Or if you're actually targeting an older <a href="http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api/3.0.1">Servlet 3.0</a> container like Tomcat 7, change the <code>&lt;version&gt;</code> to <code>3.0.1</code> (note: there's no <code>3.0</code> due to a mistake on their side).</p> <p>If you happen to actually deploy to a <a href="http://mvnrepository.com/artifact/javax/javaee-api/7.0">Java EE 7</a> application server like WildFly 8, use the below dependency instead. It covers the entire <a href="http://docs.oracle.com/javaee/7/api/">Java EE API</a>, including <code>javax.servlet</code> (and <code>javax.faces</code>, so you'd then remove those individual JSF API/impl dependencies):</p> <pre class="lang-xml prettyprint-override"><code>&lt;dependency&gt; &lt;groupId&gt;javax&lt;/groupId&gt; &lt;artifactId&gt;javaee-api&lt;/artifactId&gt; &lt;version&gt;7.0&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <p>Also here, if you're targeting an older <a href="http://mvnrepository.com/artifact/javax/javaee-api/6.0">Java EE 6</a> application server like JBoss AS 7, change the <code>&lt;version&gt;</code> to <code>6.0</code>.</p>
61,126,851
How can I use GPU on Google Colab after exceeding usage limit?
<p>I'm using Google Colab's free version to run my TensorFlow code. After about 12 hours, it gives an error message</p> <blockquote> <p>&quot;You cannot currently connect to a GPU due to usage limits in Colab.&quot;</p> </blockquote> <p>I tried factory resetting the runtime to use the GPU again but it does not work. Furthermore, I restarted all sessions but this doesn't work either. Is there any method for me to be able to use the GPU again on Google Colab's free version?</p>
66,142,367
4
3
null
2020-04-09 17:31:36.057 UTC
6
2022-06-10 01:07:51.843 UTC
2022-05-13 11:40:03.75 UTC
null
11,483,646
null
8,444,367
null
1
31
gpu|google-colaboratory
77,244
<p>If you use GPU regularly, runtime durations will become shorter and shorter and disconnections more frequent. The cooldown period before you can connect to another GPU will extend from hours to days to weeks. Google tracks everything. They not only know your accounts' usage but also the usage of accounts that appear related to your account and will adjust usage limits accordingly if they even suspect someone of trying to abuse the system. They will never give you an explicit reason why the runtime disconnected or why you can't connect to GPU other than the generic message about &quot;usage limits&quot;. Neither will they ever give users a straightforward way to track their usage because all that would do is make it easier for people to skirt the restrictions. If your account is basically blacklisted they will never actually tell you your account is blacklisted because that creates more headaches for them. You'll just get the same message about usage limits when trying to connect forever. They prefer to have users confused and guessing because that keeps all the power with Google. And for a free service, who's to say there's anything wrong with that.</p> <p><strong>Edit:</strong> For Colab Pro they likely won't fatally restrict an account for over-usage but they can significantly restrict it by extending the cooldown period to 3-5 days, reducing runtime durations from 24 hrs to 6-8 hrs, etc. Keep in mind this is for people running multiple accounts multiple times a week for the maximum duration. If you're just using a single account once or twice a week you shouldn't have a problem.</p>
11,424,037
Do checkbox inputs only post data if they're checked?
<p>Is it standard behaviour for browsers to only send the checkbox input value data if it is checked upon form submission?</p> <p>And if no value data is supplied, is the default value always "on"?</p> <p>Assuming the above is correct, is this consistent behaviour across all browsers?</p>
11,424,089
12
0
null
2012-07-11 00:48:49.15 UTC
44
2019-07-24 13:59:54.993 UTC
2019-07-24 13:59:54.993 UTC
null
1,264,804
null
1,304,767
null
1
213
html|input|checkbox
295,380
<p>Yes, standard behaviour is the value is only sent if the checkbox is checked. This typically means you need to have a way of remembering what checkboxes you are expecting on the server side since not all the data comes back from the form.</p> <p>The default value is always "on", this should be consistent across browsers. </p> <p>This is covered in the <a href="http://www.w3.org/TR/html401/interact/forms.html">W3C HTML 4 recommendation</a>:</p> <blockquote> <p>Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. A switch is "on" when the control element's checked attribute is set. When a form is submitted, only "on" checkbox controls can become successful.</p> </blockquote>
16,677,378
Calculating the height of a binary tree
<p>I need help with the theory on calculating the height of a binary tree, typically the notation.</p> <p>I have read the following article:</p> <p><a href="https://stackoverflow.com/questions/575772/the-best-way-to-calculate-the-height-in-a-binary-search-tree-balancing-an-avl">Calculating height of a binary tree</a></p> <p>And one of the posts gives the following notation:</p> <blockquote> <p>height(node) = max(height(node.L), height(node.R)) + 1</p> </blockquote> <p>Let's assume I have the following binary tree:</p> <pre><code> 10 / \ 5 30 / \ / \ 4 8 28 42 </code></pre> <p>Do I therefore calculate the max value on the left node (8) and the max node on the right (42) and then add 1? I don't quite understand how this notation works in order to calculate the height of the tree. </p>
16,677,580
10
6
null
2013-05-21 18:51:32.06 UTC
3
2021-06-06 05:39:50.477 UTC
2017-05-23 11:53:57.677 UTC
null
-1
null
1,582,478
null
1
13
data-structures|binary-tree
45,271
<p>I'll try to explain how this recursive algorithm works:</p> <pre><code>height(10) = max(height(5), height(30)) + 1 height(30) = max(height(28), height(42)) + 1 height(42) = 0 (no children) height(28) = 0 (no children) height(5) = max(height(4), height(8)) + 1 height(4) = 0 (no children) height(8) = 0 (no children) </code></pre> <p>So if you want to calculate <code>height(10)</code>, you have to expand the recursion down, and than substitute results backwards.</p> <pre><code>height(5) = max(0, 0) + 1 height(30) = max(0, 0) + 1 height(10) = max(1, 1) + 1 height(10) = 2 </code></pre> <p><strong>EDIT:</strong> </p> <p>As noted in comments:<br> <strong><code>height of binary tree = number of layers - 1</code></strong><br> Therefore there should be assumption that height of empty node is equal to -1 i.e: </p> <pre><code>height(empty) = -1 </code></pre> <p>or </p> <pre><code>height(null) = -1 </code></pre> <p>this way </p> <pre><code>height(42) = max(height(null), height(null)) + 1 height(42) = max(-1, -1) + 1 height(42) = -1 + 1 height(42) = 0 </code></pre> <p>I have corrected calculation above.</p>
16,653,815
Horizontal stacked bar chart in Matplotlib
<p>I'm trying to create a horizontal stacked bar chart using <code>matplotlib</code> but I can't see how to make the bars actually stack rather than all start on the y-axis.</p> <p>Here's my testing code.</p> <pre><code>fig = plt.figure() ax = fig.add_subplot(1,1,1) plot_chart(df, fig, ax) ind = arange(df.shape[0]) ax.barh(ind, df['EndUse_91_1.0'], color='#FFFF00') ax.barh(ind, df['EndUse_91_nan'], color='#FFFF00') ax.barh(ind, df['EndUse_80_1.0'], color='#0070C0') ax.barh(ind, df['EndUse_80_nan'], color='#0070C0') plt.show() </code></pre> <p>Edited to use <code>left</code> kwarg after seeing tcaswell's comment.</p> <pre><code>fig = plt.figure() ax = fig.add_subplot(1,1,1) plot_chart(df, fig, ax) ind = arange(df.shape[0]) ax.barh(ind, df['EndUse_91_1.0'], color='#FFFF00') lefts = df['EndUse_91_1.0'] ax.barh(ind, df['EndUse_91_nan'], color='#FFFF00', left=lefts) lefts = lefts + df['EndUse_91_1.0'] ax.barh(ind, df['EndUse_80_1.0'], color='#0070C0', left=lefts) lefts = lefts + df['EndUse_91_1.0'] ax.barh(ind, df['EndUse_80_nan'], color='#0070C0', left=lefts) plt.show() </code></pre> <p>This seems to be the right approach, but it fails if there is no data for a particular bar as it's trying to add <code>nan</code> to a value which then returns <code>nan</code>.</p>
16,654,500
4
1
null
2013-05-20 16:17:20.673 UTC
6
2019-05-06 14:55:10.027 UTC
2013-05-20 16:43:15.233 UTC
null
1,706,564
null
1,706,564
null
1
14
python|matplotlib|pandas
54,742
<p>Since you are using pandas, it's worth mentioning that you can do stacked bar plots natively:</p> <pre><code>df2.plot(kind='bar', stacked=True) </code></pre> <p><em>See the <a href="http://pandas.pydata.org/pandas-docs/stable/visualization.html#bar-plots" rel="noreferrer">visualisation section of the docs</a>.</em></p>
16,786,787
Conversion array types
<p>I have in table column, which type is <code>CHARACTER VARYING[]</code> (that is array)</p> <p>I need concatenate existed rows whith other array</p> <p>This is my code:</p> <pre><code>UPDATE my_table SET col = array_cat(col, ARRAY['5','6','7']) </code></pre> <p>returned error: <code>function array_cat(character varying[], text[]) does not exist</code></p> <p>Reason error is that array types not matches right?</p> <p>Question: how to convert this array <code>ARRAY['5','6','7']</code> as <code>CHARACTER VARYING[]</code> type ?</p>
16,787,209
1
0
null
2013-05-28 07:58:17.463 UTC
5
2013-05-28 08:21:32.953 UTC
null
null
null
null
1,609,729
null
1
23
postgresql|postgresql-9.2
44,543
<p>Cast to <code>varchar[]</code>:</p> <pre><code> &gt; SELECT ARRAY['5','6','7']::varchar[], pg_typeof( ARRAY['5','6','7']::varchar[] ); SELECT ARRAY['5','6','7']::varchar[], pg_typeof( ARRAY['5','6','7']::varchar[] ); array | pg_typeof ---------+--------------------- {5,6,7} | character varying[] </code></pre> <p>You can use the PostgreSQL specific <code>::varchar[]</code> or the standard <code>CAST(colname AS varchar[])</code>... though as arrays are not consistent across database implementations there won't be much advantage to using the standard syntax.</p>
17,079,711
what is the difference between site_url() and base_url()?
<p>As I have read in some resources, <code>base_url()</code> and <code>site_url()</code> functions in <code>Codeigniter</code> are almost the same, although my version of Codeigniter (2.1.3) does not have a site_url() in its config.php file (in the config directory).</p> <p>Yet are there differences between them in any way since I have seen site_url() with parameters and never seen base_url() holding none?</p>
17,079,745
7
0
null
2013-06-13 05:18:45.393 UTC
14
2022-05-02 06:55:00.287 UTC
2022-05-02 06:55:00.287 UTC
null
18,676,264
null
1,764,442
null
1
44
php|codeigniter
87,534
<pre><code>echo base_url(); // http://example.com/website echo site_url(); // http://example.com/website/index.php </code></pre> <p>if you want a URL access to a resource (such as css, js, image), use <code>base_url()</code>, otherwise, <code>site_url()</code> is better.</p> <p>for a detailed reference Check this both function in CodeIgniter.</p> <pre><code>public function site_url($uri = '') { if (empty($uri)) { return $this-&gt;slash_item('base_url').$this-&gt;item('index_page'); } $uri = $this-&gt;_uri_string($uri); if ($this-&gt;item('enable_query_strings') === FALSE) { $suffix = isset($this-&gt;config['url_suffix']) ? $this-&gt;config['url_suffix'] : ''; if ($suffix !== '') { if (($offset = strpos($uri, '?')) !== FALSE) { $uri = substr($uri, 0, $offset).$suffix.substr($uri, $offset); } else { $uri .= $suffix; } } return $this-&gt;slash_item('base_url').$this-&gt;slash_item('index_page').$uri; } elseif (strpos($uri, '?') === FALSE) { $uri = '?'.$uri; } return $this-&gt;slash_item('base_url').$this-&gt;item('index_page').$uri; } </code></pre> <p>Base URL function.</p> <pre><code>public function base_url($uri = '') { return $this-&gt;slash_item('base_url').ltrim($this-&gt;_uri_string($uri), '/'); } </code></pre>
16,821,101
How to set up ES cluster?
<p>Assuming I have 5 machines I want to run an elasticsearch cluster on, and they are all connected to a shared drive. I put a single copy of elasticsearch onto that shared drive so all three can see it. Do I just start the elasticsearch on that shared drive on eall of my machines and the clustering would automatically work its magic? Or would I have to configure specific settings to get the elasticsearch to realize that its running on 5 machines? If so, what are the relevant settings? Should I worry about configuring for replicas or is it handled automatically?</p>
16,821,222
4
1
null
2013-05-29 18:16:06.787 UTC
38
2020-08-16 18:18:37.297 UTC
2013-05-29 18:53:59.98 UTC
null
971,888
null
971,888
null
1
83
elasticsearch
107,839
<p>its super easy.</p> <p>You'll need each machine to have it's own copy of ElasticSearch (simply copy the one you have now) -- the reason is that each machine / node whatever is going to keep it's own files that are sharded accross the cluster.</p> <p>The only thing you really need to do is edit the config file to include the name of the cluster.</p> <p>If all machines have the same cluster name elasticsearch will do the rest automatically (as long as the machines are all on the same network)</p> <p>Read here to get you started: <a href="https://www.elastic.co/guide/en/elasticsearch/guide/current/deploy.html">https://www.elastic.co/guide/en/elasticsearch/guide/current/deploy.html</a></p> <p>When you create indexes (where the data goes) you define at that time how many replicas you want (they'll be distributed around the cluster)</p>
16,678,072
Can we set a Git default to fetch all tags during a remote pull?
<p>I currently have a git remote setup like the following:</p> <pre><code>[remote "upstream"] url = &lt;redacted&gt; fetch = +refs/heads/*:refs/remotes/upstream/* </code></pre> <p>When I issue <code>git pull</code> on branch master, all remote heads are fetched into remotes/upstream, then remotes/upstream/master is merged into master. Any tags that can be reached are also fetched at the same time, which is very convenient.</p> <p>I'd like <code>git pull</code> to additionally fetch <em>all</em> tags from the remote, not just those that are directly reachable from the heads. I originally tried seting <code>tagopt == --tags</code>, but found this caused only tags to be fetch and thus broke everything. (Junio even says that's a <a href="http://git.661346.n2.nabble.com/unclear-documentation-of-git-fetch-tags-option-and-tagopt-config-tp7572964p7573006.html" rel="noreferrer">horrendous misconfiguation</a>).</p> <p>Is there a way to make <code>git pull</code> fetch all remote tags by default, in addition to the remote heads?</p>
16,678,319
7
2
null
2013-05-21 19:35:09.513 UTC
39
2021-11-17 04:49:32.843 UTC
2019-11-15 10:33:31.18 UTC
null
1,657,610
null
1,310,220
null
1
186
git
184,447
<p>You should be able to accomplish this by adding a refspec for tags to your local config. Concretely:</p> <pre><code>[remote "upstream"] url = &lt;redacted&gt; fetch = +refs/heads/*:refs/remotes/upstream/* fetch = +refs/tags/*:refs/tags/* </code></pre>
20,875,341
why golang is slower than scala?
<p>In this <a href="http://benchmarksgame.alioth.debian.org/u64/compare.php?lang=go&amp;lang2=scala" rel="noreferrer">test</a>, we can see that the performance of golang is sometimes much slower than scala. In my opinion, since the code of golang is compiled directly to c/c++ compatible binary code, while the code of scala is compiled to JVM byte code, golang should have much better performance, especially in these computation-intensive algorithm the benchmark did. Is my understanding incorrect?</p> <p><a href="http://benchmarksgame.alioth.debian.org/u64/chartvs.php?r=eNoljskRAEEIAlPCA48ozD%2Bb1dkX1UIhzELXeGcih5BqXeksDvbs8Vgi9HFr23iGiD82SgxJqRWkKNctgkMVUfwlHXnZWDkut%2BMK1nGawoYeDLlYQ8eLG1tvF91Dd8NVGm4sBfGaYo0Pok0rWQ%3D%3D&amp;m=eNozMFFwSU1WMDIwNFYoNTNRyAMAIvoEBA%3D%3D&amp;w=eNpLz%2FcvTk7MSQQADkoDKg%3D%3D" rel="noreferrer">http://benchmarksgame.alioth.debian.org/u64/chartvs.php?r=eNoljskRAEEIAlPCA48ozD%2Bb1dkX1UIhzELXeGcih5BqXeksDvbs8Vgi9HFr23iGiD82SgxJqRWkKNctgkMVUfwlHXnZWDkut%2BMK1nGawoYeDLlYQ8eLG1tvF91Dd8NVGm4sBfGaYo0Pok0rWQ%3D%3D&amp;m=eNozMFFwSU1WMDIwNFYoNTNRyAMAIvoEBA%3D%3D&amp;w=eNpLz%2FcvTk7MSQQADkoDKg%3D%3D</a></p>
20,880,746
5
8
null
2014-01-02 02:08:43.127 UTC
9
2016-09-22 20:20:52.25 UTC
2016-09-22 20:20:52.25 UTC
null
73,955
null
547,524
null
1
25
performance|scala|go
33,658
<p>Here's what I think's going on in the four benchmarks where the go solutions are the slowest compared to the scala solutions.</p> <ol> <li><strong>mandelbrot</strong>: the scala implementation has its internal loop unrolled one time. It may be also that the JVM can vectorise the calculation like this, which I think the go compiler doesn't yet do. This is good manual optimisation plus better JVM support for speeding arithmetic.</li> <li><strong>regex-dna</strong>: the scala implementation isn't doing what the benchmark requires: it's asked to """(one pattern at a time) match-replace the pattern in the redirect file, and record the sequence length""" but it's just calculating the length and printing that. The go version does the match-replace so is slower.</li> <li><strong>k-nucleotide</strong>: the scala implementation has been optimised by using bit-twiddling to pack nucleotides into a long rather than use chars. It's a good optimisation that could also be applied to the Go code.</li> <li><strong>binary-trees</strong>: this tests gc performance by filling RAM. It's true that java gc is much faster than the go gc, but the argument for this not being the top priority for go is that usually one can avoid gc in real programs by not producing garbage in the first place.</li> </ol>
20,695,333
Why does unitless line-height behave differently from percentage or em in this example?
<p>I'm perplexed by the behavior of the following CSS, also illustrated <a href="http://jsfiddle.net/Y7Jta/3/">in this fiddle</a>.</p> <pre><code>&lt;style type="text/css"&gt; p { font-size: 14px; } .percentage { line-height: 150%; } .em-and-a-half { line-height: 1.5em; } .decimal { line-height: 1.5; } .smaller { font-size:50%; } .caption { font-weight: bolder; font-size: 80%; } &lt;/style&gt; &lt;p class="caption"&gt;default line spacing&lt;/p&gt; &lt;p&gt;This tutorial provides a brief introduction to the programming &lt;span class=""&gt;language&lt;/span&gt; by using one of its picture-drawing libraries. This tutorial provides a brief introduction to the programming language. This tutorial provides a brief introduction to the programming language.&lt;/p&gt; &lt;p&gt;This tutorial provides a brief introduction to the programming &lt;span class="smaller"&gt;language&lt;/span&gt; by using one of its picture-drawing libraries. This tutorial provides a brief introduction to the programming language. This tutorial provides a brief introduction to the programming language.&lt;/p&gt; &lt;p class="caption"&gt;line-height: 150%&lt;/p&gt; &lt;p class="percentage"&gt;This tutorial provides a brief introduction to the programming &lt;span class=""&gt;language&lt;/span&gt; by using one of its picture-drawing libraries. This tutorial provides a brief introduction to the programming language. This tutorial provides a brief introduction to the programming language.&lt;/p&gt; &lt;p class="percentage"&gt;This tutorial provides a brief introduction to the programming &lt;span class="smaller"&gt;language&lt;/span&gt; by using one of its picture-drawing libraries. This tutorial provides a brief introduction to the programming language. This tutorial provides a brief introduction to the programming language.&lt;/p&gt; &lt;p class="caption"&gt;line-height: 1.5em&lt;/p&gt; &lt;p class="em-and-a-half"&gt;This tutorial provides a brief introduction to the programming &lt;span class=""&gt;language&lt;/span&gt; by using one of its picture-drawing libraries. This tutorial provides a brief introduction to the programming language. This tutorial provides a brief introduction to the programming language.&lt;/p&gt; &lt;p class="em-and-a-half"&gt;This tutorial provides a brief introduction to the programming &lt;span class="smaller"&gt;language&lt;/span&gt; by using one of its picture-drawing libraries. This tutorial provides a brief introduction to the programming language. This tutorial provides a brief introduction to the programming language.&lt;/p&gt; &lt;p class="caption"&gt;line-height: 1.5&lt;/p&gt; &lt;p class="decimal"&gt;This tutorial provides a brief introduction to the programming &lt;span class=""&gt;language&lt;/span&gt; by using one of its picture-drawing libraries. This tutorial provides a brief introduction to the programming language. This tutorial provides a brief introduction to the programming language.&lt;/p&gt; &lt;p class="decimal"&gt;This tutorial provides a brief introduction to the programming &lt;span class="smaller"&gt;language&lt;/span&gt; by using one of its picture-drawing libraries. This tutorial provides a brief introduction to the programming language. This tutorial provides a brief introduction to the programming language.&lt;/p&gt; </code></pre> <p>The first two paragraphs have default line spacing. The second paragraph has one word that is smaller. But it doesn't affect the line spacing in that paragraph. Not that it should, but then —</p> <p>The next two paragraphs have <code>line-height: 150%</code>. Again, the second paragraph has one word that's smaller. But this time, for reasons unclear, the smaller font creates extra space between the first two lines (at least in Safari, Chrome, Firefox and Explorer). This is the original problem in my CSS that I was trying to fix. (I speculate that it has something to do with the browser shrinking the word and then shifting it downward vertically to realign the baselines.)</p> <p>The next two paragraphs have <code>line-height: 1.5em</code>. My understanding is that <code>1.5em</code> is the same as <code>150%</code>. And indeed, the behavior is the same: extra space between the first two lines of the second paragraph.</p> <p><strong>But here's where it gets weird</strong>: the next two paragraphs have <code>line-height: 1.5</code> — no unit specified. This time, the extra-space problem disappears.</p> <p><a href="https://i.stack.imgur.com/6bJu2.png"><img src="https://i.stack.imgur.com/6bJu2.png" width="124" height="152"></a></p> <p>In sum, CSS seems to be giving consistent line-spacing results when the line heights of the parent &amp; child are different (through inheritance of the unitless value) but inconsistent results when the line heights of the parent &amp; child are the same. </p> <p>Thus my questions: </p> <ol> <li><p>I know there's an intentional semantic difference <a href="http://www.w3.org/TR/2011/PR-CSS2-20110412/visudet.html#propdef-line-height">in the CSS spec</a> between <code>1.5</code> and <code>150%</code> or its synonym, <code>1.5em</code>. (Namely: a unitless value is passed to the child element and its line height is calculated using the child's font size, whereas a percentage or em value will cause a line height to be calculated for the parent, and then that calculated value is passed to the child.) But how does this account for the difference in behavior seen here? Where is the extra space coming from? If it's a consequence of some CSS positioning rule, then what is that rule?</p></li> <li><p>Or, if these examples should all render the same way, then which one is implemented incorrectly? (Note on Q2: The fact that the rendering quirk happens the same way across different browsers strongly suggests that none of them are implemented incorrectly, which will take you back to question (1).)</p></li> <li><p><strike>In practical terms, is there a downside to switching to unitless measurements like <code>1.5</code> for <code>line-height</code>?</strike> (Answer: no)</p></li> </ol>
20,818,206
4
13
2013-12-28 16:15:05.443 UTC
2013-12-20 02:29:44.2 UTC
23
2013-12-28 19:36:19.35 UTC
2013-12-28 16:27:17.57 UTC
null
1,486,915
null
1,486,915
null
1
58
html|css
15,254
<p>Based on clues in the proposed answers, I think the rendering behavior seen in these examples is counterintuitive, but correct, and mandated by the interaction of several rules in the spec, and the overall <a href="http://www.w3.org/TR/CSS21/box.html">CSS box model</a>.</p> <ol> <li><p>CSS calculates the leading L needed for a box by the formula <code>line-height</code> = L + AD, where AD is <a href="http://www.w3.org/TR/2011/PR-CSS2-20110412/visudet.html#leading">"the distance from the top to the bottom"</a> of the font. Then "half the leading is added above A and the other half below D." So text that has <code>font-size:16px</code> and <code>line-height:24px</code> will have 4px of leading above and below. Text that <code>font-size:8px</code> and <code>line-height:24px</code> will have 8px of leading above and below.</p></li> <li><p>By default, however, <a href="http://www.w3.org/TR/2011/PR-CSS2-20110412/visudet.html#line-height">"user agent must align the glyphs ... by their relevant baselines."</a>. This starts to explain what's happening here. When <code>line-height</code> is specified by percentage or em, a computed value is inherited by the child (here, the <code>smaller</code> span). Meaning, the <code>smaller</code> span gets the same <code>line-height</code> as the parent block. But because of the L + AD formula, the text of that span has more leading on the top and bottom, and thus the baseline sits higher in its box. The browser pushes down the <code>smaller</code> span vertically to match the baselines.</p></li> <li><p>But then the browser has a new problem — how to deal with the line spacing in the enclosing block, which has been disrupted by this baseline-adjusting process. The spec resolves this too: the <code>line-height</code> of a block-level element <a href="http://www.w3.org/TR/2011/PR-CSS2-20110412/visudet.html#propdef-line-height">"specifies the minimal height of line boxes within the element"</a>. Meaning, CSS makes no promise that you'll get your exact <code>line-height</code>, just that you'll get at least that amount. So the browser pushes the lines apart in the enclosing block so that the realigned child box will fit.</p></li> </ol> <p>The reason this is counterinitutive is that it's the opposite of how most word processors and page-layout programs work. In these programs, a smaller stretch of text within a paragraph is aligned by its baseline (like CSS) but line height is enforced as a distance between baselines, not as a box surrounding the smaller text. But that's not a bug — CSS is designed around a <a href="http://www.w3.org/TR/CSS21/box.html">box model</a>. So in the end, we could say that this spacing behavior is a consequence of that model.</p> <p>That still leaves us to explain the behavior in the example with the unitless line-height:</p> <ol> <li><p>First, note that when no <code>line-height</code> is specified, the browser will apply a unitless line-height by default. This is <a href="http://www.w3.org/TR/2011/PR-CSS2-20110412/visudet.html#propdef-line-height">required by the spec</a>: the initial value of <code>line-height</code> is <code>normal</code>, which is defined to have "the same meaning as &lt;number&gt;", and the spec recommends a value "between 1.0 and 1.2". And that's consistent with what we see in the examples above, where the paragraphs with <code>line-height: 1.5</code> have the same behavior as the paragraphs with no line-height setting (i.e., they are impliedly getting <code>line-height: normal</code>)</p></li> <li><p>As others have pointed out, when the paragraph has <code>line-height: 1.5</code>, the calculated line-height of the paragraph is not inherited by the <code>smaller</code> span. Rather, the <code>smaller</code> span calculates its own line height based on its own font size. When the paragraph has <code>line-height: 1.5; font-size: 14px</code>, then its calculated line height is 14px * 1.5 = 21px. And if the <code>smaller</code> span only has the property <code>font-size: 50%</code>, then its font size is 14px * 50% = 7px, and its line height is 7px * 1.5 = 10.5px (which will generally be rounded to a whole pixel). But overall, the <code>smaller</code> box is half the size of the surrounding text.</p></li> <li><p>As before, the browser will vertically align the <code>smaller</code> span to the adjacent baseline. But this time, because the box around <code>smaller</code> is shorter than the surrounding text, this realignment doesn't have any side effects in the enclosing block. It already fits, so there's no need to spread the lines of the parent paragraph, as there was before.</p></li> </ol> <p><strong>Both cases represent a consistent implementation of the spec.</strong> That's good news, because it means we can predict the line-spacing behavior.</p> <p>That brings us back to the original reason for this question. While I now understand that the CSS box model requires this behavior, as a practicing typographer, this is rarely the behavior I want. What I want is for the lines within a paragraph to have consistent &amp; exact line spacing, even if some spans of text within that paragraph are smaller. </p> <p>Unfortunately, it seems there's no way to directly enforce exact line spacing in CSS as one can in a word processor or page-layout program. Again, this is because of the CSS box model: it doesn't use a baseline-to-baseline line-spacing model, and <code>line-height</code> is specified to be a minimum measurement, not maximum.</p> <p>But we can at least say that unitless line-height values produce the best <em>approximation</em> of exact line spacing in CSS. Fussy typographers like myself should feel comfortable using them, because unitless values are <a href="http://www.w3.org/TR/2011/PR-CSS2-20110412/visudet.html#propdef-line-height">endorsed by the spec</a>, and they produce consistent results across browsers. They are not a hack, nor are they deprecated.</p> <p>The caveat is that they're still only an approximation. Unitless line-height values don't change the underlying CSS box model, nor the CSS box-positioning rules. So it's possible that in some edge cases, they won't have the intended result. But eternal vigilance is the price of good typography. Be careful out there.</p>
4,498,585
How to select first and last <th> only?
<p>My table has <code>id="mytable"</code>. I'm trying to apply some CSS on the first and last <code>&lt;th&gt;</code> only. I tried this but it doesn't work.</p> <pre><code>#mytable th:first, #mytable th:last{ //css goes here } </code></pre>
4,498,596
2
0
null
2010-12-21 11:05:31.943 UTC
7
2017-06-17 20:57:22.623 UTC
2017-06-17 20:57:22.623 UTC
null
4,370,109
null
509,023
null
1
27
css|html-table
45,376
<pre><code>#mytable th:last-child, #mytable th:first-child { //css goes here } </code></pre>
26,702,757
Check if the given string follows the given pattern
<p>A friend of mine just had his interview at Google and got rejected because he couldn't give a solution to this question.</p> <p>I have my own interview in a couple of days and can't seem to figure out a way to solve it.</p> <p>Here's the question:</p> <blockquote> <p>You are given a pattern, such as [a b a b]. You are also given a string, example &quot;redblueredblue&quot;. I need to write a program that tells whether the string follows the given pattern or not.</p> <p>A few examples:</p> <p>Pattern: [a b b a] String: catdogdogcat returns 1</p> <p>Pattern: [a b a b] String: redblueredblue returns 1</p> <p>Pattern: [a b b a] String: redblueredblue returns 0</p> </blockquote> <p>I thought of a few approaches, like getting the number of unique characters in the pattern and then finding that many unique substrings of the string then comparing with the pattern using a hashmap. However, that turns out to be a problem if the substring of a is a part of b.</p> <p>It'd be really great if any of you could help me out with it. :)</p> <p>UPDATE:</p> <p>Added Info: There can be any number of characters in the pattern (a-z). Two characters won't represent the same substring. Also, a character can't represent an empty string.</p>
26,705,386
16
5
null
2014-11-02 18:24:16.07 UTC
15
2021-11-09 17:05:08.36 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
1,772,080
null
1
22
string|algorithm|dynamic-programming|graph-algorithm
18,555
<p>Don't you just need to translate the pattern to a regexp using backreferences, i.e. something like this (Python 3 with the "re" module loaded):</p> <pre><code>&gt;&gt;&gt; print(re.match('(.+)(.+)\\2\\1', 'catdogdogcat')) &lt;_sre.SRE_Match object; span=(0, 12), match='catdogdogcat'&gt; &gt;&gt;&gt; print(re.match('(.+)(.+)\\1\\2', 'redblueredblue')) &lt;_sre.SRE_Match object; span=(0, 14), match='redblueredblue'&gt; &gt;&gt;&gt; print(re.match('(.+)(.+)\\2\\1', 'redblueredblue')) None </code></pre> <p>The regexp looks pretty trivial to generate. If you need to support more than 9 backrefs, you can use named groups - see the <a href="https://docs.python.org/3.4/library/re.html">Python regexp docs</a>.</p>
9,870,417
magento set store id programmatically
<p>I am currently working on a magento site that is in 2 languages (French and Dutch). The approach I am taking is as follows:</p> <ul> <li>Create a folder in the web root (named nl)</li> <li>Import the index.php and .htaccess file to that folder</li> <li><p>In the index.php I modify the following line:</p> <pre><code>Mage::run('nl'); // to specify the store view i want to load </code></pre></li> </ul> <p>When I check, the categories, CMS content etc are still in the default language. The following code:</p> <pre><code>Mage::app()-&gt;getStore()-&gt;getName(); </code></pre> <p>returns the fr store's name. </p> <p>What is it that I'm doing wrong? I think a viable solution would be to set the store to run in index.php...</p> <p>Could someone please let me know how to load a store by ID?</p>
9,901,463
3
0
null
2012-03-26 10:22:40.82 UTC
5
2018-12-11 10:01:41.277 UTC
2018-12-11 10:01:41.277 UTC
null
1,033,581
null
660,298
null
1
10
php|magento|magento-1.4
47,400
<p>After hours of huffing and puffing i was able to figure out a way to set the store id programatically :)</p> <p>In the index.php file, (in your language specific folder), add the following:-</p> <pre><code>$store_id = 'your_store_id_here'; $mageRunCode = 'store view code'; $mageRunType = 'store'; Mage::app()-&gt;setCurrentStore($store_id); Mage::run($mageRunCode, $mageRunType); </code></pre> <p>Hope someone will find this information useful :)</p>
9,833,834
Android - ListView only show the first result
<p>I am working on an android app which interacts with Twitter using their search API. Everythings works well except that when I want to show the result using a ListView, only the first result is shown. </p> <pre><code>ArrayList&lt;TwitterJSONResults&gt; arrayList = new ArrayList&lt;TwitterJSONResults&gt;(data.getResults().size()); for (int i = 0; i &lt; data.getResults().size(); i++) { arrayList.add(data.getResults().get(i)); } ArrayAdapter&lt;TwitterJSONResults&gt; resultAdapter = new ArrayAdapter&lt;TwitterJSONResults&gt;( this, android.R.layout.simple_list_item_1, arrayList); listview.setAdapter(resultAdapter); resultAdapter.notifyDataSetChanged(); </code></pre> <p>The code snippet above show how I add the results to the adapter and set this adapter to the the listview, What am I doing wrong?</p>
9,841,847
8
6
null
2012-03-23 03:32:21.083 UTC
6
2019-12-06 06:02:40.873 UTC
null
null
null
null
495,416
null
1
32
android|listview|element
35,147
<p>Don't put ListView inside of a ScrollView :)</p>
9,931,437
404 - A public action method X was not found on controller Y (ActionInvoker.InvokeAction returns false)
<p>This is NOT a duplicate question, and the problem is driving me crazy. I am getting the typical error "A public action method X was not found on controller Y" which returns a <code>404 Not Found</code>. The screenshot gives you a good idea:</p> <p><img src="https://i.stack.imgur.com/uWE7m.gif" alt="Visual Studio debugging session"></p> <p><strong>The image shows the debugger paused right before the line that throws the exception is executed</strong> (<code>base.HandleUnknownAction(actionName)</code>). Now, before you jump into conclusions, here's some info:</p> <ol> <li>This was working at some point perfectly well.</li> <li>The HTTP verb (<code>GET</code>) should be accepted by the <code>UpdateCart</code> action (see annotations above method signature).</li> <li>The parameters sent are irrelevant: the error happens with <code>POST</code>, <code>GET</code> and any combination of parameters.</li> <li>Other similar actions in the same controller work well.</li> <li>I took the screenshot with <code>UpdateCart</code> marked <code>virtual</code>, but removing <code>virtual</code> makes no difference.</li> <li><strong>The screenshot shows that <code>ActionInvoker.InvokeAction(this.ControllerContext, "UpdateCart")</code> returns false</strong>. Not sure why the reflection performed over my controller can't find the method, but it's RIGHT THERE!!</li> </ol> <p>The routes are the default ones and they work, since otherwise I wouldn't have been able to stop the debugger to take the screenshot above. Here's the code from <code>Global.asax.cs</code>:</p> <pre><code>public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Tickets", action = "Index", id = UrlParameter.Optional } ); } </code></pre> <p>Any ideas are greatly appreciated.</p> <p><strong>EDIT</strong></p> <p>Ethan Brown's answer below is correct: <code>HttpGet</code> and <code>HttpPost</code> are mutually exclusive. The solution was to replace these attributes with <code>[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]</code>.</p>
9,932,926
2
4
null
2012-03-29 18:40:42.843 UTC
5
2014-04-30 22:08:07.257 UTC
2013-10-11 20:32:02.167 UTC
null
498,609
null
498,609
null
1
39
.net|asp.net-mvc|asp.net-mvc-3|.net-4.0
19,930
<p>The problem is that you're specifying both the <code>HttpGet</code> and <code>HttpPost</code> attributes. If you leave both of them off, the action accepts both POST and GET requests. My guess is that the <code>HttpGet</code> and <code>HttpPost</code> attributes don't signal to MVC to allow the corresponding request type, but to <em>deny</em> the opposite type. So by including <code>[HttpPost]</code>, you're denying GET requests, and by including <code>[HttpGet]</code>, you're denying POST requests...effectively denying all request types. Leave the attributes off and it will accept both types.</p> <p><strong>Update</strong>: I just checked the MVC source, and my assumption is correct. In <code>ActionMethodSelector</code>, it checks the attributes thusly:</p> <pre><code>if (attrs.All(attr =&gt; attr.IsValidForRequest(controllerContext, methodInfo))) { matchesWithSelectionAttributes.Add(methodInfo); } </code></pre> <p>In other words, all <code>ActionMethodSelectorAttribute</code> (from which <code>HttpPostAttribute</code> and <code>HttpGetAttribute</code> derive) must return true for the action to be invoked. One or the other is always going to return false, so the action will never execute.</p>
9,702,795
Large github commit diff not shown
<p>This happens to me both with Compare view as well as standard commits that are large in the amount of files changed.</p> <p>The screenshot below is from a compare between two branches with 380 files changed. The files at the beginning of the diff log have their diffs visualized but at a certain point down the page it stops visualizing the diffs. I understand you don't want massive pages but I can't seem to find a way to view a file's diff individually. Instead I have to check these both out locally and do the diff manually.</p> <p>Does anyone have a simpler solution whether it be software driven or (preferably) a link i'm missing on github?</p> <p><img src="https://i.imgur.com/ISdfk.jpg" alt="Diff screenshot"></p>
25,632,477
7
3
null
2012-03-14 13:18:44.227 UTC
7
2021-10-11 12:19:45.813 UTC
null
null
null
null
390,407
null
1
42
git|github|diff
24,612
<p>Adding <code>.patch</code> to the end of the URL somewhat helps. Removes the nice UI and comment functionality, of course.</p> <p>An example. If your pull request is: <a href="https://github.com/JustinTulloss/zeromq.node/pull/47" rel="noreferrer">https://github.com/JustinTulloss/zeromq.node/pull/47</a>, then the patch can be found at <a href="https://github.com/JustinTulloss/zeromq.node/pull/47.patch" rel="noreferrer">https://github.com/JustinTulloss/zeromq.node/pull/47.patch</a></p>
10,097,887
Using sessions & session variables in a PHP Login Script
<p>I have just finished creating an entire login and register systsem in PHP, but my problem is I haven't used any sessions yet. I'm kind of a newbie in PHP and I've never used sessions before. What I want to do is, after the user registers and fills out the login form, they will still stay on the same page. So, there will be one part of the which will be if the session is logged_in and the other part will be else (the user is not logged in so display the login form). Can anyone tell me how to get started?</p>
10,097,986
9
4
null
2012-04-10 23:24:18.557 UTC
36
2021-05-24 06:18:57.977 UTC
2016-12-17 06:09:31.22 UTC
null
2,145,800
null
1,325,291
null
1
49
php|session|authentication
256,076
<p>Hope this helps :)</p> <p>begins the session, you need to say this at the top of a page or before you call session code</p> <pre><code> session_start(); </code></pre> <p>put a user id in the session to track who is logged in</p> <pre><code> $_SESSION['user'] = $user_id; </code></pre> <p>Check if someone is logged in</p> <pre><code> if (isset($_SESSION['user'])) { // logged in } else { // not logged in } </code></pre> <p>Find the logged in user ID</p> <pre><code>$_SESSION['user'] </code></pre> <p>So on your page</p> <pre><code> &lt;?php session_start(); if (isset($_SESSION['user'])) { ?&gt; logged in HTML and code here &lt;?php } else { ?&gt; Not logged in HTML and code here &lt;?php } </code></pre>
9,974,987
How to send an email with a file attachment in Android
<p>I want to attach .vcf file with my mail and send through the mail. But the mail is received on the address without the attachment.I have used the below code but the code for this and i don't know where i am wrong.</p> <pre><code>try { String filelocation="/mnt/sdcard/contacts_sid.vcf"; Intent intent = new Intent(Intent.ACTION_SENDTO); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, ""); intent.putExtra(Intent.EXTRA_STREAM, Uri.parse( "file://"+filelocation)); intent.putExtra(Intent.EXTRA_TEXT, message); intent.setData(Uri.parse("mailto:")); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); activity.startActivity(intent); activity.finish(); } catch(Exception e) { System.out.println("is exception raises during sending mail"+e); } </code></pre>
9,975,439
5
0
null
2012-04-02 10:46:04.407 UTC
25
2020-09-17 17:23:04.79 UTC
2013-12-26 18:22:12.643 UTC
null
864,358
null
1,051,054
null
1
56
android|email|email-attachments|vcf-vcard
96,309
<p>Use the below code to send a file within a email.</p> <pre><code>String filename="contacts_sid.vcf"; File filelocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename); Uri path = Uri.fromFile(filelocation); Intent emailIntent = new Intent(Intent.ACTION_SEND); // set the type to 'email' emailIntent .setType("vnd.android.cursor.dir/email"); String to[] = {"[email protected]"}; emailIntent .putExtra(Intent.EXTRA_EMAIL, to); // the attachment emailIntent .putExtra(Intent.EXTRA_STREAM, path); // the mail subject emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Subject"); startActivity(Intent.createChooser(emailIntent , "Send email...")); </code></pre>
28,323,925
Push segue from UITableViewCell to ViewController in Swift
<p>I'm encountering problems with my UITableViewCells. I connected my UITableView to a API to populate my cells. </p> <p>Then I've created a function which grabs the <code>indexPath.row</code> to identify which JSON-object inside the array that should be sent to the <code>RestaurantViewController</code>. </p> <blockquote> <p><a href="https://mega.co.nz/#!t89CiAKD!qOemhVZ6yCNDfsc-H43Yk4vady7yIqUx3V9d-4NrglQ" rel="noreferrer">Link to my Xcode Project for easier debugging and problem-solving</a></p> </blockquote> <p>Here's how my small snippet looks for setting the "row-clicks" to a global variable.</p> <pre><code>func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { i = indexPath.row } </code></pre> <p>And here's my <code>prepareForSegue()</code> function that should hook up my push-segue to the <code>RestaurantViewController</code>.</p> <pre><code>override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if segue.identifier == "toRestaurant"{ let navigationController = segue.destinationViewController as UINavigationController let vc = navigationController.topViewController as RestaurantViewController vc.data = currentResponse[i] as NSArray } } </code></pre> <p>And here's how I've set up my segue from the <code>UITableViewCell</code> <img src="https://i.stack.imgur.com/gRQbL.png" alt=""></p> <p>Here's my result, I've tried to click every single one of these cells but I won't be pushed to another viewController...I also don't get an error. What is wrong here?</p> <p><img src="https://i.stack.imgur.com/dlMRV.jpg" alt=""></p> <blockquote> <p>Tried solutions that won't work</p> </blockquote> <pre><code>override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if segue.identifier == "toRestaurant"{ let vc = segue.destinationViewController as RestaurantViewController //let vc = navigationController.topViewController as RestaurantViewController vc.data = currentResponse[i] as NSArray } } </code></pre>
28,428,558
9
17
null
2015-02-04 14:32:36.07 UTC
8
2020-11-14 14:00:12.173 UTC
2015-02-09 14:29:01.163 UTC
null
1,308,651
null
1,308,651
null
1
13
ios|iphone|uitableview|swift|uistoryboardsegue
35,154
<p>The problem is that you're not handling your data correctly. If you look into your <code>currentResponse</code> Array, you'll see that it holds NSDictionaries but in your <code>prepareForSegue</code> you try to cast a NSDictionary to a NSArray, which will make the app crash.</p> <p>Change the <code>data</code> variable in <code>RestaurantViewController</code> to a NSDictionary and change your <code>prepareForSegue</code> to pass a a NSDictionary</p> <pre><code>override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if let cell = sender as? UITableViewCell { let i = redditListTableView.indexPathForCell(cell)!.row if segue.identifier == &quot;toRestaurant&quot; { let vc = segue.destinationViewController as RestaurantViewController vc.data = currentResponse[i] as NSDictionary } } } </code></pre> <p>For Swift 5</p> <pre><code>func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if let cell = sender as? UITableViewCell { let i = self.tableView.indexPath(for: cell)!.row if segue.identifier == &quot;toRestaurant&quot; { let vc = segue.destination as! RestaurantViewController vc.data = currentResponse[i] as NSDictionary } } } </code></pre>
7,820,162
Remove <div> using jQuery
<p>I have this HTML code:</p> <pre><code>&lt;div id="note_list"&gt; &lt;div class="note"&gt; Text 1 &lt;a href=""&gt;X&lt;/a&gt; &lt;/div&gt; &lt;div class="note"&gt; Text 2 &lt;a href=""&gt;X&lt;/a&gt; &lt;/div&gt; &lt;div class="note"&gt; Text 3 &lt;a href=""&gt;X&lt;/a&gt; &lt;/div&gt; &lt;div class="note"&gt; Text 4 &lt;a href=""&gt;X&lt;/a&gt; &lt;/div&gt; &lt;div class="note"&gt; Text 5 &lt;a href=""&gt;X&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Now I would like to use jQuery to <em>delete</em> a <code>&lt;div&gt;</code> element AFTER the 'X' clicking, is it possible?</p> <p>First X closes:</p> <pre><code> &lt;div class="note"&gt; Text 1 &lt;a href=""&gt;X&lt;/a&gt; &lt;/div&gt; </code></pre> <p>etc etc. Can I remove a <em>div</em> without using <code>id=""</code>?</p> <p>Thank you! </p>
7,820,191
3
1
null
2011-10-19 10:51:34.463 UTC
2
2018-09-24 13:55:39.24 UTC
2018-09-24 13:55:39.24 UTC
null
814,702
null
887,651
null
1
16
javascript|jquery
58,658
<pre><code>$(".note a").click(function(e) { e.preventDefault(); $(this).parent().remove(); }); </code></pre> <p>or instead of <code>remove()</code> you could use <code>slideUp()</code></p>
8,304,387
Android: How do I force the update of all widgets of a particular kind
<p>I have seen many questions along these lines, and I keep seeing the same answer over and over. I don't want to have to have a Service for every kind of widget my app has, especially seeing as my app already has 2 persistent services.</p> <p>Specifically, if one of my existing services sees that data has changed, I want to update my widgets. Doing this on a timer is annoying, as it could be days between updates or there might be several within one hour. I want my widgets to ALWAYS show up to date information.</p> <p>Android widget design seems to work on the basis that your widget pulls information when it wants it, I think there are many sensible scenarios where an activity may wish to push data to a widget.</p> <p>Read the answer below for how I worked out how to do precisely this. As far as I can see there are no adverse effects if it is done properly.</p>
8,304,682
3
0
null
2011-11-29 00:43:34.617 UTC
11
2016-10-06 00:45:23.24 UTC
2012-05-06 14:02:24.327 UTC
null
11,343
null
923,279
null
1
16
android|widget
29,257
<p>To force our widgets for a particular widget provider to be updated, we will need to do the following:</p> <ul> <li>Set up our provider to receive a specialized broadcast</li> <li>Send the specialized broadcast with: <ol> <li>All the current widget Id's associated with the provider</li> <li>The data to send</li> <li>Keys that only our provider responds to (Important!)</li> </ol></li> <li>Getting our widget to update on click (without a service!)</li> </ul> <p><strong>Step 1 - Set up our AppWidgetProvider</strong></p> <p>I will not go through the details of creating the info xml file or changes to the Android Manifest - if you don't know how to create a widget properly, then there are plenty of tutorials out there you should read first.</p> <p>Here is an example <code>AppWidgetProvider</code> Class:</p> <pre><code>public class MyWidgetProvider extends AppWidgetProvider { public static final String WIDGET_IDS_KEY ="mywidgetproviderwidgetids"; public static final String WIDGET_DATA_KEY ="mywidgetproviderwidgetdata"; } @Override public void onReceive(Context context, Intent intent) { if (intent.hasExtra(WIDGET_IDS_KEY)) { int[] ids = intent.getExtras().getIntArray(WIDGET_IDS_KEY); if (intent.hasExtra(WIDGET_DATA_KEY)) { Object data = intent.getExtras().getParcelable(WIDGET_DATA_KEY); this.update(context, AppWidgetManager.getInstance(context), ids, data); } else { this.onUpdate(context, AppWidgetManager.getInstance(context), ids); } } else super.onReceive(context, intent); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { update(context, appWidgetManager, appWidgetIds, null); } //This is where we do the actual updating public void update(Context context, AppWidgetmanager manager, int[] ids, Object data) { //data will contain some predetermined data, but it may be null for (int widgetId : ids) { . . //Update Widget here . . manager.updateAppWidget(widgetId, remoteViews); } } </code></pre> <p><strong>Step 2 - Sending the broadcast</strong></p> <p>Here we can create a static method that will get our widgets to update. It is important that we use our own keys with the widget update action, if we use AppWidgetmanager.EXTRA_WIDGET_IDS we will not only break our own widget, but others as well.</p> <pre><code>public static void updateMyWidgets(Context context, Parcelable data) { AppWidgetManager man = AppWidgetManager.getInstance(context); int[] ids = man.getAppWidgetIds( new ComponentName(context,MyWidgetProvider.class)); Intent updateIntent = new Intent(); updateIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); updateIntent.putExtra(MyWidgetProvider.WIDGET_ID_KEY, ids); updateIntent.putExtra(MyWidgetProvider.WIDGET_DATA_KEY, data); context.sendBroadcast(updateIntent); } </code></pre> <p>If using this method with multiple providers MAKE SURE they use different keys. Otherwise you may find widget a's code updating widget b and that can have some bizarre consequences.</p> <p><strong>Step 3 - updating on click</strong></p> <p>Another nice thing to do is to get our widget to update magiacally whenever it is clicked. Add the following code into the update method to acheive this:</p> <pre><code>RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.mywidget_layout); Intent updateIntent = new Intent(); updateIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); updateIntent.putExtra(myWidgetProvider.WIDGET_IDS_KEY, ids); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, 0, updateIntent, PendingIntent.FLAG_UPDATE_CURRENT); views.setOnClickPendingIntent(R.id.view_container, pendingIntent); </code></pre> <p>This code will cause the onUpdate method to be called whenever the widget is clicked on.</p> <p><strong>Notes</strong></p> <ul> <li>Any call to updateWidgets() will cause all instances of our widget to be updated.</li> <li>Clicking the widget will cause all instances of our widget to be updated</li> <li>NO SERVICE REQUIRED</li> <li>Of course, be careful not to update to often - widget updates use battery power.</li> <li>Bear in mind that the broadcast is received by ALL widget providers, and its our special keys that ensure it is only our widgets that actually update.</li> </ul>
11,649,621
scott account locked in SQL Plus
<p>When I am trying to logging to Oracle Sql plus by entering 'scott' as username and 'tiger' as password, it shows 'the account is locked'. How to unlock 'scott' account. The screen shot of SQL Plus CLI is given below. </p> <p><img src="https://i.stack.imgur.com/0DiMc.png" alt="The screen shot is given below"></p>
11,650,536
6
0
null
2012-07-25 12:23:02.04 UTC
8
2021-01-25 16:49:31.52 UTC
2014-02-03 17:47:51.833 UTC
null
881,229
null
1,442,566
null
1
10
oracle11g|sqlplus
80,374
<p>Login in to your DB with user <code>SYS</code></p> <pre><code>SQL*Plus: Release 11.2.0.1.0 Production on Wed Jul 25 15:13:25 2012 Copyright (c) 1982, 2010, Oracle. All rights reserved. Enter user-name: sys as sysdba Enter password: </code></pre> <p>then issue</p> <pre><code>alter user scott account unlock; </code></pre> <p>Then you will be able to login as scott.</p> <pre><code>conn scott/tiger </code></pre>
11,612,647
Raw image data from camera like "645 PRO"
<p>A time ago I already asked this question and I also got a good answer:</p> <blockquote> <p>I've been searching this forum up and down but I couldn't find what I really need. I want to get raw image data from the camera. Up till now I tried to get the data out of the imageDataSampleBuffer from that method captureStillImageAsynchronouslyFromConnection:completionHandler: and to write it to an NSData object, but that didn't work. Maybe I'm on the wrong track or maybe I'm just doing it wrong. What I don't want is for the image to be compressed in any way.</p> <p>The easy way is to use jpegStillImageNSDataRepresentation: from AVCaptureStillImageOutput, but like I said I don't want it to be compressed.</p> <p>Thanks!</p> </blockquote> <p><a href="https://stackoverflow.com/questions/10698663/raw-image-data-from-camera">Raw image data from camera</a></p> <p>I thought I could work with this, but I finally noticed that I need to get raw image data more directly in a similar way as it is done in "645 PRO".</p> <p><a href="http://jag.gr/2012/04/17/645-pro-raw-redux/" rel="nofollow noreferrer">645 PRO: RAW Redux</a></p> <p>The pictures on that site show that they get the raw data before any jpeg compression is done. That is what I want to do. My guess is that I need to transform <code>imageDataSampleBuffer</code> but I don't see a way to do it completely without compression. "645 PRO" also saves its pictures in TIFF so I think it uses at least one additional library. </p> <p>I don't want to make a photo app but I need the best quality I get to check for certain features in a picture.</p> <p>Thanks!</p> <p><strong>Edit 1:</strong> So after trying and searching in different directions for a while now I decided to give a status update.</p> <p>The final goal of this project is to check for certain features in a picture which will happen with the help of opencv. But until the app is able to do it on the phone I'm trying to get mostly uncompressed pictures out of the phone to analyse them on the computer.</p> <p>Therefore I want to save the "NSData instance containing the uncompressed BGRA bytes returned from the camera" I'm able to get with Brad Larson's code as bmp or TIFF file. As I said in a comment I tried using opencv for this (it will be needed anyway). But the best I could do was turning it into a UIImage with a function from <a href="http://computer-vision-talks.com/2012/06/opencv-tutorial-part-3/" rel="nofollow noreferrer">Computer Vision Talks</a>.</p> <pre><code>void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer); cv::Mat frame(height, width, CV_8UC4, (void*)baseAddress); UIImage *testImag = [UIImage imageWithMat:frame andImageOrientation:UIImageOrientationUp]; //imageWithMat... being the function from Computer Vision Talks which I can post if someone wants to see it </code></pre> <p><strong>ImageMagick - Approach</strong></p> <p>Another thing I tried was using ImageMagick as suggested in <a href="https://stackoverflow.com/questions/8714753/how-to-create-a-tiff-on-the-ipad">another post</a>. But I couldn't find a way to do it without using something like <code>UIImagePNGRepresentation</code>or <code>UIImageJPEGRepresentation</code>.</p> <p>For now I'm trying to do something with libtiff using this <a href="http://www.ibm.com/developerworks/linux/library/l-libtiff/" rel="nofollow noreferrer">tutorial</a>.</p> <p>Maybe someone has an idea or knows a much easier way to convert my buffer object into an uncompressed picture. Thanks in advance again!</p> <p><strong>Edit 2:</strong></p> <p>I found something! And I must say I was very blind.</p> <pre><code>void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer); cv::Mat frame(height, width, CV_8UC4, (void*)baseAddress); NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"ocv%d.TIFF", picNum]]; const char* cPath = [filePath cStringUsingEncoding:NSMacOSRomanStringEncoding]; const cv::string newPaths = (const cv::string)cPath; cv::imwrite(newPaths, frame); </code></pre> <p>I just have to use the imwrite function from opencv. This way I get TIFF-files around 30 MB directly after the beyer-Polarisation!</p>
11,795,983
4
2
null
2012-07-23 12:34:30.3 UTC
9
2017-01-13 19:42:20.66 UTC
2017-05-23 12:32:08.41 UTC
null
-1
null
1,409,716
null
1
12
ios|image|opencv|camera|imagemagick
8,391
<p>I could solve it with OpenCV. Thanks to everyone who helped me.</p> <pre><code>void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer); cv::Mat frame(height, width, CV_8UC4, (void*)baseAddress); NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"ocv%d.BMP", picNum]]; const char* cPath = [filePath cStringUsingEncoding:NSMacOSRomanStringEncoding]; const cv::string newPaths = (const cv::string)cPath; cv::imwrite(newPaths, frame); </code></pre> <p>I just have to use the imwrite function from opencv. This way I get BMP-files around 24 MB directly after the bayer-filter!</p>
11,532,989
Android: decrypt RSA text using a Public key stored in a file
<p>I've been several days trying to do it without success.</p> <p>There are plenty of similar questions here in StackOverflow and even two of them are exactly the same as mine but unanswered and unresolved: 1) <a href="https://stackoverflow.com/questions/7037780/convert-php-rsa-publickey-into-android-publickey">Convert PHP RSA PublicKey into Android PublicKey</a> 2) <a href="https://stackoverflow.com/questions/9823409/android-how-to-decrypt-an-openssl-encrypted-file-with-rsa-key">Android: how to decrypt an openssl encrypted file with RSA key?</a></p> <p>My scenario: I have some text encrypted using RSA (not encrypted by me). I have a "public.key" file in my res/raw folder with the public key needed to decrypt it (the public key related to the private key used to encrypt the message), with a format like the following example: <img src="https://i.stack.imgur.com/mR39v.png" alt="enter image description here"></p> <p>I see a lot of examples of how to decrypt a RSA text, like the following one:</p> <pre><code>public static byte[] decryptRSA( PublicKey key, byte[] text) throws Exception { byte[] dectyptedText = null; Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, key); dectyptedText = cipher.doFinal(text); return dectyptedText; } </code></pre> <p>But my question is, how to get the proper PublicKey instance from the file? No examples of this.</p> <p>If I simply try:</p> <pre><code> InputStream is = getResources().openRawResource(R.raw.public); DataInputStream dis = new DataInputStream(is); byte [] keyBytes = new byte [(int) is.available()]; dis.readFully(keyBytes); dis.close(); X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePublic(spec); </code></pre> <p>I get an InvalidKeyException in the return sentence. Would I need to decode Hex or Base64? Aren't the first and last lines of the public key file a problem (the ones with "----BEGIN PUBLIC KEY----" and so)?</p> <p>Maybe we could get the answer of this properly for the first time in StackOverflow:-)</p>
11,541,406
4
7
null
2012-07-18 01:12:21.753 UTC
12
2012-08-23 23:12:55.047 UTC
2017-05-23 12:18:18.82 UTC
null
-1
null
1,062,587
null
1
18
android|rsa|encryption
21,050
<p>Finally solved!!! Drums, trumpets and a symphony of enchanting sounds!!!</p> <pre><code>public static byte[] decryptRSA(Context mContext, byte[] message) throws Exception { // reads the public key stored in a file InputStream is = mContext.getResources().openRawResource(R.raw.sm_public); BufferedReader br = new BufferedReader(new InputStreamReader(is)); List&lt;String&gt; lines = new ArrayList&lt;String&gt;(); String line = null; while ((line = br.readLine()) != null) lines.add(line); // removes the first and last lines of the file (comments) if (lines.size() &gt; 1 &amp;&amp; lines.get(0).startsWith("-----") &amp;&amp; lines.get(lines.size()-1).startsWith("-----")) { lines.remove(0); lines.remove(lines.size()-1); } // concats the remaining lines to a single String StringBuilder sb = new StringBuilder(); for (String aLine: lines) sb.append(aLine); String keyString = sb.toString(); Log.d("log", "keyString:"+keyString); // converts the String to a PublicKey instance byte[] keyBytes = Base64.decodeBase64(keyString.getBytes("utf-8")); X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey key = keyFactory.generatePublic(spec); // decrypts the message byte[] dectyptedText = null; Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, key); dectyptedText = cipher.doFinal(Base64.decodeBase64(message)); return dectyptedText; } </code></pre> <p>The solution was to Base64 decode not only the public key read from the file, but also the crypted message itself!</p> <p>By the way, I read the public key from the file the way @Nikolay suggested (tnx again man).</p> <p>Thank you all very much for your help. StackOverflow rocks!</p>
11,495,842
How SurfaceHolder callbacks are related to Activity lifecycle?
<p>I've been trying to implement an application that requires camera preview on a surface. As I see the things, both activity and surface lifecycles consist of the following states:</p> <ol> <li>When I first launch my Activity: <code>onResume()-&gt;onSurfaceCreated()-&gt;onSurfaceChanged()</code></li> <li>When I leave my Activity: <code>onPause()-&gt;onSurfaceDestroyed()</code></li> </ol> <p>In this scheme, I can do corresponding calls like open/release camera and start/stop preview in <code>onPause/onResume</code> and <code>onSurfaceCreated()/onSurfaceDestroyed()</code>.</p> <p>It works fine, unless I lock the screen. When I launch the app, then lock the screen and unlock it later I see:</p> <p><code>onPause()</code> - and nothing else after the screen is locked - then <code>onResume()</code> after unlock - and no surface callbacks after then. Actually, <code>onResume()</code> is called after the power button is pressed and the screen is on, but the lock screen is still active, so, it's before the activity becomes even visible.</p> <p>With this scheme, I get a black screen after unlock, and no surface callbacks are called.</p> <p>Here's a code fragment that doesn't involve actual work with the camera, but the <code>SurfaceHolder</code> callbacks. The issue above is reproduced even with this code on my phone (callbacks are called in a normal sequence when you press "Back" button, but are missing when you lock the screen):</p> <pre><code>class Preview extends SurfaceView implements SurfaceHolder.Callback { private static final String tag= "Preview"; public Preview(Context context) { super(context); Log.d(tag, "Preview()"); SurfaceHolder holder = getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public void surfaceCreated(SurfaceHolder holder) { Log.d(tag, "surfaceCreated"); } public void surfaceDestroyed(SurfaceHolder holder) { Log.d(tag, "surfaceDestroyed"); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { Log.d(tag, "surfaceChanged"); } } </code></pre> <p>Any ideas on why the surface remains undestroyed after the Activity is paused? Also, how do you handle camera lifecycle in such cases?</p>
13,671,391
5
1
null
2012-07-15 21:40:50.977 UTC
37
2016-06-25 07:43:56.727 UTC
null
null
null
null
1,527,426
null
1
73
android|camera|surfaceview
46,291
<p><strong>Edit:</strong> if the targetSDK is greater than 10, putting the app to sleep calls <code>onPause</code> <em>and</em> <code>onStop</code>. <a href="https://stackoverflow.com/a/25497907/1094605">Source</a> </p> <p>I looked at the lifecycle of both the Activity and the SurfaceView in a tiny camera app on my gingerbread phone. You are entirely correct; the surface is not destroyed when the power button is pressed to put the phone to sleep. When the phone goes to sleep, the Activity does <code>onPause</code>. (And does not do <code>onStop</code>.) It does <code>onResume</code> when the phone wakes up, and, as you point out, it does this while the lock screen is still visible and accepting input, which is a bit odd. When I make the Activity invisible by pressing the Home button, the Activity does both <code>onPause</code> and <code>onStop</code>. Something causes a callback to <code>surfaceDestroyed</code> in this case between the end of <code>onPause</code> and the start of <code>onStop</code>. It's not very obvious, but it does seem very consistent.</p> <p>When the power button is pressed to sleep the phone, unless something is explicitly done to stop it, the camera keeps running! If I have the camera do a per-image callback for each preview frame, with a Log.d() in there, the log statements keep coming while the phone is pretending to sleep. I think that is <em>Very Sneaky</em>.</p> <p>As another confusion, the callbacks to <code>surfaceCreated</code> and <code>surfaceChanged</code> happen <em>after</em> <code>onResume</code> in the activity, if the surface is being created.</p> <p>As a rule, I manage the camera in the class that implements the SurfaceHolder callbacks.</p> <pre><code>class Preview extends SurfaceView implements SurfaceHolder.Callback { private boolean previewIsRunning; private Camera camera; public void surfaceCreated(SurfaceHolder holder) { camera = Camera.open(); // ... // but do not start the preview here! } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // set preview size etc here ... then myStartPreview(); } public void surfaceDestroyed(SurfaceHolder holder) { myStopPreview(); camera.release(); camera = null; } // safe call to start the preview // if this is called in onResume, the surface might not have been created yet // so check that the camera has been set up too. public void myStartPreview() { if (!previewIsRunning &amp;&amp; (camera != null)) { camera.startPreview(); previewIsRunning = true; } } // same for stopping the preview public void myStopPreview() { if (previewIsRunning &amp;&amp; (camera != null)) { camera.stopPreview(); previewIsRunning = false; } } } </code></pre> <p>and then in the Activity:</p> <pre><code>@Override public void onResume() { preview.myStartPreview(); // restart preview after awake from phone sleeping super.onResume(); } @Override public void onPause() { preview.myStopPreview(); // stop preview in case phone is going to sleep super.onPause(); } </code></pre> <p>and that seems to work OK for me. Rotation events cause the Activity to be destroyed and recreated, which causes the SurfaceView to be destroyed and recreated too.</p>
11,675,077
Measure the time it takes to execute a t-sql query
<p>I have two t-sql queries using SqlServer 2005. How can I measure how long it takes for each one to run? </p> <p>Using my stopwatch doesn't cut it.</p>
11,675,263
7
1
null
2012-07-26 17:49:59.587 UTC
67
2022-09-08 06:17:26.107 UTC
null
null
null
null
130,112
null
1
192
performance|sql-server-2005
254,444
<p>One simplistic approach to measuring the "elapsed time" between events is to just grab the current date and time.</p> <p>In SQL Server Management Studio</p> <pre><code>SELECT GETDATE(); SELECT /* query one */ 1 ; SELECT GETDATE(); SELECT /* query two */ 2 ; SELECT GETDATE(); </code></pre> <p>To calculate elapsed times, you could grab those date values into variables, and use the DATEDIFF function:</p> <pre><code>DECLARE @t1 DATETIME; DECLARE @t2 DATETIME; SET @t1 = GETDATE(); SELECT /* query one */ 1 ; SET @t2 = GETDATE(); SELECT DATEDIFF(millisecond,@t1,@t2) AS elapsed_ms; SET @t1 = GETDATE(); SELECT /* query two */ 2 ; SET @t2 = GETDATE(); SELECT DATEDIFF(millisecond,@t1,@t2) AS elapsed_ms; </code></pre> <p>That's just one approach. You can also get elapsed times for queries using SQL Profiler.</p>
4,022,535
How to have a "random" order on a set of objects with paging in Django?
<p>I have a model with 100 or so entries - the client would like these entries to appear in a 'random' order, but would also like paging in there.</p> <pre><code>def my_view(request): object_list = Object.objects.all().order_by('?') paginator = Paginator(object_list, 10) page = 1 # or whatever page we have display_list = paginator.page(page) .... </code></pre> <p>So my question should really be - how can I have my <code>object_list</code> created once per user session?</p>
4,027,044
4
0
null
2010-10-26 09:54:15.507 UTC
9
2016-06-21 06:15:58.34 UTC
null
null
null
null
214,841
null
1
16
django|django-models
9,717
<p>Exactly how random must these be? Does it have to be different for each user, or is it merely the <strong>appearance</strong> of randomness that is important?</p> <p>If it is the latter, then you can simply add a field called <code>ordering</code> to the model in question, and populate it with random integers.</p> <p>Otherwise, unless the recordset is small (and, given it is being paged, I doubt it), then storing a separate random queryset for each session could become a memory issue very quickly unless you know that the user base is very small. Here is one possible solution that mimics randomness but in reality creates only 5 random sets:</p> <pre><code>import random from django.core import cache RANDOM_EXPERIENCES=5 def my_view(request): if not request.session.get('random_exp'): request.session['random_exp']=random.randrange(0,RANDOM_EXPERIENCES) object_list = cache.get('random_exp_%d' % request.session['random_exp']) if not object_list: object_list = list(Object.objects.all().order_by('?')) cache.set('random_exp_%d' % request.session['random_exp'], object_list, 100) paginator = Paginator(object_list, 10) page = 1 # or whatever page we have display_list = paginator.page(page) .... </code></pre> <p>In this example, instead of creating a separate queryset for each user (resulting in potentially thousands of querysets in storage) and storing it in request.session (a less efficient storage mechanism than cache, which can be set to use something very efficient indeed, like memcached), we now have just 5 querysets stored in cache, but hopefully a sufficiently random experience for most users. If you want more randomness, increasing the value for RANDOM_EXPERIENCES should help. I think you could probably go up as high as 100 with few perfomance issues.</p> <p>If the records themselves change infrequently, you can set an extremely high timeout for the cache.</p> <h1>Update</h1> <p>Here's a way to implement it that uses slightly more memory/storage but ensures that each user can "hold on" to their queryset without danger of its cache timing out (assuming that 3 hours is long enough to look at the records).</p> <pre><code>import datetime ... if not request.session.get('random_exp'): request.session['random_exp']="%d_%d" % ( datetime.datetime.strftime(datetime.datetime.now(),'%Y%m%dH'), random.randrange(0, RANDOM_EXPERIENCES) ) object_list = cache.get("random_exp_%s" % request.session['random_exp']) if not object_list: object_list = list(Object.objects.all().order_by('?')) cache.set(cache_key, "random_exp_%s" % request.session['random_exp'], 60*60*4) </code></pre> <p>Here we create a cached queryset that does not time out for 4 hours. However, the request.session key is set to the year, month, day, and hour so that someone coming in sees a recordset current for that hour. Anyone who has already viewed the queryset will be able to see it for at least another 3 hours (or for as long as their session is still active) before it expires. At most, there will be 5*RANDOM_EXPERIENCES querysets stored in cache.</p>
3,653,811
ICD-9 Code List in XML, CSV, or Database format
<p>I am looking for a complete list of ICD-9 Codes (Medical Codes) for Diseases and Procedures in a format that can be imported into a database and referenced programmatically. My question is basically exactly the same as <a href="https://stackoverflow.com/questions/1520257/looking-for-resources-for-icd-9-codes">Looking for resources for ICD-9 codes</a>, but the original poster neglected to mention where exactly he "got ahold of" his complete list. </p> <p>Google is definitely not my friend here as I have spent many hours googling the problem and have found many rich text type lists (such as the CDC) or websites where I can drill down to the complete list interactively, but I cannot find where to get the list that would populate these websites and can be parsed into a Database. I believe the files here <a href="ftp://ftp.cdc.gov/pub/Health_Statistics/NCHS/Publications/ICD9-CM/2009/" rel="nofollow noreferrer">ftp://ftp.cdc.gov/pub/Health_Statistics/NCHS/Publications/ICD9-CM/2009/</a> have what I am looking for but the files are rich text format and contain a lot of garbage and formatting that would be difficult to remove accurately. </p> <p>I know this has to have been done by others and I am trying to avoid duplicating other peoples effort but I just cannot find an xml/CSV/Excel list.</p>
3,761,425
4
1
null
2010-09-06 19:13:49.517 UTC
18
2016-01-18 12:27:39.657 UTC
2017-05-23 10:31:17.15 UTC
null
-1
null
66,231
null
1
33
database|medical
47,197
<p>After removing the RTF it wasn't too hard to parse the file and turn it into a CSV. My resulting parsed files containing all 2009 ICD-9 codes for Diseases and Procedures are here: <a href="http://www.jacotay.com/files/Disease_and_ProcedureCodes_Parsed.zip" rel="noreferrer">http://www.jacotay.com/files/Disease_and_ProcedureCodes_Parsed.zip</a> My parser that I wrote is here: <a href="http://www.jacotay.com/files/RTFApp.zip" rel="noreferrer">http://www.jacotay.com/files/RTFApp.zip</a> Basically it is a two step process - take the files from the CDC FTP site, and remove the RTF from them, then select the RTF-free files and parse them into the CSV files. The code here is pretty rough because I only needed to get the results out once.</p> <p>Here is the code for the parsing app in case the external links go down (back end to a form that lets you select a filename and click the buttons to make it go)</p> <pre><code>Public Class Form1 Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click Dim p As New OpenFileDialog With {.CheckFileExists = True, .Multiselect = False} Dim pResult = p.ShowDialog() If pResult = Windows.Forms.DialogResult.Cancel OrElse pResult = Windows.Forms.DialogResult.Abort Then Exit Sub End If txtFileName.Text = p.FileName End Sub Private Sub btnGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGo.Click Dim pFile = New IO.FileInfo(txtFileName.Text) Dim FileText = IO.File.ReadAllText(pFile.FullName) FileText = RemoveRTF(FileText) IO.File.WriteAllText(Replace(pFile.FullName, pFile.Extension, "_fixed" &amp; pFile.Extension), FileText) End Sub Function RemoveRTF(ByVal rtfText As String) Dim rtBox As System.Windows.Forms.RichTextBox = New System.Windows.Forms.RichTextBox '// Get the contents of the RTF file. Note that when it is '// stored in the string, it is encoded as UTF-16. rtBox.Rtf = rtfText Dim plainText = rtBox.Text Return plainText End Function Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim pFile = New IO.FileInfo(txtFileName.Text) Dim FileText = IO.File.ReadAllText(pFile.FullName) Dim DestFileLine As String = "" Dim DestFileText As New System.Text.StringBuilder 'Need to parse at lines with numbers, lines with all caps are thrown away until next number FileText = Strings.Replace(FileText, vbCr, "") Dim pFileLines = FileText.Split(vbLf) Dim CurCode As String = "" For Each pLine In pFileLines If pLine.Length = 0 Then Continue For End If pLine = pLine.Replace(ChrW(9), " ") pLine = pLine.Trim Dim NonCodeLine As Boolean = False If IsNumeric(pLine.Substring(0, 1)) OrElse (pLine.Length &gt; 3 AndAlso (pLine.Substring(0, 1) = "E" OrElse pLine.Substring(0, 1) = "V") AndAlso IsNumeric(pLine.Substring(1, 1))) Then Dim SpacePos As Int32 SpacePos = InStr(pLine, " ") Dim NewCode As String NewCode = "" If SpacePos &gt;= 3 Then NewCode = Strings.Left(pLine, SpacePos - 1) End If If SpacePos &lt; 3 OrElse Strings.Mid(pLine, SpacePos - 1, 1) = "." OrElse InStr(NewCode, "-") &gt; 0 Then NonCodeLine = True Else If CurCode &lt;&gt; "" Then DestFileLine = Strings.Replace(DestFileLine, ",", "&amp;#44;") DestFileLine = Strings.Replace(DestFileLine, """", "&amp;quot;").Trim DestFileText.AppendLine(CurCode &amp; ",""" &amp; DestFileLine &amp; """") CurCode = "" DestFileLine = "" End If CurCode = NewCode DestFileLine = Strings.Mid(pLine, SpacePos + 1) End If Else NonCodeLine = True End If If NonCodeLine = True AndAlso CurCode &lt;&gt; "" Then 'If we are not on a code keep going, otherwise check it Dim pReg As New System.Text.RegularExpressions.Regex("[a-z]") Dim pRegCaps As New System.Text.RegularExpressions.Regex("[A-Z]") If pReg.IsMatch(pLine) OrElse pLine.Length &lt;= 5 OrElse pRegCaps.IsMatch(pLine) = False OrElse (Strings.Left(pLine, 3) = "NOS" OrElse Strings.Left(pLine, 2) = "IQ") Then DestFileLine &amp;= " " &amp; pLine Else 'Is all caps word DestFileLine = Strings.Replace(DestFileLine, ",", "&amp;#44;") DestFileLine = Strings.Replace(DestFileLine, """", "&amp;quot;").Trim DestFileText.AppendLine(CurCode &amp; ",""" &amp; DestFileLine &amp; """") CurCode = "" DestFileLine = "" End If End If Next If CurCode &lt;&gt; "" Then DestFileLine = Strings.Replace(DestFileLine, ",", "&amp;#44;") DestFileLine = Strings.Replace(DestFileLine, """", "&amp;quot;").Trim DestFileText.AppendLine(CurCode &amp; ",""" &amp; DestFileLine &amp; """") CurCode = "" DestFileLine = "" End If IO.File.WriteAllText(Replace(pFile.FullName, pFile.Extension, "_parsed" &amp; pFile.Extension), DestFileText.ToString) End Sub </code></pre> <p>End Class</p>
4,013,725
converting a canvas into bitmap image in android
<p>I am trying to develop an app on canvas,I am drawing a bitmap on the canvas. After drawing, I am trying to convert into bitmap image.</p> <p>Can anyone give me a suggestion?</p>
4,013,780
4
1
null
2010-10-25 10:37:08.793 UTC
13
2020-04-18 09:30:07.92 UTC
2020-04-18 09:30:07.92 UTC
null
5,446,749
null
486,301
null
1
53
android|bitmap|android-canvas
98,770
<p>Advice depends upon what you are trying to do.</p> <p>If you are concerned that your controls take a long time to draw, and you want to draw to a bitmap so you can blit the bitmap rather than re-drawing via a canvas, then you <em>don't</em> want to be double-guessing the platform - controls automatically cache their drawing to temporary bitmaps, and these can even be fetched from the control using <a href="http://developer.android.com/reference/android/view/View.html#getDrawingCache%28%29" rel="noreferrer"><code>getDrawingCache()</code></a></p> <p>If you want to draw using a canvas to a bitmap, the usual recipe is:</p> <ol> <li>Create a bitmap of the correct size using <a href="http://developer.android.com/reference/android/graphics/Bitmap.html#createBitmap%28int,%20int,%20android.graphics.Bitmap.Config%29" rel="noreferrer"><code>Bitmap.createBitmap()</code></a></li> <li>Create a canvas instance pointing that this bitmap using <a href="http://developer.android.com/reference/android/graphics/Canvas.html#Canvas%28android.graphics.Bitmap%29" rel="noreferrer"><code>Canvas(Bitmap)</code></a> constructor</li> <li>Draw to the canvas</li> <li>Use the bitmap</li> </ol>
3,677,338
How-to get the Application path using javascript
<p>If I have my application hosted in a directory. The application path is the directory name.</p> <p>For example</p> <p><code>http://192.168.1.2/AppName/some.html</code></p> <p>How to get using javascript the application name like in my case <code>/AppName</code>.</p> <p><code>document.domain</code> is returning the hostname and <code>document.URL</code> is returning the whole Url.</p> <p><strong>EDIT</strong></p> <p>Thr app path could be more complex, like <code>/one/two/thre/</code></p>
3,677,392
5
0
null
2010-09-09 14:06:43.547 UTC
3
2018-02-23 13:22:46.61 UTC
2010-09-09 14:14:00.663 UTC
null
137,348
null
137,348
null
1
12
javascript
40,635
<p>This will give you a result but would have to be modified if you have more levels (see commented code).</p> <pre><code>var path = location.pathname.split('/'); if (path[path.length-1].indexOf('.html')&gt;-1) { path.length = path.length - 1; } var app = path[path.length-2]; // if you just want 'three' // var app = path.join('/'); // if you want the whole thing like '/one/two/three' console.log(app); </code></pre>
3,374,591
CTFramesetterSuggestFrameSizeWithConstraints sometimes returns incorrect size?
<p>In the code below, <code>CTFramesetterSuggestFrameSizeWithConstraints</code> sometimes returns a <code>CGSize</code> with a height that is not big enough to contain all the text that is being passed into it. I did look at <a href="https://stackoverflow.com/questions/2707710/core-texts-ctframesettersuggestframesizewithconstraints-returns-incorrect-size">this answer</a>. But in my case the width of the text box needs to be constant. Is there any other/better way to figure out the correct height for my attributed string? Thanks!</p> <pre><code>CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attributedString); CGSize tmpSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0,0), NULL, CGSizeMake(self.view.bounds.size.width, CGFLOAT_MAX), NULL); CGSize textBoxSize = CGSizeMake((int)tmpSize.width + 1, (int)tmpSize.height + 1); </code></pre>
3,376,983
7
0
null
2010-07-30 19:05:57.847 UTC
27
2022-07-19 08:55:46.16 UTC
2017-05-23 12:02:45.493 UTC
null
-1
null
294,974
null
1
14
iphone|xcode|core-graphics|core-text
11,621
<p><code>CTFramesetterSuggestFrameSizeWithConstraints()</code> is broken. I filed a bug on this a while back. Your alternative is to use <code>CTFramesetterCreateFrame()</code> with a path that is sufficiently high. Then you can measure the rect of the CTFrame that you get back. Note that you cannot use <code>CGFLOAT_MAX</code> for the height, as CoreText uses a flipped coordinate system from the iPhone and will locate its text at the "top" of the box. This means that if you use <code>CGFLOAT_MAX</code>, you won't have enough precision to actually tell the height of the box. I recommend using something like 10,000 as your height, as that's 10x taller than the screen itself and yet gives enough precision for the resulting rectangle. If you need to lay out even taller text, you can do this multiple times for each section of text (you can ask CTFrameRef for the range in the original string that it was able to lay out).</p>
3,355,349
What does the word "semantic" mean in Computer Science context?
<p>I keep coming across the use of this word and I never understand its use or the meaning being conveyed.</p> <p>Phrases like...</p> <blockquote> <p>&quot;add semantics for those who read&quot;</p> <p>&quot;HTML5 semantics&quot;</p> <p>&quot;semantic web&quot;</p> <p>&quot;semantically correctly way to...&quot;</p> </blockquote> <p>... confuse me and I'm not just referring to the web. Is the word just another way to say &quot;grammar&quot; or &quot;syntax&quot;?</p> <p>Thanks!</p>
3,355,473
7
4
null
2010-07-28 16:57:34.013 UTC
12
2016-08-11 18:38:57.29 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
196,921
null
1
36
definition|semantics
21,827
<p>Semantics are the meaning of various elements in the program (or whatever).</p> <p>For example, let's look at this code:</p> <pre><code>int width, numberOfChildren; </code></pre> <p>Both of these variables are integers. From the compiler's point of view, they are exactly the same. However, judging by the names, one is the width of something, while the other is a count of some other things.</p> <pre><code>numberOfChildren = width; </code></pre> <p>Syntactically, this is 100% okay, since you can assign integers to each other. However, semantically, this is totally wrong, since the width and the number of children (probably) don't have any relationship. In this case, we'd say that this is semantically incorrect, even if the compiler permits it.</p>
3,955,688
How to debug Ruby scripts
<p>I copied the following Ruby code from the Internet and made a few changes but it doesn't work.</p> <p>What can I do to debug the program by myself?</p>
7,994,758
17
3
null
2010-10-17 23:01:54.747 UTC
46
2021-08-16 06:24:08.873 UTC
2020-02-26 22:24:04.433 UTC
null
128,421
null
38,765
null
1
169
ruby|debugging
179,231
<p>Use <a href="http://pryrepl.org/" rel="noreferrer">Pry</a> (<a href="https://github.com/pry/pry" rel="noreferrer">GitHub</a>).</p> <p>Install via:</p> <pre><code>$ gem install pry $ pry </code></pre> <p>Then add:</p> <pre><code>require 'pry'; binding.pry </code></pre> <p>into your program.</p> <p>As of <code>pry</code> 0.12.2 however, there are no navigation commands such as <code>next</code>, <code>break</code>, etc. Some other gems additionally provide this, see for example <a href="https://stackoverflow.com/a/29903754/895245"><code>pry-byebug</code></a>.</p>
8,135,132
How to encode URL parameters?
<p>I am trying to pass parameters to a URL which looks like this:</p> <pre><code>http://www.foobar.com/foo?imageurl= </code></pre> <p>And I want to pass the parameters such as an image URL which is generated itself by another API, and the link for the image turns out as:</p> <pre><code>http://www.image.com/?username=unknown&amp;password=unknown </code></pre> <p>However, when I try to use the URL:</p> <pre><code>http://www.foobar.com/foo?imageurl=http://www.image.com/?username=unknown&amp;password=unknown </code></pre> <p>It doesn't work.</p> <p>I have also tried using <code>encodeURI()</code> and <code>encodeURIComponent()</code> on the imageURL, and that too doesn't work.</p>
8,135,197
4
5
null
2011-11-15 10:48:10.647 UTC
9
2021-10-14 13:07:20.19 UTC
2020-08-02 21:08:19.703 UTC
null
2,430,549
null
362,271
null
1
156
javascript|url|encodeuricomponent
194,156
<p><strong>With PHP</strong></p> <pre><code>echo urlencode("http://www.image.com/?username=unknown&amp;password=unknown"); </code></pre> <p>Result</p> <pre><code>http%3A%2F%2Fwww.image.com%2F%3Fusername%3Dunknown%26password%3Dunknown </code></pre> <p><strong>With Javascript:</strong></p> <pre><code>var myUrl = "http://www.image.com/?username=unknown&amp;password=unknown"; var encodedURL= "http://www.foobar.com/foo?imageurl=" + encodeURIComponent(myUrl); </code></pre> <p>DEMO: <a href="http://jsfiddle.net/Lpv53/" rel="noreferrer">http://jsfiddle.net/Lpv53/</a></p>
7,970,988
Print out the values of a (Mat) matrix in OpenCV C++
<p>I want to dump the values of a matrix in OpenCV to the console using cout. I quickly learned that I do not understand OpenvCV's type system nor C++ templates well enough to accomplish this simple task.</p> <p>Would a reader please post (or point me to) a little function or code snippet that prints a Mat?</p> <p>Regards, Aaron</p> <p>PS: Code that uses the newer C++ Mat interface as opposed to the older CvMat interface is preferential.</p>
7,971,568
5
0
null
2011-11-01 18:22:36.7 UTC
11
2022-01-10 19:55:02.88 UTC
null
null
null
null
290,962
null
1
67
c++|opencv
121,600
<p>See the first answer to <a href="https://stackoverflow.com/questions/1844736/accesing-a-matrix-element-in-the-mat-object-not-the-cvmat-object-in-opencv-c">Accessing a matrix element in the &quot;Mat&quot; object (not the CvMat object) in OpenCV C++</a><br> Then just loop over all the elements in <code>cout &lt;&lt; M.at&lt;double&gt;(0,0);</code> rather than just 0,0</p> <p>Or better still with the C++ interface:</p> <pre><code>cv::Mat M; cout &lt;&lt; "M = " &lt;&lt; endl &lt;&lt; " " &lt;&lt; M &lt;&lt; endl &lt;&lt; endl; </code></pre>
7,906,332
How to calculate combination and permutation in R?
<p>How one can calculate the number of combinations and permutations in R?</p> <p>The <a href="http://rss.acs.unt.edu/Rdoc/library/Combinations/html/00Index.html" rel="noreferrer">Combinations package</a> failed to install on Linux with the following message:</p> <pre><code>&gt; install.packages(&quot;Combinations&quot;) Installing package(s) into ‘/home/maxim/R/x86_64-pc-linux-gnu-library/2.13’ (as ‘lib’ is unspecified) Warning message: In getDependencies(pkgs, dependencies, available, lib) : package ‘Combinations’ is not available (for R version 2.13.1) </code></pre>
7,910,439
6
2
null
2011-10-26 16:41:57.03 UTC
24
2021-03-03 22:51:55.217 UTC
2021-01-04 16:31:15.407 UTC
null
6,646,912
Maxim Veksler
48,062
null
1
38
r|combinations
150,586
<p>You can use the <code>combinat</code> package with R 2.13:</p> <pre><code>install.packages("combinat") require(combinat) permn(3) combn(3, 2) </code></pre> <p>If you want to know the number of combination/permutations, then check the size of the result, e.g.:</p> <pre><code>length(permn(3)) dim(combn(3,2))[2] </code></pre>
7,793,927
Message Queue vs Message Bus -- what are the differences?
<p>And are there any? To me, MB knows both subscribers and publishers and acts as a mediator, notifying subscribers on new messages (effectively a "push" model). MQ, on the other hand, is more of a "pull" model, where consumers pull messages off a queue.</p> <p>Am I completely off track here?</p>
7,836,610
7
0
null
2011-10-17 12:45:36.793 UTC
57
2020-07-02 09:39:03.793 UTC
2011-10-18 05:07:47.95 UTC
null
168,868
null
60,188
null
1
140
message-queue|message-bus
94,433
<p>By and large, when it comes to vendor software products, they are used interchangeably, and do not have the strong distinctions in terms of push or pull as you describe.</p> <p>The <em>BUS</em> vs. <em>QUEUE</em> is indeed somewhat a legacy concept, most recently stemming from systems like IBM MQ and Tibco Rendezvous. MQ was originally a 1:1 system, indeed a queue to decouple various systems.</p> <p>Tibco by contrast was (sold as a) messaging backbone, where you could have multiple publishers and subscribers on the same topics.</p> <p>Both however (and newer competing products) can play in each other's space these days. Both can be set to interrupt as well as polling for new messages. Both mediate the interactions between various systems.</p> <p><strong>However</strong> the phrase <em>message-queue</em> is also used for internal intra-thread message pumps and the like, and in this context, the usage is indeed different. If you think of the classic Windows message pump, this indeed is more the pull model you describe, but it is really more intra-app than inter-app or inter-box.</p>
8,263,891
Simple way to check if placeholder is supported?
<p>I want to use the <code>HTML5</code> <code>"placeholder"</code> attribute in my code if the user's browser supports it otherwise just print the field name on top of the form. But I only want to check whether placeholder is supported and not what version/name of browser the user is using.</p> <p>So Ideally i would want to do something like</p> <pre><code> &lt;body&gt; &lt;script&gt; if (placeholderIsNotSupported) { &lt;b&gt;Username&lt;/b&gt;; } &lt;/script&gt; &lt;input type = "text" placeholder ="Username"&gt; &lt;/body&gt; </code></pre> <p>Except Im not sure of the javascript bit. Help is appreciated!</p>
8,263,907
9
0
null
2011-11-25 00:57:16.817 UTC
6
2016-02-25 18:42:14.98 UTC
2011-11-25 01:08:59.267 UTC
null
648,927
null
648,927
null
1
53
javascript|html|placeholder
23,911
<pre><code>function placeholderIsSupported() { var test = document.createElement('input'); return ('placeholder' in test); } </code></pre> <p>I used a <a href="http://www.cssnewbie.com/cross-browser-support-for-html5-placeholder-text-in-forms/" rel="noreferrer">jQuery-ized version</a> as a starting point. (Just giving credit where it's due.)</p>
4,679,080
phpMyadmin - Error #1064
<p>When trying to create this table in my db, I get an error:</p> <blockquote> <p>#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'unsigned NOT NULL default '0', PRIMARY KEY (reminder_id), KEY reminder_id (rem' at line 5</p> </blockquote> <pre><code>CREATE TABLE reminder_events ( reminder_id bigint(20) unsigned NOT NULL auto_increment, reminder_name varchar(255) NOT NULL default '', reminder_desc text, reminder_date varchar(8) unsigned NOT NULL default '0', PRIMARY KEY (reminder_id), KEY reminder_id (reminder_id) ) TYPE=MyISAM; </code></pre> <p>Can anyone see what I'm doing wrong?</p>
4,679,113
3
0
null
2011-01-13 10:34:40.393 UTC
null
2016-02-23 14:07:18.097 UTC
2011-01-13 10:58:01.157 UTC
null
466,826
null
447,208
null
1
2
mysql|phpmyadmin|mysql-error-1064
38,586
<p>The problem is that you're trying to define a text field (varchar) as being unsigned, which is something that can only apply to a numerical field.</p> <p>i.e.: "<code>reminder_date varchar(8) unsigned NOT NULL default '0',</code>" makes no sense.</p> <p>However, as the field is called "reminder_date", I'm guessing you're attempting to store a date, in which case you <em>really</em> want to use MySQLs DATE field type.</p> <p>e.g.: "<code>reminder_date DATE NOT NULL,</code>"</p> <p>Additionally, if you're going to want to search on any of these fields, you should also add some indexes to speed up the searches. So, if you wanted to be able to search on the name and date, you could use:</p> <pre><code>CREATE TABLE reminder_events ( reminder_id bigint(20) unsigned NOT NULL auto_increment, reminder_name varchar(255) NOT NULL DEFAULT '', reminder_desc text, reminder_date DATE NOT NULL, PRIMARY KEY (reminder_id), KEY reminder_id (reminder_id), KEY reminder_name (reminder_name), KEY reminder_date (reminder_date) ) TYPE=MyISAM; </code></pre>
4,315,660
ALTER TABLE in Magento setup script without using SQL
<p><a href="https://stackoverflow.com/users/336905/jonathan-day">Jonathon Day</a> says</p> <blockquote> <p>"updates SHOULD NOT be in the form of SQL commands". I haven't come across any DDL or DML statments that cannot be executed via Magento's config structures.</p> </blockquote> <p>(In the question <a href="https://stackoverflow.com/q/4208030/471559">How can I migrate configuration changes from development to production environment?</a>)</p> <p>I would like to know how best to add/modify/remove a column or index to/from a table in this manner, but without relying on SQL? Is it even possible?</p> <p>Furthermore, what other actions can only be done in SQL?</p>
4,318,501
3
3
null
2010-11-30 15:54:46.293 UTC
60
2017-02-26 16:34:03.81 UTC
2017-05-23 12:26:09.273 UTC
null
-1
null
471,559
null
1
55
php|sql|magento|installation|entity-attribute-value
43,394
<p>You can use such methods within your setup script:</p> <ul> <li><p>Use <code>Varien_Db_Ddl_Table</code> class to create new tables, where you can configure all the fields, keys, relations in combination with <code>$this-&gt;getConnection()-&gt;createTable($tableObject)</code> Example:</p> <pre><code>/* @var $this Mage_Core_Model_Resource_Setup */ $table = new Varien_Db_Ddl_Table(); $table-&gt;setName($this-&gt;getTable('module/table')); $table-&gt;addColumn('id', Varien_Db_Ddl_Table::TYPE_INT, 10, array('unsigned' =&gt; true, 'primary' =&gt; true)); $table-&gt;addColumn('name', Varien_Db_Ddl_Table::TYPE_VARCHAR, 255); $table-&gt;addIndex('name', 'name'); $table-&gt;setOption('type', 'InnoDB'); $table-&gt;setOption('charset', 'utf8'); $this-&gt;getConnection()-&gt;createTable($table); </code></pre></li> <li><p>Use setup connection (<code>$this-&gt;getConnection()</code>) methods:</p> <ul> <li><code>addColumn()</code> method adds new column to exiting table. It has such parameters: <ul> <li><code>$tableName</code> - the table name that should be modified</li> <li><code>$columnName</code>- the name of the column, that should be added</li> <li><code>$definition</code> - definition of the column (<code>INT(10)</code>, <code>DECIMAL(12,4)</code>, etc)</li> </ul></li> <li><code>addConstraint()</code> method creates a new constraint foreign key. It has such parameters <ul> <li><code>$fkName</code> - the foreign key name, should be unique per database, if you don't specify <code>FK_</code> prefix, it will be added automatically</li> <li><code>$tableName</code> - the table name for adding a foreign key</li> <li><code>$columnName</code> - the column name that should be referred to another table, if you have complex foreign key, use comma to specify more than one column</li> <li><code>$refTableName</code> - the foreign table name, which will be handled</li> <li><code>$refColumnName</code> - the column name(s) in the foreign table</li> <li><code>$onDelete</code> - action on row removing in the foreign table. Can be empty string (do nothing), <code>cascade</code>, <code>set null</code>. This field is optional, and if it is not specified, <code>cascade</code> value will be used. </li> <li><code>$onUpdate</code> action on row key updating in the foreign table. Can be empty string (do nothing), <code>cascade</code>, <code>set null</code>. This field is optional, and if it is not specified, <code>cascade</code> value will be used. </li> <li><code>$purge</code> - a flag for enabling cleaning of the rows after foreign key adding (e.g. remove the records that are not referenced)</li> </ul></li> <li><code>addKey()</code> method is used for adding of indexes to a table. It has such parameters: <ul> <li><code>$tableName</code> - the table name where the index should be added</li> <li><code>$indexName</code> - the index name</li> <li><code>$fields</code> - column name(s) used in the index</li> <li><code>$indexType</code> - type of the index. Possible values are: <code>index</code>, <code>unique</code>, <code>primary</code>, <code>fulltext</code>. This parameter is optional, so the default value is <code>index</code></li> </ul></li> <li><code>dropColumn()</code> method is used for removing of columns from the existing table. It has such parameters: <ul> <li><code>$tableName</code> - the table name that should be modified</li> <li><code>$columnName</code>- the name of the column, that should removed</li> </ul></li> <li><code>dropForeignKey()</code> method is used for removing of foreign keys. It has such parameters: <ul> <li><code>$tableName</code> - the table name for removing a foreign key</li> <li><code>$fkName</code> - the foreign key name</li> </ul></li> <li><code>dropKey()</code> method is used for removing of the table indexes. It has such parameters: <ul> <li><code>$tableName</code> - the table name where the index should be removed</li> <li><code>$keyName</code> - the index name</li> </ul></li> <li><code>modifyColumn</code> method is used to modify existing column in the table. It has such parameters: <ul> <li><code>$tableName</code> - the table name that should be modified</li> <li><code>$columnName</code>- the name of the column, that should be renamed</li> <li><code>$definition</code> - a new definition of the column (<code>INT(10)</code>, <code>DECIMAL(12,4)</code>, etc)</li> </ul></li> <li><code>changeColumn</code> method is used to modify and rename existing column in the table. It has such parameters: <ul> <li><code>$tableName</code> - the table name that should be modified</li> <li><code>$oldColumnName</code>- the old name of the column, that should be renamed and modified</li> <li><code>$newColumnName</code>- a new name of the column</li> <li><code>$definition</code> - a new definition of the column (<code>INT(10)</code>, <code>DECIMAL(12,4)</code>, etc)</li> </ul></li> <li><code>changeTableEngine</code> method is used to change table engine, from MyISAM to InnoDB for instance. It has such parameters: <ul> <li><code>$tableName</code> - the table name</li> <li><code>$engine</code> - new engine name (<code>MEMORY</code>, <code>MyISAM</code>, <code>InnoDB</code>, etc)</li> </ul></li> </ul></li> </ul> <p>Also you can use <code>tableColumnExists</code> method to check existence of the column. </p> <p>It is not the full list of methods that are available for you, to get rid of direct SQL queries writing. You can find more at <code>Varien_Db_Adapter_Pdo_Mysql</code> and <code>Zend_Db_Adapter_Abstract</code> classes. </p> <p>Do not hesitate to look into the class definition which you are going to use, you can find a lot of interesting things for yourself :)</p>
4,813,888
Get content of a cell given the row and column numbers
<p>I want to get the content of a cell given its row and column number. The row and column number are stored in cells (here B1,B2). I know the following solutions work, but they feel a bit hacky. </p> <p>Sol 1</p> <pre><code>=CELL("contents",INDIRECT(ADDRESS(B1,B2))) </code></pre> <p>Sol 2</p> <pre><code>=CELL("contents",OFFSET($A$1, B1-1,B2-1)) </code></pre> <p>Is there no less verbose method? (like =CellValue(row,col) or whatever)?</p> <p>Edit / Clarification: I just want to use the excel worksheet formulas. No VBA. In short, I pretty much look for the equivalent of the VBA Cells() method as an excel Formula.</p>
4,814,166
3
1
null
2011-01-27 07:51:05.243 UTC
18
2018-02-26 15:31:37.16 UTC
2015-01-14 14:42:05.38 UTC
null
4,241,535
null
76,024
null
1
96
excel|excel-formula
556,675
<p>You don't need the CELL() part of your formulas:</p> <pre><code>=INDIRECT(ADDRESS(B1,B2)) </code></pre> <p>or </p> <pre><code>=OFFSET($A$1, B1-1,B2-1) </code></pre> <p>will both work. Note that both <code>INDIRECT</code> and <code>OFFSET</code> are volatile functions. Volatile functions can slow down calculation because they are calculated at every single recalculation.</p>
4,150,780
Removing underline from specific anchor tag
<p>Why does the following anchor tag has text underlined?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.pagerLink { background-color: #E4F5F8; border: 1px solid #C0DEED; text-decoration: none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;a class="pagerLink" href="#"&gt;test&lt;/a&gt;</code></pre> </div> </div> </p>
4,150,803
4
0
null
2010-11-11 01:50:13.657 UTC
0
2020-07-11 08:01:45.067 UTC
2020-07-11 08:01:45.067 UTC
null
6,904,888
null
167,520
null
1
15
css
71,612
<p>Probably because another style block has better <a href="http://www.webdesignfromscratch.com/html-css/css-inheritance-cascade/" rel="noreferrer">precedence</a> than your <code>pagerLink</code> class. Try:</p> <pre><code>.pagerLink { background-color: #E4F5F8; border: 1px solid #C0DEED; text-decoration: none !important; } </code></pre>
4,219,743
balancing an AVL tree (C++)
<p>I'm having the hardest time trying to figure out how to balance an AVL tree for my class. I've got it inserting with this:</p> <pre><code>Node* Tree::insert(int d) { cout &lt;&lt; "base insert\t" &lt;&lt; d &lt;&lt; endl; if (head == NULL) return (head = new Node(d)); else return insert(head, d); } Node* Tree::insert(Node*&amp; current, int d) { cout &lt;&lt; "insert\t" &lt;&lt; d &lt;&lt; endl; if (current == NULL) current = new Node(d); else if (d &lt; current-&gt;data) { insert(current-&gt;lchild, d); if (height(current-&gt;lchild) - height(current-&gt;rchild)) { if (d &lt; current-&gt;lchild-&gt;getData()) rotateLeftOnce(current); else rotateLeftTwice(current); } } else if (d &gt; current-&gt;getData()) { insert(current-&gt;rchild, d); if (height(current-&gt;rchild) - height(current-&gt;lchild)) { if (d &gt; current-&gt;rchild-&gt;getData()) rotateRightOnce(current); else rotateRightTwice(current); } } return current; } </code></pre> <p>My plan was to have the calls to balance() check to see if the tree needs balancing and then balance as needed. The trouble is, I can't even figure out how to traverse the tree to find the correct unbalanced node. I know how to traverse the tree recursively, but I can't seem to translate that algorithm into finding the lowest unbalanced node. I'm also having trouble writing an iterative algorithm. Any help would be appreciated. :)</p>
4,219,934
4
2
null
2010-11-18 21:25:48.733 UTC
9
2016-09-12 03:13:03.493 UTC
2010-11-20 08:33:02.357 UTC
null
459,950
null
459,950
null
1
20
c++|algorithm|data-structures|binary-tree|avl-tree
40,632
<p>You can measure the <code>height</code> of a branch at a given point to calculate the unbalance</p> <p><em>(remember a difference in height (levels) >= 2 means your tree is not balanced)</em> </p> <pre><code>int Tree::Height(TreeNode *node){ int left, right; if(node==NULL) return 0; left = Height(node-&gt;left); right = Height(node-&gt;right); if(left &gt; right) return left+1; else return right+1; } </code></pre> <p>Depending on the unevenness then you can <strong>rotate</strong> as necessary</p> <pre><code>void Tree::rotateLeftOnce(TreeNode*&amp; node){ TreeNode *otherNode; otherNode = node-&gt;left; node-&gt;left = otherNode-&gt;right; otherNode-&gt;right = node; node = otherNode; } void Tree::rotateLeftTwice(TreeNode*&amp; node){ rotateRightOnce(node-&gt;left); rotateLeftOnce(node); } void Tree::rotateRightOnce(TreeNode*&amp; node){ TreeNode *otherNode; otherNode = node-&gt;right; node-&gt;right = otherNode-&gt;left; otherNode-&gt;left = node; node = otherNode; } void Tree::rotateRightTwice(TreeNode*&amp; node){ rotateLeftOnce(node-&gt;right); rotateRightOnce(node); } </code></pre> <p>Now that we know how to rotate, lets say you want to <strong>insert</strong> a value in the tree... First we check whether the tree <strong>is empty</strong> or not</p> <pre><code>TreeNode* Tree::insert(int d){ if(isEmpty()){ return (root = new TreeNode(d)); //Is empty when root = null } else return insert(root, d); //step-into the tree and place "d" } </code></pre> <p>When the tree is not empty we use <strong>recursion</strong> to traverse the tree and get to where is needed</p> <pre><code>TreeNode* Tree::insert(TreeNode*&amp; node, int d_IN){ if(node == NULL) // (1) If we are at the end of the tree place the value node = new TreeNode(d_IN); else if(d_IN &lt; node-&gt;d_stored){ //(2) otherwise go left if smaller insert(node-&gt;left, d_IN); if(Height(node-&gt;left) - Height(node-&gt;right) == 2){ if(d_IN &lt; node-&gt;left-&gt;d_stored) rotateLeftOnce(node); else rotateLeftTwice(node); } } else if(d_IN &gt; node-&gt;d_stored){ // (3) otherwise go right if bigger insert(node-&gt;right, d_IN); if(Height(node-&gt;right) - Height(node-&gt;left) == 2){ if(d_IN &gt; node-&gt;right-&gt;d_stored) rotateRightOnce(node); else rotateRightTwice(node); } } return node; } </code></pre> <p>You should always check for balance <em>(and do rotations if necessary)</em> when modifying the tree, no point waiting until the end when the tree is a mess to balance it. That just complicates things...</p> <hr> <p><strong>UPDATE</strong></p> <p>There is a mistake in your implementation, in the code below you are not checking correctly whether the tree is unbalanced. You need to check whether the height is equals to 2 (therefore unbalance). As a result the code bellow...</p> <pre><code>if (height(current-&gt;lchild) - height(current-&gt;rchild)) { ... if (height(current-&gt;rchild) - height(current-&gt;lchild)) {... </code></pre> <p>Should become...</p> <pre><code>if (height(current-&gt;lchild) - height(current-&gt;rchild) == 2) { ... if (height(current-&gt;rchild) - height(current-&gt;lchild) == 2) {... </code></pre> <hr> <p><strong>Some Resources</strong></p> <ul> <li><a href="http://sourceforge.net/projects/standardavl/" rel="noreferrer">AVL Tree ~ Imprementation in C++</a></li> <li><a href="http://webdiis.unizar.es/asignaturas/EDA/AVLTree/avltree.html" rel="noreferrer">AVL Tree ~ Applet</a> </li> </ul>
4,635,680
What is the best way to get date and time in Clojure?
<p>I need to log some events on a Clojure Client-Server scenario, but it seems to me that Clojure does not provide a date/time function. Can any one confirm this or I am missing something here?! If I am correct then I need to use java interop, right?</p>
4,635,979
5
0
null
2011-01-08 19:23:49.57 UTC
6
2018-10-23 17:56:47.487 UTC
2016-03-16 17:39:52.92 UTC
null
425,313
null
487,855
null
1
45
java|datetime|clojure
40,260
<p>If all you need is to get the current time and date for your logger, then this function is OK:</p> <pre><code> (defn now [] (new java.util.Date)) </code></pre> <p>Now that you mentioned this, it would be useful to have support for immutable Date objects.</p>
4,203,634
Singleton with parameters
<p>I need a singleton class to be instantiated with some arguments. The way I'm doing it now is:</p> <pre><code>class SingletonExample { private SingletonExample mInstance; //other members... private SingletonExample() { } public SingletonExample Instance { get { if (mInstance == null) { throw new Exception("Object not created"); } return mInstance; } } public void Create(string arg1, string arg2) { mInstance = new SingletonExample(); mInstance.Arg1 = arg1; mInstance.ObjectCaller = new ObjectCaller(arg2); //etc... basically, create object... } } </code></pre> <p>The instance is created 'late', meaning I don't have all of the needed arguments on app startup.</p> <p>In general I don't like forcing an ordering of method calls, but I don't see another way here. The IoC wouldn't resolve it either, since where I can register it in the container, I can also call Create()... </p> <p>Do you consider this an OK scenario? Do you have some other idea? </p> <p><strong>edit</strong>: I <em>know</em> that what I wrote as an example it's not thread safe, thread-safe isn't part of the question</p>
4,203,775
6
7
null
2010-11-17 10:54:08.66 UTC
9
2022-09-14 10:53:54.853 UTC
2010-11-17 11:23:55.813 UTC
null
79,444
null
79,444
null
1
41
c#|design-patterns|parameters|singleton|arguments
70,163
<p>A Singleton with parameters smells fishy to me. </p> <p>Consider whateva's answer and the following code:</p> <pre><code>Singleton x = Singleton.getInstance("hello", "world"); Singleton y = Singleton.getInstance("foo", "bar"); </code></pre> <p>Obviously, x==y and y works with x's creation parameters, while y's creation parameters are simply ignored. Results are probably... confusing at least.</p> <p>If you really, really fell like you have to do it, do it like this:</p> <pre><code>class SingletonExample { private static SingletonExample mInstance; //other members... private SingletonExample() { // never used throw new Exception("WTF, who called this constructor?!?"); } private SingletonExample(string arg1, string arg2) { mInstance.Arg1 = arg1; mInstance.ObjectCaller = new ObjectCaller(arg2); //etc... basically, create object... } public static SingletonExample Instance { get { if (mInstance == null) { throw new Exception("Object not created"); } return mInstance; } } public static void Create(string arg1, string arg2) { if (mInstance != null) { throw new Exception("Object already created"); } mInstance = new SingletonExample(arg1, arg2); } } </code></pre> <p>In a multithreading environment, add synchronisation to avoid race conditions.</p>
4,535,782
Select count of rows in another table in a Postgres SELECT statement
<p>I don't know quite how to phrase this so please help me with the title as well. :)</p> <p>I have two tables. Let's call them <code>A</code> and <code>B</code>. The <code>B</code> table has a <code>a_id</code> foreign key that points at <code>A.id</code>. Now I would like to write a <code>SELECT</code> statement that fetches all <code>A</code> records, with an additional column containing the count of <code>B</code> records per <code>A</code> row for each row in the result set.</p> <p>I'm using Postgresql 9 right now, but I guess this would be a generic SQL question?</p> <p>EDIT:</p> <p>In the end I went for trigger-cache solution, where <code>A.b_count</code> is updated via a function each time <code>B</code> changes.</p>
4,535,814
6
1
null
2010-12-26 23:05:36.12 UTC
16
2021-04-20 14:42:42.55 UTC
2010-12-27 00:32:01.853 UTC
user234932
null
user234932
null
null
1
73
sql|postgresql
100,650
<pre><code>SELECT A.*, (SELECT COUNT(*) FROM B WHERE B.a_id = A.id) AS TOT FROM A </code></pre>
4,149,462
iPhone Enterpise Deployment: Mobile Device Management
<p>I was reading up on iPhone in the enterprise and saw something about Mobile Device Management servers. As far as I can tell, there are a few 3rd party MDM vendors, but Apple says that one could implement their own.</p> <p>The iPhone Configuration Utility allows you to set up a Server URL, Check in URL, Topic, Identity, and some other things for an MDM, but there's little information on how to build a server that hooks in with these.</p> <p>I've looked in the Enterprise Deployment, iPhone Configuration, and even the iPhone Mobile Device Management docs, but have found little aside from vague mentions or the occasional diagram. Is there a documented protocol somewhere?</p>
11,074,375
7
0
null
2010-11-10 21:51:52.837 UTC
14
2018-04-13 11:10:13.8 UTC
null
null
null
null
1,603,984
null
1
13
iphone|enterprise|mdm
5,550
<p>The best document for iOS MDM implementation is <a href="https://media.blackhat.com/bh-us-11/Schuetz/BH_US_11_Schuetz_InsideAppleMDM_WP.pdf" rel="nofollow noreferrer">https://media.blackhat.com/bh-us-11/Schuetz/BH_US_11_Schuetz_InsideAppleMDM_WP.pdf</a>. You can get sufficient detail to implement iOS MDM. Refer this <a href="https://stackoverflow.com/questions/8068317/how-to-develop-iphone-mdm-server">How to develop iPhone MDM Server?</a> and this <a href="https://stackoverflow.com/questions/9743690/generate-mdm-certificate">generate MDM certificate</a> </p>
4,700,357
Comparing strings in Java
<p>Im trying to compare the values of two edittext boxes. What i would like is to just compare passw1 = passw2. As my code is now comparing two strings i have entered as i could not get to compare them.</p> <pre><code> final EditText passw1= (EditText) findViewById(R.id.passw1); final EditText passw2= (EditText) findViewById(R.id.passw2); Button buttoks = (Button) findViewById(R.id.Ok); buttoks.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (passw1.toString().equalsIgnoreCase("1234") &amp;&amp; passw2.toString().equalsIgnoreCase("1234")){ Toast.makeText(getApplication(),"Username and password match", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplication(),"Username and password doesn't match", Toast.LENGTH_SHORT).show(); } } }); </code></pre>
4,700,411
9
0
null
2011-01-15 15:24:02.22 UTC
3
2022-08-22 05:03:02.617 UTC
2011-01-15 16:23:46.75 UTC
null
47,961
null
554,215
null
1
9
java|android|string
118,718
<p>[EDIT] I made a mistake earlier, because, to get the text, you need to use .getText().toString().</p> <p>Here is a full working example:</p> <pre><code>package com.psegina.passwordTest01; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Toast; public class Main extends Activity implements OnClickListener { LinearLayout l; EditText user; EditText pwd; Button btn; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); l = new LinearLayout(this); user = new EditText(this); pwd = new EditText(this); btn = new Button(this); l.addView(user); l.addView(pwd); l.addView(btn); btn.setOnClickListener(this); setContentView(l); } public void onClick(View v){ String u = user.getText().toString(); String p = pwd.getText().toString(); if( u.equals( p ) ) Toast.makeText(getApplicationContext(), "Matches", Toast.LENGTH_SHORT).show(); else Toast.makeText(getApplicationContext(), user.getText()+" != "+pwd.getText(), Toast.LENGTH_SHORT).show(); } } </code></pre> <p>Original answer (Will not work because of the lack of toString())</p> <p>Try using .getText() instead of .toString().</p> <pre><code>if( passw1.getText() == passw2.getText() ) #do something </code></pre> <p>.toString() returns a String representation of the whole object, meaning it won't return the text you entered in the field (see for yourself by adding a Toast which will show the output of .toString())</p>
4,576,331
UIButton label text is being clipped
<p>I have a UIButton built in Interface Builder that has a default label. In Xcode, I'm changing the label text dynamically like so:</p> <pre><code>myButton.titleLabel.text = @"this is the new label"; </code></pre> <p>However, when the text updates, the new string is being clipped down to the same size as the original string and ends up looking like:</p> <pre><code>this...label </code></pre> <p>Anyone know why this is happening?</p>
4,581,917
9
0
null
2011-01-01 23:39:11.633 UTC
5
2022-04-16 08:46:25.5 UTC
2011-01-03 03:25:12.09 UTC
null
714
null
496,326
null
1
43
iphone|cocoa-touch|uibutton
33,081
<p>You should use <a href="http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIButton_Class/UIButton/UIButton.html#//apple_ref/doc/uid/TP40006815-CH3-SW7" rel="noreferrer">setTitle:forState:</a> to change the title of a <code>UIButton</code>. If you change the title yourself, the button has no indication that it needs to resize the label – you'd end up having to do something like this:</p> <pre><code>myButton.titleLabel.text = @"this is the new label"; [myButton setNeedsLayout]; </code></pre> <p>but I'm not even sure that would work in all cases. Methods like <code>setTitle:forState:</code> are provided so that you can provide titles for multiple states without having to update the button manually, and so that the button knows that it needs to be laid out with a new title.</p>
4,108,313
How do I find the length of an array?
<p>Is there a way to find how many values an array has? Detecting whether or not I've reached the end of an array would also work.</p>
4,108,340
30
5
null
2010-11-05 17:15:54.193 UTC
165
2022-06-27 09:37:26.33 UTC
2011-11-30 13:20:01.94 UTC
null
497,934
null
497,934
null
1
671
c++|arrays
1,845,318
<p>If you mean a C-style array, then you can do something like:</p> <pre><code>int a[7]; std::cout &lt;&lt; &quot;Length of array = &quot; &lt;&lt; (sizeof(a)/sizeof(*a)) &lt;&lt; std::endl; </code></pre> <p>This doesn't work on pointers (i.e. it <strong>won't work for either of the following</strong>):</p> <pre><code>int *p = new int[7]; std::cout &lt;&lt; &quot;Length of array = &quot; &lt;&lt; (sizeof(p)/sizeof(*p)) &lt;&lt; std::endl; </code></pre> <p>or:</p> <pre><code>void func(int *p) { std::cout &lt;&lt; &quot;Length of array = &quot; &lt;&lt; (sizeof(p)/sizeof(*p)) &lt;&lt; std::endl; } int a[7]; func(a); </code></pre> <p>In C++, if you want this kind of behavior, then you should be using a container class; probably <a href="http://en.cppreference.com/w/cpp/container/vector" rel="noreferrer"><code>std::vector</code></a>.</p>
14,449,499
MVC 4 Intranet Authentication with Custom Roles
<p>I have spent some time searching and found a lot of confusing answers, so I will post here for clarification.</p> <p>I am using MVC4 VS2012 created an Intranet site using domain authentication. Everything works. However, to manage the users that have access to different areas of this webapp I prefer not to use AD groups that I cannot manage and nor can the users of the webapp. </p> <p>Is there an alternative? I assume this would involve associating/storing domain names belonging to custom roles and using the Authorize attribute to control access. </p> <pre><code>[Authorize(Roles = "Managers")] </code></pre> <p>Can anyone suggest the best pattern for this or point me in the right direction?</p> <p>I see a similar solution <a href="https://stackoverflow.com/questions/6043100/asp-net-mvc-and-windows-authentication-with-custom-roles">link</a>, but I am still not sure how to use this against a stored list of roles and validate the user against those roles. Can anyone elaborate if this solution would work?</p> <pre><code> protected void Application_AuthenticateRequest(object sender, EventArgs args) { if (HttpContext.Current != null) { String[] roles = GetRolesFromSomeDataTable(HttpContext.Current.User.Identity.Name); GenericPrincipal principal = new GenericPrincipal(HttpContext.Current.User.Identity, roles); Thread.CurrentPrincipal = HttpContext.Current.User = principal; } } </code></pre>
14,466,907
1
0
null
2013-01-22 00:14:41.553 UTC
10
2015-08-05 10:15:16.95 UTC
2017-05-23 12:34:01.36 UTC
null
-1
null
1,757,668
null
1
15
asp.net-mvc-4|visual-studio-2012|security|intranet
12,850
<p>I'm using this configuration with SQL Server and MVC3.</p> <p>Web.config:</p> <pre><code>&lt;system.web&gt; &lt;roleManager enabled="true" defaultProvider="SqlRoleManager"&gt; &lt;providers&gt; &lt;clear /&gt; &lt;add name="SqlRoleManager" type="System.Web.Security.SqlRoleProvider" connectionStringName="SqlRoleManagerConnection" applicationName="YourAppName" /&gt; &lt;/providers&gt; &lt;/roleManager&gt; </code></pre> <p>....</p> <pre><code>&lt;authentication mode="Windows" /&gt; </code></pre> <p>....</p> <pre><code>&lt;connectionStrings&gt; &lt;add name="SqlRoleManagerConnection" connectionString="Data Source=YourDBServer;Initial Catalog=AppServices;Integrated Security=True;" providerName=".NET Framework Data Provider for OLE DB" /&gt; &lt;/connectionStrings&gt; </code></pre> <p>To inicialize roles:</p> <p>Global.asax.cs</p> <pre><code>using System.Web.Security; //// protected void Application_Start() { //You could run this code one time and then manage the rest in your application. // For example: // Roles.CreateRole("Administrator"); // Roles.AddUserToRole("YourDomain\\AdminUser", "Administrator"); Roles.CreateRole("CustomRole"); Roles.AddUserToRole("YourDomain\\DomainUser", "CustomRole"); } </code></pre> <p>In your Controller</p> <pre><code>[Authorize(Roles ="CustomRole")] public class HomeController : Controller { </code></pre> <p>To manage users</p> <pre><code> public class Usuario { public string UserName { get; set; } public string RoleName { get; set; } public string Name { get; set; } public const string Domain = "YourDomain\\"; public void Delete() { Roles.RemoveUserFromRole(this.UserName, this.RoleName); } public void Save() { if (Roles.IsUserInRole(Usuario.Domain + this.UserName, this.RoleName) == false) { Roles.AddUserToRole(Usuario.Domain + this.UserName, this.RoleName); } } } </code></pre> <p>Users Class</p> <pre><code>public class Usuarios : List&lt;Usuario&gt; { public void GetUsuarios() //Get application's users { if (Roles.RoleExists("CustomRole")) { foreach (string _usuario in Roles.GetUsersInRole("CustomRole")) { var usuario = new Usuario(); usuario.UserName = _usuario; usuario.RoleName = "CustomRole"; this.Add(usuario); } } // public void GetUsuariosRed() //Get Network Users (AD) { var domainContext = new PrincipalContext(ContextType.Domain); var groupPrincipal = GroupPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, "Domain Users"); foreach (var item in groupPrincipal.Members) { var usuario = new Usuario(); usuario.UserName = item.SamAccountName; usuario.Name = item.Name; this.Add(usuario); } } </code></pre> <p>You can create an "Admin" controller like this, to manage the users:</p> <pre><code>[Authorize(Roles = "AdminCustomRole")] public class AdminController : Controller { // public ActionResult Index() { var Usuarios = new Usuarios(); Usuarios.GetUsuarios(); return View(Usuarios); } [HttpGet] public ActionResult CreateUser() { var Usuarios = new Usuarios(); Usuarios.GetUsuariosRed(); return View(Usuarios); } // </code></pre> <p>In my application, custom roles are fixed.</p>
14,584,115
PHP strtotime +1 month adding an extra month
<p>I have a simple variable that adds one month to today:</p> <pre><code>$endOfCycle = date("Y-m", strtotime("+1 month")); </code></pre> <p>Today is January 2013, so I would expect to get back 2013-02 but I'm getting 2013-03 instead. I can't figure out why it's jumping to March.</p>
14,584,265
7
1
null
2013-01-29 13:30:14.74 UTC
4
2013-01-31 12:30:51.707 UTC
null
null
null
null
1,819,502
null
1
24
php|date|strtotime
124,418
<p>It's jumping to March because today is 29th Jan, and adding a month gives 29th Feb, which doesn't exist, so it's moving to the next valid date.</p> <p>This will happen on the 31st of a lot of months as well, but is obviously more noticable in the case of January to Feburary because Feb is shorter.</p> <p>If you're not interested in the day of month and just want it to give the next month, you should specify the input date as the first of the current month. This will always give you the correct answer if you add a month.</p> <p>For the same reason, if you want to always get the last day of the next month, you should start by calculating the first of the month after the one you want, and subtracting a day.</p>
14,522,540
Close a MessageBox after several seconds
<p>I have a Windows Forms application VS2010 C# where I display a MessageBox for show a message. </p> <p>I have an okay button, but if they walk away, I want to timeout and close the message box after lets say 5 seconds, automatically close the message box.</p> <p>There are custom MessageBox (that inherited from Form) or another reporter Forms, but it would be interesting not necessary a Form.</p> <p>Any suggestions or samples about it?</p> <p><strong>Updated:</strong> </p> <p>For WPF<br> <a href="https://stackoverflow.com/questions/4362235/automatically-close-messagebox-in-c-sharp">Automatically close messagebox in C#</a></p> <p>Custom MessageBox (using Form inherit)<br> <a href="http://www.codeproject.com/Articles/17253/A-Custom-Message-Box" rel="noreferrer">http://www.codeproject.com/Articles/17253/A-Custom-Message-Box</a></p> <p><a href="http://www.codeproject.com/Articles/327212/Custom-Message-Box-in-VC" rel="noreferrer">http://www.codeproject.com/Articles/327212/Custom-Message-Box-in-VC</a></p> <p><a href="http://tutplusplus.blogspot.com.es/2010/07/c-tutorial-create-your-own-custom.html" rel="noreferrer">http://tutplusplus.blogspot.com.es/2010/07/c-tutorial-create-your-own-custom.html</a></p> <p><a href="http://medmondson2011.wordpress.com/2010/04/07/easy-to-use-custom-c-message-box-with-a-configurable-checkbox/" rel="noreferrer">http://medmondson2011.wordpress.com/2010/04/07/easy-to-use-custom-c-message-box-with-a-configurable-checkbox/</a></p> <p>Scrollable MessageBox<br> <a href="https://stackoverflow.com/questions/4681936/a-scrollable-messagebox-in-c-sharp">A Scrollable MessageBox in C#</a></p> <p>Exception Reporter<br> <a href="https://stackoverflow.com/questions/49224/good-crash-reporting-library-in-c-sharp">https://stackoverflow.com/questions/49224/good-crash-reporting-library-in-c-sharp</a></p> <p><a href="http://www.codeproject.com/Articles/6895/A-Reusable-Flexible-Error-Reporting-Framework" rel="noreferrer">http://www.codeproject.com/Articles/6895/A-Reusable-Flexible-Error-Reporting-Framework</a></p> <p><strong>Solution:</strong></p> <p>Maybe I think the following answers are good solution, without use a Form.</p> <p><a href="https://stackoverflow.com/a/14522902/206730">https://stackoverflow.com/a/14522902/206730</a><br> <a href="https://stackoverflow.com/a/14522952/206730">https://stackoverflow.com/a/14522952/206730</a></p>
14,522,952
15
7
null
2013-01-25 13:14:23.383 UTC
37
2022-05-17 03:35:14.21 UTC
2017-05-23 12:09:59.617 UTC
null
-1
null
206,730
null
1
93
c#|winforms|messagebox
198,881
<p>Try the following approach:</p> <pre><code>AutoClosingMessageBox.Show("Text", "Caption", 1000); </code></pre> <p>Where the <code>AutoClosingMessageBox</code> class implemented as following:</p> <pre><code>public class AutoClosingMessageBox { System.Threading.Timer _timeoutTimer; string _caption; AutoClosingMessageBox(string text, string caption, int timeout) { _caption = caption; _timeoutTimer = new System.Threading.Timer(OnTimerElapsed, null, timeout, System.Threading.Timeout.Infinite); using(_timeoutTimer) MessageBox.Show(text, caption); } public static void Show(string text, string caption, int timeout) { new AutoClosingMessageBox(text, caption, timeout); } void OnTimerElapsed(object state) { IntPtr mbWnd = FindWindow("#32770", _caption); // lpClassName is #32770 for MessageBox if(mbWnd != IntPtr.Zero) SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero); _timeoutTimer.Dispose(); } const int WM_CLOSE = 0x0010; [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)] static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)] static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam); } </code></pre> <p><strong>Update:</strong> If you want to get the return value of the underlying MessageBox when user selects something before the timeout you can use the following version of this code:</p> <pre><code>var userResult = AutoClosingMessageBox.Show("Yes or No?", "Caption", 1000, MessageBoxButtons.YesNo); if(userResult == System.Windows.Forms.DialogResult.Yes) { // do something } ... public class AutoClosingMessageBox { System.Threading.Timer _timeoutTimer; string _caption; DialogResult _result; DialogResult _timerResult; AutoClosingMessageBox(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None) { _caption = caption; _timeoutTimer = new System.Threading.Timer(OnTimerElapsed, null, timeout, System.Threading.Timeout.Infinite); _timerResult = timerResult; using(_timeoutTimer) _result = MessageBox.Show(text, caption, buttons); } public static DialogResult Show(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None) { return new AutoClosingMessageBox(text, caption, timeout, buttons, timerResult)._result; } void OnTimerElapsed(object state) { IntPtr mbWnd = FindWindow("#32770", _caption); // lpClassName is #32770 for MessageBox if(mbWnd != IntPtr.Zero) SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero); _timeoutTimer.Dispose(); _result = _timerResult; } const int WM_CLOSE = 0x0010; [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)] static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)] static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam); } </code></pre> <p><strong>Yet another Update</strong> </p> <p>I have checked the @Jack's case with <code>YesNo</code> buttons and discovered that the approach with sending the <code>WM_CLOSE</code> message does not work at all.<br> I will provide a <em>fix</em> in the context of the separate <a href="https://github.com/DmitryGaravsky/AutoClosingMessageBox" rel="noreferrer">AutoclosingMessageBox</a> library. This library contains redesigned approach and, I believe, can be useful to someone.<br> It also available via <a href="https://www.nuget.org/packages/AutoClosingMessageBox" rel="noreferrer">NuGet package</a>:</p> <pre><code>Install-Package AutoClosingMessageBox </code></pre> <p><strong>Release Notes (v1.0.0.2):</strong><br> - New Show(IWin32Owner) API to support most popular scenarios (in the context of <a href="https://github.com/DmitryGaravsky/AutoClosingMessageBox/issues/1" rel="noreferrer">#1</a> );<br> - New Factory() API to provide full control on MessageBox showing; </p>
35,703,556
What does it mean to squash commits in git?
<p>What does Squashing commits in git mean. How do I squash commits in Github?</p> <p>I'm new to Git and I requested to be assigned to a newcomer bug in coala-analyzer. I fixed the bug, and now I was asked to squash my commits. How do I do it? </p>
35,704,829
3
0
null
2016-02-29 15:40:26.78 UTC
58
2022-01-08 16:18:09.733 UTC
2018-11-07 15:55:44.233 UTC
null
636,987
null
5,589,746
null
1
214
git|github
121,722
<p>You can think of Git as an advanced database of snapshots of your working directory(ies). </p> <p>One very nice feature of Git is the ability to rewrite the history of commits.<br> The principal reason for doing this is that a lot of such history is relevant only for the developer who generated it, so it must be simplified, or made more nice, before submitting it to a shared repository.</p> <p><strong>Squashing a commit</strong> means, from an idiomatic point of view, to move the changes introduced in said commit into its parent so that you end up with one commit instead of two (or more).<br> If you repeat this process multiple times, you can reduce <em>n</em> commit to a single one. </p> <p>Visually, if you started your work at the commit tagged <em>Start</em>, you want this</p> <p><a href="https://i.stack.imgur.com/sShta.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sShta.png" alt="Git commits squashing"></a></p> <p>You may notice that the new commit has a slightly darker shade of blue. This is intentional.</p> <p>In Git squashing is achieved with a <em>Rebase</em>, of a special form called <em>Interactive Rebase</em>.<br> Simplifying when you rebase a set of commits into a branch <em>B</em>, you apply all the changes introduced by those commits as they were done, starting from <em>B</em> instead of their original ancestor.</p> <p>A visual clue</p> <p><a href="https://i.stack.imgur.com/CAHMp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CAHMp.png" alt="enter image description here"></a> </p> <p>Note again the different shades of blue.</p> <p>An interactive rebase let you choose how commits should be rebased. If you run this command:</p> <pre><code> git rebase -i branch </code></pre> <p>You would end up with a file that lists the commits that will be rebased</p> <pre><code> pick ae3... pick ef6... pick 1e0... pick 341... </code></pre> <p>I didn't name the commits, but these four ones are intended to be the commits from <em>Start</em> to <em>Head</em></p> <p>The nice thing about this list is that <strong>it is editable</strong>.<br> You can omit commits, or you can <strong>squash them</strong>.<br> All you have to do is to change the first word to <em>squash</em>.</p> <pre><code> pick ae3... squash ef6... squash 1e0... squash 341... </code></pre> <p>If you close the editor and no merge conflicts are found, you end up with this history:</p> <p><a href="https://i.stack.imgur.com/2LiYf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2LiYf.png" alt="enter image description here"></a></p> <p>In your case, you don't want to rebase into another branch, but rather into a previous commit.<br> In order to transform the history as shown in the very first example, you have to run something like</p> <pre><code>git rebase -i HEAD~4 </code></pre> <p>change the "commands" to <em>squash</em> for all the commits apart from the first one, and then close your editor.</p> <hr> <p><strong>Note about altering history</strong></p> <p>In Git, commits are never edited. They can be pruned, made not reachable, cloned but not changed.<br> When you rebase, you are actually creating new commits.<br> The old ones are not longer reachable by any refs, so are not shown in the history but they are still there! </p> <p>This is what you actually get for a rebase:</p> <p><a href="https://i.stack.imgur.com/fszS3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fszS3.png" alt="enter image description here"></a></p> <p>If you have already pushed them somewhere, rewriting the history will actually make a branch!</p>
25,719,319
Is it possible to make Font Awesome icons larger than 'fa-5x'?
<p>I am using this HTML code:</p> <pre><code>&lt;div class="col-lg-4"&gt; &lt;div class="panel"&gt; &lt;div class="panel-heading"&gt; &lt;div class="row"&gt; &lt;div class="col-xs-3"&gt; &lt;i class="fa fa-cogs fa-5x"&gt;&lt;/i&gt; &lt;/div&gt; &lt;div class="col-xs-9 text-right"&gt; &lt;div class="huge"&gt; &lt;?=db_query("SELECT COUNT(*) FROM orders WHERE customer = '" . $_SESSION['customer'] . "' AND EntryDate BETWEEN '" . date('d-M-y', strtotime('Monday this week')) . "' AND '" . date('d-M-y', strtotime('Friday this week')) . "'");?&gt; &lt;/div&gt; &lt;div&gt;orders this week&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;a href="view/orders"&gt; &lt;div class="panel-footer"&gt; &lt;span class="pull-left"&gt;View Details&lt;/span&gt; &lt;span class="pull-right"&gt;&lt;i class="fa fa-arrow-circle-right"&gt;&lt;/i&gt;&lt;/span&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Which creates:</p> <p><img src="https://i.stack.imgur.com/V2DsN.png" alt="enter image description here"></p> <p>Is it possible to make the icon larger than <code>fa-5x</code>? There is a lot of white space beneath it that I would like it to take up.</p>
25,719,710
7
0
null
2014-09-08 07:31:01.617 UTC
9
2021-08-28 14:35:04.203 UTC
null
null
null
null
3,973,427
null
1
67
html|css|twitter-bootstrap|font-awesome
122,718
<p>Font awesome is just a font so you can use the font size attribute in your CSS to change the size of the icon.</p> <p>So you can just add a class to the icon like this:</p> <pre><code>.big-icon { font-size: 32px; } </code></pre>
43,469,241
Passing lambda instead of interface
<p>I have created an interface:</p> <pre><code>interface ProgressListener { fun transferred(bytesUploaded: Long) } </code></pre> <p>but can use it only as an anonymous class, not lambda</p> <pre><code>dataManager.createAndSubmitSendIt(title, message, object : ProgressListener { override fun transferred(bytesUploaded: Long) { System.out.println(bytesUploaded.toString()) } }) </code></pre> <p>I think it should be a possibility to replace it by lambda:</p> <pre><code>dataManager.createAndSubmitSendIt(title, message, {System.out.println(it.toString())}) </code></pre> <p>But I am getting error: <code>Type mismatch; required - ProgressListener, found - () -&gt; Unit?</code></p> <p>What am I doing wrong?</p>
43,470,351
5
0
null
2017-04-18 10:07:19.767 UTC
12
2022-06-01 19:36:00.937 UTC
2020-07-26 22:12:56.68 UTC
null
13,363,205
null
4,978,624
null
1
86
lambda|kotlin
25,985
<p>As @zsmb13 said, SAM conversions are only supported for Java interfaces.</p> <p>You could create an extension function to make it work though:</p> <pre><code>// Assuming the type of dataManager is DataManager. fun DataManager.createAndSubmitSendIt(title: String, message: String, progressListener: (Long) -&gt; Unit) { createAndSubmitSendIt(title, message, object : ProgressListener { override fun transferred(bytesUploaded: Long) { progressListener(bytesUploaded) } }) } </code></pre> <h3>Edit</h3> <p>Kotlin 1.4 introduced function interfaces that enable SAM conversions for interfaces defined in Kotlin. This means that you can call your function with a lambda if you define your interface with the <code>fun</code> keyword. Like this:</p> <pre><code>fun interface ProgressListener { fun transferred(bytesUploaded: Long) } </code></pre>
2,617,969
How can I change the images on an ImageButton in Android when using a OnTouchListener?
<p>I have the following code which creates an ImageButton and plays a sound when clicked:</p> <pre><code>ImageButton SoundButton1 = (ImageButton)findViewById(R.id.sound1); SoundButton1.setImageResource(R.drawable.my_button); SoundButton1.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN ) { mSoundManager.playSound(1); return true; } return false; } }); </code></pre> <p>The problem is that I want the image on the ImageButton to change when you press it. The OnTouchListener appears to be overriding the touch and not allowing the images to change. As soon as I remove the OnTouchListener, the ImageButton swaps to a different image when pressed. Any ideas on how I can have the images change on the ImageButton while still using the OnTouchListener? Thank you very much!</p>
2,617,986
2
0
null
2010-04-11 17:32:35.377 UTC
2
2013-09-03 12:34:36.007 UTC
2013-09-03 12:34:36.007 UTC
null
1,006,780
null
313,717
null
1
13
android|imagebutton
57,498
<p>I think the solution is simple: remove the <code>return true</code> from the ontouchlistener. Since that blocks all further operations that respond to touch and input. Make it <code>return false</code> too.</p> <p>This way it will allow other actions to also respond to the touch.</p>
2,571,232
Parse HTML with PHP's HTML DOMDocument
<p>I was trying to do it with "getElementsByTagName", but it wasn't working, I'm new to using DOMDocument to parse HTML, as I used to use regex until yesterday some kind fokes here told me that DOMEDocument would be better for the job, so I'm giving it a try :)</p> <p>I google around for a while looking for some explains but didn't find anything that helped (not with the class anyway)</p> <p>So I want to capture "Capture this text 1" and "Capture this text 2" and so on.</p> <p>Doesn't look to hard, but I can't figure it out :(</p> <pre><code>&lt;div class="main"&gt; &lt;div class="text"&gt; Capture this text 1 &lt;/div&gt; &lt;/div&gt; &lt;div class="main"&gt; &lt;div class="text"&gt; Capture this text 2 &lt;/div&gt; &lt;/div&gt; </code></pre>
2,571,242
2
0
null
2010-04-03 12:23:59.473 UTC
12
2016-01-22 01:18:27.01 UTC
null
null
null
null
138,541
null
1
22
php|html|parsing|domdocument
47,011
<p>If you want to get :</p> <ul> <li>The text</li> <li>that's inside a <code>&lt;div&gt;</code> tag with <code>class="text"</code></li> <li>that's, itself, inside a <code>&lt;div&gt;</code> with <code>class="main"</code></li> </ul> <p>I would say the easiest way is not to use <a href="http://fr.php.net/manual/en/domdocument.getelementsbytagname.php" rel="noreferrer"><strong><code>DOMDocument::getElementsByTagName</code></strong></a> -- which will return all tags that have a specific name <em>(while you only want some of them)</em>.</p> <p>Instead, I would use an XPath query on your document, using the <a href="http://fr.php.net/manual/en/class.domxpath.php" rel="noreferrer"><strong><code>DOMXpath</code></strong></a> class.</p> <p><br> For example, something like this should do, to load the HTML string into a DOM object, and instance the <code>DOMXpath</code> class :</p> <pre><code>$html = &lt;&lt;&lt;HTML &lt;div class="main"&gt; &lt;div class="text"&gt; Capture this text 1 &lt;/div&gt; &lt;/div&gt; &lt;div class="main"&gt; &lt;div class="text"&gt; Capture this text 2 &lt;/div&gt; &lt;/div&gt; HTML; $dom = new DOMDocument(); $dom-&gt;loadHTML($html); $xpath = new DOMXPath($dom); </code></pre> <p><br> And, then, you can use XPath queries, with the <a href="http://fr.php.net/manual/en/domxpath.query.php" rel="noreferrer"><strong><code>DOMXPath::query</code></strong></a> method, that returns the list of elements you were searching for :</p> <pre><code>$tags = $xpath-&gt;query('//div[@class="main"]/div[@class="text"]'); foreach ($tags as $tag) { var_dump(trim($tag-&gt;nodeValue)); } </code></pre> <p><br> And executing this gives me the following output :</p> <pre><code>string 'Capture this text 1' (length=19) string 'Capture this text 2' (length=19) </code></pre>
2,937,120
How to get javascript object references or reference count?
<h2>How to get reference count for an object</h2> <ul> <li>Is it possible to determine if a javascript object has <strong>multiple references</strong> to it? </li> <li>Or if it has references <strong>besides the one I'm accessing it with</strong>? </li> <li>Or even just to get the <strong>reference count</strong> itself?</li> <li>Can I find this information from javascript itself, or will I need to keep track of my own reference counters.</li> </ul> <p>Obviously, there must be at least one reference to it for my code access the object. But what I want to know is if there are any other references to it, or if my code is the only place it is accessed. I'd like to be able to delete the object if nothing else is referencing it.</p> <p><strong>If you know the answer, there is no need to read the rest of this question.</strong> Below is just an example to make things more clear.</p> <hr> <h2>Use Case</h2> <p>In my application, I have a <code>Repository</code> object instance called <code>contacts</code> that contains an array of <strong>ALL</strong> my contacts. There are also multiple <code>Collection</code> object instances, such as <code>friends</code> collection and a <code>coworkers</code> collection. Each collection contains an array with a different set of items from the <code>contacts</code> <code>Repository</code>.</p> <h2>Sample Code</h2> <p>To make this concept more concrete, consider the code below. Each instance of the <code>Repository</code> object contains a list of all items of a particular type. You might have a repository of <strong>Contacts</strong> and a separate repository of <strong>Events</strong>. To keep it simple, you can just get, add, and remove items, and add many via the constructor.</p> <pre><code>var Repository = function(items) { this.items = items || []; } Repository.prototype.get = function(id) { for (var i=0,len=this.items.length; i&lt;len; i++) { if (items[i].id === id) { return this.items[i]; } } } Repository.prototype.add = function(item) { if (toString.call(item) === "[object Array]") { this.items.concat(item); } else { this.items.push(item); } } Repository.prototype.remove = function(id) { for (var i=0,len=this.items.length; i&lt;len; i++) { if (items[i].id === id) { this.removeIndex(i); } } } Repository.prototype.removeIndex = function(index) { if (items[index]) { if (/* items[i] has more than 1 reference to it */) { // Only remove item from repository if nothing else references it this.items.splice(index,1); return; } } } </code></pre> <p>Note the line in <code>remove</code> with the comment. I only want to remove the item from my master repository of objects if no other objects have a reference to the item. Here's <code>Collection</code>:</p> <pre><code>var Collection = function(repo,items) { this.repo = repo; this.items = items || []; } Collection.prototype.remove = function(id) { for (var i=0,len=this.items.length; i&lt;len; i++) { if (items[i].id === id) { // Remove object from this collection this.items.splice(i,1); // Tell repo to remove it (only if no other references to it) repo.removeIndxe(i); return; } } } </code></pre> <p>And then this code uses <code>Repository</code> and <code>Collection</code>:</p> <pre><code>var contactRepo = new Repository([ {id: 1, name: "Joe"}, {id: 2, name: "Jane"}, {id: 3, name: "Tom"}, {id: 4, name: "Jack"}, {id: 5, name: "Sue"} ]); var friends = new Collection( contactRepo, [ contactRepo.get(2), contactRepo.get(4) ] ); var coworkers = new Collection( contactRepo, [ contactRepo.get(1), contactRepo.get(2), contactRepo.get(5) ] ); contactRepo.items; // contains item ids 1, 2, 3, 4, 5 friends.items; // contains item ids 2, 4 coworkers.items; // contains item ids 1, 2, 5 coworkers.remove(2); contactRepo.items; // contains item ids 1, 2, 3, 4, 5 friends.items; // contains item ids 2, 4 coworkers.items; // contains item ids 1, 5 friends.remove(4); contactRepo.items; // contains item ids 1, 2, 3, 5 friends.items; // contains item ids 2 coworkers.items; // contains item ids 1, 5 </code></pre> <p>Notice how <code>coworkers.remove(2)</code> didn't remove id 2 from contactRepo? This is because it was still referenced from <code>friends.items</code>. However, <code>friends.remove(4)</code> causes id 4 to be removed from <code>contactRepo</code>, because no other collection is referring to it.</p> <h2>Summary</h2> <p>The above is what I want to do. I'm sure there are ways I can do this by keeping track of my own reference counters and such. But if there is a way to do it using javascript's built-in reference management, I'd like to hear about how to use it.</p>
2,937,218
2
5
null
2010-05-30 00:45:49.19 UTC
15
2017-02-12 09:02:07.67 UTC
null
null
null
null
220,599
null
1
71
javascript|garbage-collection|reference
34,481
<p>No, no, no, no; and yes, if you really need to count references you will have to do it manually. JS has no interface to this, GC, or weak references.</p> <p>Whilst you <em>could</em> implement a manual reference-counted object list, it's questionable whether all the extra overhead (in performance terms but more importantly code complexity) is worth it.</p> <p>In your example code it would seem simpler to forget the <code>Repository</code>, use a plain <code>Array</code> for your lists, and let standard garbage collection take care of dropping unused people. If you needed to get a list of all people in use, you'd just <code>concat</code> the <code>friends</code> and <code>coworkers</code> lists (and sort/uniquify them if you needed to).</p>
30,098,942
javascript set all values in array of object
<p>Two part question about similar problems. I've got 2 different arrays,</p> <p><strong>array 1:</strong></p> <pre><code> array1 = [{ name : "users", checked : true }, { name : "active users", checked : false }, { name : "completions", checked : false }] </code></pre> <p>I would like to know if there is an easy way to set all the checked values to true at once. I know this is possible with a for loop:</p> <pre><code> for (var i = 0 ; i &lt; array.length ; i++) { array[i].checked = false } </code></pre> <p>Even though this is not a lot of code i'm just curious if there is a way to do this without iterating over every object in the array. (not sure if this is even possible or whether this makes any difference whatsoever, so if please correct me if i am wrong about any of this). </p> <p><strong>array 2:</strong></p> <pre><code>array2 = [{ value1 : false, value2 : true, value3 : false, value4 : false, value5 : false, }] </code></pre> <p>Is it possible to simply set all the values to true or false at once (again i can use a for loop, but would prefer not to)</p> <p>(i'm using angular and lodash, but haven't been able to find a 'lodash' or 'angular' solution, but any solution will do)</p>
30,099,032
4
1
null
2015-05-07 10:50:25.203 UTC
2
2018-04-19 06:16:46.55 UTC
null
null
null
null
4,219,258
null
1
26
javascript|arrays
51,980
<p>You can't do this without looping over the elements, however there are functional abstractions you can use instead of <code>for</code>:</p> <p>For array 1, you can use <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Browser_compatability" rel="noreferrer">map</a></p> <pre><code>array1.map(function(x) { x.checked = true; return x }); </code></pre> <p>Or using <a href="https://lodash.com/docs#map" rel="noreferrer">_.map</a> from lodash:</p> <pre><code>_.map(array1, function(x) { x.checked = true; return x }); </code></pre> <p>For array 2 you can use <a href="https://lodash.com/docs#mapValues" rel="noreferrer">_.mapValues</a> from lodash.</p> <pre><code>_.mapValues(array2[0], function() { return true; }); </code></pre> <p>You can see that lodash implements <code>_.map</code> using <code>while</code> at <a href="https://github.com/lodash/lodash/blob/a1b15df6489f47498edda244552c9804e046a45d/lodash.js#L3125" rel="noreferrer">https://github.com/lodash/lodash/blob/a1b15df6489f47498edda244552c9804e046a45d/lodash.js#L3125</a></p>
38,546,108
Django Aggregation - Expression contains mixed types. You must set output_field
<p>I'm trying to achive an Aggregation Query and that's my code:</p> <pre><code>TicketGroup.objects.filter(event=event).aggregate( total_group=Sum(F('total_sold')*F('final_price'))) </code></pre> <p>I have 'total_sold' and 'final_price' in TicketGroup object and all what I want to do is sum and multiply values to get the total sold of all TicketGroups together. </p> <p>All I get is this error:</p> <blockquote> <p>Expression contains mixed types. You must set output_field</p> </blockquote> <p>What I am doing wrong, since I'm calling 'total_group' as my output field?</p> <p>Thanks!</p>
38,546,324
2
0
null
2016-07-23 20:23:57.777 UTC
10
2019-06-20 13:38:49.457 UTC
null
null
null
null
3,350,765
null
1
59
django|aggregate-functions|django-queryset|django-orm
30,129
<p>By <code>output_field</code> Django means to provide field type for the result of the <code>Sum</code>.</p> <pre><code>from django.db.models import FloatField, F total_group=Sum(F('total_sold')*F('final_price'), output_field=FloatField()) </code></pre> <p>should do the trick.</p>
49,615,857
Angular paramMap vs queryParamMap?
<p>What are the different paramMap and queryParamMap?</p> <p>Angular website says paramMap - An Observable that contains a map of the required and optional parameters specific to the route. The map supports retrieving single and multiple values from the same parameter.</p> <p>queryParamMap - An Observable that contains a map of the query parameters available to all routes. The map supports retrieving single and multiple values from the query parameter.</p> <p>I would like to know when I have to use with examples. </p> <p>Thanks</p>
49,617,621
2
0
null
2018-04-02 17:32:33.853 UTC
4
2020-10-11 14:40:59.427 UTC
null
null
null
null
7,466,200
null
1
39
angular|routing
25,638
<p>ParamMap for routes like <code>user/:id</code>. <code>Id</code> param belongs only this route.</p> <p>QueryParamMap is for eg. <code>user/:id?tab=edit</code>. <code>Tab</code> is a global query param, it can be read from the ActivatedRoute in the user route's component as well as any of its ancestors.</p>
35,831,496
Key error when selecting columns in pandas dataframe after read_csv
<p>I'm trying to read in a CSV file into a pandas dataframe and select a column, but keep getting a key error.</p> <p>The file reads in successfully and I can view the dataframe in an iPython notebook, but when I want to select a column any other than the first one, it throws a key error.</p> <p>I am using this code:</p> <pre><code>import pandas as pd transactions = pd.read_csv('transactions.csv',low_memory=False, delimiter=',', header=0, encoding='ascii') transactions['quarter'] </code></pre> <p>This is the file I'm working on: <a href="https://www.dropbox.com/s/81iwm4f2hsohsq3/transactions.csv?dl=0" rel="noreferrer">https://www.dropbox.com/s/81iwm4f2hsohsq3/transactions.csv?dl=0</a></p> <p>Thank you! </p>
35,831,531
5
0
null
2016-03-06 19:30:52.2 UTC
16
2022-09-11 11:31:59.95 UTC
2020-06-14 05:49:15.373 UTC
null
1,883,468
null
1,883,468
null
1
49
python|csv|pandas
172,815
<p>use <code>sep='\s*,\s*'</code> so that you will take care of spaces in column-names:</p> <pre><code>transactions = pd.read_csv('transactions.csv', sep=r'\s*,\s*', header=0, encoding='ascii', engine='python') </code></pre> <p>alternatively you can make sure that you don't have unquoted spaces in your CSV file and use your command (unchanged)</p> <p>prove:</p> <pre><code>print(transactions.columns.tolist()) </code></pre> <p>Output:</p> <pre><code>['product_id', 'customer_id', 'store_id', 'promotion_id', 'month_of_year', 'quarter', 'the_year', 'store_sales', 'store_cost', 'unit_sales', 'fact_count'] </code></pre>
34,848,505
How to make a loading animation in Console Application written in JavaScript or NodeJs?
<p>How to make a loading animation in Console Application written in JavaScript or NodeJs?</p> <p>Example animation or other animation.</p> <pre><code>1. -- 2. \ 3. | 4. / 5. -- </code></pre>
34,848,607
4
0
null
2016-01-18 06:31:05.81 UTC
11
2022-01-23 22:20:28.63 UTC
null
null
null
null
5,790,663
null
1
23
javascript|node.js
23,332
<p>Not really possible in browser console. In Node.js:</p> <pre><code>var twirlTimer = (function() { var P = ["\\", "|", "/", "-"]; var x = 0; return setInterval(function() { process.stdout.write("\r" + P[x++]); x &amp;= 3; }, 250); })(); </code></pre>
45,230,531
Programmatically change Redux-Form Field value
<p>When I use <code>redux-form</code> v7, I find there is no way to set the field value. Now in my <code>form</code>, I have two <code>select</code> component. The second's value will be clear when the first <code>select</code> component value changed.</p> <p>In class render:</p> <pre><code>&lt;div className={classNames(style.line, style.largeLine)}&gt; &lt;div className={style.lable}&gt;site:&lt;/div&gt; &lt;div className={style.content}&gt; &lt;Field name="site" options={sites} clearable={false} component={this.renderSelectField} validate={[required]} /&gt; &lt;/div&gt; &lt;/div&gt; &lt;div className={classNames(style.line, style.largeLine)}&gt; &lt;div className={style.lable}&gt;net:&lt;/div&gt; &lt;div className={style.content}&gt; &lt;Field name="net" options={nets} clearable={false} component={this.renderSelectField} validate={[required]} warning={warnings.net} /&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Now I add the <code>select</code> change hook, and how can I change the other <code>select</code> value</p> <pre><code>renderSelectField = props =&gt; { const { input, type, meta: { touched, error }, ...others } = props const { onChange } = input const _onChange = value =&gt; { onChange(value) this.handleSelectChange({ value, type: input.name }) } return ( &lt;CHSelect error={touched &amp;&amp; error} {...input} {...others} onChange={_onChange} onBlur={null} /&gt; ) } </code></pre>
45,231,071
1
0
null
2017-07-21 06:29:56.527 UTC
9
2021-01-26 22:54:07.267 UTC
2018-11-02 12:17:37.703 UTC
null
1,033,581
null
6,708,649
null
1
46
javascript|reactjs|redux|redux-form
57,445
<p>You can have the onChange logic in <code>this.handleSelectChange({ value, type: input.name })</code> and use <a href="http://redux-form.com/7.0.0/docs/api/Props.md/#-code-change-field-string-value-any-function-code-" rel="noreferrer"><code>change</code> action from redux-form</a></p> <p>According to the docs:</p> <blockquote> <p><strong>change(field:String, value:any) : Function</strong></p> <p>Changes the value of a field in the Redux store. This is a bound action creator, so it returns nothing.</p> </blockquote> <p>Code:</p> <pre><code>import { change } from &quot;redux-form&quot;; handleSelectChange = (value, type) =&gt; { if (type === &quot;site&quot;) { this.props.change('net', &quot;newValue&quot;); } } const mapDispatchToProps = (dispatch) =&gt; { return bindActionCreators({change}, dispatch); } </code></pre>
64,202,815
Getting issue in keychain: iPhone Distribution Certificate is not trusted
<p>I'm working on iOS enterprise application, now our iOS distribution certificate is expired and I'm creating new certificate using below steps:</p> <ol> <li>Create certificate sigining request from keychain access.</li> <li>Login with developer.apple.com and generate distribution certificate using certificate sigining request.</li> <li>download new iOS distribution certificate and install.</li> </ol> <p>After this I'm able to see iOS Distribution certificate in keychain access but getting error: <strong>&quot;iPhone Distribution certificate is not trusted&quot;.</strong></p> <p><a href="https://i.stack.imgur.com/1BiHu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1BiHu.png" alt="enter image description here" /></a></p> <p>Also, I have tried it using Automatically manage signing, and tried to export ipa file, but I'm getting below error:</p> <p><a href="https://i.stack.imgur.com/ha9G2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ha9G2.png" alt="enter image description here" /></a></p> <p>Please help me to resolve this errors.</p>
64,209,916
6
0
null
2020-10-05 05:16:38.307 UTC
4
2022-06-21 14:14:43.293 UTC
null
null
null
null
1,806,232
null
1
34
ios|ios-enterprise
20,819
<p><a href="https://developer.apple.com/de/support/expiration/" rel="noreferrer">https://developer.apple.com/de/support/expiration/</a> should be the answer. Just install the certificate manually or upgrade to Xcode 11.4.1 or later. After upgrading to Xcode &gt;= 11.4.1 I had to open a Xcode project and had to wait few seconds. Afterwards the new Apple Worldwide Developer Relations Intermediate Certificate automatically has been installed.</p>
31,881,754
md-select can't set selected value
<p>I have a <code>md-select</code> set up as follows:</p> <pre><code>&lt;md-select placeholder="Category" ng-model="current.Category" flex &gt; &lt;md-option ng-repeat="item in categories" ng-value="{{item}}"&gt;{{item.Name}}&lt;/md-option&gt; &lt;/md-select&gt; </code></pre> <p><code>@scope.categories</code> value is</p> <pre><code>[ { "Name":"Commercial &amp; Industrial", "ParentId":null, "Categories":[ { "Name":"Deceptive Marketing", "ParentId":19, "Categories":[ ], "Id":24, "ModifiedDate":"2015-08-06T07:49:53.0489545", "CreatedDate":"2015-08-06T15:49:51.707" }, { "Name":"Aggressive Agents", "ParentId":19, "Categories":[ ], "Id":25, "ModifiedDate":"2015-08-06T07:50:10.0026497", "CreatedDate":"2015-08-06T15:50:08.63" } ], "Id":19, "ModifiedDate":"08/06/2015 @ 7:49AM", "CreatedDate":"08/06/2015 @ 3:49PM" }, { "Name":"Competitive Supply", "ParentId":null, "Categories":[ { "Name":"Security Deposit", "ParentId":20, "Categories":[ ], "Id":21, "ModifiedDate":"2015-08-06T07:49:30.3966895", "CreatedDate":"2015-08-06T15:49:25.8" }, { "Name":"Meter", "ParentId":20, "Categories":[ ], "Id":22, "ModifiedDate":"2015-08-06T07:49:34.6571155", "CreatedDate":"2015-08-06T15:49:33.3" }, { "Name":"Bill", "ParentId":20, "Categories":[ ], "Id":23, "ModifiedDate":"2015-08-06T07:49:41.7268224", "CreatedDate":"2015-08-06T15:49:40.357" } ], "Id":20, "ModifiedDate":"08/06/2015 @ 7:49AM", "CreatedDate":"08/06/2015 @ 3:49PM" } ] </code></pre> <p>The <code>md-select</code> works fine. But what I can't figure out is how to set select value. When I try setting the model <code>current.Category</code> to one of the values from the <code>$scope.categories</code> it doesn't get set. </p>
31,882,550
7
0
null
2015-08-07 15:44:08.383 UTC
6
2018-05-01 18:51:34.617 UTC
2015-08-07 16:34:33.203 UTC
null
3,201,696
null
2,501,497
null
1
24
angularjs|angular-material
48,218
<p>The documentation isn't explicit, but you should use <code>ng-selected</code>. I've created a <a href="http://codepen.io/anon/pen/VLRweg">codepen</a> to illustrate, but basically:</p> <pre><code>&lt;md-option ng-repeat="(index,item) in categories" ng-value="{{item}}" ng-selected="index == 1"&gt; {{item.Name}} &lt;/md-option&gt; </code></pre> <p>This'll select the the second category (index 1 in your category array).</p>
31,811,074
OpenStreetMap: get coordinates from address
<p>Is there any function in OpenStreetMap that gives you the coordinated from an address ?</p> <p>something like </p> <pre><code>http://router.project-osrm.org/locate?request=GetGeocoding&amp;nbaddresses=1&amp;outputFormat=json&amp;addresses_0=1240+Place+Jourdan+PARIS </code></pre>
31,818,027
1
0
null
2015-08-04 13:46:29.96 UTC
11
2015-08-04 19:50:33.02 UTC
2015-08-04 14:02:17.077 UTC
null
4,450,024
null
4,450,024
null
1
33
geolocation
40,801
<p>I have it, Nominatim is a tool to search OSM data by name and address and to generate synthetic addresses of OSM points (reverse geocoding).</p> <p><a href="http://nominatim.openstreetmap.org/search?q=135+pilkington+avenue,+birmingham&amp;format=json&amp;polygon=1&amp;addressdetails=1" rel="noreferrer">http://nominatim.openstreetmap.org/search?q=135+pilkington+avenue,+birmingham&amp;format=json&amp;polygon=1&amp;addressdetails=1</a></p>
27,989,762
Get this week's monday's date in Postgres?
<p>How can I get this week's monday's date in PostgreSQL?</p> <p>For example, today is 01/16/15 (Friday). This week's monday date is 01/12/15.</p>
27,990,193
4
0
null
2015-01-16 17:45:46.143 UTC
3
2020-09-14 05:50:46.297 UTC
null
null
null
null
1,360,959
null
1
33
postgresql
27,163
<pre><code>SELECT current_date + cast(abs(extract(dow FROM current_date) - 7) + 1 AS int); </code></pre> <p>works, although there might be more elegant ways of doing it.</p> <p>The general idea is to get the current day of the week, <code>dow</code>, subtract 7, and take the abs, which will give you the number of days till the end of the week, and add 1, to get to Monday. This gives you next Monday.</p> <p>EDIT: having completely misread the question, to get the prior Monday, is much simpler:</p> <pre><code>SELECT current_date - ((6 + cast(extract(dow FROM current_date) AS int)) % 7) </code></pre> <p>ie, subtract the current day of the week from today's date (the number of day's past Monday) and add one, to get back to Monday.</p>
28,156,011
how to change editor behavior in intellij idea
<p>I have installed IntelliJIdea 14.0.2 just now. I do not know its default editor but it is opening my source files in <code>vi</code> option now. So, not letting me do default action like <code>Ctrl + v</code>, <code>Ctrl + d</code> which was present before and I used to like it.</p> <p>So, how to change this behavior like present in <code>sublime - editors</code>?</p>
28,158,198
4
0
null
2015-01-26 18:05:10.023 UTC
17
2019-03-13 19:46:05.34 UTC
2016-12-14 16:07:53.797 UTC
null
2,197,975
null
4,281,491
null
1
60
vim|intellij-idea|sublimetext|vi|ideavim
46,121
<p>If you don't need vi keybindings, uninstall the IdeaVIM plugin.</p>
28,071,459
compare 2 cells in excel by using vba
<p>I would like to compare 2 cells' value and see whether they are match or not. I know how to do it on excel but I dont' know how to put it vba code.</p> <p><strong>Input &amp; output:</strong></p> <ol> <li>The value of cell A1 is already in the excel.</li> <li>Manually enter a value in Cell B1.</li> <li>click on a button_click sub to see whether the value on 2 cells are the same or not.</li> <li>Show "Yes" or "No" on cell C1 </li> </ol> <p><strong>Excel formula:</strong></p> <pre><code>=IF(A1=B1,"yes","no") </code></pre>
28,072,507
5
0
null
2015-01-21 15:55:18.31 UTC
1
2018-11-21 13:06:51.28 UTC
null
null
null
null
4,233,291
null
1
8
vba|excel
109,141
<p>You can use the IIF function in VBA. It is similar to the Excel IF</p> <pre><code>[c1] = IIf([a1] = [b1], "Yes", "No") </code></pre>
27,112,461
WooCommerce - send custom email on custom order status change
<p>I added a custom status <code>wc-order-confirmed</code>:</p> <pre><code>// Register new status function register_order_confirmed_order_status() { register_post_status( 'wc-order-confirmed', array( 'label' =&gt; 'Potvrzení objednávky', 'public' =&gt; true, 'exclude_from_search' =&gt; false, 'show_in_admin_all_list' =&gt; true, 'show_in_admin_status_list' =&gt; true, 'label_count' =&gt; _n_noop( 'Potvrzení objednávky &lt;span class="count"&gt;(%s)&lt;/span&gt;', 'Potvrzení objednávky &lt;span class="count"&gt;(%s)&lt;/span&gt;' ) ) ); } add_action( 'init', 'register_order_confirmed_order_status' ); // Add to list of WC Order statuses function add_order_confirmed_to_order_statuses( $order_statuses ) { $new_order_statuses = array(); // add new order status after processing foreach ( $order_statuses as $key =&gt; $status ) { $new_order_statuses[ $key ] = $status; if ( 'wc-processing' === $key ) { $new_order_statuses['wc-order-confirmed'] = 'Potvrzení objednávky'; } } return $new_order_statuses; } add_filter( 'wc_order_statuses', 'add_order_confirmed_to_order_statuses' ); </code></pre> <p>I added a custom email <code>wc_confirmed_order</code>:</p> <pre><code>/** * A custom confirmed Order WooCommerce Email class * * @since 0.1 * @extends \WC_Email */ class WC_Confirmed_Order_Email extends WC_Email { /** * Set email defaults * * @since 0.1 */ public function __construct() { // set ID, this simply needs to be a unique name $this-&gt;id = 'wc_confirmed_order'; // this is the title in WooCommerce Email settings $this-&gt;title = 'Potvrzení objednávky'; // this is the description in WooCommerce email settings $this-&gt;description = 'Confirmed Order Notification'; // these are the default heading and subject lines that can be overridden using the settings $this-&gt;heading = 'Potvrzení objednávky'; $this-&gt;subject = 'Potvrzení objednávky'; // these define the locations of the templates that this email should use, we'll just use the new order template since this email is similar $this-&gt;template_html = 'emails/customer-confirmed-order.php'; $this-&gt;template_plain = 'emails/plain/admin-new-order.php'; // Trigger on confirmed orders add_action( 'woocommerce_order_status_pending_to_order_confirmed', array( $this, 'trigger' ) ); add_action( 'woocommerce_order_status_processing_to_order_confirmed', array( $this, 'trigger' ) ); // Call parent constructor to load any other defaults not explicity defined here parent::__construct(); // this sets the recipient to the settings defined below in init_form_fields() $this-&gt;recipient = $this-&gt;get_option( 'recipient' ); // if none was entered, just use the WP admin email as a fallback if ( ! $this-&gt;recipient ) $this-&gt;recipient = get_option( 'admin_email' ); } /** * Determine if the email should actually be sent and setup email merge variables * * @since 0.1 * @param int $order_id */ public function trigger( $order_id ) { // bail if no order ID is present if ( ! $order_id ) return; if ( $order_id ) { $this-&gt;object = wc_get_order( $order_id ); $this-&gt;recipient = $this-&gt;object-&gt;billing_email; $this-&gt;find['order-date'] = '{order_date}'; $this-&gt;find['order-number'] = '{order_number}'; $this-&gt;replace['order-date'] = date_i18n( wc_date_format(), strtotime( $this-&gt;object-&gt;order_date ) ); $this-&gt;replace['order-number'] = $this-&gt;object-&gt;get_order_number(); } if ( ! $this-&gt;is_enabled() || ! $this-&gt;get_recipient() ) return; // woohoo, send the email! $this-&gt;send( $this-&gt;get_recipient(), $this-&gt;get_subject(), $this-&gt;get_content(), $this-&gt;get_headers(), $this-&gt;get_attachments() ); } /** * get_content_html function. * * @since 0.1 * @return string */ public function get_content_html() { ob_start(); wc_get_template( $this-&gt;template_html, array( 'order' =&gt; $this-&gt;object, 'email_heading' =&gt; $this-&gt;get_heading() ) ); return ob_get_clean(); } /** * get_content_plain function. * * @since 0.1 * @return string */ public function get_content_plain() { ob_start(); wc_get_template( $this-&gt;template_plain, array( 'order' =&gt; $this-&gt;object, 'email_heading' =&gt; $this-&gt;get_heading() ) ); return ob_get_clean(); } /** * Initialize Settings Form Fields * * @since 2.0 */ public function init_form_fields() { $this-&gt;form_fields = array( 'enabled' =&gt; array( 'title' =&gt; 'Enable/Disable', 'type' =&gt; 'checkbox', 'label' =&gt; 'Enable this email notification', 'default' =&gt; 'yes' ), 'recipient' =&gt; array( 'title' =&gt; 'Recipient(s)', 'type' =&gt; 'text', 'description' =&gt; sprintf( 'Enter recipients (comma separated) for this email. Defaults to &lt;code&gt;%s&lt;/code&gt;.', esc_attr( get_option( 'admin_email' ) ) ), 'placeholder' =&gt; '', 'default' =&gt; '' ), 'subject' =&gt; array( 'title' =&gt; 'Subject', 'type' =&gt; 'text', 'description' =&gt; sprintf( 'This controls the email subject line. Leave blank to use the default subject: &lt;code&gt;%s&lt;/code&gt;.', $this-&gt;subject ), 'placeholder' =&gt; '', 'default' =&gt; '' ), 'heading' =&gt; array( 'title' =&gt; 'Email Heading', 'type' =&gt; 'text', 'description' =&gt; sprintf( __( 'This controls the main heading contained within the email notification. Leave blank to use the default heading: &lt;code&gt;%s&lt;/code&gt;.' ), $this-&gt;heading ), 'placeholder' =&gt; '', 'default' =&gt; '' ), 'email_type' =&gt; array( 'title' =&gt; 'Email type', 'type' =&gt; 'select', 'description' =&gt; 'Choose which format of email to send.', 'default' =&gt; 'html', 'class' =&gt; 'email_type', 'options' =&gt; array( 'plain' =&gt; __( 'Plain text', 'woocommerce' ), 'html' =&gt; __( 'HTML', 'woocommerce' ), 'multipart' =&gt; __( 'Multipart', 'woocommerce' ), ) ) ); } } // end \WC_confirmed_Order_Email class </code></pre> <p>I can see the email in the email settings, and the status in the order statuses dropdown. Now, I need to send my new email whenever the order status is changed to <code>wc-order-confirmed</code>. The transition hook seems to never be firing.</p> <p>I also tried:</p> <pre><code>/** * Register the "woocommerce_order_status_pending_to_quote" hook which is necessary to * allow automatic email notifications when the order is changed to refunded. * * @modified from http://stackoverflow.com/a/26413223/2078474 to remove anonymous function */ add_action( 'woocommerce_init', 'so_25353766_register_email' ); function so_25353766_register_email(){ add_action( 'woocommerce_order_status_pending_to_order_confirmed', array( WC(), 'send_transactional_email' ), 10, 10 ); add_action( 'woocommerce_order_status_processing_to_order_confirmed', array( WC(), 'send_transactional_email' ), 10, 10 ); } </code></pre> <p>Which also doesn't seem to work at all... Any ideas, please?</p>
27,122,473
4
0
null
2014-11-24 19:18:47.3 UTC
10
2020-07-29 18:48:24.523 UTC
null
null
null
null
1,049,961
null
1
15
php|wordpress|woocommerce
41,290
<p>As Xcid's answer indicates, you need to register the email. </p> <p>In WC 2.2+ I believe you can do this via the following:</p> <pre><code>add_action( 'woocommerce_order_status_wc-order-confirmed', array( WC(), 'send_transactional_email' ), 10, 10 ); </code></pre> <p>I'd added a filter to WooCommerce 2.3, so when that comes out custom emails will be able to be added to the list of email actions that WooCommerce registers:</p> <pre><code>// As of WooCommerce 2.3 function so_27112461_woocommerce_email_actions( $actions ){ $actions[] = 'woocommerce_order_status_wc-order-confirmed'; return $actions; } add_filter( 'woocommerce_email_actions', 'so_27112461_woocommerce_email_actions' ); </code></pre>
46,222,692
ASP.NET Core 2 Seed Database
<p>I've seen some of the similar examples on SO regarding this but I don't know enough about the language just yet to see what I'm doing wrong. I've cobbled together a demo to learn more but I'm having trouble seeding my database.</p> <p>I receive the following error:</p> <blockquote> <p>InvalidOperationException: Cannot resolve scoped service 'demoApp.Models.AppDbContext' from root provider.</p> <p>Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, ServiceProvider serviceProvider)</p> </blockquote> <p>Here are the three files in question:</p> <p><strong>Models/AppDbContext.cs</strong></p> <pre><code>public class AppDbContext : DbContext { public AppDbContext(DbContextOptions&lt;AppDbContext&gt; options) : base(options) { } public DbSet&lt;Product&gt; Products{ get; set; } public DbSet&lt;Category&gt; Categories { get; set; } } </code></pre> <p><strong>Models/DBInitializer.cs</strong></p> <pre><code>public static class DbInitializer { public static void Seed(IApplicationBuilder applicationBuilder) { //I'm bombing here AppDbContext context = applicationBuilder.ApplicationServices.GetRequiredService&lt;AppDbContext&gt;(); if (!context.Products.Any()) { // Add range of products } context.SaveChanges(); } private static Dictionary&lt;string, Category&gt; _categories; public static Dictionary&lt;string, Category&gt; Categories { get { if (_categories == null) { // Add categories... } return _categories; } } } </code></pre> <p><strong>Startup.cs</strong></p> <pre><code>public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddTransient&lt;ICategoryRepository, CategoryRepository&gt;(); services.AddTransient&lt;IProductRepository, ProductRepository&gt;(); services.AddDbContext&lt;AppDbContext&gt;(options =&gt; options.UseSqlServer(Configuration.GetConnectionString(&quot;DefaultConnection&quot;))); services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); app.UseStatusCodePages(); // Kersplat! DbInitializer.Seed(app); } else ... app.UseStaticFiles(); app.UseMvc(routes =&gt; {...}); } </code></pre> <p>Can someone help explain what I'm doing wrong and how to remedy the situation?</p>
46,688,953
2
0
null
2017-09-14 15:11:02.937 UTC
11
2018-02-26 09:32:59.79 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
1,322,017
null
1
14
c#|asp.net|.net|.net-core-2.0
31,775
<p>In ASP.NET Core 2.0 the following changes are recommended. (Seeding in startup.cs works for Core 1.x. For 2.0 go into Program.cs, modify the Main method to do the following on application startup: Get a database context instance from the dependency injection container. Call the seed method, passing to it the context. Dispose the context when the seed method is done. (Here's a sample from the Microsoft site. <a href="https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro" rel="noreferrer">https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro</a> )</p> <pre><code>public static void Main(string[] args) { var host = BuildWebHost(args); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService&lt;yourDBContext&gt;(); DbInitializer.Seed(context);//&lt;---Do your seeding here } catch (Exception ex) { var logger = services.GetRequiredService&lt;ILogger&lt;Program&gt;&gt;(); logger.LogError(ex, "An error occurred while seeding the database."); } } host.Run(); } </code></pre>
41,946,475
git: why can't I delete my branch after a squash merge?
<p>I have a git repo with <code>mainline</code> (equivalent to <code>master</code>) and some local feature branches. For example:</p> <pre><code>$ git branch * mainline feature1 feature2 feature3 </code></pre> <p>When I do the following, I am able to squash merge all of my edits in a feature branch into one commit to <code>mainline</code>:</p> <pre><code>$ git checkout mainline $ git pull $ git checkout feature1 $ git rebase mainline $ git checkout mainline $ git merge --squash feature1 $ git commit $ git push </code></pre> <p>My question is, at this point, when I try to delete the <code>feature1</code> branch, it tells me it is not fully merged:</p> <pre><code>$ git branch -d feature1 error: The branch 'feature1' is not fully merged. If you are sure you want to delete it, run 'git branch -D feature1'. </code></pre> <p>What causes this error? I thought <code>git merge --squash feature1</code> merged <code>feature1</code> into <code>mainline</code>.</p>
41,947,745
2
0
null
2017-01-30 22:24:05.75 UTC
11
2020-03-03 07:01:00.683 UTC
null
null
null
null
1,002,119
null
1
53
git|merge|git-merge
10,597
<p>This happens because Git doesn't know that the squash merge is "equivalent to" the various branch-specific commits. You must forcibly delete the branch, with <code>git branch -D</code> instead of <code>git branch -d</code>.</p> <p>(The rest of this is merely about <em>why</em> this is the case.)</p> <h3>Draw the commit graph</h3> <p>Let's draw (part of) the commit graph (this step is appropriate for so many things in Git...). In fact, let's step back one more step, so that we start before your <code>git rebase</code>, with something like this:</p> <pre><code>...--o--o--o &lt;-- mainline \ A--B--C &lt;-- feature1 </code></pre> <p>A branch <em>name</em>, like <code>mainline</code> or <code>feature1</code>, points only to one specific commit. That commit points back (leftward) to a previous commit, and so on, and it's these backward pointers that form the actual branches.</p> <p>The top row of commits, all just called <code>o</code> here, are kind of boring, so we didn't give them letter-names. The bottom row of commits, <code>A-B-C</code>, are <em>only</em> on branch <code>feature1</code>. <code>C</code> is the newest such commit; it leads back to <code>B</code>, which leads back to <code>A</code>, which leads back to one of the boring <code>o</code> commits. (As an aside: the leftmost <code>o</code> commit, along with all earlier commits in the <code>...</code> section, is on <em>both</em> branches.)</p> <p>When you ran <code>git rebase</code>, the three <code>A-B-C</code> commits were <em>copied</em> to <em>new</em> commits appended to the tip of <code>mainline</code>, giving us:</p> <pre><code>...--o--o--o &lt;-- mainline \ \ \ A'-B'-C' &lt;-- feature1 \ A--B--C [old feature1, now abandoned] </code></pre> <p>The new <code>A'-B'-C'</code> commits are mostly the same as the original three, but they are <em>moved</em> in the graph. (Note that all three boring <code>o</code> commits are on both branches now.) Abandoning the original three means that Git usually doesn't <em>have</em> to compare the copies to the originals. (If the originals had been reachable by some other name—a branch that appended to the old <code>feature1</code>, for instance—Git <em>can</em> figure this out, at least in most cases. The precise details of how Git figures this out are not particularly important here.)</p> <p>Anyway, now you go on to run <code>git checkout mainline; git merge --squash feature1</code>. This makes one new commit that is a "squash copy" of the three—or however many—commits that are on <code>feature1</code>. I will stop drawing the old abandoned ones, and call the new squash-commit <code>S</code> for Squash:</p> <pre><code>...--o--o--o--S &lt;-- mainline \ A'-B'-C' &lt;-- feature1 </code></pre> <h3>"Delete safety" is determined entirely by commit history</h3> <p>When you ask Git to delete <code>feature1</code>, it performs a safety check: "is <code>feature1</code> merged into <code>mainline</code>?" This "is merged into" test is based purely on the <em>graph connectivity</em>. The name <code>mainline</code> points to commit <code>S</code>; commit <code>S</code> points back to the first boring <code>o</code> commit, which leads back to more boring <code>o</code> commits. Commit <code>C'</code>, the tip of <code>feature1</code>, is <em>not</em> reachable from <code>S</code>: we're not allowed to move rightward, only leftward.</p> <p>Contrast this with making a "normal" merge <code>M</code>:</p> <pre><code>...--o--o--o---------M &lt;-- mainline \ / A'-B'-C' &lt;-- feature1 </code></pre> <p>Using the same test—"is the tip commit of <code>feature1</code> reachable from the tip commit of <code>mainline</code>?"—the answer is now <em>yes</em>, because commit <code>M</code> has a down-and-left link to commit <code>C'</code>. (Commit <code>C'</code> is, in Git internal parlance, the <em>second parent</em> of merge commit <code>M</code>.)</p> <p>Since squash merges are not actually <em>merges</em>, though, there is no connection from <code>S</code> back to <code>C'</code>.</p> <p>Again, Git doesn't even <em>try</em> to see if <code>S</code> is "the same as" <code>A'</code>, <code>B'</code>, or <code>C'</code>. If it did, though, it would say "not the same", because <code>S</code> is only the same as the <em>sum</em> of all three commits. The only way to get <code>S</code> to match the squashed commits is to have only one such commit (and in this case, there's no need to squash in the first place).</p>
24,508,053
Difference between ng-model and data-ng-model
<p>I am new with the <strong>AngularJs</strong>. Can anyone say the difference between ng-model and data-ng-model?</p> <p><strong>With ng-model</strong></p> <pre><code>First Name : &lt;input type="text" ng-model="fname" id="fname"&gt; Second Name : &lt;input type="text" ng-model="lname" id="lname"&gt; </code></pre> <p><strong>With data-ng-model</strong></p> <pre><code>First Name : &lt;input type="text" data-ng-model="fname" id="fname"&gt; Second Name : &lt;input type="text" data-ng-model="lname" id="lname"&gt; </code></pre>
24,508,309
6
0
null
2014-07-01 10:31:55.707 UTC
5
2022-03-03 16:24:06.95 UTC
2018-08-26 22:00:22.047 UTC
null
5,939,058
null
3,783,175
null
1
36
angularjs
35,624
<p>Best Practice: Prefer using the dash-delimited format (e.g. ng-bind for ngBind). <strong>If you want to use an HTML validating tool, you can instead use the data-prefixed version (e.g. data-ng-bind for ngBind).</strong> The other forms shown above are accepted for legacy reasons but we advise you to avoid them.</p>
10,757,963
how to loop through an array to find more than one pattern using perl regex?
<p>I'm trying to find two patterns within an array and put the results into another array.</p> <p>For example</p> <pre><code> $/ = "__Data__"; __Data__ #SCSI_test # put this line into @arrayNewLines kdkdkdkdkdkdkdkd dkdkdkdkdkdkdkdkd - ccccccccccccccc # put this line into @arrayNewLines </code></pre> <p>Code</p> <pre><code> while(&lt;FILEREAD&gt;) { chomp; my @arrayOld = split(\n,@array); foreach my $i (0 .. $#arrayOld) { if($arrayOld[$i] =~ /^-(.*)/g or /\#(.*)/g) { my @arrayNewLines = $arrayOld[$i]; print "@arrayNewLines\n"; } } } </code></pre> <p>This code only prints out only ccccccccccccccc But I would like it to output ccccccccccccccc #SCSI_test</p>
10,759,110
2
0
null
2012-05-25 16:17:14.48 UTC
null
2016-06-04 01:10:09.347 UTC
2012-05-25 16:21:16.69 UTC
null
176,569
null
1,169,845
null
1
2
perl
43,713
<p>That code does not print just <code>cccccc...</code>, it prints everything. Your problem is this line:</p> <pre><code>if($arrayOld[$i] =~ /^-(.*)/g or /\#(.*)/g) { </code></pre> <p>What you are doing here is first checking <code>$arrayOld[$i]</code> and then checking <code>$_</code>, because <code>/\#(.*)/</code> is perl shorthand for <code>$_ =~ /\#(.*)/</code>. Since the line contains a hash character <code>#</code>, it will always match, and the line will always print.</p> <p>Your line is equivalent to:</p> <pre><code>if( $arrayOld[$i] =~ /^-(.*)/g or $_ =~ /\#(.*)/g) { </code></pre> <p>The answer there is to join the regexes:</p> <pre><code>if($arrayOld[$i] =~ /^-|#/) { </code></pre> <p>However, your code is far from clean after that... starting from the top:</p> <p>If you set the input record separator <code>$/</code> to <code>__Data__</code> with that input, you will get two records (<a href="http://search.cpan.org/perldoc?Data%3a%3aDumper" rel="nofollow">Data::Dumper</a> output shown below):</p> <pre><code>$VAR1 = '__Data__'; $VAR1 = ' #SCSI_test # put this line into @arrayNewLines kdkdkdkdkdkdkdkd dkdkdkdkdkdkdkdkd - ccccccccccccccc # put this line into @arrayNewLines '; </code></pre> <p>When you <code>chomp</code> the records, you will remove <code>__Data__</code> from the end, so the first line will become empty. So in essence, you will always have a leading empty field. This is nothing horrible, but something to remember.</p> <p>Your <code>split</code> statement is wrong. First off, the first argument should be a regex: <code>/\n/</code>. The second argument should be a scalar, not an array. <code>split(/\n/,@array)</code> will evaluate to <code>split(/\n/, 2)</code>, because the array is in scalar context and returns its size instead of its elements.</p> <p>Also, of course, since you are in a loop reading lines from the <code>FILEREAD</code> handle, that <code>@array</code> array will always contain the same data, and has nothing to do with the data from the file handle. What you want is: <code>split /\n/, $_</code>.</p> <p>This loop:</p> <pre><code>foreach my $i (0 .. $#arrayOld) { </code></pre> <p>is not a very good loop structure for this problem. Also, there is no need to use an intermediate array. Just use:</p> <pre><code>for my $line (split /\n/, $_) { </code></pre> <p>When you do</p> <pre><code>my @arrayNewLines = $arrayOld[$i]; print "@arrayNewLines\n"; </code></pre> <p>You are setting the entire array to a scalar, then printing it, which is completely redundant. You get the same effect just printing the scalar directly.</p> <p>Your code should look like this:</p> <pre><code>while(&lt;FILEREAD&gt;) { chomp; foreach my $line (split /\n/, $_) { if($line =~ /^-|#/) { print "$line\n"; } } } </code></pre> <p>It is also recommended that you use lexical file handles, so instead of </p> <pre><code>open FILEREAD, "somefile" or die $!; # read with &lt;FILEREAD&gt; </code></pre> <p>use:</p> <pre><code>open my $fh, "&lt;", "somefile" or die $!; # read with &lt;$fh&gt; </code></pre>
21,362,301
Yii2: check exist ActiveRecord model in database
<p>How to check existence of model in DB? In Yii 1 version it was so <code>User::model()-&gt;exist()</code></p>
21,374,795
2
0
null
2014-01-26 10:30:07.217 UTC
2
2018-11-26 11:53:07.18 UTC
2014-05-23 20:24:46.27 UTC
null
724,036
null
1,491,378
null
1
26
php|yii2
41,098
<p>In Yii2 you can add <code>exists()</code> to your query chain:</p> <pre><code>User::find() -&gt;where( [ 'id' =&gt; 1 ] ) -&gt;exists(); </code></pre> <p>(The generated SQL looks like this: <code>SELECT 1 FROM `tbl_user` WHERE `id`=1</code>.) </p> <p>Here is <a href="https://github.com/yiisoft/yii2/blob/d7ffda020b391b2fecf167a6f7e7a718bfc311fc/framework/db/Query.php#L410-L426" rel="noreferrer"><code>Query-&gt;exists()</code>from Yii2 source</a>:</p> <pre><code>/** * Returns a value indicating whether the query result contains any row of data. * @param Connection $db the database connection used to generate the SQL statement. * If this parameter is not given, the `db` application component will be used. * @return bool whether the query result contains any row of data. */ public function exists($db = null) { if ($this-&gt;emulateExecution) { return false; } $command = $this-&gt;createCommand($db); $params = $command-&gt;params; $command-&gt;setSql($command-&gt;db-&gt;getQueryBuilder()-&gt;selectExists($command-&gt;getSql())); $command-&gt;bindValues($params); return (bool) $command-&gt;queryScalar(); } </code></pre>
47,604,184
How to create a custom streaming data source?
<p>I have a custom reader for Spark Streaming that reads data from WebSocket. I'm going to try Spark Structured Streaming.</p> <p>How to create a streaming data source in Spark Structured Streaming?</p>
47,608,536
4
0
null
2017-12-02 03:10:59.39 UTC
14
2022-05-28 14:29:49.637 UTC
2018-10-27 12:57:08.847 UTC
null
1,560,062
null
2,134,595
null
1
13
apache-spark|spark-structured-streaming
8,410
<p>A streaming data source implements <a href="https://github.com/apache/spark/blob/master/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/Source.scala" rel="noreferrer">org.apache.spark.sql.execution.streaming.Source</a>.</p> <p>The scaladoc of <code>org.apache.spark.sql.execution.streaming.Source</code> should give you enough information to get started (just follow the types to develop a compilable Scala type).</p> <p>Once you have the <code>Source</code> you have to register it so you can use it in <code>format</code> of a <code>DataStreamReader</code>. The trick to make the streaming source available so you can use it for <code>format</code> is to register it by creating the <code>DataSourceRegister</code> for the streaming source. You can find examples in <a href="https://github.com/apache/spark/blob/master/sql/core/src/main/resources/META-INF/services/org.apache.spark.sql.sources.DataSourceRegister" rel="noreferrer">META-INF/services/org.apache.spark.sql.sources.DataSourceRegister</a>:</p> <pre><code>org.apache.spark.sql.execution.datasources.csv.CSVFileFormat org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider org.apache.spark.sql.execution.datasources.json.JsonFileFormat org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat org.apache.spark.sql.execution.datasources.text.TextFileFormat org.apache.spark.sql.execution.streaming.ConsoleSinkProvider org.apache.spark.sql.execution.streaming.TextSocketSourceProvider org.apache.spark.sql.execution.streaming.RateSourceProvider </code></pre> <p>That's the file that links the short name in <code>format</code> to the implementation.</p> <p>What I usually recommend people doing during my Spark workshops is to start development from both sides:</p> <ol> <li><p>Write the streaming query (with <code>format</code>), e.g.</p> <pre><code>val input = spark .readStream .format("yourCustomSource") // &lt;-- your custom source here .load </code></pre></li> <li><p>Implement the streaming <code>Source</code> and a corresponding <code>DataSourceRegister</code> (it could be the same class)</p></li> <li><p>(optional) Register the <code>DataSourceRegister</code> by writing the fully-qualified class name, say <code>com.mycompany.spark.MyDataSourceRegister</code>, to <code>META-INF/services/org.apache.spark.sql.sources.DataSourceRegister</code>:</p> <pre><code>$ cat META-INF/services/org.apache.spark.sql.sources.DataSourceRegister com.mycompany.spark.MyDataSourceRegister </code></pre></li> </ol> <p>The last step where you register the <code>DataSourceRegister</code> implementation for your custom <code>Source</code> is optional and is only to register the data source alias that your end users use in <a href="http://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.DataFrameReader@format(source:String):org.apache.spark.sql.DataFrameReader" rel="noreferrer">DataFrameReader.format</a> method.</p> <blockquote> <p><strong>format(source: String): DataFrameReader</strong> Specifies the input data source format.</p> </blockquote> <p>Review the code of <a href="https://github.com/apache/spark/blob/master/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/RateSourceProvider.scala" rel="noreferrer">org.apache.spark.sql.execution.streaming.RateSourceProvider</a> for a good head start.</p>
7,605,011
Why is 0 == "" true in JavaScript
<p>Why is <code>0 == ""</code> true in JavaScript? I have found a <a href="https://stackoverflow.com/questions/4567393/why-do-alert0-and-alertfalse-0-both-output-true-in-javascript">similar post here</a>, but why is a number 0 similar an empty string? Of course, <code>0 === ""</code> is false.</p>
7,605,024
1
9
null
2011-09-30 01:09:50.8 UTC
13
2012-07-23 00:12:11.147 UTC
2017-05-23 11:47:08.953 UTC
null
-1
null
356,726
null
1
35
javascript
15,207
<pre><code>0 == '' </code></pre> <p>The left operand is of the type Number.<br> The right operand is of the type String.</p> <p>In this case, the right operand is coerced to the type Number:</p> <pre><code>0 == Number('') </code></pre> <p>which results in</p> <pre><code>0 == 0 </code></pre> <hr> <p>From the <strong>Abstract Equality Comparison Algorithm</strong> (number 4):</p> <blockquote> <p>If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).</p> </blockquote> <p>Source: <a href="http://es5.github.com/#x11.9.3">http://es5.github.com/#x11.9.3</a></p>
2,936,598
MongoDB Schema Design - Real-time Chat
<p>I'm starting a project which I think will be particularly suited to MongoDB due to the speed and scalability it affords.</p> <p>The module I'm currently interested in is to do with real-time chat. If I was to do this in a traditional RDBMS I'd split it out into:</p> <ul> <li>Channel (A channel has many users)</li> <li>User (A user has one channel but many messages)</li> <li>Message (A message has a user)</li> </ul> <p>The the purpose of this use case, I'd like to assume that there will be typically 5 channels active at one time, each handling at most 5 messages per second.</p> <p>Specific queries that need to be fast:</p> <ul> <li>Fetch new messages (based on an bookmark, time stamp maybe, or an incrementing counter?)</li> <li>Post a message to a channel</li> <li>Verify that a user can post in a channel</li> </ul> <p>Bearing in mind that the document limit with MongoDB is 4mb, how would you go about designing the schema? What would yours look like? Are there any gotchas I should watch out for?</p>
2,937,029
3
0
null
2010-05-29 21:02:38.86 UTC
11
2017-07-11 09:47:56.043 UTC
2017-09-22 18:01:22.247 UTC
null
-1
null
283,844
null
1
13
mongodb|rabbitmq|activemq|schema-design|nosql
13,548
<p>I used <a href="http://code.google.com/p/redis/" rel="nofollow noreferrer">Redis</a>, NGINX &amp; PHP-FPM for my chat project. Not super elegant, but it does the trick. There are a few pieces to the puzzle.</p> <ol> <li><p>There is a very simple PHP script that receives client commands and puts them in one massive LIST. It also checks all room LISTs and the users private LIST to see if there are messages it must deliver. This is polled by a client written in jQuery &amp; it's done every few seconds.</p></li> <li><p>There is a command line PHP script that operates server side in an infinite loop, 20 times per second, which checks this list and then processes these commands. The script handles who is in what room and permissions in the scripts memory, this info is not stored in Redis. </p></li> <li><p>Redis has a LIST for each room &amp; a LIST for each user which operates as a private queue. It also has multiple counters for each room the user is in. If the users counter is less than the total messages in the room, then it gets the difference and sends it to the user.</p></li> </ol> <p>I haven't been able to stress test this solution, but at least from my basic benchmarking it could probably handle many thousands of messages per second. There is also the opportunity to port this over to something like Node.js to increase performance. Redis is also maturing and has some interesting features like Pub/Subscribe commands, which might be of interest, that would possibly remove the polling on the server side possibly.</p> <p>I looked into Comet based solutions, but many of them were complicated, poorly documented or would require me learning an entirely new language(e.g. Jetty->Java, APE->C),etc... Also delivery and going through proxies can sometimes be an issue with Comet. So that is why I've stuck with polling.</p> <p>I imagine you could do something similar with MongoDB. A collection per room, a collection per user &amp; then a collection which maintains counters. You'll still need to write a back-end daemon or script to handle manging where these messages go. You could also use MongoDB's "limited collections", which keeps the documents sorted &amp; also automatically clears old messages out, but that could be complicated in maintaining proper counters.</p>
2,524,737
Fixed-size floating point types
<p>In the <code>stdint.h</code> (C99), <a href="http://www.boost.org/doc/libs/1_42_0/libs/integer/doc/html/boost_integer/cstdint.html" rel="noreferrer">boost/cstdint.hpp</a>, and <code>cstdint</code> (C++0x) headers there is, among others, the type <code>int32_t</code>.</p> <p>Are there similar fixed-size floating point types? Something like <code>float32_t</code>?</p>
2,524,933
4
7
null
2010-03-26 16:07:46.027 UTC
10
2017-11-09 06:57:37.833 UTC
2017-04-30 01:46:02.81 UTC
Roger Pate
1,267,663
null
235,472
null
1
111
c++|c|boost|floating-point
59,149
<p>Nothing like this exists in the C or C++ standards at present. In fact, there isn't even a guarantee that <code>float</code> will be a binary floating-point format at all.</p> <p>Some compilers guarantee that the <code>float</code> type will be the IEEE-754 32 bit binary format. Some do not. In reality, <code>float</code> is in fact the IEEE-754 <code>single</code> type on <em>most</em> non-embedded platforms, though the usual caveats about some compilers evaluating expressions in a wider format apply.</p> <p>There is a working group discussing adding C language bindings for the 2008 revision of IEEE-754, which could consider recommending that such a typedef be added. If this were added to C, I expect the C++ standard would follow suit... eventually.</p>
8,876
Evidence Based Scheduling Tool
<p>Are there any free tools that implement evidence-based scheduling like <a href="http://www.joelonsoftware.com/items/2007/10/26.html" rel="nofollow noreferrer">Joel talks about</a>? There is FogBugz, of course, but I am looking for a simple and free tool that can apply EBS on some tasks that I give estimates (and actual times which are complete) for.</p>
8,882
2
6
null
2008-08-12 14:16:41.757 UTC
8
2013-09-27 20:20:26.243 UTC
2013-09-27 20:20:26.243 UTC
buyutec
277,932
buyutec
31,505
null
1
30
fogbugz
3,135
<p>FogBugz is free for up to 2 users by the way. As far I know this is the only tool that does EBS.</p> <p>See here <a href="http://www.workhappy.net/2008/06/get-fogbugz-for.html" rel="noreferrer">http://www.workhappy.net/2008/06/get-fogbugz-for.html</a></p>
2,864,796
EasyMock vs Mockito: design vs maintainability?
<p>One way of thinking about this is: if we care about the design of the code then EasyMock is the better choice as it gives feedback to you by its concept of expectations.</p> <p>If we care about the maintainability of tests (easier to read, write and having less brittle tests which are not affected much by change), then Mockito seems a better choice.</p> <p>My questions are:</p> <ul> <li>If you have used EasyMock in large scale projects, do you find that your tests are harder to maintain? </li> <li>What are the limitations of Mockito (other than endo testing)?</li> </ul>
2,872,197
5
1
null
2010-05-19 10:50:38.81 UTC
20
2015-08-24 08:29:26.807 UTC
2013-06-13 22:32:33.627 UTC
null
843,804
null
238,012
null
1
57
easymock|mockito
33,338
<p>I'm an EasyMock developer so a bit partial but of course I've used EasyMock on large scale projects.</p> <p>My opinion is that EasyMock tests will indeed breaks once in a while. EasyMock forces you to do a complete recording of what you expect. This requires some discipline. You should really record what is expected not what the tested method currently needs. For instance, if it doesn't matter how many time a method is called on a mock, don't be afraid of using <code>andStubReturn</code>. Also, if you don't care about a parameter, use <code>anyObject()</code> and so on. Thinking in TDD can help on that.</p> <p>My analyze is that EasyMock tests will break more often but Mockito ones won't when you would want them to. I prefer my tests to break. At least I'm aware of what was the impacts of my development. This is of course, my personal point of view.</p>
2,429,642
Why it's impossible to throw exception from __toString()?
<p>Why it's impossible to throw exception from __toString()?</p> <pre><code>class a { public function __toString() { throw new Exception(); } } $a = new a(); echo $a; </code></pre> <p>the code above produces this:</p> <pre><code>Fatal error: Method a::__toString() must not throw an exception in /var/www/localhost/htdocs/index.php on line 12 </code></pre> <p>I was pointed to <a href="http://php.net/manual/en/migration52.incompatible.php" rel="noreferrer">http://php.net/manual/en/migration52.incompatible.php</a> where this behavior is described, but why? Any reasons to do that?</p> <p>May be anyone here knows this?</p> <p>At bug tracker php-dev-team as usual says nothing but see manual: <a href="http://bugs.php.net/50699" rel="noreferrer">http://bugs.php.net/50699</a></p>
2,429,735
6
1
null
2010-03-12 00:15:45.803 UTC
5
2019-06-28 11:19:41.26 UTC
2013-02-17 05:54:49.537 UTC
null
127,880
null
251,311
null
1
47
php|exception
19,957
<p>After a couple searches I found this, which says:</p> <blockquote> <p>Johannes explained that <strong>there is no way to ensure that an exception thrown during a cast to string would be handled correctly by the Zend Engine</strong>, and that this won't change unless large parts of the Engine are rewritten. He added that there have been discussions about such issues in the past, and suggested that Guilherme check the archives.</p> </blockquote> <p>The <a href="http://schlueters.de/" rel="noreferrer">Johannes</a> referenced above is the PHP 5.3 Release Manager, so it's probably as "official" an explanation as you might find as to why PHP behaves this way.</p> <p>The section goes on to mention:</p> <blockquote> <p><code>__toString()</code> will, strangely enough, accept <a href="http://php.net/manual/en/function.trigger-error.php" rel="noreferrer">trigger_error()</a>.</p> </blockquote> <p>So not all is lost in terms of error reporting within <code>__toString()</code>.</p>
2,762,778
Grab remaining text after last "/" in a php string
<p>So, lets say I have a <code>$somestring</code> thats holds the value "main/physician/physician_view".</p> <p>I want to grab just "physician_view". I want it to also work if the passed string was "main/physician_view" or "site/main/physician/physician_view". </p> <p>Hopefully my question makes sense. Any help would be appreciated!</p>
2,762,807
7
1
null
2010-05-04 04:16:40.077 UTC
7
2017-01-24 20:19:25.833 UTC
null
null
null
null
160,797
null
1
56
php|string
50,580
<p>There are many ways to do this. I would probably use:</p> <pre><code>array_pop(explode('/', $string)); </code></pre>
3,161,816
Truncate a string to first n characters of a string and add three dots if any characters are removed
<p>How can I get the first n characters of a string in PHP? What's the fastest way to trim a string to a specific number of characters, and append '...' if needed?</p>
3,161,830
20
5
null
2010-07-01 21:28:19.95 UTC
77
2021-08-08 10:14:43.583 UTC
2021-03-03 03:36:42.34 UTC
null
2,943,403
null
376,947
null
1
360
php|string|ellipsis|truncation
491,867
<pre><code>//The simple version for 10 Characters from the beginning of the string $string = substr($string,0,10).'...'; </code></pre> <p>Update:</p> <p>Based on suggestion for checking length (and also ensuring similar lengths on trimmed and untrimmed strings):</p> <pre><code>$string = (strlen($string) &gt; 13) ? substr($string,0,10).'...' : $string; </code></pre> <p>So you will get a string of max 13 characters; either 13 (or less) normal characters or 10 characters followed by '...'</p> <p>Update 2:</p> <p>Or as function:</p> <pre><code>function truncate($string, $length, $dots = "...") { return (strlen($string) &gt; $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string; } </code></pre> <p>Update 3:</p> <p>It's been a while since I wrote this answer and I don't actually use this code any more. I prefer this function which prevents breaking the string in the middle of a word using the <code>wordwrap</code> function:</p> <pre><code>function truncate($string,$length=100,$append="&amp;hellip;") { $string = trim($string); if(strlen($string) &gt; $length) { $string = wordwrap($string, $length); $string = explode("\n", $string, 2); $string = $string[0] . $append; } return $string; } </code></pre>
45,635,726
KafkaAvroSerializer for serializing Avro without schema.registry.url
<p>I'm a noob to Kafka and Avro. So i have been trying to get the Producer/Consumer running. So far i have been able to produce and consume simple Bytes and Strings, using the following : Configuration for the Producer :</p> <pre><code> Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer"); Schema.Parser parser = new Schema.Parser(); Schema schema = parser.parse(USER_SCHEMA); Injection&lt;GenericRecord, byte[]&gt; recordInjection = GenericAvroCodecs.toBinary(schema); KafkaProducer&lt;String, byte[]&gt; producer = new KafkaProducer&lt;&gt;(props); for (int i = 0; i &lt; 1000; i++) { GenericData.Record avroRecord = new GenericData.Record(schema); avroRecord.put("str1", "Str 1-" + i); avroRecord.put("str2", "Str 2-" + i); avroRecord.put("int1", i); byte[] bytes = recordInjection.apply(avroRecord); ProducerRecord&lt;String, byte[]&gt; record = new ProducerRecord&lt;&gt;("mytopic", bytes); producer.send(record); Thread.sleep(250); } producer.close(); } </code></pre> <p>Now this is all well and good, the problem comes when i'm trying to serialize a POJO. So , i was able to get the AvroSchema from the POJO using the utility provided with Avro. Hardcoded the schema, and then tried to create a Generic Record to send through the KafkaProducer the producer is now set up as :</p> <pre><code> Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.KafkaAvroSerializer"); Schema.Parser parser = new Schema.Parser(); Schema schema = parser.parse(USER_SCHEMA); // this is the Generated AvroSchema KafkaProducer&lt;String, byte[]&gt; producer = new KafkaProducer&lt;&gt;(props); </code></pre> <p>this is where the problem is : the moment i use KafkaAvroSerializer, the producer doesn't come up due to : <em>missing mandatory parameter : schema.registry.url</em></p> <p>I read up on why this is required, so that my consumer is able to decipher whatever the producer is sending to me. But isn't the schema already embedded in the AvroMessage? Would be really great if someone can share a working example of using KafkaProducer with the KafkaAvroSerializer without having to specify schema.registry.url</p> <p>would also really appreciate any insights/resources on the utility of the schema registry.</p> <p>thanks!</p>
45,637,006
5
1
null
2017-08-11 12:52:12.147 UTC
12
2020-07-06 03:33:32.94 UTC
2018-09-30 07:09:49.21 UTC
null
2,308,683
null
3,692,045
null
1
27
java|apache-kafka|avro|confluent-schema-registry
33,295
<p>Note first: <code>KafkaAvroSerializer</code> is not provided in vanilla apache kafka - it is provided by Confluent Platform. (<a href="https://www.confluent.io/" rel="noreferrer">https://www.confluent.io/</a>), as part of its open source components (<a href="http://docs.confluent.io/current/platform.html#confluent-schema-registry" rel="noreferrer">http://docs.confluent.io/current/platform.html#confluent-schema-registry</a>)</p> <p>Rapid answer: no, if you use <code>KafkaAvroSerializer</code>, you will need a schema registry. See some samples here: <a href="http://docs.confluent.io/current/schema-registry/docs/serializer-formatter.html" rel="noreferrer">http://docs.confluent.io/current/schema-registry/docs/serializer-formatter.html</a></p> <p>The basic idea with schema registry is that each topic will refer to an avro schema (ie, you will only be able to send data coherent with each other. But a schema can have multiple version, so you still need to identify the schema for each record)</p> <p>We don't want to write the schema for everydata like you imply - often, schema is bigger than your data! That would be a waste of time parsing it everytime when reading, and a waste of ressources (network, disk, cpu)</p> <p>Instead, a schema registry instance will do a binding <code>avro schema &lt;-&gt; int schemaId</code> and the serializer will then write only this id before the data, after getting it from registry (and caching it for later use). </p> <p>So inside kafka, your record will be <code>[&lt;id&gt; &lt;bytesavro&gt;]</code> (and magic byte for technical reason), which is an overhead of only 5 bytes (to compare to the size of your schema) And when reading, your consumer will find the corresponding schema to the id, and deserializer avro bytes regarding it. You can find way more in confluent doc</p> <p>If you really have a use where you want to write the schema for every record, you will need an other serializer (I think writing your own, but it will be easy, just reuse <a href="https://github.com/confluentinc/schema-registry/blob/master/avro-serializer/src/main/java/io/confluent/kafka/serializers/AbstractKafkaAvroSerializer.java" rel="noreferrer">https://github.com/confluentinc/schema-registry/blob/master/avro-serializer/src/main/java/io/confluent/kafka/serializers/AbstractKafkaAvroSerializer.java</a> and remove the schema registry part to replace it with the schema, same for reading). But if you use avro, I would really discourage this - one day a later, you will need to implement something like avro registry to manage versioning</p>
51,084,907
How to increase the connection limit for the Google Cloud SQL Postgres database?
<p>The number of connections for Google Cloud SQL PostgreSQL databases is relatively low. Depending on the plan this is somewhere between 25 and 500, while the limit for MySQL in Google Cloud SQL is between 250 and 4000, reaching 4000 very quickly.</p> <p>We currently have a number of trial instances for different customers running on Kubernetes and backed by the same Google Cloud SQL Postgres server. Each instance uses a separate set of database, roles and connections (one per service). We've already reached the limit of connections for our plan (50) and we're not even close to getting to the memory or cpu limits. Connection pooling seems not to be an option, because the connections are with different users. I'm wondering now why the limit is so low and if there's a way to increase the limit without having to upgrade to a more expensive plan.</p>
55,479,093
2
0
null
2018-06-28 14:02:39.32 UTC
8
2019-05-20 23:43:11.177 UTC
2018-06-29 00:19:24.53 UTC
null
1,774,564
null
10,006,000
null
1
35
postgresql|google-cloud-platform|google-cloud-sql
26,840
<p>It looks like google just released this as a beta feature. When creating or editing a database instance, you can add a flag called <code>max_connections</code>, where you can enter a new limit between 14 and 262143 connections.</p> <p><a href="https://i.stack.imgur.com/sUyEn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sUyEn.png" alt="gcp cloud sql connection limit flag"></a></p>
10,421,334
microdata schema.org: how to mix together schemas?
<p>hello I have a page ( <a href="http://schema.org/WebPage">http://schema.org/WebPage</a> ) that contains a review ( <a href="http://schema.org/Review">http://schema.org/Review</a> )</p> <p>the question are:</p> <ul> <li>how to deal with duplicate contents?</li> <li>is correct making elements belong to two or more scopes?</li> <li>how to do this, repeating text twice?</li> <li>or i should avoid multiple references?</li> </ul> <p>example:</p> <pre><code>&lt;html itemscope itemtype="http://schema.org/WebPage"&gt; &lt;meta name="description" content="_________" itemprop="description"&gt; ... &lt;div itemscope itemtype="http://schema.org/Review"&gt; &lt;div itemprop="description"&gt;_________&lt;/div&gt; &lt;/div&gt; ... &lt;/html&gt; </code></pre> <p>the description belongs to the Review AND to the WebPage, so... what I should write in this case?</p> <p>(note: in the previous example the string "<strong><em>_</em>_</strong>" is the same text paragraph, repeated twice)</p> <hr> <p>EDIT:</p> <p>can this be a solution? (the html5 spec doesn't talk about this, but defines the itemref attribute)</p> <pre><code>&lt;html itemscope itemtype="http://schema.org/WebPage" id="WEBPAGE"&gt; ... &lt;div itemscope itemtype="http://schema.org/Review" id="REVIEW"&gt; &lt;div itemprop="description" itemref="WEBPAGE REVIEW"&gt;_________&lt;/div&gt; &lt;/div&gt; ... &lt;/html&gt; </code></pre> <p>FEEL FREE TO IMPROVE THE QUESTION!</p>
10,477,242
1
0
null
2012-05-02 20:39:31.147 UTC
14
2013-10-01 11:23:26.28 UTC
2012-05-05 15:26:39.987 UTC
null
1,252,794
null
1,252,794
null
1
14
html|seo|microdata|schema.org
5,610
<h2>Quick answers</h2> <ul> <li><em>how to deal with duplicate contents?</em> <ul> <li><strong>use the attribute itemref</strong></li> </ul> </li> <li><em>is correct making elements belong to two or more scopes?</em> <ul> <li><strong>Yes, this is what you use itemref for</strong></li> </ul> </li> <li><em>how to do this, repeating text twice?</em> <ul> <li><strong>No, you only need to refer to the element</strong></li> </ul> </li> <li><em>or i should avoid multiple references?</em> <ul> <li><strong>I don't see any reason why you don't wanna use multiple references</strong></li> </ul> </li> </ul> <hr /> <h2>Some Examples</h2> <p><strong>Include by wrapping</strong></p> <p>When you use the itemref attribute you include all property contained within the referred element to a different scope.</p> <pre><code>&lt;body itemscope itemtype=&quot;http://schema.org/WebPage&quot; itemref=&quot;wrapper&quot;&gt; ... &lt;div itemscope itemtype=&quot;http://schema.org/Review&quot;&gt; ... &lt;div id=&quot;wrapper&quot;&gt; &lt;div itemprop=&quot;description&quot;&gt;_________&lt;/div&gt; &lt;div itemprop=&quot;some-other-property&quot;&gt;_________&lt;/div&gt; &lt;/div&gt; ... &lt;/div&gt; ... &lt;/body&gt; </code></pre> <p><strong>Include by wrapping - a different example</strong></p> <p>Lets say you have a product with a few different offers outside the scope.</p> <pre><code>&lt;div itemscope itemtype=&quot;http://schema.org/Product&quot; itemref=&quot;wrapper&quot;&gt; ... &lt;/div&gt; &lt;div id=&quot;wrapper&quot;&gt; &lt;div itemprop=&quot;offers&quot; itemscope itemtype=&quot;http://schema.org/Offer&quot;&gt; ... &lt;/div&gt; &lt;div itemprop=&quot;offers&quot; itemscope itemtype=&quot;http://schema.org/Offer&quot;&gt; ... &lt;/div&gt; &lt;div itemprop=&quot;offers&quot; itemscope itemtype=&quot;http://schema.org/Offer&quot;&gt; ... &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>Include a specific property</strong></p> <p>You might only wish to include one specific property outside the scope, to do this we can simply set the id directly on the targeted element with the itemprop specified.</p> <pre><code>&lt;body itemscope itemtype=&quot;http://schema.org/WebPage&quot; itemref=&quot;target&quot;&gt; ... &lt;div itemscope itemtype=&quot;http://schema.org/Review&quot;&gt; &lt;div id=&quot;target&quot; itemprop=&quot;description&quot;&gt;_________&lt;/div&gt; &lt;/div&gt; ... &lt;/body&gt; </code></pre> <p><strong>Multiple references</strong></p> <p>Maybe a wrapper isn't applicable, then you can use multiple references. You separate them simply by space.</p> <pre><code>&lt;body itemscope itemtype=&quot;http://schema.org/WebPage&quot; itemref=&quot;desc name&quot;&gt; ... &lt;div itemscope itemtype=&quot;http://schema.org/Review&quot;&gt; &lt;div id=&quot;desc&quot; itemprop=&quot;description&quot;&gt;_________&lt;/div&gt; &lt;div id=&quot;name&quot; itemprop=&quot;name&quot;&gt;_________&lt;/div&gt; &lt;/div&gt; ... &lt;/body&gt; </code></pre> <hr /> <h2>Source</h2> <p>See also thees pages for some other explanations and examples:<br /> <a href="http://www.w3.org/TR/2011/WD-microdata-20110405/" rel="noreferrer">http://www.w3.org/TR/2011/WD-microdata-20110405/</a><br /> <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/microdata.html" rel="noreferrer">http://www.whatwg.org/specs/web-apps/current-work/multipage/microdata.html</a></p>
33,080,068
Running composer in a different directory than current
<p>I don't know if this question has been asked, because searching finds results mostly about moving the libraries installation directory.</p> <p>I have a globally installed composer command. Is there a way to run, for example, <code>composer install</code> in a different directory than current, i.e. to specify the directory in which I would like tu run the command?</p> <p>E.g. being in <code>/home/someuser</code>, I would like to acquire the same result as in running <code>composer install</code> it inside <code>/home/someuser/myproject</code>. Of course, one way would be to simply change the current directory, run composer and go back.</p>
33,082,705
4
0
null
2015-10-12 11:32:41.41 UTC
14
2021-12-09 13:13:21.93 UTC
null
null
null
null
940,569
null
1
91
php|composer-php
72,597
<p>Try <code>composer install -h</code>. There you'll find an option <code>--working-dir</code> (or <code>-d</code>). And that's what you're looking for.</p> <p>Then run:</p> <pre><code>composer install --working-dir=/home/someuser/myproject </code></pre> <p>You can find more in <a href="https://getcomposer.org/doc/03-cli.md#global-options" rel="noreferrer">composer docs</a>.</p> <br> <p>Depending on your operating system, the <code>=</code> might need to be removed:</p> <pre><code>composer install --working-dir /home/someuser/myproject </code></pre>
19,441,055
Why does Hadoop need classes like Text or IntWritable instead of String or Integer?
<p>Why does Hadoop need to introduce these new classes? They just seem to complicate the interface</p>
19,441,225
4
0
null
2013-10-18 03:22:56.42 UTC
13
2016-05-16 16:21:47.81 UTC
null
null
null
null
165,495
null
1
36
hadoop
28,371
<p>In order to handle the Objects in Hadoop way. For example, hadoop uses <code>Text</code> instead of java's <code>String</code>. The <code>Text</code> class in hadoop is similar to a java <code>String</code>, however, <code>Text</code> implements interfaces like <code>Comparable</code>, <code>Writable</code> and <code>WritableComparable</code>. </p> <p>These interfaces are all necessary for MapReduce; the <code>Comparable</code> interface is used for comparing when the reducer sorts the keys, and <code>Writable</code> can write the result to the local disk. It does not use the java <code>Serializable</code> because java <code>Serializable</code> is too big or too heavy for hadoop, <code>Writable</code> can serializable the hadoop Object in a very light way. </p>
32,502,830
delete the last row in a table using sql query?
<p>I am trying to delete the last record in the table named <strong>&quot;marks&quot;</strong> in the database using <strong>MySql query</strong>.<br /> The query I tried for this is as follows:</p> <pre><code>DELETE MAX(`id`) FROM `marks`; </code></pre> <p>There are 8 columns in the table. I want to delete the last column without specifying <code>id</code>, as in:</p> <p><code>DELETE FROM marks where id=8;</code></p> <p>After deleting the 8th record, I want to delete the 7th; after that 6th and so on, up to 1st record without specifying the <code>id</code> manually.</p>
32,502,953
5
0
null
2015-09-10 13:09:56.853 UTC
4
2022-01-19 19:03:56.993 UTC
2022-01-19 19:03:56.993 UTC
null
5,411,817
null
4,277,736
null
1
16
mysql
67,796
<p>If <code>id</code> is auto-increment then you can use the following </p> <pre><code>delete from marks order by id desc limit 1 </code></pre>
34,268,406
Calling instance method on each object in array
<p>Let's assume this situation: I have an array of objects and I want call instance method on each one of them. I can do something like that:</p> <pre><code>//items is an array of objects with instanceMethod() available items.forEach { $0.instanceMethod() } </code></pre> <p>The same situation is with <code>map</code>. For example I want to map each object to something else with <code>mappingInstanceMethod</code> which returns value:</p> <pre><code>let mappedItems = items.map { $0.mappingInstanceMethod() } </code></pre> <p>Is there a cleaner way to do that?</p> <p>For example in Java one can do:</p> <pre><code>items.forEach(Item::instanceMethod); </code></pre> <p>instead of</p> <pre><code>items.forEach((item) -&gt; { item.instanceMethod(); }); </code></pre> <p>Is similiar syntax available in Swift? </p>
34,269,544
3
0
null
2015-12-14 13:36:01.66 UTC
1
2021-01-12 23:34:02.507 UTC
2015-12-14 14:19:22.803 UTC
null
1,816,253
null
1,816,253
null
1
30
swift
14,805
<p>What you are doing in</p> <pre><code>items.forEach { $0.instanceMethod() } let mappedItems = items.map { $0.mappingInstanceMethod() } </code></pre> <p>is a clean and Swifty way. As explained in <a href="https://stackoverflow.com/questions/34049116/is-there-a-way-to-reference-instance-function-when-calling-sequencetype-foreach">Is there a way to reference instance function when calling SequenceType.forEach?</a>, the first statement cannot be reduced to </p> <pre><code>items.forEach(Item.instanceMethod) </code></pre> <p>There is one exception though: It works with <code>init</code> methods which take a single argument. Example:</p> <pre><code>let ints = [1, 2, 3] let strings = ints.map(String.init) print(strings) // ["1", "2", "3"] </code></pre>
51,778,266
Digit only TextFormField in Flutter
<p>Im am working on an app that requires a price input in <code>¥</code> and as such has no decimal places. If we use <code>keyboardType: TextInputType.numberWithOptions()</code> we can get a number pad input. If we use <code>validator: (input) { }</code> we can check if input is valid but we cannot prevent it.</p> <p>The problem is we can save a draft that will not need validation. So it is better for us to only allow digit input in the first place.</p> <pre><code>import 'package:flutter/material.dart'; void main() =&gt; runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Digits Only', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() =&gt; new _MyHomePageState(); } class _MyHomePageState extends State&lt;MyHomePage&gt; { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ TextFormField( autovalidate: true, keyboardType: TextInputType.number, validator: (input) { final isDigitsOnly = int.tryParse(input); return isDigitsOnly == null ? 'Input needs to be digits only' : null; }, ), ], ), ), ); } } </code></pre> <p>Is there a way to prevent certain text input and only allow digits?</p>
51,778,460
4
0
null
2018-08-10 02:54:53.907 UTC
8
2021-04-12 10:19:26.687 UTC
2019-10-31 17:43:36.087 UTC
null
666,221
null
2,819,510
null
1
53
flutter|dart
53,476
<p>Yep, you can use the <code>inputFormatters</code> attribute and add the <code>WhitelistingTextInputFormatter.digitsOnly</code> expression</p> <pre><code> import 'package:flutter/services.dart'; TextFormField( ... inputFormatters: [WhitelistingTextInputFormatter.digitsOnly], ) </code></pre> <p>You can find more info here: <a href="https://docs.flutter.io/flutter/services/TextInputFormatter-class.html" rel="noreferrer">https://docs.flutter.io/flutter/services/TextInputFormatter-class.html</a></p> <p>After flutter 1.12, <code>WhitelistingTextInputFormatter</code> was deprecated and you are running a newer version, use :</p> <p><code>FilteringTextInputFormatter.digitsOnly</code></p> <p><a href="https://api.flutter.dev/flutter/services/FilteringTextInputFormatter-class.html" rel="noreferrer">https://api.flutter.dev/flutter/services/FilteringTextInputFormatter-class.html</a></p>