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
8,116,648
Why is the ELF entry point 0x8048000 not changeable with the "ld -e" option?
<p>Following up <a href="https://stackoverflow.com/questions/2187484/elf-binary-entry-point">Why is the ELF execution entry point virtual address of the form 0x80xxxxx and not zero 0x0?</a> and <a href="https://stackoverflow.com/questions/2966426/why-do-virtual-memory-addresses-for-linux-binaries-start-at-0x8048000">Why do virtual memory addresses for linux binaries start at 0x8048000?</a>, why cannot I make <code>ld</code> use a different entry point than the default with <code>ld -e</code>?</p> <p>If I do so, I either get a <code>segmentation fault</code> with return code 139, even for addresses close by the default entry point. Why?</p> <p><strong>EDIT:</strong></p> <p>I will make the question more specific:</p> <pre><code> .text .globl _start _start: movl $0x4,%eax # eax = code for 'write' system call movl $1,%ebx # ebx = file descriptor to standard output movl $message,%ecx # ecx = pointer to the message movl $13,%edx # edx = length of the message int $0x80 # make the system call movl $0x0,%ebx # the status returned by 'exit' movl $0x1,%eax # eax = code for 'exit' system call int $0x80 # make the system call .data .globl message message: .string "Hello world\n" # The message as data </code></pre> <p>If I compile this with <code>as program.s -o program.o</code> and then link it statically with <code>ld -N program.o -o program</code>, <code>readelf -l program</code> shows <code>0x0000000000400078</code> as the <code>VirtAddr</code> of the text segment and <code>0x400078</code> as entry point. When run, `Hello world" is printed.</p> <p>However, when I try to link with <code>ld -N -e0x400082 -Ttext=0x400082 program.o -o program</code> (moving text segment and entry point by 4 bytes), the program will be <code>killed</code>. Inspecting it with <code>readelf -l</code> now shows two different headers of type <code>LOAD</code>, one at <code>0x0000000000400082</code> and one at <code>0x00000000004000b0</code>.</p> <p>When I try <code>0x400086</code>, it all works, and there is only one <code>LOAD</code> section.</p> <ol> <li>What's going on here?</li> <li>Which memory addresses may I chose, which ones cannot I chose and why?</li> </ol> <p>Thanks you.</p>
8,117,753
1
1
null
2011-11-14 02:25:59.28 UTC
9
2022-08-09 15:05:49.92 UTC
2017-05-23 12:33:32.933 UTC
null
-1
null
263,061
null
1
10
linker|elf|memory-layout
7,955
<blockquote> <p>why cannot I make ld use a different entry point than the default with ld -e</p> </blockquote> <p>You sure can. This:</p> <pre class="lang-c prettyprint-override"><code>int foo(int argc, char *argv[]) { return 0; } </code></pre> <pre class="lang-bash prettyprint-override"><code>gcc main.c -Wl,-e,foo </code></pre> <p>wouldn't work, because the execution doesn't start at main. It starts at <code>_start</code>, which is linked from <code>crt0.o</code> (part of glibc) and arranges for things like dynamic linking, etc. to start up properly. By redirecting <code>_start</code> to <code>foo</code>, you've bypassed all that required glibc initialization, and so things don't work.</p> <p>But if you don't need dynamic linking, and are willing to do what glibc normally does for you, then you can name the entry point whatever you want. Example:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;syscall.h&gt; int foo() { syscall(SYS_write, 1, &quot;Hello, world\n&quot;, 13); syscall(SYS_exit, 0); } </code></pre> <pre class="lang-bash prettyprint-override"><code>gcc t.c -static -nostartfiles -Wl,-e,foo &amp;&amp; ./a.out Hello, world </code></pre> <p>Oh, and your title of this question doesn't match your actual question (bad idea(TM)).</p> <p>To answer the question in the title, you sure <em>can</em> change the address your executable is linked at. By default, you get <code>0x8048000</code> load address (only in 32-bits; 64-bit default is <code>0x400000</code>).</p> <p>You can easily change that to e.g. <code>0x80000</code> by adding <code>-Wl,-Ttext-segment=0x80000</code> to the link line.</p> <p>Update:</p> <blockquote> <p>However, when I try to link with ld -N -e0x400082 -Ttext=0x400082 program.o -o program (moving text segment and entry point by 4 bytes), the program will be killed.</p> </blockquote> <p>Well, it is impossible to assign <code>Ttext</code> to <code>0x400082</code> without violating <code>.text</code> section alignment constraint (which is 4). You must keep the .text address aligned on at least 4-byte boundary (or change the required alignment of <code>.text</code>).</p> <p>When I set the start address to 0x400078, 0x40007c, 0x400080, 0x400084, ..., 0x400098 and use GNU-ld 2.20.1, the program works.</p> <p>However, when I use current CVS snapshot of binutils, the program works for 0x400078, 0x40007c, 0x400088, 0x40008c, and gets Killed for 0x400080, 0x400084, 0x400090, 0x400094, 0x400098. This might be a bug in the linker, or I am violating some other constraint (I don't see which though).</p> <p>At this point, if you are <em>really</em> interested, I suggest downloading binutils sources, building <code>ld</code>, and figuring out what exactly causes it to create two <code>PT_LOAD</code> segments instead of one.</p> <p>Update 2:</p> <blockquote> <p>Force new segment for sections with overlapping LMAs.</p> </blockquote> <p>Ah! That just means you need to move <code>.data</code> out of the way. This makes a working executable:</p> <pre><code>ld -N -o t t.o -e0x400080 -Ttext=0x400080 -Tdata=0x400180 </code></pre>
21,805,674
Do I need to cast to unsigned char before calling toupper(), tolower(), et al.?
<p>A while ago, someone with high reputation here on Stack Overflow wrote in a comment that it is necessary to cast a <code>char</code>-argument to <code>unsigned char</code> before calling <code>std::toupper</code> and <code>std::tolower</code> (and similar functions).</p> <p>On the other hand, Bjarne Stroustrup does not mention the need to do so in <em>the C++ Programming Language</em>. He just uses <code>toupper</code> like</p> <blockquote> <pre><code>string name = &quot;Niels Stroustrup&quot;; void m3() { string s = name.substr(6,10); // s = &quot;Stroustr up&quot; name.replace(0,5,&quot;nicholas&quot;); // name becomes &quot;nicholas Stroustrup&quot; name[0] = toupper(name[0]); // name becomes &quot;Nicholas Stroustrup&quot; } </code></pre> </blockquote> <p>(Quoted from said book, 4th edition.)</p> <p><a href="http://en.cppreference.com/w/cpp/string/byte/toupper" rel="nofollow noreferrer">The reference</a> says that the input needs to be representable as <code>unsigned char</code>. For me this sounds like it holds for every <code>char</code> since <code>char</code> and <code>unsigned char</code> have the same size.</p> <p>So is this cast unnecessary or was Stroustrup careless?</p> <p>Edit: The <a href="http://gcc.gnu.org/onlinedocs/libstdc++/manual/strings.html" rel="nofollow noreferrer">libstdc++ manual</a> mentions that the input character must be from the <a href="http://pic.dhe.ibm.com/infocenter/zos/v1r12/index.jsp?topic=/com.ibm.zos.r12.cbclx01/charset.htm" rel="nofollow noreferrer">basic source character set</a>, but does not cast. I guess this is covered by @Keith Thompson's reply, they all have a positive representation as <code>signed char</code> and <code>unsigned char</code>?</p>
21,805,970
5
3
null
2014-02-16 00:30:40.47 UTC
12
2021-12-22 22:37:46.033 UTC
2021-03-07 11:26:30.153 UTC
null
3,002,139
null
3,002,139
null
1
35
c++|language-lawyer|undefined-behavior|toupper|tolower
4,457
<p>Yes, the argument to <code>toupper</code> needs to be converted to <code>unsigned char</code> to avoid the risk of undefined behavior.</p> <p>The types <code>char</code>, <code>signed char</code>, and <code>unsigned char</code> are three distinct types. <code>char</code> has the same range and representation as <em>either</em> <code>signed char</code> <em>or</em> <code>unsigned char</code>. (Plain <code>char</code> is very commonly signed and able to represent values in the range -128..+127.)</p> <p>The <code>toupper</code> function takes an <code>int</code> argument and returns an <code>int</code> result. Quoting the C standard, section 7.4 paragraph 1:</p> <blockquote> <p>In all cases the argument is an <strong><code>int</code></strong>, the value of which shall be representable as an <strong><code>unsigned char</code></strong> or shall equal the value of the macro <strong><code>EOF</code></strong> . If the argument has any other value, the behavior is undefined.</p> </blockquote> <p>(C++ incorporates most of the C standard library, and defers its definition to the C standard.)</p> <p>The <code>[]</code> indexing operator on <code>std::string</code> returns a reference to <code>char</code>. If plain <code>char</code> is a signed type, and if the value of <code>name[0]</code> happens to be negative, then the expression</p> <pre><code>toupper(name[0]) </code></pre> <p>has undefined behavior.</p> <p>The language guarantees that, even if plain <code>char</code> is signed, all members of the basic character set have non-negative values, so given the initialization</p> <pre><code>string name = &quot;Niels Stroustrup&quot;; </code></pre> <p>the program doesn't risk undefined behavior. But yes, in general a <code>char</code> value passed to <code>toupper</code> (or to any of the functions declared in <code>&lt;cctype&gt;</code> / <code>&lt;ctype.h&gt;</code>) needs to be converted to <code>unsigned char</code>, so that the implicit conversion to <code>int</code> won't yield a negative value and cause undefined behavior.</p> <p>The <code>&lt;ctype.h&gt;</code> functions are commonly implemented using a lookup table. Something like:</p> <pre><code>// assume plain char is signed char c = -2; c = toupper(c); // undefined behavior </code></pre> <p>may index outside the bounds of that table.</p> <p>Note that converting to <code>unsigned</code>:</p> <pre><code>char c = -2; c = toupper((unsigned)c); // undefined behavior </code></pre> <p>doesn't avoid the problem. If <code>int</code> is 32 bits, converting the <code>char</code> value <code>-2</code> to <code>unsigned</code> yields <code>4294967294</code>. This is then implicitly converted to <code>int</code> (the parameter type), which <em>probably</em> yields <code>-2</code>.</p> <p><code>toupper</code> <em>can</em> be implemented so it behaves sensibly for negative values (accepting all values from <code>CHAR_MIN</code> to <code>UCHAR_MAX</code>), but it's not required to do so. Furthermore, the functions in <code>&lt;ctype.h&gt;</code> are required to accept an argument with the value <code>EOF</code>, which is typically <code>-1</code>.</p> <p>The C++ standard makes adjustments to some C standard library functions. For example, <code>strchr</code> and several other functions are replaced by overloaded versions that enforce <code>const</code> correctness. There are no such adjustments for the functions declared in <code>&lt;cctype&gt;</code>.</p>
21,505,894
Spring MVC + Hibernate: id to load is required for loading
<p>This is such a noob question, I know and I apologize. I'm trying to edit existing record with Hibernates session.merge() method and I get the following error:</p> <pre><code>java.lang.IllegalArgumentException: id to load is required for loading </code></pre> <p>This is my object:</p> <pre><code>@Id @GeneratedValue(strategy = IDENTITY) @Column(name = "TITLE_ID", unique = true, nullable = false) private Integer titleId; @NotNull @NotBlank @Column(name = "TITLE_DESCRIPTION", nullable = false, length = 10) private String titleDescription; // default constructor, getters &amp; setters </code></pre> <p>This is service layer method:</p> <pre><code> public void edit(Title title) { logger.debug("Editing existing title"); // Retrieve session from Hibernate Session session = sessionFactory.getCurrentSession(); // Retrieve existing title via id Title existingTitle = (Title) session.get(Title.class, title.getTitleId()); // Assign updated values to this title existingTitle.setTitleDescription(title.getTitleDescription()); // Save updates session.merge(existingTitle); } </code></pre> <p>This is controller POST method:</p> <pre><code>@RequestMapping(value="/edit", method = RequestMethod.POST) public String postEditTitle(@Valid @ModelAttribute("titleAttribute") Title title, BindingResult result) { logger.debug("Received request to edit title"); if (result.hasErrors()) { return "editTitle"; } else { titleService.edit(title); return "redirect:/essays/main/title"; } } </code></pre> <p>What am I missing? Any help will be much appreciated.</p>
21,506,213
1
3
null
2014-02-02 01:19:07.59 UTC
1
2016-09-20 18:21:39.997 UTC
2014-02-02 01:42:20.867 UTC
null
3,083,473
null
3,083,473
null
1
20
hibernate|spring-mvc
51,694
<p>The problem isn't with Hibernate. <code>title.getTitleId()</code> is null when you pass it to <code>session.get()</code>, and that's a problem with your web service/application.</p> <ol> <li>Your GET might not be providing the id in the model object</li> <li>Your client code (form, client app, ajax call, whatever it is) might not be retaining the ID between the GET and POST</li> <li>Your POST might not be providing the id in the model object.</li> </ol> <p>You can provide more details here, or ask a new question, if you're having difficulties retaining attributes across the web, rest or WS session.</p>
59,162,596
I do not understand why this compiles
<p>I'm certainly missing something, but I do not understand why this compiles (with both g++ &amp; clang++):</p> <pre><code>struct A { }; struct B { }; int main() { A a(B); } </code></pre> <p>First of all, <code>B</code> is a type... not a value. How should I interpret this code?</p>
59,162,617
3
8
null
2019-12-03 17:40:42.42 UTC
7
2019-12-07 22:08:46.597 UTC
2019-12-07 22:08:46.597 UTC
null
2,001,017
null
2,001,017
null
1
81
c++|syntax|declaration|most-vexing-parse
7,166
<p>It's interpreted as the declaration of a function named <code>a</code>, which takes one argument of type <code>B</code> and returns <code>A</code>.</p>
1,688,657
How do I extract Google Analytics campaign data from their cookie with Javascript?
<p>I'd like to be able to pull out the data stored in the Google Analytics tracking cookie with all the campaign tracking information using Javascript. It needs to work with the newer version of GA using ga.js, not urchin.js. I found a method that works with urchin.js but we don't use that for our tracking. Does anybody know how to extract the <code>Campaign</code>, <code>Source</code>, <code>Medium</code>, <code>Content</code> and <code>Term</code> from the cookie Google uses? </p>
1,689,194
4
1
null
2009-11-06 16:22:01.967 UTC
9
2015-10-05 08:20:39.633 UTC
2015-10-05 08:20:39.633 UTC
null
5,079,510
null
186,116
null
1
14
javascript|cookies|google-analytics|tracking
14,085
<p>I ended up figuring this out on my own. I just dug into what the cookie had stored and extracted the information. Here's what I came up with:</p> <pre><code>var ga_source = ''; var ga_campaign = ''; var ga_medium = ''; var ga_term = ''; var ga_content = ''; var gc = ''; var c_name = "__utmz"; if (document.cookie.length&gt;0){ c_start=document.cookie.indexOf(c_name + "="); if (c_start!=-1){ c_start=c_start + c_name.length+1; c_end=document.cookie.indexOf(";",c_start); if (c_end==-1) c_end=document.cookie.length; gc = unescape(document.cookie.substring(c_start,c_end)); } } if(gc != ""){ var z = gc.split('.'); if(z.length &gt;= 4){ var y = z[4].split('|'); for(i=0; i&lt;y.length; i++){ if(y[i].indexOf('utmcsr=') &gt;= 0) ga_source = y[i].substring(y[i].indexOf('=')+1); if(y[i].indexOf('utmccn=') &gt;= 0) ga_campaign = y[i].substring(y[i].indexOf('=')+1); if(y[i].indexOf('utmcmd=') &gt;= 0) ga_medium = y[i].substring(y[i].indexOf('=')+1); if(y[i].indexOf('utmctr=') &gt;= 0) ga_term = y[i].substring(y[i].indexOf('=')+1); if(y[i].indexOf('utmcct=') &gt;= 0) ga_content = y[i].substring(y[i].indexOf('=')+1); } } } </code></pre> <p>I'm sure it could be more streamlined but I was just happy to get this far with it. Once you have these variables you can do whatever you need with them.</p>
1,347,728
Using an MVC HtmlHelper from a WebForm
<p>I'm in the process of adding some UI functionality to a hybrid WebForms/MVC site. In this case, I'm adding some AJAX UI features to a WebForms page (via jQuery), and the data is coming from an MVC JsonResult. Everything is working 100%, with one exception:</p> <p>I would like to implement the XSRF protection of AntiForgeryToken. I have used it in combination with the ValidateAntiForgeryToken attribute on my pure MVC applications, but would like to know how to implement the Html.AntiForgeryToken() method in WebForms. <a href="https://stackoverflow.com/questions/1274319/access-htmlhelpers-from-webform-when-using-asp-net-mvc">Here's an example using a UrlHelper</a>.</p> <p>I'm having some trouble getting ViewContext / RequestContext "mocked" up correctly. How should I go about using HtmlHelpers within a WebForms page?</p> <p><strong>Edit</strong>: I'm looking to retrieve the AntiForgeryToken from my WebForms page, not from the MVC JsonResult.</p>
2,553,583
4
1
null
2009-08-28 15:25:07.163 UTC
11
2013-05-01 18:41:05.157 UTC
2017-05-23 12:15:07.893 UTC
null
-1
null
56,018
null
1
19
asp.net-mvc|webforms|html-helper
10,375
<p>The key method is in the MVC source code: <code>GetAntiForgeryTokenAndSetCookie</code></p> <p>This creates an instance of an internal sealed class called <code>AntiForgeryData</code>.</p> <p>The instance is serialised into a cookie "__RequestVerificationToken_" + a base 64 encoded version of the application path.</p> <p>The same instance of <code>AntiForgeryData</code> is serialised into a hidden input.</p> <p>The unique part of the <code>AntiForgeryData</code> is got with an <code>RNGCryptoServiceProvider.GetBytes()</code></p> <p>All of this could be spoofed in a WebForms page, the only messy bit is the serialisation of the hidden sealed class. Unfortunately the key method (<code>GetAntiForgeryTokenAndSetCookie</code>) relies on <code>ViewContext.HttpContext.Request</code> to get at the cookies, while the WebForm needs to use <code>HttpContext.Current.Request</code> instead.</p> <hr> <p><strong>Update</strong></p> <p>Not much testing and a lot of code, but I think I've cracked this with a little reflection. Where I've used reflection I've left the equivalent line commented out above:</p> <pre><code>using System; using System.Reflection; using System.Web; using System.Web.Mvc; /// &lt;summary&gt;Utility to provide MVC anti forgery tokens in WebForms pages&lt;/summary&gt; public class WebFormAntiForgery { /// &lt;summary&gt;Create an anti forgery token in a WebForms page&lt;/summary&gt; /// &lt;returns&gt;The HTML input and sets the cookie&lt;/returns&gt; public static string AntiForgeryToken() { string formValue = GetAntiForgeryTokenAndSetCookie(); // string fieldName = AntiForgeryData.GetAntiForgeryTokenName(null); var mvcAssembly = typeof(HtmlHelper).Assembly; var afdType = mvcAssembly.GetType("System.Web.Mvc.AntiForgeryData"); string fieldName = Convert.ToString(afdType.InvokeMember( "GetAntiForgeryTokenName", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, new object[] { null })); TagBuilder builder = new TagBuilder("input"); builder.Attributes["type"] = "hidden"; builder.Attributes["name"] = fieldName; builder.Attributes["value"] = formValue; return builder.ToString(TagRenderMode.SelfClosing); } static string GetAntiForgeryTokenAndSetCookie() { var mvcAssembly = typeof(HtmlHelper).Assembly; var afdType = mvcAssembly.GetType("System.Web.Mvc.AntiForgeryData"); // new AntiForgeryDataSerializer(); var serializerType = mvcAssembly.GetType("System.Web.Mvc.AntiForgeryDataSerializer"); var serializerCtor = serializerType.GetConstructor(new Type[0]); object serializer = serializerCtor.Invoke(new object[0]); // string cookieName = AntiForgeryData.GetAntiForgeryTokenName(HttpContext.Current.Request.ApplicationPath); string cookieName = Convert.ToString(afdType.InvokeMember( "GetAntiForgeryTokenName", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, new object[] { HttpContext.Current.Request.ApplicationPath })); // AntiForgeryData cookieToken; object cookieToken; HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName]; if (cookie != null) { // cookieToken = Serializer.Deserialize(cookie.Value); cookieToken = serializerType.InvokeMember("Deserialize", BindingFlags.InvokeMethod, null, serializer, new object[] { cookie.Value }); } else { // cookieToken = AntiForgeryData.NewToken(); cookieToken = afdType.InvokeMember( "NewToken", BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, new object[0]); // string cookieValue = Serializer.Serialize(cookieToken); string cookieValue = Convert.ToString(serializerType.InvokeMember("Serialize", BindingFlags.InvokeMethod, null, serializer, new object[] { cookieToken })); var newCookie = new HttpCookie(cookieName, cookieValue) { HttpOnly = true }; HttpContext.Current.Response.Cookies.Set(newCookie); } // AntiForgeryData formToken = new AntiForgeryData(cookieToken) // { // CreationDate = DateTime.Now, // Salt = salt // }; var ctor = afdType.GetConstructor(new Type[] { afdType }); object formToken = ctor.Invoke(new object[] { cookieToken }); afdType.InvokeMember("CreationDate", BindingFlags.SetProperty, null, formToken, new object[] { DateTime.Now }); afdType.InvokeMember("Salt", BindingFlags.SetProperty, null, formToken, new object[] { null }); // string formValue = Serializer.Serialize(formToken); string formValue = Convert.ToString(serializerType.InvokeMember("Serialize", BindingFlags.InvokeMethod, null, serializer, new object[] { formToken })); return formValue; } } </code></pre> <p>Usage is then similar to MVC:</p> <pre><code>WebFormAntiForgery.AntiForgeryToken() </code></pre> <p>It creates the same cookie and the same HTML as the MVC methods.</p> <p>I haven't bothered with the salt and domain methods, but they would be fairly easy to add in.</p>
1,438,535
How to run a command at compile time within Makefile generated by CMake?
<p>I would like to pass some options to a compiler. The option would have to be calculated at compile time - everytime when 'make' is invoked, not when 'cmake', so execute_process command does not cut it. (does it?)</p> <p>For instance passing a date to a g++ compiler like that:</p> <pre><code>g++ prog.cpp -o prog -DDATETIME="17:09:2009,14:25" </code></pre> <p>But with DATETIME calculated at compile time.</p> <p>Any idea how to do it in CMake?</p> <p><strong>Bounty edit:</strong></p> <p>A least hackish solution will be accepted.</p> <p>Please note that I want to be able to exectue an arbitrary command at compile time, not only 'date'.</p> <p><strong>Edit 2:</strong></p> <p>It have to work on Linux, Windows (VS), Mingw, Cygwin and OS X. You can't assume Ruby, Perl or Python as they are non standard on Windows. You can assume BOOST, but I guess it's no use.</p> <p>The goal is to force cmake to generate Makefile (in case of Linux) that when make is executed, will do the job. </p> <p>Creating custom *.h file is ok, but it has to be initiated by a Makefile (or equivalent on other OS) by make. The creation of *.h doesn't have to (and shouldn't have to) use cmake.</p>
1,468,695
4
0
null
2009-09-17 12:23:30.33 UTC
15
2014-07-29 21:38:45.11 UTC
2014-07-29 21:38:45.11 UTC
null
364,818
null
61,342
null
1
34
build-process|cmake|pre-compilation
40,215
<p>You're leaving out some information, such as which platforms you need to run this on and if there are any additional tools you can use. If you can use Ruby, Perl, of Python, things become much simpler. I'll assume that you want to run on both Unix and Windows pqlatform and that there are no extra tools available.</p> <p>If you want the output from the command in a preprocessor symbol, the easiest way is to generate a header file instead of fiddling around with command line parameters. Remember that CMake has a script-mode (-P) where it only processes script commands in the file, so you can do something like this:</p> <p>CMakeLists.txt:</p> <pre><code>project(foo) cmake_minimum_required(VERSION 2.6) add_executable(foo main.c custom.h) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_custom_command(OUTPUT custom.h COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_SOURCE_DIR}/custom.cmake) </code></pre> <p>The file "custom.h" is generated at compile time by the command "cmake -P custom.cmake". custom.cmake looks like this:</p> <pre><code>execute_process(COMMAND uname -a OUTPUT_VARIABLE _output OUTPUT_STRIP_TRAILING_WHITESPACE) file(WRITE custom.h "#define COMPILE_TIME_VALUE \"${_output}\"") </code></pre> <p>It executes the command (in this case "uname -a", you'll replace it with whatever command you wish), and puts the output in the variable _output, which it then writes to custom.h. Note that this will only work if the command outputs a single line. (If you need multiline output, you'll have to write a more complex custom.cmake, depending on how you want the multiline data into your program.)</p> <p>The main program looks like this:</p> <pre><code>#include &lt;stdio.h&gt; #include "custom.h" int main() { printf("COMPILE_TIME_VALUE: %s\n", COMPILE_TIME_VALUE); return 0; } </code></pre> <p>If you actually want to to calculate compiler options at compile time, things become much trickier. For Bourne-shell generators you can just insert the command inside backticks. If you get mad while figuring out quoting, move all the logic of your command inside a shell-script so you only need to put <code>mycommand.sh</code> in your add_definitions():</p> <pre><code>if(UNIX) add_definitions(`${CMAKE_CURRENT_SOURCE_DIR}/custom-options.sh`) endif() </code></pre> <p>For Windows batch file based generators things are much tricker, and I don't have a good solution. The problem is that the <code>PRE_BUILD</code> commands are not executed as part of the same batch file as the actual compiler invocation (study the BuildLog.htm for details), so my initial idea did not work (generating a custom.bat in a <code>PRE_BUILD</code> step and then do "call custom.bat" on it to get a variable set which can later be referenced in the compiler command line). If there is an equivalent of backticks in batch files, that would solve the problem.</p> <p>Hope this gives some ideas and starting points. </p> <p>(Now to the inevitable counter-question: what are you <strong>really</strong> trying to do?)</p> <p>EDIT: I'm not sure why you don't want to let CMake be used to generate the header-file. Using ${CMAKE_COMMAND} will expand to the CMake used to generate the Makefiles/.vcproj-files, and since CMake doesn't really support portable Makefiles/.vcproj-files you will need to rerun CMake on the target machines.</p> <p>CMake also has a bunch of utility commands (Run "cmake -E" for a list) for this explicit reason. You can for example do</p> <pre><code>add_custom_command(OUTPUT custom.h COMMAND ${CMAKE_COMMAND} -E copy file1.h file2.h) </code></pre> <p>to copy file1.h to file2.h.</p> <p>Anyway, if you don't want to generate the header-files using CMake, you will either need to invoke separate .bat/.sh scripts to generate the header file, or do it using echo:</p> <pre><code>add_custom_command(OUTPUT custom.h COMMAND echo #define SOMETHING 1 &gt; custom.h) </code></pre> <p>Adjust quoting as needed.</p>
26,277,151
Force composer to require PHP Version between Version X and Version Y
<p>we have a mix of different PHP versions running on your servers (max 5.3.5) and development machines (max 5.5.9).</p> <p>Now we ran into the problem that we did a "composer update" to get the latest Version of some external Bundles. Since your composer.json looks like</p> <pre><code>"require": { "php": "&gt;=5.3.3", ..... }, </code></pre> <p>we get some Bundles that required PHP 5.5. No problem on our dev machines, but on the server :(</p> <p>Is there any possibility to tell composer to require a PHP version between 5.3.3 and 5.3.5? Or a max available Version?</p> <p>I tried</p> <pre><code>"require": { "php": "&gt;=5.3.3, &lt;=5.3.5", ..... }, </code></pre> <p>and</p> <pre><code>"require": { "php": "&lt;=5.3.5", ..... }, </code></pre> <p>but both didn't work out. I get a "The requested package php could not be found in any version, there may be a typo in the package name." Error.</p> <p>Any Ideas? Thanks in advance</p>
26,287,000
6
1
null
2014-10-09 11:23:08.05 UTC
14
2021-02-03 11:13:44.95 UTC
null
null
null
null
1,121,500
null
1
75
php|composer-php
110,920
<p>I find it questionable to say the least that you are developing with the newest PHP available and are running production with a very outdated version. There will be plenty of possible problems arising from this, not only because of security patches that you would be missing, but more importantly because of PHP bug fixes that got introduced mostly in versions 5.3.9 and 5.3.23 that changes PHP behavior in some details pretty fundamentally. Not talking about the risk of accidentally using features of 5.4 or 5.5.</p> <p>And there really is no way to make Composer deal with this situation. The PHP version that is used when running <code>composer update</code> determines the resolution of dependencies, being influenced by PHP version and installed PHP extensions.</p> <p>You cannot define that a package should only be used for PHP versions between 5.3.3 and 5.3.5 if the PHP you are using for the update is not matching this version requirement. Because the used PHP version exceeds the upper version constraint, such a package is not eligible for fulfilling the version requirement, and Composer reports that no package has been found (not telling that it has seen the packages, but they had to be ignored because of the version constraint).</p> <p>There are probably three obvious ways out:</p> <ol> <li><p>Downgrade your development environment to the production version you are really using. If more than one is used: The oldest one. That way any requirements for PHP versions will be matched. Run <code>composer update</code> then, and you are done.</p></li> <li><p>Upgrade your production environment. Needs no further explanation, but I have to mention that not only are you missing a lot of very nice PHP features, you are also missing a substantial performance increase, because PHP 5.5 is really that much faster than 5.3.</p></li> <li><p>Add a "platform.php" configuration to either the global or project's composer.json. This will tell Composer to override the PHP version running Composer itself, and instead calculate the dependencies with that different PHP version. <code>composer config -g platform.php 5.3.5</code> for global setting (will affect all further Composer runs), without <code>-g</code> for local setting (will only affect Composer operations in that project, in case you develop on more than one project with different production versions of PHP).</p></li> </ol>
26,377,305
Item with app:showAsAction not showing
<p>I can't understand why wrong and incompatible (AndroidStudio tells me "Should use app:showAsAction with the appcompat library) code</p> <pre><code>&lt;menu xmlns:android="http://schemas.android.com/apk/res/android" &gt; &lt;item android:id="@+id/action_search" android:title="@string/action_search" android:icon="@drawable/search" android:showAsAction="always" /&gt; &lt;/menu&gt; </code></pre> <p>works perfect, but proper and compatible version like</p> <pre><code>&lt;menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" &gt; &lt;item android:id="@+id/action_search" android:title="@string/action_search" android:icon="@drawable/search" app:showAsAction="always" /&gt; &lt;/menu&gt; </code></pre> <p>not showing my icon at all.</p> <p>I'm testing on Samsung GT P5210 (android v. 4.4.2) and Nexus 7 (4.4.4)</p>
26,378,366
3
2
null
2014-10-15 07:55:30.017 UTC
11
2019-07-24 11:44:24.837 UTC
null
null
null
null
2,450,219
null
1
33
android|android-menu
55,596
<p>Things you should always check when you want to use action bar are</p> <p>1) Extend <code>ActionBarActivity</code> instead of <code>Activity</code></p> <p><code>public class MainMenu extends ActionBarActivity{</code></p> <p>2) Have the <strong>right style</strong> selected as defined at manifest</p> <p><strong>Manifest</strong></p> <pre><code>&lt;application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" &gt; </code></pre> <p><strong>Style</strong></p> <pre><code> &lt;style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"&gt; &lt;/style&gt; </code></pre> <p>3) Select the <strong>right title</strong> for <code>showAsAction</code></p> <pre><code> &lt;menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:**yourapp**="http://schemas.android.com/apk/res-auto" &gt; &lt;item android:id="@+id/action_search" android:icon="@drawable/ic_action_search" android:title="@string/action_search" **yourapp**:showAsAction="ifRoom" /&gt; ... &lt;/menu&gt; </code></pre> <p>This is what most people get wrong</p> <p>4) Define your <code>Menu</code> in <code>Activity</code></p> <pre><code>@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu items for use in the action bar MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_activity_actions, menu); return super.onCreateOptionsMenu(menu); } </code></pre> <p>If you do all the following your action bar should work.</p> <p>Then you should add the <code>onClickListener</code> for every position...</p>
7,425,241
How to return NULL object in C++
<p>I know that this might be a duplicate of: <a href="https://stackoverflow.com/questions/2639255/c-return-a-null-object-if-search-result-not-found">Return a &quot;NULL&quot; object if search result not found</a></p> <p>BUT, there's something different going on with my code because the asterisk doesn't solve my problem, which is this:</p> <pre><code>Normal Sphere::hit(Ray ray) { //stuff is done here if(something happens) { return NULL; } //other stuff return Normal(something, somethingElse); } </code></pre> <p>But I get an error referencing the <code>return NULL</code> line: <code>conversion from ‘int’ to non-scalar type ‘Normal’ requested</code></p> <p>And another error and warning that referencing the last return line: <code>warning: taking address of temporary</code> and <code>conversion from ‘Normal*’ to non-scalar type 'Normal' requested</code></p> <p>I understand why I am getting this warning, but I don't know how to fix it. How do I return a <code>Normal</code> object in the last line that persists after the function ends and how do I return a <code>NULL</code> object that first time? (If there's a term for these types of returns, please let me know so I can also read up on it more.)</p> <p>To clarify a commenter's question, I've tried these things:</p> <p>I tried doing this: <code>Normal *Sphere::hit(Ray ray)</code> in the cpp file and <code>Normal *hit( Ray ray );</code> in the header file and I get this error: <code>error: prototype for ‘Normal* Sphere::hit(Ray)’ does not match any in class 'Sphere'</code></p> <p>I also tried this: <code>Normal Sphere::*hit(Ray ray)</code> in the cpp file and <code>Normal *hit( Ray ray);</code> in the header file and I get this error for the second return statement: <code>cannot convert 'Normal*' to 'Normal Sphere::*' in return</code></p> <p><strong>Further clarification:</strong> I'm not asking about how pointers work. (That wasn't the main question.) I'm wondering about syntax regarding pointers in C++. So, given the function I've specified above, I've gleaned that I should specify a return a pointer because C++ doesn't have null objects. Got it. BUT, the problem then becomes: what should the function prototype look like? In the cpp file, I have what Bala suggested (which is what I had originally but changed it because of the following error):</p> <pre><code>Normal* Sphere::hit(Ray ray) { //stuff is done here if(something happens) { return NULL; } //other stuff return new Normal(something, somethingElse); } </code></pre> <p>In the header file, I have <code>Normal *hit(Ray ray)</code>, but I still get this message: <code>prototype for 'Normal* Sphere::hit(Ray)' does not match any in class 'Sphere'</code> At this point, it is unclear to me why it can't find that function prototype. Here is the header file:</p> <pre><code>class Sphere { public: Sphere(); Vector3 center; float radius; Normal* hit(Ray ray); }; </code></pre> <p>Can anyone see why it's complaining that there doesn't exist a matching prototype for <code>hit</code> in the <code>Sphere</code> class? (I might move this to a separate question...)</p>
7,425,255
7
3
null
2011-09-15 02:30:59.913 UTC
4
2019-08-25 00:53:10.983 UTC
2017-05-23 12:25:33.427 UTC
null
-1
null
945,805
null
1
26
c++
90,132
<p>I think you need something like</p> <pre><code>Normal* Sphere::hit(Ray ray) { //stuff is done here if(something happens) { return NULL; } //other stuff return new Normal(something, somethingElse); } </code></pre> <p>to be able to return NULL;</p>
7,463,414
What’s the best way to load a JSONObject from a json text file?
<p>What would be the easiest way to load a file containing JSON into a JSONObject.</p> <p>At the moment I am using json-lib.</p> <p>This is what I have, but it throws an exception:</p> <pre><code>XMLSerializer xml = new XMLSerializer(); JSON json = xml.readFromFile("samples/sample7.json”); //line 507 System.out.println(json.toString(2)); </code></pre> <p>The output is:</p> <pre><code>Exception in thread "main" java.lang.NullPointerException at java.io.Reader.&lt;init&gt;(Reader.java:61) at java.io.InputStreamReader.&lt;init&gt;(InputStreamReader.java:55) at net.sf.json.xml.XMLSerializer.readFromStream(XMLSerializer.java:386) at net.sf.json.xml.XMLSerializer.readFromFile(XMLSerializer.java:370) at corebus.test.deprecated.TestMain.main(TestMain.java:507) </code></pre>
7,463,501
8
3
null
2011-09-18 18:20:14.937 UTC
14
2022-02-08 08:49:38.2 UTC
null
null
null
null
587,196
null
1
40
java|json
203,225
<p>try this:</p> <pre><code>import net.sf.json.JSONObject; import net.sf.json.JSONSerializer; import org.apache.commons.io.IOUtils; public class JsonParsing { public static void main(String[] args) throws Exception { InputStream is = JsonParsing.class.getResourceAsStream( "sample-json.txt"); String jsonTxt = IOUtils.toString( is ); JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt ); double coolness = json.getDouble( "coolness" ); int altitude = json.getInt( "altitude" ); JSONObject pilot = json.getJSONObject("pilot"); String firstName = pilot.getString("firstName"); String lastName = pilot.getString("lastName"); System.out.println( "Coolness: " + coolness ); System.out.println( "Altitude: " + altitude ); System.out.println( "Pilot: " + lastName ); } } </code></pre> <p>and this is your sample-json.txt , should be in json format</p> <pre><code>{ 'foo':'bar', 'coolness':2.0, 'altitude':39000, 'pilot': { 'firstName':'Buzz', 'lastName':'Aldrin' }, 'mission':'apollo 11' } </code></pre>
7,261,916
Enter., Backspace and the navigation keys not responding in Visual Studio 2010 w/ Powertools/Resharper
<p>I have this very annoying problem that in Razor Views the Enter, Backspace and the navigation keys frequently do not respond. I have to restart VS to get it back to normal again. Am I missing something?</p>
7,266,520
10
4
null
2011-08-31 18:43:56.86 UTC
21
2021-11-02 17:22:28.92 UTC
null
null
null
Dabblernl
108,493
null
1
85
visual-studio-2010|resharper
47,557
<p>I had the same problem and solved it by saving the razor file (Ctrl + S). Once I did this I could use the Enter, Backspace and Navigation keys again. </p> <p>I believe that Alt + Enter may also work.</p> <p>I don't often get into this state and the above solution does not solve the underlying problem. I believe that it may have something to do with ReSharper but have not figured out if this assumption is true or not.</p> <p>There are a number of pages that discuss this type of problem: <a href="https://connect.microsoft.com/VisualStudio/feedback/details/616775/certain-keyboard-keys-stop-working-when-using-vs2010" rel="noreferrer" title="Link 1">Link 1</a> <a href="https://connect.microsoft.com/VisualStudio/feedback/details/521892/backspace-and-arrow-key-issues" rel="noreferrer" title="Link 2">Link 2</a> <a href="http://connect.microsoft.com/VisualStudio/feedback/details/567055" rel="noreferrer" title="Link 3">Link 3</a></p>
7,036,324
What is the regex for "Any positive integer, excluding 0"
<p>How can <code>^\d+$</code> be improved to disallow <code>0</code>?</p> <p>EDIT (Make it more concrete): </p> <p><strong>Examples to allow:</strong><br> 1<br> 30<br> 111<br> <strong>Examples to disallow:</strong><br> 0<br> 00<br> -22</p> <p>It doesn't matter if positive numbers with a leading zero are allowed or not (e.g. <code>022</code>).</p> <p>This is for Java JDK Regex implementation.</p>
7,036,361
13
3
null
2011-08-12 06:22:04.223 UTC
16
2019-07-30 10:45:13.337 UTC
2011-08-12 06:43:40.663 UTC
null
223,686
null
223,686
null
1
109
java|regex
184,876
<p>Try this:</p> <pre><code>^[1-9]\d*$ </code></pre> <p>...and some padding to exceed 30 character SO answer limit :-).</p> <p><a href="https://regex101.com/r/BlHg0v/1" rel="noreferrer">Here is Demo </a></p>
14,321,930
C ++ error: a expected initializer before [function name]
<p>I am refreshing my self on C++ (have not did it since school) and I wrote a simple program just to mess around. My problem is when I compile the program it chokes stating "error: expected initializer before 'stringThing'" is there a reason why this is doing this? I know this may be a noob question so I checked stackoverflow and could not find any relevant questions that gave me a answer.</p> <p>*I am using GNU GCC compiler </p> <p>Code:</p> <pre><code>#include &lt;iostream&gt; using namespace std; void string stringThing (string shiftdir, string &amp;teststring) { if (shiftdir == "right") { teststring = teststring &gt;&gt; " " &gt;&gt; "Bit Shifted right"; } else { teststring = teststring &lt;&lt; " " &lt;&lt; "Bit Shifted left"; } } int main() { string test; cout &lt;&lt; stringThing("right", "I have done a ") &lt;&lt; endl; return 0; } </code></pre>
14,321,987
2
2
null
2013-01-14 15:57:37.983 UTC
1
2013-01-14 19:14:52.107 UTC
null
null
null
null
1,086,571
null
1
8
c++|gcc|compiler-errors
68,159
<p>The return type for <code>stringThing</code> must be either <code>void</code> <em>or</em> <code>string</code>, not both. You also must include <code>&lt;string&gt;</code>, if you want to use string.</p> <p>Since you want to output the return value of <code>stringThing()</code> in <code>main</code>, I guess it should be</p> <pre><code>std::string stringThing (std::string shiftdir, const std::string &amp;teststring) </code></pre> <p>But then, you must also return a string from your function</p> <pre><code>if (shiftdir == "right") return teststring + " " + "Bit Shifted right"; else return teststring + " " + "Bit Shifted left"; </code></pre> <p>for example.</p> <p>Your parameter <code>std::string &amp;teststring</code> won't work with your <code>const char*</code> argument. So either declare it as a copy by value <code>string</code> only, or better <code>const string&amp;</code>.</p>
14,338,817
Is Shadow DOM able to secure elements?
<h2>Goal: an encapculated widget</h2> <p>Suppose I'm the developer of a widget showing a list of friends, such as:</p> <blockquote> <p><em>Your friends Michael, Anna and Shirley love this webpage!</em></p> </blockquote> <h2>First approach: script that creates <code>span</code></h2> <p>Naively, I create a script which places this information in a <code>span</code> on the website. However, the owners of ExampleSite can now access the names of your friends by simple DOM operations! <br> That's a big <strong>privacy / security</strong> issue.</p> <h2>Second approach: an <code>iframe</code></h2> <p>I don't want ExampleSite to have access to their friends' names. So instead, I let website owners add the widget with an <code>iframe</code>:</p> <pre><code>&lt;iframe src=&quot;http://fakebook.com/friends?page=http%3A%2F%2Fexample.org%2F&quot;&gt;&lt;/iframe&gt; </code></pre> <p>This works, because the owners of ExampleSite cannot scrape the contents of the <code>iframe</code>. However, this whole <code>iframe</code> thing is rather ugly, because it <strong>does not integrate</strong> into the styling of the website, while a <code>span</code> does.</p> <h2>Desired approach: Shadow DOM</h2> <p>When reading about <a href="http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/" rel="nofollow noreferrer">Shadow Dom</a> yesterday, I wondered whether that could be a solution to both issues. It would allow me to have a script that creates a <code>span</code> the original website cannot access:</p> <pre><code>var host = document.querySelector('#friends'); var root = host.webkitCreateShadowRoot(); root.textContent = 'Your friends Michael, Anna and Shirley love this webpage!'; </code></pre> <br> However, **does a Shadow DOM hide its contents from the surrounding page?** <br> The assumption here is that nobody except my script can access `root`, but is that correct? <p>The <a href="http://www.w3.org/TR/shadow-dom/" rel="nofollow noreferrer">Shadow DOM spec</a> after all says that it offers <em>functional encapsulation</em>, but I actually want <em>trust encapsulation</em>. And while the Component Model Use Cases actually list <a href="http://www.w3.org/2008/webapps/wiki/Component_Model_Use_Cases#Like.2F.2B1_Button" rel="nofollow noreferrer">this use case</a>, I'm not sure whether Shadow DOM realizes the necessary <em>confinement</em> property.</p>
14,346,490
1
7
null
2013-01-15 13:28:10.873 UTC
9
2022-01-18 13:50:06.563 UTC
2022-01-18 13:50:06.563 UTC
null
476,820
null
476,820
null
1
17
security|dom|widget|web-component|shadow-dom
2,849
<p>It does not, but it's in the works: <a href="https://www.w3.org/Bugs/Public/show_bug.cgi?id=20144" rel="nofollow noreferrer">https://www.w3.org/Bugs/Public/show_bug.cgi?id=20144</a></p> <p>The encapsulation of trust will involve creating a new scripting context for each shadow tree, which is overkill for most scenarios. However, as the bug says, we'll add a flag (details TBD) that would allow this.</p>
14,176,028
Why does LogicalCallContext not work with async?
<p>In this <a href="https://stackoverflow.com/questions/9781321/how-to-manage-an-ndc-like-log4net-stack-with-async-await-methods-per-task-stac">question</a> the accepted answer by Stephen Cleary says that LogicalCallContext can't work correctly with async. He also posted about it in <a href="http://social.msdn.microsoft.com/Forums/en-US/async/thread/ea21ca57-5340-439c-8ee9-f0185b5787a1" rel="noreferrer">this</a> MSDN thread.</p> <p>LogicalCallContext keeps a Hashtable storing the data sent to CallContext.LogicalGet/SetData. And it only does a shallow copy of this Hashtable. So if you store a mutable object in it, different tasks/threads will see each other's changes. This is why Stephen Cleary's example NDC program (posted on that MSDN thread) doesn't work correctly.</p> <p>But AFAICS, if you only store immutable data in the Hashtable (perhaps by using <a href="http://blogs.msdn.com/b/bclteam/archive/2012/12/18/preview-of-immutable-collections-released-on-nuget.aspx" rel="noreferrer">immutable collections</a>), that should work, and let us implement an NDC.</p> <p>However, Stephen Cleary also said in that accepted answer:</p> <blockquote> <p>CallContext can't be used for this. Microsoft has specifically <a href="https://connect.microsoft.com/VisualStudio/feedback/details/276325/provide-better-context-support-to-async-operations" rel="noreferrer">recommended</a> against using CallContext for anything except remoting. More to the point, the logical CallContext doesn't understand how async methods return early and resume later.</p> </blockquote> <p>Unfortunately, that link to the Microsoft recommendation is down (page not found). So my question is, why is this not recommended? Why can't I use LogicalCallContext in this way? What does it mean to say it doesn't understand async methods? From the caller's POV they are just methods returning Tasks, no?</p> <p>ETA: see also <a href="https://stackoverflow.com/questions/13010563/using-threadstatic-variables-with-async-await">this other question</a>. There, an answer by Stephen Cleary says:</p> <blockquote> <p>you could use CallContext.LogicalSetData and CallContext.LogicalGetData, but I recommend you don't because they don't support any kind of "cloning" when you use simple parallelism</p> </blockquote> <p>That seems to support my case. So I <em>should</em> be able to build an NDC, which is in fact what I need, just not for log4net.</p> <p>I wrote some sample code and it seems to work, but mere testing doesn't always catch concurrency bugs. So since there are hints in those other posts that this may not work, I'm still asking: is this approach valid?</p> <p><strong>ETA:</strong> When I run Stephen's proposed repro from the answer below), I don't get the wrong answers he says I would, I get correct answers. Even where he said "LogicalCallContext value here is always "1"", I always get the correct value of 0. Is this perhaps due to a race condition? Anyway, I've still not reproduced any actual problem on my own computer. Here's the exact code I'm running; it prints only "true" here, where Stephen says it should print "false" at least some of the time.</p> <pre><code>private static string key2 = "key2"; private static int Storage2 { get { return (int) CallContext.LogicalGetData(key2); } set { CallContext.LogicalSetData(key2, value);} } private static async Task ParentAsync() { //Storage = new Stored(0); // Set LogicalCallContext value to "0". Storage2 = 0; Task childTaskA = ChildAAsync(); // LogicalCallContext value here is always "1". // -- No, I get 0 Console.WriteLine(Storage2 == 0); Task childTaskB = ChildBAsync(); // LogicalCallContext value here is always "2". // -- No, I get 0 Console.WriteLine(Storage2 == 0); await Task.WhenAll(childTaskA, childTaskB); // LogicalCallContext value here may be "0" or "1". // -- I always get 0 Console.WriteLine(Storage2 == 0); } private static async Task ChildAAsync() { var value = Storage2; // Save LogicalCallContext value (always "0"). Storage2 = 1; // Set LogicalCallContext value to "1". await Task.Delay(1000); // LogicalCallContext value here may be "1" or "2". Console.WriteLine(Storage2 == 1); Storage2 = value; // Restore original LogicalCallContext value (always "0"). } private static async Task ChildBAsync() { var value = Storage2; // Save LogicalCallContext value (always "1"). Storage2 = 2; // Set LogicalCallContext value to "2". await Task.Delay(1000); // LogicalCallContext value here may be "0" or "2". Console.WriteLine(Storage2 == 2); Storage2 = value; // Restore original LogicalCallContext value (always "1"). } public static void Main(string[] args) { try { ParentAsync().Wait(); } catch (Exception e) { Console.WriteLine(e); } </code></pre> <p>So my restated question is, what (if anything) is wrong with the above code?</p> <p>Furthermore, when I look at the code for CallContext.LogicalSetData, it calls Thread.CurrentThread.GetMutableExecutionContext() and modifies that. And GetMutableExecutionContext says:</p> <pre><code>if (!this.ExecutionContextBelongsToCurrentScope) this.m_ExecutionContext = this.m_ExecutionContext.CreateMutableCopy(); this.ExecutionContextBelongsToCurrentScope = true; </code></pre> <p>And CreateMutableCopy eventually does a shallow copy of the LogicalCallContext's Hashtable that holds the user-supplied data. </p> <p>So trying to understand why this code doesn't work for Stephen, is it because ExecutionContextBelongsToCurrentScope has the wrong value sometimes? If that's the case, maybe we can notice when it does - by seeing that either the current task ID or the current thread ID have changed - and manually store separate values in our immutable structure, keyed by thread + task ID. (There are performance issues with this approach, e.g. the retention of data for dead tasks, but apart from that would it work?)</p>
14,193,164
2
3
null
2013-01-05 20:22:30.543 UTC
11
2013-05-23 16:38:41.387 UTC
2017-05-23 12:25:13.667 UTC
null
-1
null
1,314,705
null
1
27
c#|.net|synchronization|task-parallel-library|async-await
13,076
<p>Stephen confirms that this works on .Net 4.5 and Win8/2012. Not tested on other platforms, and known not to work on at least some of them. So the answer is that Microsoft got their game together and fixed the underlying issue in at least the most recent version of .Net and the async compiler.</p> <p>So the answer is, it does work, just not on older .Net versions. (So the log4net project can't use it to provide a generic NDC.)</p>
14,184,223
Using require_once for up directory not working
<p>I am using require_once like this</p> <pre><code>require_once('../mycode.php') </code></pre> <p>I am developing a wordpress plugin. My plugin folder is yves-slider where I have a file called yves-slider.php and a folder called admin. Inside admin folder I have a file called admin.php. I want to require file yves-slider.php in my admin.php which is located up one level directory. When I try to use</p> <pre><code>require_once('../yves-slider.php') </code></pre> <p>it gives me the following error</p> <blockquote> <p>Warning: require_once(../yves-slider.php): failed to open stream: No such file or directory in C:\xampp\htdocs\wordpress\wp-content\plugins\yves-slider\yves-slider-admin\yves-slider-admin.php on line 4</p> <p>Fatal error: require_once(): Failed opening required '../yves-slider.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\wordpress\wp-content\plugins\yves-slider\yves-slider-admin\yves-slider-admin.php on line 4</p> </blockquote> <p>Am I doing wrong? I am using XAMPP 3.1, I guess that's the best way to do it.</p>
14,184,250
1
1
null
2013-01-06 16:35:50.277 UTC
6
2016-08-25 13:41:28.763 UTC
2013-01-06 16:41:54.02 UTC
null
879,063
null
1,896,108
null
1
38
php|directory|require-once
33,862
<p>You want to make that relative to the current path the file is in:</p> <pre><code>require_once __DIR__ . '/../yves-slider.php'; </code></pre> <p>What probably is happening is that the current path PHP looks in is <em>not</em> the path you think it is. If you are curious about what it is (the current path) you could do <a href="http://php.net/manual/en/function.getcwd.php"><code>echo getcwd();</code></a>.</p>
9,619,001
Adding line breaks to a text/plain email
<p>I'm having a problem sending a <code>plain text</code> (not <code>HTML</code>!) email, all my line breaks are being ignored:</p> <pre><code>-&gt;setBody('Did you request a password reset for your account?\r\n\r\nIf yes, click here:\r\nhttp://www.website.com', 'text/plain'); </code></pre> <p>The above is being displayed in the email as:</p> <blockquote> <p>Did you request a password reset for your account?\r\n\r\nIf yes, click here:\nhttp://www.website.com</p> </blockquote> <p>I've checked and the header is apparently set correctly:</p> <p><code>Content-Type: text/plain; charset=utf-8</code></p> <p>Does anyone have any experience with this?</p>
9,619,138
2
1
null
2012-03-08 14:15:37.307 UTC
5
2018-04-11 11:49:07.533 UTC
2013-03-08 11:35:32 UTC
null
199,700
null
199,700
null
1
43
php|email|swiftmailer|plaintext
79,899
<p>You are using literal strings. If you would like to add the line breaks, use double quotes instead of a single quote.</p> <pre><code>-&gt;setBody("Did you request a password reset for your account?\r\n\r\nIf yes, click here:\r\nhttp://www.website.com", 'text/plain'); </code></pre>
24,717,547
iOS 8 Map Kit Obj-C Cannot Get Users Location
<p>I am working with Map Kit in iOS 8 using Obj-C NOT SWIFT. I cannot get the device location it is set a 0.00, 0.00 and I am getting the error:</p> <pre><code>Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first. </code></pre> <p>I have implemented: ( I have tried only one at a time and no luck )</p> <pre><code>if(IS_OS_8_OR_LATER) { [self.locationManager requestWhenInUseAuthorization]; [self.locationManager requestAlwaysAuthorization]; } [self.locationManager startUpdatingLocation]; </code></pre> <p>And in info.plist</p> <pre><code>NSLocationWhenInUseUsageDescription : App would like to use your location. NSLocationAlwaysUsageDescription : App would like to use your location. </code></pre> <p>I do get prompted to allow the app to use my location but after I agree nothing changes. The location is being showed as 0.00, 0.00.</p> <p>Code for displaying users location:</p> <pre><code>//Get Location self.locationManager = [[CLLocationManager alloc] init]; self.locationManager.distanceFilter = kCLDistanceFilterNone; self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; [self.locationManager startUpdatingLocation]; MKCoordinateRegion region = { { 0.0, 0.0 }, { 0.0, 0.0 } }; region.center.latitude = self.locationManager.location.coordinate.latitude; region.center.longitude = self.locationManager.location.coordinate.longitude; region.span.longitudeDelta = 0.005f; region.span.longitudeDelta = 0.005f; [mapView setRegion:region animated:YES]; </code></pre> <p>Mike.</p> <p>**EDIT: View Answer Below.</p>
24,718,342
8
2
null
2014-07-12 21:36:55.84 UTC
29
2015-03-09 11:07:56.553 UTC
2014-11-14 07:36:25.703 UTC
null
2,748,414
null
2,748,414
null
1
51
objective-c|mapkit|cllocationmanager|ios8
52,450
<p>I got it working. I've posted my code below to help anyone else having issues.</p> <p>Here is my full code to get the MapKit Map View working in iOS 8.</p> <p>In your <em>AppName</em>-Info.plist Add a new row with the key name being:</p> <pre><code>NSLocationWhenInUseUsageDescription </code></pre> <p>Or </p> <pre><code>NSLocationAlwaysUsageDescription </code></pre> <p>With the value being a string of the message that you want to be displayed:</p> <pre><code>YourAppName would like to use your location. </code></pre> <p>In your header file. (I use <em>App Name</em>-Prefix.pch but YourViewController.h will work too)</p> <pre><code>#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] &gt;= 8.0) </code></pre> <p>YourViewController.h</p> <pre><code>#import &lt;MapKit/MapKit.h&gt; #import &lt;MapKit/MKAnnotation.h&gt; @interface YourViewController : UIViewController &lt;MKMapViewDelegate, CLLocationManagerDelegate&gt; { } @property(nonatomic, retain) IBOutlet MKMapView *mapView; @property(nonatomic, retain) CLLocationManager *locationManager; </code></pre> <p>YourViewController.m</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. mapView.delegate = self; self.locationManager = [[CLLocationManager alloc] init]; self.locationManager.delegate = self; #ifdef __IPHONE_8_0 if(IS_OS_8_OR_LATER) { // Use one or the other, not both. Depending on what you put in info.plist [self.locationManager requestWhenInUseAuthorization]; [self.locationManager requestAlwaysAuthorization]; } #endif [self.locationManager startUpdatingLocation]; mapView.showsUserLocation = YES; [mapView setMapType:MKMapTypeStandard]; [mapView setZoomEnabled:YES]; [mapView setScrollEnabled:YES]; } -(void)viewDidAppear:(BOOL)animated { [super viewDidAppear:YES]; self.locationManager.distanceFilter = kCLDistanceFilterNone; self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; [self.locationManager startUpdatingLocation]; NSLog(@"%@", [self deviceLocation]); //View Area MKCoordinateRegion region = { { 0.0, 0.0 }, { 0.0, 0.0 } }; region.center.latitude = self.locationManager.location.coordinate.latitude; region.center.longitude = self.locationManager.location.coordinate.longitude; region.span.longitudeDelta = 0.005f; region.span.longitudeDelta = 0.005f; [mapView setRegion:region animated:YES]; } - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation { MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800); [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES]; } - (NSString *)deviceLocation { return [NSString stringWithFormat:@"latitude: %f longitude: %f", self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude]; } - (NSString *)deviceLat { return [NSString stringWithFormat:@"%f", self.locationManager.location.coordinate.latitude]; } - (NSString *)deviceLon { return [NSString stringWithFormat:@"%f", self.locationManager.location.coordinate.longitude]; } - (NSString *)deviceAlt { return [NSString stringWithFormat:@"%f", self.locationManager.location.altitude]; } </code></pre> <p>Enjoy!</p> <p>--Mike</p>
451,519
Staging database predicament
<p>Suppose that there are 3 databases for</p> <ul> <li>Production </li> <li>Staging </li> <li>Dev</li> </ul> <p>As far as I know, Staging database need to be in sync with Production database But, </p> <p>When we are developing, we can do whatever we want with <strong>Dev</strong> database and change schema. Now here comes the Chicken &amp; Egg problem.</p> <p>To test in Staging, <strong>Staging</strong> database schema need to be changed according to changes made in Dev database. But the Staging database need to be in sync with Production.</p> <p>How do you guys get around this problem?</p>
451,527
5
0
null
2009-01-16 18:50:50.063 UTC
10
2010-06-25 17:05:45.177 UTC
2010-06-25 17:05:45.177 UTC
Mark Brady
23,354
dance2die
4,035
null
1
11
database|staging
3,397
<p>Staging needs to be in sync with production, only up to the point where you are deploying new changes. </p> <p>That or make a 4th environment called Test where new upgrades are validated. We call ours UAT/Test, and it is typically a second database on the Staging server.</p> <p>Exact methodology will depend on how you are keeping things in sync. Are you actually using replication? Or just a backup/restore of Prod to Stage?</p>
791,069
How can I create an Delphi object from a class reference and ensure constructor execution?
<p>How can I create an instance of an object using a class reference, and ensure that the constructor is executed?</p> <p>In this code example, the constructor of TMyClass will not be called:</p> <pre><code>type TMyClass = class(TObject) MyStrings: TStrings; constructor Create; virtual; end; constructor TMyClass.Create; begin MyStrings := TStringList.Create; end; procedure Test; var Clazz: TClass; Instance: TObject; begin Clazz := TMyClass; Instance := Clazz.Create; end; </code></pre>
791,103
5
0
null
2009-04-26 15:40:53.123 UTC
13
2014-11-05 21:42:18.76 UTC
null
null
null
null
80,901
null
1
22
delphi|class|constructor|reference|delphi-2009
43,601
<p>Use this:</p> <pre><code>type TMyClass = class(TObject) MyStrings: TStrings; constructor Create; virtual; end; TMyClassClass = class of TMyClass; // &lt;- add this definition constructor TMyClass.Create; begin MyStrings := TStringList.Create; end; procedure Test; var Clazz: TMyClassClass; // &lt;- change TClass to TMyClassClass Instance: TObject; begin Clazz := TMyClass; // &lt;- you can use TMyClass or any of its child classes. Instance := Clazz.Create; // &lt;- virtual constructor will be used end; </code></pre> <p>Alternatively, you can use a type-casts to TMyClass (instead of "class of TMyClass").</p>
241,819
XML best practices: attributes vs additional elements
<p>What's the difference between the two and when should I use each:</p> <pre><code>&lt;person&gt; &lt;firstname&gt;Joe&lt;/firstname&gt; &lt;lastname&gt;Plumber&lt;/lastname&gt; &lt;/person&gt; </code></pre> <p>versus</p> <pre><code>&lt;person firstname="Joe" lastname="Plumber" /&gt; </code></pre> <p>Thanks</p>
241,847
5
0
null
2008-10-28 00:20:11.61 UTC
14
2020-11-25 09:31:26.297 UTC
2009-06-28 00:37:16.157 UTC
null
76,337
Chr15
24,059
null
1
78
xml
28,270
<p>There are element centric and attribute centric XML, in your example, the first one is element centric, the second is attribute centric.</p> <p>Most of the time, these two patterns are equivalent, however there are some exceptions.</p> <p><strong>Attribute centric</strong></p> <ul> <li>Smaller size than element centric.</li> <li>Not very interoperable, since most XML parsers will think the user data is presented by the element, Attributes are used to describe the element.</li> <li>There is no way to present nullable value for some data type. e.g. nullable int</li> <li>Can not express complex type.</li> </ul> <p><strong>Element centric</strong></p> <ul> <li>Complex type can be only presented as an element node.</li> <li>Very interoperable</li> <li>Bigger size than attribute centric. (Compression can be used to reduce the size significantly.)</li> <li>Nullable data can be expressed with attribute xsi:nil=&quot;true&quot;</li> <li>Faster to parse since the parser only looks to elements for user data.</li> </ul> <p><strong>Practical</strong></p> <p>If you really care about the size of your XML, use an attribute whenever you can, if it is appropriate. Use elements where you need something nullable, a complex type, or to hold a large text value. If you don't care about the size of XML or you have compression enabled during transportation, stick with elements as they are more extensible.</p> <p><strong>Background</strong></p> <p>In DOT NET, XmlSerializer can serialize properties of objects into either attributes or elements. In the recent WCF framework, DataContract serializer can only serialize properties into elements and it is faster than XmlSerializer; the reason is obvious, it just needs to look for user data from elements while deserializing.</p> <p>Here an article that explains it as well <a href="http://www.ibm.com/developerworks/xml/library/x-eleatt.html" rel="nofollow noreferrer">Element vs attribute</a></p>
604,399
how do you push only some of your local git commits?
<p>Suppose I have 5 local commits. I want to push only 2 of them to a centralized repo (using an SVN-style workflow). How do I do this? </p> <p>This did not work: </p> <pre><code>git checkout HEAD~3 #set head to three commits ago git push #attempt push from that head </code></pre> <p>That ends up pushing all 5 local commits. </p> <p>I suppose I could do git reset to actually undo my commits, followed by git stash and then git push -- but I've already got commit messages written and files organized and I don't want to redo them. </p> <p>My feeling is that some flag passed to push or reset would work. </p> <p>If it helps, here's my git config</p> <pre><code>[ramanujan:~/myrepo/.git]$cat config [core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true [remote "origin"] url = ssh://server/git/myrepo.git fetch = +refs/heads/*:refs/remotes/origin/* [branch "master"] remote = origin merge = refs/heads/master </code></pre>
604,504
5
0
null
2009-03-02 22:48:25.003 UTC
75
2021-05-25 06:54:52.92 UTC
2016-06-29 05:06:47.507 UTC
null
2,848,117
ramanujan
72,994
null
1
189
git|version-control
82,947
<p>Assuming your commits are on the master branch and you want to push them to the remote master branch:</p> <pre><code>$ git push origin master~3:master </code></pre> <p>If you were using git-svn:</p> <pre><code>$ git svn dcommit master~3 </code></pre> <p>In the case of git-svn, you could also use HEAD~3, since it is expecting a commit. In the case of straight git, you need to use the branch name because HEAD isn't evaluated properly in the refspec.</p> <p>You could also take a longer approach of:</p> <pre><code>$ git checkout -b tocommit HEAD~3 $ git push origin tocommit:master </code></pre> <p>If you are making a habit of this type of work flow, you should consider doing your work in a separate branch. Then you could do something like:</p> <pre><code>$ git checkout master $ git merge working~3 $ git push origin master:master </code></pre> <p>Note that the "origin master:master" part is probably optional for your setup.</p>
990,562
Win32Exception: The directory name is invalid
<p>I'm trying to run a process as a different user that has Administrator privilege in 2 different computers running Vista and their UAC enabled but in one of them I get a Win32Exception that says "The directory name is invalid"</p> <p>Can anyone tell me what is wrong with my code?</p> <pre><code>var myFile = "D:\\SomeFolder\\MyExecutable.exe"; var workingFolder = "D:\\SomeFolder"; var pInfo = new System.Diagnostics.ProcessStartInfo(); pInfo.FileName = myFile; pInfo.WorkingDirectory = workingFolder; pInfo.Arguments = myArgs; pInfo.LoadUserProfile = true; pInfo.UseShellExecute = false; pInfo.UserName = {UserAccount}; pInfo.Password = {SecureStringPassword}; pInfo.Domain = "."; System.Diagnostics.Process.Start(pInfo); </code></pre> <p><strong>UPDATE</strong></p> <p>The application that executes the above code has requireAdministrator execution level. I even set the working folder to <strong>"Path.GetDirectoryName(myFile)"</strong> and <strong>"New System.IO.FileInfo(myFile).DirectoryName"</strong></p>
2,621,943
6
5
null
2009-06-13 11:50:45.557 UTC
4
2014-08-01 05:08:59.767 UTC
2009-06-14 08:36:41.427 UTC
null
34,623
null
34,623
null
1
14
c#|processstartinfo|win32exception
41,065
<p>It is because the path length of the file exceeds 255 characters. </p>
153,928
Can I see TFS file history with labels?
<p>We currently are using both Visual Source Safe and Team Foundation Server at work (VSS for old projects, TFS for current or new projects).</p> <p>We have always used Labels in source control for each build. In VSS if you chose to see a file history you could include labels. In TFS I cannot find an option to include the lables in the history window.</p> <p>Since one of the most common questions that I get asked by support or management is 'What version did we fix/add/remove/change xxxx?', I have always relied on our build labels showing up in the history. </p> <p>Can I get Labels to show up in a file history? </p>
154,744
6
1
null
2008-09-30 16:43:20.237 UTC
6
2011-07-25 22:01:51.037 UTC
null
null
null
Jacco
5,882
null
1
31
tfs|label
28,057
<p>In the 2008 version of TFS, you don't see labels in the standard history of files and folders. If you really want to know why - see Brian Harry's blog post "<a href="http://blogs.msdn.com/bharry/archive/2005/11/18/494439.aspx" rel="noreferrer">Why TFS Labels are not like VSS Labels</a>".</p> <p>To find labels in Visual Studio, go to File, Source Control, Label, Find Label... From that you can see what versions of files were included in that label.</p> <p>The team have definitely heard that this is not ideal, and the next version of TFS (Team Foundation Server 2010, codenamed "Rosario") will include improvements to the History view to make labels easier to find - see <a href="http://go.microsoft.com/?linkid=7807943" rel="noreferrer">http://go.microsoft.com/?linkid=7807943</a> for the spec of improvements to the History view in TFS 2010.</p> <p>BTW - I actually moved to changeset based build numbering with TFS which makes labelling less necessary. See <a href="http://www.woodwardweb.com/vsts/changeset_based.html" rel="noreferrer">http://www.woodwardweb.com/vsts/changeset_based.html</a> for more details.</p> <p>Hope that helps,</p> <p>Martin.</p>
35,341,363
AttributeError: 'module' object has no attribute 'reader'
<p>I get the error:</p> <blockquote> <p>AttributeError: 'module' object has no attribute 'reader')</p> </blockquote> <p>when I run the code below but I can't see why? </p> <pre><code>import csv with open('test.csv') as f: q = csv.reader(f) </code></pre>
35,341,407
1
2
null
2016-02-11 13:59:21.77 UTC
3
2017-03-07 13:10:31.327 UTC
2016-02-11 14:10:47.507 UTC
null
2,040,863
null
5,913,517
null
1
20
python|csv
39,915
<p>You imported a <em>different</em> <code>csv</code> module, not the one in the standard library. Perhaps you named your own script <code>csv.py</code> for example.</p> <p>Find out what is imported instead by printing out the filename of the module:</p> <pre><code>import csv print(csv.__file__) </code></pre> <p>If that's not in the standard library, rename or delete this file, and remove the <code>csv.pyc</code> file if there is one next to it.</p>
20,984,220
invalid conversion from 'const char*' to 'char*'
<p>Have a code as shown below. I have problem passing the arguments.</p> <pre class="lang-cpp prettyprint-override"><code>stringstream data; char *addr=NULL; strcpy(addr,retstring().c_str()); </code></pre> <p><code>retstring()</code> is a function that returns a string.</p> <pre><code>//more code printfunc(num,addr,data.str().c_str()); </code></pre> <p>I get the error </p> <blockquote> <p>invalid conversion from 'const char*' to 'char*'.</p> <p>initializing argument 3 of 'void Printfunc(int, char*, char*)'on argument 3 of the function</p> </blockquote> <p>on the above line. The function is called as shown below</p> <pre><code>void Printfunc(int a, char *loc, char *stream) </code></pre> <p>please let me know if I need to change any initialization.</p>
20,984,255
3
4
null
2014-01-07 23:34:25.597 UTC
7
2018-05-27 12:40:57.987 UTC
2018-05-27 12:40:57.987 UTC
null
4,089,458
null
2,333,234
null
1
50
c++
183,533
<p>Well, <code>data.str().c_str()</code> yields a <code>char const*</code> but your function <code>Printfunc()</code> wants to have <code>char*</code>s. Based on the name, it doesn't change the arguments but merely prints them and/or uses them to name a file, in which case you should probably fix your declaration to be</p> <pre><code>void Printfunc(int a, char const* loc, char const* stream) </code></pre> <p>The alternative might be to turn the <code>char const*</code> into a <code>char*</code> but fixing the declaration is preferable:</p> <pre><code>Printfunc(num, addr, const_cast&lt;char*&gt;(data.str().c_str())); </code></pre>
17,944,074
How to reverse a For loop
<p>I have a problem with my macro. It deletes row that fullfil certain criteria. But when few consecutive rows fullfil those criteria an error occurs. When the row is deleted the other rows are shifted up so if i.e. row(2:2) and row(3:3) fullfil the criteria then the row(2:2) is deleted and row(3:3) is shifted up, so it becomes row(2:2), and For loop goes to another row (third one). As a result row that used to be row(3:3) and now is row(2:2) is omitted and not deleted.<br> In order to deal with this topic I think that it is enough to reverse to For loop, so it wouldn't go from up to bottom but from bottom to top. Te resulat would be double checking of some rows, but no rows would be omitted.<br> The proble is that I don't know how to revese the For loop. I have tried to change 'For x = startrow To endrow' to 'For x = endrow To startrow', but it didn't help.<br> Here is the code:</p> <pre><code>Sub Repurchase_upload() Dim Worksheet As Worksheets startrow = Worksheets("GUTS").Cells(10, 1) endrow = Worksheets("GUTS").Cells(11, 1) For x = startrow To endrow 'I have tried to change this line into: 'For x = endrow To startrow', but it didn' help If Cells(x, "A").Value &lt;&gt; "AA" And Cells(x, "A").Value &lt;&gt; "AB" And Cells(x, "A").Value &lt;&gt; "AC" And Cells(x, "A").Value &lt;&gt; "AD" And Cells(x, "A").Value &lt;&gt; "AE" And Cells(x, "A").Value &lt;&gt; "AH" And Cells(x, "A").Value &lt;&gt; "AI" And Cells(x, "A").Value &lt;&gt; "AF" And Cells(x, "A").Value &lt;&gt; "AG" Then Cells(x, "A").EntireRow.Delete End If Next End Sub </code></pre> <p>Thank you all a lot in advance,<br> with best regards,<br> Artur Rutkowski</p>
17,944,246
3
0
null
2013-07-30 10:06:17.003 UTC
1
2022-09-02 13:56:56.457 UTC
2015-01-30 14:11:27.817 UTC
null
1,505,120
null
2,615,718
null
1
13
vba|excel
48,329
<p>If you're looping and deleting rows, you need to start at the bottom and work up:</p> <pre><code>For x = endrow To startrow step -1 'Execute code Next x </code></pre> <p>Then deleting rows will not disrupt your loop.</p>
54,393,192
Error: yarn start - error Command "start" not found
<p>I am trying to learn React and I am using a private repo to start with it.</p> <p>I run <code>yarn start</code> in the directory of the repo but I get the error message:</p> <pre><code>yarn run v1.13.0 error Command "start" not found. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command. </code></pre> <p>I have both node and yarn installed.</p> <p>For node:</p> <pre><code>v10.15.0 node is /usr/local/bin/node </code></pre> <p>For yarn:</p> <pre><code>1.13.0 yarn is /usr/local/bin/yarn </code></pre> <p>I tried to reinstall both node and yarn but I get the same error message. moreover I tried to remove the yarn chance via <code>yarn cache clean</code> but nothing seems to work.</p> <p>The <code>package.json</code> contains the following:</p> <pre><code>{ "name": "02-Manipulating-Strings", "version": "1.0.0", "author": "ssaunier", "license": "UNLICENSED", "private": true, "devDependencies": { "eslint": "^4.7.2", "eslint-config-airbnb-base": "^12.0.0", "eslint-plugin-import": "^2.7.0", "jest": "^21.1.0" }, "scripts": { "test": "(eslint lib || true) &amp;&amp; jest" } } </code></pre> <p>The directory is organised in the following way:</p> <p><a href="https://i.stack.imgur.com/lIyVH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lIyVH.png" alt="project directory"></a></p>
54,393,283
29
3
null
2019-01-27 21:47:25.677 UTC
null
2022-07-19 16:01:30.443 UTC
2019-01-28 20:52:13.733 UTC
null
7,852,833
null
9,837,259
null
1
44
reactjs|npm|yarnpkg
149,614
<p>There is no <code>start</code> command inside the scripts of the <code>package.json</code> file.</p> <pre><code>"scripts": { "start": "some command to be run", // you need to add this line "test": "(eslint lib || true) &amp;&amp; jest" } </code></pre> <p>Maybe you want to run the <code>test</code> command instead - <code>npm test</code> / <code>yarn test</code>? </p>
2,038,759
What does Expression.Reduce() do?
<p>I've been working with expression trees for a few days now and I'm curious to know what Expression.Reduce() does. The <a href="http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression.reduce(VS.100).aspx" rel="noreferrer">msdn documentation</a> is not very helpful as it only states that it "reduces" the expression. Just in case, I tried an example (see below) to check if this method included mathematical reduction, but this doesn't seem to be the case.</p> <p>Does anyone know what this method does and is it possible to provide a quick example showing it in action? Any good resources out there?</p> <pre><code>static void Main(string[] args) { Expression&lt;Func&lt;double, double&gt;&gt; func = x =&gt; (x + x + x) + Math.Exp(x + x + x); Console.WriteLine(func); Expression r_func = func.Reduce(); Console.WriteLine(r_func); // This prints out the same as Console.WriteLine(func) } </code></pre>
2,044,367
5
5
null
2010-01-10 21:44:34.703 UTC
4
2020-10-01 03:57:59.657 UTC
2017-05-04 19:04:22.13 UTC
null
41,956
null
235,605
null
1
38
c#|.net|lambda|expression-trees
9,992
<p>The document you need to look at is <a href="https://github.com/IronLanguages/dlr/blob/master/Docs/expr-tree-spec.pdf" rel="nofollow noreferrer">expr-tree-spec.pdf</a>.</p> <p>This is the specification for the expression trees. Read the &quot;2.2 Reducible Nodes&quot; and &quot;4.3.5 Reduce Method&quot; sections.</p> <p>Basically, this method is intended for people implementing or porting their dynamic langauges to .NET. So that they can create their own nodes that can &quot;reduce&quot; to standard expression tree nodes and can be compiled. There are some &quot;reducible&quot; nodes in the expression trees API, but I don't know whether you can get any practical examples (since all standard expression nodes compile anyway, as the end-user you probably do not care whether they are &quot;reduced&quot; behind the scenes or not).</p> <p>Yes, MSDN documentation is very basic in this area, because the main source of info and docs for language implementers is on <a href="https://github.com/IronLanguages/dlr" rel="nofollow noreferrer">GitHub</a>, with the documentation in <a href="https://github.com/IronLanguages/dlr/tree/master/Docs" rel="nofollow noreferrer">its own subfolder</a>.</p>
1,639,797
Template issue causes linker error (C++)
<p>I have very little idea what's going in regards to C++ templates, but I'm trying to implement a function that searches a vector for an element satisfying a given property (in this case, searching for one with the name given). My declaration in my .h file is as follows:</p> <pre><code>template &lt;typename T&gt; T* find_name(std::vector&lt;T*&gt; v, std::string name); </code></pre> <p>When I compile, I get this linker error when I call the function:</p> <pre><code>Error 1 error LNK2019: unresolved external symbol "class Item * __cdecl find_name&lt;class Item&gt;(class std::vector&lt;class Item *,class std::allocator&lt;class Item *&gt; &gt;,class std::basic_string&lt;char,struct std::char_traits&lt;char&gt;,class std::allocator&lt;char&gt; &gt;)" (??$find_name@VItem@@@@YAPAVItem@@V?$vector@PAVItem@@V?$allocator@PAVItem@@@std@@@std@@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@2@@Z) referenced in function "public: class Item * __thiscall Place::get_item(class std::basic_string&lt;char,struct std::char_traits&lt;char&gt;,class std::allocator&lt;char&gt; &gt;)" (?get_item@Place@@QAEPAVItem@@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) place.obj Program2 </code></pre> <p>Again, I'm new to templates so I don't know what's going. All instances I've found of LNK2019 through Google have been about not using the correct libraries, but since this is my own function I don't see why this would be happening.</p> <p>Also, a related question: Is there a way to make a template parameter so that it has to be a subclass of a certain class, i.e. template?</p>
1,639,821
6
8
null
2009-10-28 20:09:40.34 UTC
21
2020-01-08 10:39:10.77 UTC
2009-10-30 14:30:03.24 UTC
null
25,981
null
161,638
null
1
63
c++|templates|compiler-errors
50,281
<p>You have to have your template definitions available at the calling site. That means no <code>.cpp</code> files.</p> <p>The reason is templates cannot be compiled. Think of functions as cookies, and the compiler is an oven.</p> <p>Templates are only a cookie cutter, because they don't know what type of cookie they are. It only tells the compiler how to make the function when given a type, but in itself, it can't be used because there is no concrete type being operated on. You can't cook a cookie cutter. Only when you have the tasty cookie dough ready (i.e., given the compiler the dough [type])) can you cut the cookie and cook it.</p> <p>Likewise, only when you actually use the template with a certain type can the compiler generate the actual function, and compile it. It can't do this, however, if the template definition is missing. You have to move it into the header file, so the caller of the function can make the cookie.</p>
1,684,040
Why charset names are not constants?
<p>Charset issues are confusing and complicated by themselves, but on top of that you have to remember exact names of your charsets. Is it <code>"utf8"</code>? Or <code>"utf-8"</code>? Or maybe <code>"UTF-8"</code>? When searching internet for code samples you will see all of the above. Why not just make them named constants and use <code>Charset.UTF8</code>?</p>
1,684,182
6
4
null
2009-11-05 22:18:23.893 UTC
23
2018-06-05 11:57:31.793 UTC
2018-06-05 11:57:31.793 UTC
null
1,671,066
null
20,128
null
1
213
java|character-encoding
73,002
<p>The simple answer to the question asked is that the available charset strings vary from platform to platform.</p> <p>However, there are six that are required to be present, so constants could have been made for those long ago. I don't know why they weren't.</p> <p>JDK 1.4 did a great thing by introducing the Charset type. At this point, they wouldn't have wanted to provide String constants anymore, since the goal is to get everyone using Charset instances. So why not provide the six standard Charset constants, then? I asked Martin Buchholz since he happens to be sitting right next to me, and he said there wasn't a really particularly great reason, except that at the time, things were still half-baked -- too few JDK APIs had been retrofitted to accept Charset, and of the ones that were, the Charset overloads usually performed slightly worse.</p> <p>It's sad that it's only in JDK 1.6 that they finally finished outfitting everything with Charset overloads. And that this backwards performance situation still exists (the reason why is incredibly weird and I can't explain it, but is related to security!).</p> <p>Long story short -- just define your own constants, or use Guava's Charsets class which Tony the Pony linked to (though that library is not really actually released yet).</p> <p><strong>Update:</strong> a <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/charset/StandardCharsets.html" rel="noreferrer"><code>StandardCharsets</code></a> class is in JDK 7.</p>
2,313,704
Is there a Social Security Number reserved for testing/examples?
<p>Is there a canonical "test SSN" that is used by convention, so is understood by all who see it that it is not a real SSN?</p>
2,314,156
7
1
null
2010-02-22 19:55:31.773 UTC
12
2021-02-12 18:36:06.557 UTC
2019-09-18 21:17:24.887 UTC
null
209,129
null
13,436
null
1
84
testing|test-data
126,738
<p>To expand on the Wikipedia-based answers:</p> <p>The Social Security Administration (SSA) explicitly states in this document that the having "000" in the first group of numbers "will NEVER be a valid SSN":</p> <ul> <li><a href="http://www.socialsecurity.gov/employer/stateweb.htm" rel="noreferrer">http://www.socialsecurity.gov/employer/stateweb.htm</a></li> </ul> <p>I'd consider that pretty definitive.</p> <p>However, that the 2nd or 3rd groups of numbers won't be "00" or "0000" can be inferred from a FAQ that the SSA publishes which indicates that allocation of those groups starts at "01" or "0001":</p> <ul> <li><a href="http://ssa-custhelp.ssa.gov/cgi-bin/ssa.cfg/php/enduser/std_adp.php?p_faqid=87" rel="noreferrer">http://ssa-custhelp.ssa.gov/cgi-bin/ssa.cfg/php/enduser/std_adp.php?p_faqid=87</a></li> </ul> <p>But this is only a FAQ and it's never outright stated that "00" or "0000" will never be used.</p> <p>In another FAQ they provide (<a href="http://www.socialsecurity.gov/employer/randomizationfaqs.html#a0=6" rel="noreferrer">http://www.socialsecurity.gov/employer/randomizationfaqs.html#a0=6</a>) that "00" or "0000" will never be used.</p> <p>I can't find a reference to the 'advertisement' reserved SSNs on the SSA site, but it appears that no numbers starting with a 3 digit number higher than 772 (according to the document referenced above) have been assigned yet, but there's nothing I could find that states those numbers are reserved. Wikipedia's reference is a book that I don't have access to. The Wikipedia information on the advertisement reserved numbers is mentioned across the web, but many are clearly copied from Wikipedia. I think it would be nice to have a citation from the SSA, though I suspect that now that Wikipedia has made the idea popular that these number would now have to be reserved for advertisements even if they weren't initially.</p> <p>The SSA has a page with a couple of stories about SSN's they've had to retire because they were used in advertisements/samples (maybe the SSA should post a link to whatever their current policy on this might be):</p> <ul> <li><a href="http://www.ssa.gov/history/ssn/misused.html" rel="noreferrer">http://www.ssa.gov/history/ssn/misused.html</a></li> </ul>
2,068,286
Music Recognition and Signal Processing
<p>I want to <strong>build something similar to <a href="http://www.wildbits.com/tunatic/" rel="noreferrer">Tunatic</a> or <a href="http://www.midomi.com/" rel="noreferrer">Midomi</a></strong> (try them out if you're not sure what they do) and I'm wondering what algorithms I'd have to use; The idea I have about the workings of such applications is something like this:</p> <ol> <li>have a big database with several songs</li> <li>for each song in <strong>1.</strong> reduce quality / bit-rate (to 64kbps for instance) and calculate the sound "hash"</li> <li>have the sound / excerpt of the music you want to identify</li> <li>for the song in <strong>3.</strong> reduce quality / bit-rate (again to 64kbps) and calculate sound "hash"</li> <li>if <strong>4.</strong> sound hash is in any of the <strong>2.</strong> sound hashes return the matched music</li> </ol> <p>I though of reducing the quality / bit-rate due to the environment noises and encoding differences.</p> <p><strong>Am I in the right track here?</strong> Can anyone provide me any <strong>specific documentation or examples</strong>? Midori seems to even recognize <code>hum's</code>, that's pretty awesomely impressive! How do they do that?</p> <p>Do sound hashes exist or is it something I just made up? If they do, how can I calculate them? And more importantly, <strong>how can I check if <code>child-hash</code> is in <code>father-hash</code></strong>?</p> <p>How would I go about <strong>building a similar system with Python (maybe a built-in module) or PHP</strong>?</p> <p>Some examples (preferably in Python or PHP) will be greatly appreciated. Thanks in advance!</p>
2,068,311
9
2
null
2010-01-14 23:21:37.553 UTC
18
2015-10-10 23:38:19.547 UTC
2013-09-02 03:43:45.357 UTC
null
319,204
null
89,771
null
1
14
php|python|audio|signal-processing|audio-processing
9,762
<p>I worked on the periphery of a cool framework that implements several Music Information Retrieval techniques. I'm hardly an expert (edit: actually i'm nowhere close to an expert, just to clarify), but I can tell that that the Fast Fourier Transform is used all over the place with this stuff. Fourier analysis is wacky but its application is pretty straight-forward. Basically you can get a lot of information about audio when you analyze it in the frequency domain rather than the time domain. This is what Fourier analysis gives you. </p> <p>That may be a bit off topic from what you want to do. In any case, there are some cool tools in the project to play with, as well as viewing the sourcecode for the core library itself: <a href="http://marsyas.sness.net" rel="noreferrer">http://marsyas.sness.net</a></p>
1,623,849
Fastest way to zero out low values in array?
<p>So, lets say I have 100,000 float arrays with 100 elements each. I need the highest X number of values, BUT only if they are greater than Y. Any element not matching this should be set to 0. What would be the fastest way to do this in Python? Order must be maintained. Most of the elements are already set to 0.</p> <p>sample variables:</p> <pre><code>array = [.06, .25, 0, .15, .5, 0, 0, 0.04, 0, 0] highCountX = 3 lowValY = .1 </code></pre> <p>expected result:</p> <pre><code>array = [0, .25, 0, .15, .5, 0, 0, 0, 0, 0] </code></pre>
1,623,939
9
5
null
2009-10-26 09:24:02.09 UTC
10
2019-04-12 12:35:05.52 UTC
2012-06-15 13:37:31.427 UTC
null
44,390
null
196,505
null
1
37
python|arrays|floating-point|max|min
68,597
<p>This is a typical job for <a href="https://docs.scipy.org/doc/numpy/user/quickstart.html" rel="nofollow noreferrer">NumPy</a>, which is very fast for these kinds of operations:</p> <pre><code>array_np = numpy.asarray(array) low_values_flags = array_np &lt; lowValY # Where values are low array_np[low_values_flags] = 0 # All low values set to 0 </code></pre> <p>Now, if you only need the highCountX largest elements, you can even "forget" the small elements (instead of setting them to 0 and sorting them) and only sort the list of large elements:</p> <pre><code>array_np = numpy.asarray(array) print numpy.sort(array_np[array_np &gt;= lowValY])[-highCountX:] </code></pre> <p>Of course, sorting the whole array if you only need a few elements might not be optimal. Depending on your needs, you might want to consider the standard <a href="http://docs.python.org/library/heapq.html" rel="nofollow noreferrer">heapq</a> module.</p>
1,706,551
Parse string into argv/argc
<p>Is there a way in C to parse a piece of text and obtain values for argv and argc, as if the text had been passed to an application on the command line? </p> <p>This doesn't have to work on Windows, just Linux - I also don't care about quoting of arguments.</p>
1,706,733
13
9
null
2009-11-10 09:09:04.167 UTC
14
2021-09-30 15:49:56.947 UTC
2017-02-05 14:57:42.333 UTC
null
1,743,880
null
138,256
null
1
38
c|arguments
60,625
<p>If glib solution is overkill for your case you may consider coding one yourself.</p> <p>Then you can:</p> <ul> <li>scan the string and count how many arguments there are (and you get your argc)</li> <li>allocate an array of char * (for your argv)</li> <li>rescan the string, assign the pointers in the allocated array and replace spaces with '\0' (if you can't modify the string containing the arguments, you should duplicate it).</li> <li>don't forget to free what you have allocated!</li> </ul> <p>The diagram below should clarify (hopefully):</p> <pre><code> aa bbb ccc "dd d" ee &lt;- original string aa0bbb0ccc00dd d00ee0 &lt;- transformed string | | | | | argv[0] __/ / / / / argv[1] ____/ / / / argv[2] _______/ / / argv[3] ___________/ / argv[4] ________________/ </code></pre> <p>A possible API could be:</p> <pre><code> char **parseargs(char *arguments, int *argc); void freeparsedargs(char **argv); </code></pre> <p>You will need additional considerations to implement freeparsedargs() safely.</p> <p>If your string is very long and you don't want to scan twice you may consider alteranatives like allocating more elements for the argv arrays (and reallocating if needed).</p> <p>EDIT: Proposed solution (desn't handle quoted argument).</p> <pre><code> #include &lt;stdio.h&gt; static int setargs(char *args, char **argv) { int count = 0; while (isspace(*args)) ++args; while (*args) { if (argv) argv[count] = args; while (*args &amp;&amp; !isspace(*args)) ++args; if (argv &amp;&amp; *args) *args++ = '\0'; while (isspace(*args)) ++args; count++; } return count; } char **parsedargs(char *args, int *argc) { char **argv = NULL; int argn = 0; if (args &amp;&amp; *args &amp;&amp; (args = strdup(args)) &amp;&amp; (argn = setargs(args,NULL)) &amp;&amp; (argv = malloc((argn+1) * sizeof(char *)))) { *argv++ = args; argn = setargs(args,argv); } if (args &amp;&amp; !argv) free(args); *argc = argn; return argv; } void freeparsedargs(char **argv) { if (argv) { free(argv[-1]); free(argv-1); } } int main(int argc, char *argv[]) { int i; char **av; int ac; char *as = NULL; if (argc &gt; 1) as = argv[1]; av = parsedargs(as,&amp;ac); printf("== %d\n",ac); for (i = 0; i &lt; ac; i++) printf("[%s]\n",av[i]); freeparsedargs(av); exit(0); } </code></pre>
1,520,429
Is there a CSS selector for elements containing certain text?
<p>I am looking for a CSS selector for the following table:</p> <pre><code>Peter | male | 34 Susanne | female | 12 </code></pre> <p>Is there any selector to match all TDs containing "male"?</p>
1,520,469
20
8
null
2009-10-05 14:26:09.833 UTC
72
2022-06-03 09:41:49.813 UTC
2015-03-30 05:37:27.65 UTC
null
106,224
null
159,319
null
1
741
css|css-selectors
1,030,188
<p>If I read <a href="http://www.w3.org/TR/css3-selectors/#selectors" rel="noreferrer">the specification</a> correctly, no. </p> <p>You can match on an element, the name of an attribute in the element, and the value of a named attribute in an element. I don't see anything for matching content within an element, though.</p>
8,681,252
Programmatically extract contents of InstallShield setup.exe
<p>I am trying to extract the file-contents of an InstallShield setup.exe-file. (My plan is to use it in a back-office tool, so this must be done programmatically without any user interactions.)</p> <p>Is this possible?<br> (Initial research seems to indicate it will fail.)</p> <p>If it is possible to have a generic solution, for all recent versions of InstallShield that would be best.<br> Otherwise, if a solution only works for some versions of InstallShield it would be a step on the way. (It would probably be possible to deduce which InstallShield version a <code>setup.exe</code> is by looking at version resources of the exe-file.</p> <p>I <a href="http://kb.flexerasoftware.com/doc/Helpnet/installshield12helplib/IHelpSetup_EXECmdLine.htm">found that</a> some InstallShield versions support <code>/b</code> or <code>/extract_all</code>. However there is no good way of knowing, just launching the exe and hoping it will extract and terminate orderly rather then displaying GUI dialogs doesn't seem like a good solution. So I am therefore looking for a more stable way.<br> Ideas welcome.</p>
8,694,205
5
2
null
2011-12-30 15:50:35.967 UTC
13
2016-10-21 15:09:42.41 UTC
2011-12-30 17:02:23.343 UTC
null
25,961
null
25,961
null
1
29
installation|installshield
136,940
<p>There's no supported way to do this, but won't you have to examine the files related to each installer to figure out how to actually install them after extracting them? Assuming you can spend the time to figure out which command-line applies, here are some candidate parameters that normally allow you to extract an installation.</p> <p>MSI Based (may not result in a usable image for an InstallScript MSI installation):</p> <ul> <li><p><code>setup.exe /a /s /v"/qn TARGETDIR=\"choose-a-location\""</code></p> <p>or, to also extract prerequisites (for versions where it works),</p></li> <li><code>setup.exe /a"choose-another-location" /s /v"/qn TARGETDIR=\"choose-a-location\""</code></li> </ul> <p>InstallScript based:</p> <ul> <li><code>setup.exe /s /extract_all</code></li> </ul> <p>Suite based (may not be obvious how to install the resulting files):</p> <ul> <li><code>setup.exe /silent /stage_only ISRootStagePath="choose-a-location"</code></li> </ul>
8,716,330
Purpose of returning by const value?
<p>What is the purpose of the const in this?</p> <pre><code>const Object myFunc(){ return myObject; } </code></pre> <p>I've just started reading Effective C++ and Item 3 advocates this and a Google search picks up similar suggestions but also counterexamples. I can't see how using const here would ever be preferable. Assuming a return by value is desirable, I don't see any reason to protect the returned value. The example given for why this might be helpful is preventing unintended bool casts of the return value. The actual problem then is that implicit bool casts should be prevented with the explicit keyword.</p> <p>Using const here prevents using temporary objects without assignment. So I couldn't perform arithmetic expressions with those objects. It doesn't seem like there's ever a case that an unnamed const is useful.</p> <p>What is gained by using const here and when would it be preferable?</p> <p>EDIT: Change arithmetic example to any function that modifies an object that you might want to perform before an assignment.</p>
8,716,406
4
2
null
2012-01-03 17:39:31.877 UTC
57
2017-12-01 14:30:30.127 UTC
2017-12-01 14:30:30.127 UTC
null
3,885,376
null
1,128,289
null
1
164
c++|constants
154,605
<p>In the hypothetical situation where you could perform a potentially expensive non-const operation on an object, returning by const-value prevents you from accidentally calling this operation on a temporary. Imagine that <code>+</code> returned a non-const value, and you could write:</p> <pre><code>(a + b).expensive(); </code></pre> <p>In the age of C++11, however, it is strongly advised to return values as non-const so that you can take full advantage of rvalue references, which only make sense on non-constant rvalues.</p> <p>In summary, there <em>is</em> a rationale for this practice, but it is essentially obsolete.</p>
8,555,320
Is there a Wikipedia API just for retrieve the content summary?
<p>I need just to retrieve the first paragraph of a Wikipedia page.</p> <p>Content must be HTML formatted, ready to be displayed on my website (so <em>no</em> <a href="https://en.wikipedia.org/wiki/BBCode" rel="noreferrer">BBCode</a>, or <em>Wikipedia</em> special <em>code</em>!)</p>
28,401,782
12
2
null
2011-12-18 22:25:10.817 UTC
131
2022-08-15 04:42:29.753 UTC
2022-01-17 15:29:17.28 UTC
null
4,294,399
null
946,478
null
1
174
wikipedia|wikipedia-api
156,904
<p>There's a way to get the entire &quot;introduction section&quot; without any HTML parsing! Similar to <a href="https://stackoverflow.com/questions/8555320/is-there-a-wikipedia-api-just-for-retrieve-the-content-summary/18504997#18504997">AnthonyS's answer</a> with an additional <code>explaintext</code> parameter, you can get the introduction section text in plain text.</p> <h2>Query</h2> <p>Getting Stack Overflow's introduction in plain text:</p> <p>Using the page title:</p> <p><a href="https://en.wikipedia.org/w/api.php?format=json&amp;action=query&amp;prop=extracts&amp;exintro&amp;explaintext&amp;redirects=1&amp;titles=Stack%20Overflow" rel="noreferrer">https://en.wikipedia.org/w/api.php?format=json&amp;action=query&amp;prop=extracts&amp;exintro&amp;explaintext&amp;redirects=1&amp;titles=Stack%20Overflow</a></p> <p>Or use <code>pageids</code>:</p> <p><a href="https://en.wikipedia.org/w/api.php?format=json&amp;action=query&amp;prop=extracts&amp;exintro&amp;explaintext&amp;redirects=1&amp;pageids=21721040" rel="noreferrer">https://en.wikipedia.org/w/api.php?format=json&amp;action=query&amp;prop=extracts&amp;exintro&amp;explaintext&amp;redirects=1&amp;pageids=21721040</a></p> <h3>JSON Response</h3> <p>(warnings stripped)</p> <pre class="lang-json prettyprint-override"><code>{ &quot;query&quot;: { &quot;pages&quot;: { &quot;21721040&quot;: { &quot;pageid&quot;: 21721040, &quot;ns&quot;: 0, &quot;title&quot;: &quot;Stack Overflow&quot;, &quot;extract&quot;: &quot;Stack Overflow is a privately held website, the flagship site of the Stack Exchange Network, created in 2008 by Jeff Atwood and Joel Spolsky, as a more open alternative to earlier Q&amp;A sites such as Experts Exchange. The name for the website was chosen by voting in April 2008 by readers of Coding Horror, Atwood's popular programming blog.\nIt features questions and answers on a wide range of topics in computer programming. The website serves as a platform for users to ask and answer questions, and, through membership and active participation, to vote questions and answers up or down and edit questions and answers in a fashion similar to a wiki or Digg. Users of Stack Overflow can earn reputation points and \&quot;badges\&quot;; for example, a person is awarded 10 reputation points for receiving an \&quot;up\&quot; vote on an answer given to a question, and can receive badges for their valued contributions, which represents a kind of gamification of the traditional Q&amp;A site or forum. All user-generated content is licensed under a Creative Commons Attribute-ShareAlike license. Questions are closed in order to allow low quality questions to improve. Jeff Atwood stated in 2010 that duplicate questions are not seen as a problem but rather they constitute an advantage if such additional questions drive extra traffic to the site by multiplying relevant keyword hits in search engines.\nAs of April 2014, Stack Overflow has over 2,700,000 registered users and more than 7,100,000 questions. Based on the type of tags assigned to questions, the top eight most discussed topics on the site are: Java, JavaScript, C#, PHP, Android, jQuery, Python and HTML.&quot; } } } } </code></pre> <p>Documentation: <a href="https://en.wikipedia.org/wiki/Special:ApiHelp/query+extracts" rel="noreferrer">API: query/prop=extracts</a></p>
17,772,260
Textarea Auto height
<p>I want to make height of textarea equal to height of the text within it (And remove the scroll bar)</p> <p>HTML</p> <pre><code>&lt;textarea id="note"&gt;SOME TEXT&lt;/textarea&gt; </code></pre> <p>CSS</p> <pre><code>textarea#note { width:100%; direction:rtl; display:block; max-width:100%; line-height:1.5; padding:15px 15px 30px; border-radius:3px; border:1px solid #F7E98D; font:13px Tahoma, cursive; transition:box-shadow 0.5s ease; box-shadow:0 4px 6px rgba(0,0,0,0.1); font-smoothing:subpixel-antialiased; background:linear-gradient(#F9EFAF, #F7E98D); background:-o-linear-gradient(#F9EFAF, #F7E98D); background:-ms-linear-gradient(#F9EFAF, #F7E98D); background:-moz-linear-gradient(#F9EFAF, #F7E98D); background:-webkit-linear-gradient(#F9EFAF, #F7E98D); } </code></pre> <p>JsFiddle: <a href="http://jsfiddle.net/Tw9Rj/">http://jsfiddle.net/Tw9Rj/</a></p>
17,772,322
8
3
null
2013-07-21 12:19:16.603 UTC
45
2020-04-12 12:34:03.773 UTC
2015-12-28 12:19:40.933 UTC
null
2,205,515
null
2,602,762
null
1
220
javascript|html|css
524,014
<p><s>It can be achieved using JS. Here is a 'one-line' <a href="http://jsfiddle.net/Tw9Rj/6/" rel="noreferrer">solution</a> using <a href="http://unwrongest.com/projects/elastic/" rel="noreferrer">elastic.js</a>:</p> <pre><code>$('#note').elastic(); </code></pre> <p></s></p> <p>Updated: Seems like elastic.js is not there anymore, but if you are looking for an external library, I can recommend <a href="http://www.jacklmoore.com/autosize/" rel="noreferrer">autosize.js by Jack Moore</a>. This is the working example:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>autosize(document.getElementById("note"));</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>textarea#note { width:100%; box-sizing:border-box; direction:rtl; display:block; max-width:100%; line-height:1.5; padding:15px 15px 30px; border-radius:3px; border:1px solid #F7E98D; font:13px Tahoma, cursive; transition:box-shadow 0.5s ease; box-shadow:0 4px 6px rgba(0,0,0,0.1); font-smoothing:subpixel-antialiased; background:linear-gradient(#F9EFAF, #F7E98D); background:-o-linear-gradient(#F9EFAF, #F7E98D); background:-ms-linear-gradient(#F9EFAF, #F7E98D); background:-moz-linear-gradient(#F9EFAF, #F7E98D); background:-webkit-linear-gradient(#F9EFAF, #F7E98D); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://rawgit.com/jackmoore/autosize/master/dist/autosize.min.js"&gt;&lt;/script&gt; &lt;textarea id="note"&gt;Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.&lt;/textarea&gt;</code></pre> </div> </div> </p> <p>Check this similar topics too:</p> <p><a href="https://stackoverflow.com/questions/7477/autosizing-textarea-using-prototype">Autosizing textarea using Prototype</a></p> <p><a href="https://stackoverflow.com/questions/995168/textarea-to-resize-based-on-content-length">Textarea to resize based on content length</a></p> <p><a href="https://stackoverflow.com/questions/454202/creating-a-textarea-with-auto-resize">Creating a textarea with auto-resize</a></p>
17,917,994
How to play audio continuously while orientation changes in Android?
<p>I'm new to Android and I have to create <code>MediaPlayer</code> for playing the audio music. When start my activity song starts playing. But when I change the orientation on my emulator screen <code>MediaPlayer</code> is reinitialized and another audio starts playing. How can I avoid it? </p> <p>Here is my code:</p> <pre><code>public class Audio_Activity extends Activity { MediaPlayer mp = null; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(isLaunched) { setContentView(R.layout.audio); } SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); length = settings.getInt("TheOffset", 0); init(); prefs = PreferenceManager.getDefaultSharedPreferences(this); mp = MediaPlayer.create(getApplicationContext(), R.raw.subhanallah); playMusic(); mp.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer arg0) { // TODO Auto-generated method stub } }); } private void playMusic() { httpGetAsynchTask httpGetAsyncTask = new httpGetAsynchTask(); httpGetAsyncTask.execute(); } class httpGetAsynchTask extends AsyncTask&lt;String,Integer, Void&gt; { protected void onPreExdcute() { } @Override protected Void doInBackground(String... arg0) { // TODO Auto-generated method stub final SharedPreferences.Editor prefsEdit = prefs.edit(); Log.e("Song is playing", "in Mediya Player "); mp.setLooping(false); mp.start(); int millisecond=mp.getDuration(); Log.e("Song is playing", "in Mediya Player " + millisecond); prefsEdit.putBoolean("mediaplaying", true); prefsEdit.commit(); //btnChapter.setEnabled(false); return null; } protected void onPostExecute(Void result) { super.onPostExecute(result); btnChapter.setEnabled(false); } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); Configuration config=getResources().getConfiguration(); if(config.orientation == Configuration.ORIENTATION_PORTRAIT) { setContentView(R.layout.audio); } else if(config.orientation == Configuration.ORIENTATION_LANDSCAPE) { setContentView(R.layout.audio); } } @Override public void onPause() { super.onPause(); SharedPreferences.Editor prefsEdit = prefs.edit(); boolean isPlaying = prefs.getBoolean("mediaplaying", false); if (isPlaying) { mp.pause(); int position = mp.getCurrentPosition(); Log.e("Current ", "Position -&gt; " + position); prefsEdit.putInt("mediaPosition", position); prefsEdit.commit(); } } @Override protected void onResume() { super.onResume(); mp.start(); boolean isPlaying = prefs.getBoolean("mediaplaying", false); if (isPlaying) { int position = prefs.getInt("mediaPosition", 0); mp.seekTo(position); // mp.start(); } } } </code></pre> <p>And I have done some changes in Manifest.xml file.</p> <pre><code>&lt; android:configChanges="orientation|screenSize|keyboard" &gt; </code></pre> <p>and create layout-land folder .</p> <p>Why is the music playing twice?</p>
17,921,927
11
0
null
2013-07-29 07:12:04.417 UTC
8
2019-10-16 10:35:56.943 UTC
2017-09-27 19:15:29.97 UTC
null
472,495
null
2,333,011
null
1
16
android|audio|android-mediaplayer
13,705
<p>When we declare mediaplayer as a static variable then only one instance of mp will exist. Suppose our Activity orientation changes now, Everything will be recreated on orientation change but Mp variable will not be recreated because of static property. In this way we just make a condition </p> <pre><code>if(mp!=null &amp;&amp; !mp.isPlaying()){ mp = MediaPlayer.create(getApplicationContext(), R.raw.subhanallah); playMusic(); } </code></pre> <p>in our onCreate() method, this will check whether music is already playing or not, if its playing then if condition will not allow application to start music player again. and if Music is not playing then if condition will allow the application to restart the music. </p> <hr> <p>Here is your update code: </p> <pre><code>public class Audio_Activity extends Activity { static MediaPlayer mp = null; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(isLaunched) { setContentView(R.layout.audio); } SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); length = settings.getInt("TheOffset", 0); init(); prefs = PreferenceManager.getDefaultSharedPreferences(this); if(mp == null) { initializeMP(); } if(!mp.isPlaying()) { playMusic(); } mp.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer arg0) { // TODO Auto-generated method stub } }); } private void playMusic() { httpGetAsynchTask httpGetAsyncTask = new httpGetAsynchTask(); httpGetAsyncTask.execute(); } public void initializeMP() { mp = MediaPlayer.create(getApplicationContext(), R.raw.subhanallah); } class httpGetAsynchTask extends AsyncTask&lt;String,Integer, Void&gt; { protected void onPreExdcute() { } @Override protected Void doInBackground(String... arg0) { // TODO Auto-generated method stub final SharedPreferences.Editor prefsEdit = prefs.edit(); Log.e("Song is playing", "in Mediya Player "); if(mp == null) { initializeMP() } mp.setLooping(false); mp.start(); int millisecond=mp.getDuration(); Log.e("Song is playing", "in Mediya Player " + millisecond); prefsEdit.putBoolean("mediaplaying", true); prefsEdit.commit(); //btnChapter.setEnabled(false); return null; } protected void onPostExecute(Void result) { super.onPostExecute(result); btnChapter.setEnabled(false); } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); Configuration config=getResources().getConfiguration(); if(config.orientation == Configuration.ORIENTATION_PORTRAIT) { setContentView(R.layout.audio); } else if(config.orientation == Configuration.ORIENTATION_LANDSCAPE) { setContentView(R.layout.audio); } } @Override public void onPause() { super.onPause(); SharedPreferences.Editor prefsEdit = prefs.edit(); boolean isPlaying = prefs.getBoolean("mediaplaying", false); if (isPlaying) { if(mp!=null) { mp.pause(); } int position = mp.getCurrentPosition(); Log.e("Current ", "Position -&gt; " + position); prefsEdit.putInt("mediaPosition", position); prefsEdit.commit(); } } @Override protected void onResume() { super.onResume(); if(mp == null) { initializeMP(); } mp.start(); boolean isPlaying = prefs.getBoolean("mediaplaying", false); if (isPlaying) { int position = prefs.getInt("mediaPosition", 0); mp.seekTo(position); // mp.start(); } } } </code></pre>
44,580,702
Android room persistent library - how to insert class that has a List object field
<p>In <a href="https://developer.android.com/topic/libraries/architecture/room.html" rel="noreferrer">Android room persistent library</a> how to insert entire Model object into table which has in itself another list.</p> <p>Let me show you what i mean :</p> <pre><code>@Entity(tableName = TABLE_NAME) public class CountryModel { public static final String TABLE_NAME = "Countries"; @PrimaryKey private int idCountry; private List&lt;CountryLang&gt; countryLang = null; public int getIdCountry() { return idCountry; } public void setIdCountry(int idCountry) { this.idCountry = idCountry; } public String getIsoCode() { return isoCode; } public void setIsoCode(String isoCode) { this.isoCode = isoCode; } /** here i am providing a list of coutry information how to insert this into db along with CountryModel at same time **/ public List&lt;CountryLang&gt; getCountryLang() { return countryLang; } public void setCountryLang(List&lt;CountryLang&gt; countryLang) { this.countryLang = countryLang; } } </code></pre> <p>my DAO looks like this:</p> <pre><code>@Dao public interface CountriesDao{ @Query("SELECT * FROM " + CountryModel.TABLE_NAME +" WHERE isoCode =:iso_code LIMIT 1") LiveData&lt;List&lt;CountryModel&gt;&gt; getCountry(String iso_code); @Query("SELECT * FROM " + CountryModel.TABLE_NAME ) LiveData&lt;List&lt;CountryModel&gt;&gt; getAllCountriesInfo(); @Insert(onConflict = REPLACE) Long[] addCountries(List&lt;CountryModel&gt; countryModel); @Delete void deleteCountry(CountryModel... countryModel); @Update(onConflict = REPLACE) void updateEvent(CountryModel... countryModel); } </code></pre> <p>When i call <code>database.CountriesDao().addCountries(countryModel);</code> i get the following room db compile error: <strong>Error:(58, 31) error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.</strong></p> <p>should there be another table called CountryLang ? and if so how to tell room to connect them on insert statement ?</p> <p>The CountryLang object itself looks like this:</p> <pre><code>public class CountryLang { private int idCountry; private int idLang; private String name; public int getIdCountry() { return idCountry; } public void setIdCountry(int idCountry) { this.idCountry = idCountry; } public int getIdLang() { return idLang; } public void setIdLang(int idLang) { this.idLang = idLang; } public String getName() { return name; } public void setName(String name) { this.name = name; } } </code></pre> <p>the response looks like this:</p> <pre><code>"country_lang": [ { "id_country": 2, "id_lang": 1, "name": "Austria" } ] </code></pre> <p>For every country so its not going to be more then one item here. Im comfortable desgning it for just one item in the country_lang list. So i can just make a table for country_lang and then some how link it to CountryModel. but how ? can i use foreign key ? i was hoping i did not have to use a flat file. so your saying i have to store it as json ? Is it recommended not to use room for temporary ? what to use instead ?</p>
48,026,515
8
12
null
2017-06-16 04:13:41.687 UTC
26
2022-07-08 04:09:54.213 UTC
2018-05-25 09:55:14.37 UTC
null
882,251
null
835,883
null
1
72
android|android-room
83,178
<p>As Omkar said, you cannot. Here, I describe why you should always use <code>@Ignore</code> annotation according to the documentation: <a href="https://developer.android.com/training/data-storage/room/referencing-data.html#understand-no-object-references" rel="noreferrer">https://developer.android.com/training/data-storage/room/referencing-data.html#understand-no-object-references</a></p> <p>You will treat the Country object in a table to retrieve the data of its competence only; The Languages objects will go to another table but you can keep the same Dao:</p> <ul> <li>Countries and Languages objects are independent, just define the primaryKey with more fields in Language entity (countryId, languageId). You can save them in series in the Repository class when the active thread is the Worker thread: two requests of inserts to the Dao.</li> <li>To load the Countries object you have the countryId.</li> <li>To load the related Languages objects you already have the countryId, but you will need to wait that country is loaded first, before to load the languages, so that you can set them in the parent object and return the parent object only.</li> <li>You can probably do this in series in the Repository class when you load the country, so you will load synchronously country and then languages, as you would do at the Server side! (without ORM libraries).</li> </ul>
35,903,100
What does `T {}` do in Scala
<p>Browsing Shapeless code, I came across this seemingly extraneous <code>{}</code> <a href="https://github.com/milessabin/shapeless/blob/e007f47e02607fd008ceb8d22d95695aaece3f52/core/src/main/scala/shapeless/singletons.scala#L30">here</a> and <a href="https://github.com/milessabin/shapeless/blob/56a3de48094e691d56a937ccf461d808de391961/core/src/main/scala/shapeless/syntax/singletons.scala#L39">here</a>:</p> <pre><code>trait Witness extends Serializable { type T val value: T {} } trait SingletonOps { import record._ type T def narrow: T {} = witness.value } </code></pre> <p>I almost ignored it as a typo since it does nothing but apparently it does something. See this commit: <a href="https://github.com/milessabin/shapeless/commit/56a3de48094e691d56a937ccf461d808de391961">https://github.com/milessabin/shapeless/commit/56a3de48094e691d56a937ccf461d808de391961</a></p> <p>I have no idea what it does. Can someone explain?</p>
35,916,154
1
5
null
2016-03-09 21:35:54.977 UTC
13
2016-03-10 12:10:58.903 UTC
2016-03-09 22:00:51.373 UTC
null
471,136
null
471,136
null
1
41
scala|shapeless
2,140
<p>Any type can be followed by a <code>{}</code> enclosed sequence of type and abstract non-type member definitions. This is known as a "refinement" and is used to provide additional precision over the base type that is being refined. In practice refinements are most commonly used to express constraints on abstract type members of the type being refined.</p> <p>It's a little known fact that this sequence is allowed to be empty, and in the form that you can see in the shapeless source code, <code>T {}</code> is the type <code>T</code> with an empty refinement. Any empty refinement is ... empty ... so doesn't add any additional constraints to the refined type and hence the types <code>T</code> and <code>T {}</code> are equivalent. We can get the Scala compiler to verify that for us like so,</p> <pre><code>scala&gt; implicitly[Int =:= Int {}] res0: =:=[Int,Int] = &lt;function1&gt; </code></pre> <p>So why would I do such an apparently pointless thing in shapeless? It's because of the interaction between the presence of refinements and type inference. If you look in <a href="http://www.scala-lang.org/files/archive/spec/2.11/06-expressions.html#local-type-inference" rel="noreferrer">the relevant section</a> of the Scala Language Specification you will see that the type inference algorithm attempts to avoid inferring singleton types in at least some circumstances. Here is an example of it doing just that,</p> <pre><code>scala&gt; class Foo ; val foo = new Foo defined class Foo foo: Foo = Foo@8bd1b6a scala&gt; val f1 = foo f1: Foo = Foo@8bd1b6a scala&gt; val f2: foo.type = foo f2: foo.type = Foo@8bd1b6a </code></pre> <p>As you can see from the definition of <code>f2</code> the Scala compiler knows that the value <code>foo</code> has the more precise type <code>foo.type</code> (ie. the singleton type of <code>val foo</code>), however, unless explicitly requested it won't infer that more precise type. Instead it infers the non-singleton (ie. widened) type <code>Foo</code> as you can see in the case of <code>f1</code>.</p> <p>But in the case of <code>Witness</code> in shapeless I explicitly <em>want</em> the singleton type to be inferred for uses of the <code>value</code> member (the whole point of <code>Witness</code> is enable us to pass between the type and value levels via singleton types), so is there any way the Scala compiler can be persuaded to do that?</p> <p>It turns out that an empty refinement does exactly that,</p> <pre><code>scala&gt; def narrow[T &lt;: AnyRef](t: T): t.type = t narrow: [T &lt;: AnyRef](t: T)t.type scala&gt; val s1 = narrow("foo") // Widened s1: String = foo scala&gt; def narrow[T &lt;: AnyRef](t: T): t.type {} = t // Note empty refinement narrow: [T &lt;: AnyRef](t: T)t.type scala&gt; val s2 = narrow("foo") // Not widened s2: String("foo") = foo </code></pre> <p>As you can see in the above REPL transcript, in the first case <code>s1</code> has been typed as the widened type <code>String</code> whereas <code>s2</code> has been assigned the singleton type <code>String("foo")</code>.</p> <p>Is this mandated by the SLS? No, but it is consistent with it, and it makes some sort of sense. Much of Scala's type inference mechanics are implementation defined rather than spec'ed and this is probably one of the least surprising and problematic instances of that.</p>
15,742,231
How to add event in native IOS Calendar
<p>I want to open native IOS calendar(ical) from my application and add event. Is there any way i can open calendar for particular event?</p> <p>I also follow <a href="https://stackoverflow.com/questions/6647725/open-iphone-calendar-app-programmatically">Open iphone calendar app programmatically</a> but not yet succeeded.</p>
15,743,261
3
2
null
2013-04-01 11:04:14.043 UTC
12
2021-11-15 07:16:02.97 UTC
2017-05-23 12:24:59.333 UTC
user529758
-1
null
1,294,801
null
1
10
ios|icalendar|uidocumentinteraction
15,533
<p>See the <a href="http://developer.apple.com/library/ios/#documentation/DataManagement/Conceptual/EventKitProgGuide/Introduction/Introduction.html" rel="noreferrer">Calendar and Reminders Programming Guide</a>. But the basic process is:</p> <ol> <li><p>Add the <code>EventKit.Framework</code> and <code>EventKitUI.Framework</code> to your project. (See <a href="http://developer.apple.com/library/mac/#recipes/xcode_help-project_editor/Articles/AddingaLibrarytoaTarget.html" rel="noreferrer">Linking to a Library or Framework</a>.)</p></li> <li><p>Import the header:</p> <pre><code>#import &lt;EventKitUI/EventKitUI.h&gt; </code></pre></li> <li><p>If creating an event, you use :</p> <pre><code>- (IBAction)didPressCreateEventButton:(id)sender { EKEventStore *store = [[EKEventStore alloc] init]; if([store respondsToSelector:@selector(requestAccessToEntityType:completion:)]) { // iOS 6 [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) { if (granted) { dispatch_async(dispatch_get_main_queue(), ^{ [self createEventAndPresentViewController:store]; }); } }]; } else { // iOS 5 [self createEventAndPresentViewController:store]; } } - (void)createEventAndPresentViewController:(EKEventStore *)store { EKEvent *event = [self findOrCreateEvent:store]; EKEventEditViewController *controller = [[EKEventEditViewController alloc] init]; controller.event = event; controller.eventStore = store; controller.editViewDelegate = self; [self presentViewController:controller animated:YES completion:nil]; } </code></pre></li> <li><p>Your view controller should conform to the <code>EKEventEditViewDelegate</code> protocol:</p> <pre><code>@interface ViewController () &lt;EKEventEditViewDelegate&gt; </code></pre> <p>and implement the <code>didCompleteWithAction</code> method:</p> <pre><code>- (void)eventEditViewController:(EKEventEditViewController *)controller didCompleteWithAction:(EKEventEditViewAction)action { [self dismissViewControllerAnimated:YES completion:nil]; } </code></pre></li> <li><p>You can obviously create your event any way you want. For example, this is looks for an event in the next week with the appropriate title, and if it doesn't find it, create a new event (hour long event that starts in four hours):</p> <pre><code>- (EKEvent *)findOrCreateEvent:(EKEventStore *)store { NSString *title = @"My event title"; // try to find an event EKEvent *event = [self findEventWithTitle:title inEventStore:store]; // if found, use it if (event) return event; // if not, let's create new event event = [EKEvent eventWithEventStore:store]; event.title = title; event.notes = @"My event notes"; event.location = @"My event location"; event.calendar = [store defaultCalendarForNewEvents]; NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *components = [[NSDateComponents alloc] init]; components.hour = 4; event.startDate = [calendar dateByAddingComponents:components toDate:[NSDate date] options:0]; components.hour = 1; event.endDate = [calendar dateByAddingComponents:components toDate:event.startDate options:0]; return event; } - (EKEvent *)findEventWithTitle:(NSString *)title inEventStore:(EKEventStore *)store { // Get the appropriate calendar NSCalendar *calendar = [NSCalendar currentCalendar]; // Create the start range date components NSDateComponents *oneDayAgoComponents = [[NSDateComponents alloc] init]; oneDayAgoComponents.day = -1; NSDate *oneDayAgo = [calendar dateByAddingComponents:oneDayAgoComponents toDate:[NSDate date] options:0]; // Create the end range date components NSDateComponents *oneWeekFromNowComponents = [[NSDateComponents alloc] init]; oneWeekFromNowComponents.day = 7; NSDate *oneWeekFromNow = [calendar dateByAddingComponents:oneWeekFromNowComponents toDate:[NSDate date] options:0]; // Create the predicate from the event store's instance method NSPredicate *predicate = [store predicateForEventsWithStartDate:oneDayAgo endDate:oneWeekFromNow calendars:nil]; // Fetch all events that match the predicate NSArray *events = [store eventsMatchingPredicate:predicate]; for (EKEvent *event in events) { if ([title isEqualToString:event.title]) { return event; } } return nil; } </code></pre></li> </ol>
5,307,283
Exception in thread "AWT-EventQueue-0"?
<p>I'm working on a simple calculator program using java and javax.swing</p> <p>Basically, when you press a button, the program is supposed to fetch the function of that button (number or operation) and display it in the textArea.</p> <p>The whole logic for the calculator itself doesn't matter. Also, there's a <em>clear</em> menu item that clears all the text in textArea.</p> <p>However, every time a press a button, I get the following error:</p> <blockquote> <p>Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at calculator.CalculatorGUI.actionPerformed(CalculatorGUI.java:106)`</p> </blockquote> <p>I'm also getting a similar error when I press the <strong>clear</strong> menu item, it seems like java doesn't like it when I want to change the text in the text area.</p> <p>Here's my code: (<strong>Line 106</strong> is in the <code>actionPerfomed</code> method, I've labeld it for your convenience)</p> <pre><code>public class CalculatorGUI implements ActionListener { // The calculator for actually calculating! // private RPNCalculator calculator; // The main frame for the GUI private JFrame frame; // The menubar for the GUI private JMenuBar menuBar; // The textbox private JTextArea textArea; private JScrollPane scrollArea; // Areas for numbers and operators private JPanel numKeysPane; private JPanel opKeysPane; private String input; final String[] numbers = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" }; final String[] operations = { "+", "-", "*", "/" }; /** * Constructor */ public CalculatorGUI() { // Initialize the calculator calculator = new RPNCalculator(); } /** * Initialize and display the calculator */ public void showCalculator() { String buttonValue; JButton button; JMenu menu; JMenuItem menuItem; // Create the main GUI components frame = new JFrame("RPN Calculator"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); numKeysPane = new JPanel(new GridLayout(4, 3)); opKeysPane = new JPanel(new GridLayout(2, 2)); initializeMenu(); initializeNumberPad(); initializeOps(); JTextArea textArea = new JTextArea(); textArea.setEditable(false); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); JScrollPane scrollArea = new JScrollPane(textArea); // Create the components to go into the frame and // stick them in a container named contents frame.getContentPane().add(numKeysPane, BorderLayout.CENTER); frame.getContentPane().add(scrollArea, BorderLayout.NORTH); frame.getContentPane().add(opKeysPane, BorderLayout.LINE_END); // Finish setting up the frame, and show it. frame.pack(); frame.setVisible(true); } /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent e) { String s = (String)e.getActionCommand(); // calculator.performCommand(s); textArea.append(s + " "); // &lt;&lt;--- THIS IS LINE 106 } /** * Initialize the number pad for the calculator */ private void initializeNumberPad() { JButton button; for (int i = 0; i &lt; numbers.length; i++) { button = new JButton(numbers[i]); button.addActionListener(this); numKeysPane.add(button); } } private void initializeOps(){ JButton button; for (int i = 0; i &lt; operations.length; i++){ button = new JButton(operations[i]); button.addActionListener(this); opKeysPane.add(button); } } /** * Initialize the menu for the GUI */ private void initializeMenu() { JMenu menu; JMenuItem menuItem; JMenuItem menuItem2; // Create a menu with one item, Quit menu = new JMenu("Calculator"); menuItem = new JMenuItem("Quit"); // When quit is selected, destroy the application menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // A trace message so you can see this // is invoked. System.err.println("Close window"); frame.setVisible(false); frame.dispose(); } }); menuItem2 = new JMenuItem("Clear"); menuItem2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ textArea.setText(""); } }); menu.add(menuItem2); menu.add(menuItem); // Create the menu bar menuBar = new JMenuBar(); menuBar.add(menu); frame.setJMenuBar(menuBar); } /** * Helper method for displaying an error as a pop-up * @param message The message to display */ private static void errorPopup(String message) { JOptionPane.showMessageDialog(null, message); } } </code></pre> <p>Any help would be greatly appreciated! Thanks!</p>
5,307,339
2
2
null
2011-03-15 03:41:43.587 UTC
2
2019-01-31 15:48:12.047 UTC
2019-01-31 15:48:12.047 UTC
null
6,047,266
null
591,578
null
1
7
java|swing
82,943
<p>You don't ever initialize the <code>JTextArea</code> member field called <code>textArea</code>. You are shadowing the member field in your declaration. Try this:</p> <pre><code> textArea = new JTextArea(); textArea.setEditable(false); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); </code></pre> <p>instead of</p> <pre><code> JTextArea textArea = new JTextArea(); textArea.setEditable(false); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); </code></pre>
16,089,958
What does $%,.2f represent?
<p>I am currently reading the Deitel's book on Java, and came across this code in one of their programs:</p> <pre><code>public String toString() { return String.format( "%s: %s\n%s: $%,.2f; %s: %.2f", "commission employee", super.toString(), "gross sales", getGrossSales(), "commission rate", getCommissionRate() ); } </code></pre> <p>As the title says, what does the "$%," in front of the ".2f" represent? I already know what a .2f means.</p>
16,090,011
3
0
null
2013-04-18 17:54:55.917 UTC
0
2013-04-18 18:03:37.187 UTC
null
null
null
null
1,688,755
null
1
4
java|printf
62,332
<p>The <code>$</code> character means nothing special here. It's just a literal <code>$</code> to show up in the string. The <code>%</code> character takes it's usual meaning here -- to substitute with a value (here, with 2 decimal places).</p> <p>Note that it's possible for the <code>$</code> character to have meaning after the <code>%</code> character. Please see the "Argument Index" section of the <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html" rel="noreferrer"><code>Formatter</code></a> javadocs for details.</p>
521,554
Unable to get ASP.Net UpdateProgress to display
<p>I'm trying to display an update progress loading image whenever my update panel does it's Ajax thing. I've looked around at tutorials and it seems really straightforward but I'm having no luck. Here is pretty much what I have...</p> <pre><code>&lt;div id="panelWrapper"&gt; &lt;asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"&gt; &lt;ContentTemplate&gt; &lt;asp:UpdateProgress ID="TaskUpdateProgress" runat="server" DynamicLayout="False" AssociatedUpdatePanelID="UpdatePanel1" DisplayAfter="0"&gt; &lt;ProgressTemplate&gt; &lt;asp:Image ImageUrl="~/Images/ajax-loader.gif" Width="16px" Height="16px" runat="server" ID="TaskLoadingImage"/&gt; &lt;/ProgressTemplate&gt; &lt;/asp:UpdateProgress&gt; &lt;div id="UrlDiv" class="URLNotification"&gt; &lt;asp:Label ID="UrlLabel" runat="server" Text="URL:" AssociatedControlID="Url" /&gt; &lt;asp:HyperLink ID="Url" runat="server" Text="Click &amp;quotGenerate" to create the URL." /&gt; &lt;/div&gt; &lt;br /&gt; &lt;asp:CheckBoxList runat="server" ID="IncludeItems" TextAlign="Right"&gt; &lt;asp:ListItem Selected="True"&gt;Include 1&lt;/asp:ListItem&gt; &lt;asp:ListItem Selected="True"&gt;Include 2&lt;/asp:ListItem&gt; &lt;/asp:CheckBoxList&gt; &lt;br /&gt; &lt;div id="buttons" style="display:inline;"&gt; &lt;asp:Button ID="Generate" runat="server" OnClicked="Generate_Clicked" Text="Generate" /&gt; &lt;asp:Button ID="Add" runat="server" OnClientClick="add();" Text="Add"/&gt; &lt;/div&gt; &lt;/ContentTemplate&gt; &lt;/asp:UpdatePanel&gt; </code></pre> <p></p> <p>I also have some absolute positioning styling in a stylesheet. I've tried a bunch of variations of what you see here and have not found much good information as to what may be the issue. Any ideas? If you need anything else, let me know. </p> <p><b>EDIT:</b> The only new information I've found is that...<br /><br /> "In the following scenarios, the UpdateProgress control will not display automatically:</p> <p>The UpdateProgress control is associated with a specific update panel, but the asynchronous postback results from a control that is not inside that update panel.</p> <p>The UpdateProgress control is not associated with any UpdatePanel control, and the asynchronous postback does not result from a control that is not inside an UpdatePanel and is not a trigger. For example, the update is performed in code."</p> <p>I'm pretty confident neither of these fit into my case. All that is happening is the button (which is inside the update panel) is clicked calling some code behind which set's the URL text to be reloaded for the update panel.</p>
521,984
7
1
null
2009-02-06 18:30:12.037 UTC
1
2019-12-19 17:46:27.32 UTC
2009-02-06 19:13:19.5 UTC
Carter
49,294
Carter
49,294
null
1
7
asp.net|ajax|updatepanel|loader
40,429
<p>I guess I figured out what was going on. The issue wasn't with anything I was doing wrong with the UpdateProgress or Panel. It was that I had other stuff loading in the background that was apparently holding up the UpdatePanel's Ajaxyness. </p> <p>So basically what happened was that the loading icon wouldn't show up on the initial page load. I realized this because I actually waited till after everything on the page was completely loaded to fire off the button. Sure enough the loader showed up. </p> <p>I assumed that the update panel refresh would at least be requested the instant the click event was heard so the loader icon would immediately show during the time other stuff is loading. This doesn't appear to be the case though... </p>
330,010
How do I show a caret (^) in math mode in LaTeX?
<p>I'm trying to display a caret (<code>^</code>) in math mode in LaTeX to represent the exclusive or operation implemented in the "C languages". By default, <code>^</code> is for creating a superscript in math mode. The closest I can seem to get is by using <code>\wedge</code>, which isn't the same.</p>
330,071
7
4
null
2008-12-01 03:59:10.57 UTC
3
2012-10-27 02:57:56.297 UTC
2011-09-20 12:50:11.82 UTC
Jonathan Leffler
496,830
Anthony Cramp
488
null
1
20
latex|math-mode
46,570
<p>You might want to use the common symbol for exclusive or instead, \oplus (but give it a proper name with something like <code>\newcommand\XOR{\oplus}</code>). </p> <p>The caret is a bit too small to be noticeable as a binary operator. However, if you do insist using a caret instead, use this:</p> <pre><code>\newcommand\XOR{\mathbin{\char`\^}} $x \XOR y$ </code></pre> <p>The <code>\mathbin</code> puts the right spacing around the symbol for a binary operator, and the <code>\char</code> ensures that the glyph is obtained from the roman font.</p>
620,841
How to hide the Dock icon
<p>I want to make a preference for hiding the Dock icon and showing an <code>NSStatusItem</code>. I can create the StatusItem but I don't know how to remove the icon from Dock. :-/</p> <p>Any ideas?</p>
620,950
7
1
null
2009-03-06 23:15:38.837 UTC
57
2021-08-25 08:05:44.053 UTC
2015-10-17 08:10:30.703 UTC
null
43,615
xPablo
59,518
null
1
83
macos|cocoa|icons|dock|lsuielement
42,748
<p>I think you are looking for the <code>LSUIElement</code> in the Info.plist</p> <blockquote> <p>LSUIElement (String). If this key is set to “1”, Launch Services runs the application as an agent application. Agent applications do not appear in the Dock or in the Force Quit window. Although they typically run as background applications, they can come to the foreground to present a user interface if desired.</p> </blockquote> <p>See a short discussion <a href="http://www.cocoabuilder.com/archive/message/cocoa/2009/2/3/229461" rel="noreferrer">here</a> about turning it on/off</p>
257,926
How to blend CMMI and Scrum?
<p>I work in a shop that is certified at CMMI level 5. This certification is important because it gives us access to certain customers and contracts. I'm looking at how to blend Scrum with CMMI. I've found some info on mixing Scrum with CMMI-3, but quite a bit of it is "hand wavy" and wouldn't hold up to intense scrutiny. Specifically, the organizational KPAs seem challenging.</p> <p>What experiences have you had (good and bad) mixing the two processes?</p>
298,199
8
0
null
2008-11-03 04:14:23.907 UTC
10
2012-12-18 18:56:02.463 UTC
null
null
null
Mike Post
20,788
null
1
17
process|agile|scrum|cmmi
4,796
<p>This seems an interesting paper by the SEI folks at Carnegie Mellon (not just about Scrum though):</p> <blockquote> <p>CMMI and Agile are compatible. At the project level, CMMI focuses at a high level of abstraction on what projects do, not on what development methodology is used, while Agile methods focus on how projects develop products. Therefore, CMMI and Agile methods can co-exist</p> </blockquote> <p><a href="http://www.sei.cmu.edu/publications/documents/08.reports/08tn003.html" rel="noreferrer">CMMI or Agile: Why not embrace both (PDF)</a></p>
293,353
Fluent Interfaces - Method Chaining
<p>Method chaining is the only way I know to build fluent interfaces.</p> <p>Here's an example in C#:</p> <pre><code>John john = new JohnBuilder() .AddSmartCode(&quot;c#&quot;) .WithfluentInterface(&quot;Please&quot;) .ButHow(&quot;Dunno&quot;); Assert.IsNotNull(john); [Test] public void Should_Assign_Due_Date_With_7DayTermsVia_Invoice_Builder() { DateTime now = DateTime.Now; IInvoice invoice = new InvoiceBuilder() .IssuedOn(now) .WithInvoiceNumber(40) .WithPaymentTerms(PaymentTerms.SevenDays) .Generate(); Assert.IsTrue(invoice.DateDue == now.AddDays(7)); } </code></pre> <p>So how do others create fluent interfaces. How do you create it? What language/platform/technology is needed?</p>
293,370
8
3
null
2008-11-16 02:13:53.313 UTC
25
2021-02-21 21:36:52.337 UTC
2021-02-21 21:36:52.337 UTC
Chris Pietschmann
1,783,163
john
2,041
null
1
33
language-agnostic|design-patterns|oop|fluent-interface
13,095
<p>You can create a fluent interface in any version of .NET or any other language that is Object Oriented. All you need to do is create an object whose methods always return the object itself.</p> <p>For example in C#:</p> <pre><code>public class JohnBuilder { public JohnBuilder AddSmartCode(string s) { // do something return this; } public JohnBuilder WithfluentInterface(string s) { // do something return this; } public JohnBuilder ButHow(string s) { // do something return this; } } </code></pre> <p>Usage:</p> <pre><code>John = new JohnBuilder() .AddSmartCode("c#") .WithfluentInterface("Please") .ButHow("Dunno"); </code></pre>
1,296,979
How to set the From email address for mailx command?
<p>I am working on a KornShell (ksh) script running on a Solaris server that will send out an email when and error condition is met. I am sending the email via <code>mailx</code>. </p> <p><strong>Question:</strong> How do I set the "From" email address on the <code>mailx</code> command?</p> <p><strong>Current Code:</strong></p> <pre><code>echo ${msg_txt} | mailx -s "Script Failure" ${to_email} </code></pre> <p>Note: The command works fine, however, the "From" is the name of the user I am running the script as and I would like for this to another email address.</p> <p>How would I accomplish this? </p>
1,297,010
8
0
null
2009-08-18 22:43:55.24 UTC
10
2019-08-22 10:41:29.937 UTC
2019-08-22 10:41:29.937 UTC
null
6,290,553
null
150,509
null
1
42
shell|email|solaris|ksh|mailx
159,061
<p>You can use the "-r" option to set the sender address:</p> <pre><code>mailx -r [email protected] -s ... </code></pre>
545,724
using c# .net libraries to check for IMAP messages from gmail servers
<p>Does anyone have any sample code in that makes use of the .Net framework that connects to googlemail servers via IMAP SSL to check for new emails?</p>
545,771
10
1
null
2009-02-13 12:17:53.517 UTC
17
2019-06-29 05:03:38.3 UTC
2019-06-29 05:03:38.3 UTC
Gortok
1,033,581
Paul
51,604
null
1
34
c#|.net|email|imap
115,838
<p>The URL listed here might be of interest to you</p> <p><a href="http://www.codeplex.com/InterIMAP" rel="noreferrer">http://www.codeplex.com/InterIMAP</a> </p> <p>which was extension to </p> <p><a href="http://www.codeproject.com/KB/IP/imaplibrary.aspx?fid=91819&amp;df=90&amp;mpp=25&amp;noise=5&amp;sort=Position&amp;view=Quick&amp;fr=26&amp;select=2562067#xx2562067xx" rel="noreferrer">http://www.codeproject.com/KB/IP/imaplibrary.aspx?fid=91819&amp;df=90&amp;mpp=25&amp;noise=5&amp;sort=Position&amp;view=Quick&amp;fr=26&amp;select=2562067#xx2562067xx</a></p>
1,086,539
Assigning the return value of new by reference is deprecated
<p>I've just got an error.</p> <p>When I try to assign an object like this: </p> <pre><code>$obj_md = new MDB2(); </code></pre> <p>The error I get is "Assigning the return value of new by reference is deprecated". Actually I've been looking for a solution but the only one I've seen is just turn down the politicy of php.ini (error_reporting). I've tried it too, but it didn't work. </p> <p>It's so confusing..I hope you could help me. Thanks in advance.</p>
1,086,559
10
3
null
2009-07-06 11:35:24.72 UTC
9
2019-05-06 09:48:25.877 UTC
2012-07-01 01:09:13.86 UTC
null
367,456
null
104,325
null
1
63
php|php-5.2
226,200
<p>In PHP5 this idiom is deprecated</p> <pre><code>$obj_md =&amp; new MDB2(); </code></pre> <p>You sure you've not missed an ampersand in your sample code? That would generate the warning you state, but it is not required and can be removed.</p> <p>To see why this idiom was used in PHP4, see <a href="https://web.archive.org/web/20091020154940/http://www.php.net/manual/en/oop4.newref.php" rel="nofollow noreferrer">this manual page</a> (note that PHP4 is long dead and this link is to an archived version of the relevant page)</p>
318,144
What is the difference between include and require in Ruby?
<p>My question is similar to "<a href="https://stackoverflow.com/questions/156362/what-is-the-difference-between-include-and-extend-in-ruby">What is the difference between include and extend in Ruby?</a>".</p> <p>What's the difference between <code>require</code> and <code>include</code> in Ruby? If I just want to use the methods from a module in my class, should I <code>require</code> it or <code>include</code> it?</p>
318,170
10
1
null
2008-11-25 17:12:31.187 UTC
175
2020-01-12 22:20:52.187 UTC
2017-05-23 12:26:36.137 UTC
xsl
-1
Owen
2,109
null
1
511
ruby|include|require
267,719
<blockquote> <p><em>What's the difference between "include" and "require" in Ruby?</em></p> <p><strong>Answer:</strong></p> <p>The include and require methods do very different things.</p> <p>The require method does what include does in most other programming languages: run another file. It also tracks what you've required in the past and won't require the same file twice. To run another file without this added functionality, you can use the load method.</p> <p>The include method takes all the methods from another module and includes them into the current module. This is a language-level thing as opposed to a file-level thing as with require. The include method is the primary way to "extend" classes with other modules (usually referred to as mix-ins). For example, if your class defines the method "each", you can include the mixin module Enumerable and it can act as a collection. This can be confusing as the include verb is used very differently in other languages.</p> </blockquote> <p><a href="https://web.archive.org/web/20150405161656/http://ruby.about.com/b/2008/10/23/a-quick-peek-at-ruby-include-vs-require.htm" rel="noreferrer">Source</a></p> <p>So if you just want to use a module, rather than extend it or do a mix-in, then you'll want to use <code>require</code>.</p> <p>Oddly enough, Ruby's <code>require</code> is analogous to C's <code>include</code>, while Ruby's <code>include</code> is almost nothing like C's <code>include</code>.</p>
592,824
C# Help reading foreign characters using StreamReader
<p>I'm using the code below to read a text file that contains foreign characters, the file is encoded ANSI and looks fine in notepad. The code below doesn't work, when the file values are read and shown in the datagrid the characters appear as squares, could there be another problem elsewhere?</p> <pre><code>StreamReader reader = new StreamReader(inputFilePath, System.Text.Encoding.ANSI); using (reader = File.OpenText(inputFilePath)) </code></pre> <p>Thanks</p> <p><strong>Update 1</strong>: I have tried all encodings found under <code>System.Text.Encoding</code>. and all fail to show the file correctly.</p> <p><strong>Update 2</strong>: I've changed the file encoding (resaved the file) to unicode and used <code>System.Text.Encoding.Unicode</code> and it worked just fine. So why did notepad read it correctly? And why didn't <code>System.Text.Encoding.Unicode</code> read the ANSI file?</p>
592,829
11
2
null
2009-02-26 22:55:58.92 UTC
13
2022-03-14 15:38:56.757 UTC
2017-01-27 11:44:59.963 UTC
Scott
4,390,133
Scott
null
null
1
64
c#|encoding
151,581
<p>Yes, it could be with the actual encoding of the file, probably unicode. Try UTF-8 as that is the most common form of unicode encoding. Otherwise if the file ASCII then standard ASCII encoding should work.</p>
154,469
Unnamed/anonymous namespaces vs. static functions
<p>A feature of C++ is the ability to create unnamed (anonymous) namespaces, like so:</p> <pre><code>namespace { int cannotAccessOutsideThisFile() { ... } } // namespace </code></pre> <p>You would think that such a feature would be useless -- since you can't specify the name of the namespace, it's impossible to access anything within it from outside. But these unnamed namespaces <em>are</em> accessible within the file they're created in, as if you had an implicit using-clause to them.</p> <p>My question is, why or when would this be preferable to using static functions? Or are they essentially two ways of doing the exact same thing?</p>
154,482
11
1
null
2008-09-30 19:02:00.437 UTC
199
2021-11-23 16:38:45.667 UTC
2017-12-06 18:57:51.6 UTC
null
545,127
Head Geek
12,193
null
1
613
c++|namespaces
283,770
<p><s>The C++ Standard reads in section 7.3.1.1 Unnamed namespaces, paragraph 2:</s> <s></p> <blockquote> <p>The use of the static keyword is deprecated when declaring objects in a namespace scope, the unnamed-namespace provides a superior alternative. </s></p> </blockquote> <p>Static only applies to names of objects, functions, and anonymous unions, not to type declarations.</p> <h2>Edit:</h2> <p>The decision to deprecate this use of the <code>static</code> keyword (affecting visibility of a variable declaration in a translation unit) has been reversed (<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1012" rel="noreferrer">ref</a>). In this case using a <code>static</code> or an unnamed <code>namespace</code> are back to being essentially two ways of doing the exact same thing. For more discussion please see <a href="https://stackoverflow.com/questions/4726570/deprecation-of-the-static-keyword-no-more">this</a> SO question.</p> <p>Unnamed <code>namespace</code>'s still have the advantage of allowing you to define translation-unit-local types. Please see <a href="https://stackoverflow.com/questions/4422507/superiority-of-unnamed-namespace-over-static">this</a> SO question for more details.</p> <p>Credit goes to <a href="https://stackoverflow.com/users/1220179/mike-percy">Mike Percy</a> for bringing this to my attention.</p>
246,249
Programmatically add custom event in the iPhone Calendar
<p>Is there any way to add iCal event to the iPhone Calendar from the custom App?</p>
17,331,677
11
0
null
2008-10-29 09:39:47.767 UTC
118
2019-05-18 04:03:37.857 UTC
2019-05-14 18:35:34.563 UTC
Mozilla
2,272,431
Mozilla
26,980
null
1
184
ios|iphone|calendar|eventkit
142,794
<p>Based on <a href="https://developer.apple.com/library/archive/documentation/DataManagement/Conceptual/EventKitProgGuide/ReadingAndWritingEvents.html#//apple_ref/doc/uid/TP40004775-SW1" rel="noreferrer">Apple Documentation</a>, this has changed a bit as of iOS 6.0.</p> <p>1) You should request access to the user's calendar via "requestAccessToEntityType:completion:" and execute the event handling inside of a block.</p> <p>2) You need to commit your event now or pass the "commit" param to your save/remove call</p> <p>Everything else stays the same...</p> <p>Add the EventKit framework and <code>#import &lt;EventKit/EventKit.h&gt;</code> to your code.</p> <p>In my example, I have a NSString *savedEventId instance property.</p> <p>To add an event:</p> <pre><code> EKEventStore *store = [EKEventStore new]; [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) { if (!granted) { return; } EKEvent *event = [EKEvent eventWithEventStore:store]; event.title = @"Event Title"; event.startDate = [NSDate date]; //today event.endDate = [event.startDate dateByAddingTimeInterval:60*60]; //set 1 hour meeting event.calendar = [store defaultCalendarForNewEvents]; NSError *err = nil; [store saveEvent:event span:EKSpanThisEvent commit:YES error:&amp;err]; self.savedEventId = event.eventIdentifier; //save the event id if you want to access this later }]; </code></pre> <p>Remove the event:</p> <pre><code> EKEventStore* store = [EKEventStore new]; [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) { if (!granted) { return; } EKEvent* eventToRemove = [store eventWithIdentifier:self.savedEventId]; if (eventToRemove) { NSError* error = nil; [store removeEvent:eventToRemove span:EKSpanThisEvent commit:YES error:&amp;error]; } }]; </code></pre> <p>This adds events to your default calendar, if you have multiple calendars then you'll have find out which one that is</p> <p><em>Swift version</em></p> <p>You need to import the EventKit framework</p> <pre><code>import EventKit </code></pre> <p>Add event</p> <pre><code>let store = EKEventStore() store.requestAccessToEntityType(.Event) {(granted, error) in if !granted { return } var event = EKEvent(eventStore: store) event.title = "Event Title" event.startDate = NSDate() //today event.endDate = event.startDate.dateByAddingTimeInterval(60*60) //1 hour long meeting event.calendar = store.defaultCalendarForNewEvents do { try store.saveEvent(event, span: .ThisEvent, commit: true) self.savedEventId = event.eventIdentifier //save event id to access this particular event later } catch { // Display error to user } } </code></pre> <p>Remove event</p> <pre><code>let store = EKEventStore() store.requestAccessToEntityType(EKEntityTypeEvent) {(granted, error) in if !granted { return } let eventToRemove = store.eventWithIdentifier(self.savedEventId) if eventToRemove != nil { do { try store.removeEvent(eventToRemove, span: .ThisEvent, commit: true) } catch { // Display error to user } } } </code></pre>
1,234,094
How can I generate truly (not pseudo) random numbers with C#?
<p>I know that the Random class can generate pseudo-random numbers but is there a way to generate truly random numbers?</p>
1,234,105
12
1
null
2009-08-05 15:45:54.77 UTC
12
2016-09-22 17:08:23.95 UTC
2009-08-05 16:00:32.06 UTC
null
4,228
null
148,535
null
1
33
c#|algorithm|math
25,759
<p>The answer here has two main sides to it. There are some quite important subtleties to which you should pay due attention...</p> <h2>The Easy Way (for simplicity &amp; practicality)</h2> <p>The <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.aspx" rel="noreferrer"><code>RNGCryptoServiceProvider</code></a>, which is part of the Crypto API in the BCL, should do the job for you. It's still technically a pseudo-random number generated, but the quality of "randomness" is much higher - suitable for cryptographic purposes, as the name might suggest.</p> <p>There are other crypographic APIs with high quality pseudo random generaters available too. Algorithms such as the <a href="http://en.wikipedia.org/wiki/Mersenne_twister" rel="noreferrer">Mersenne twister</a> are quite popular.</p> <p>Comparing this to the <code>Random</code> class in the BCL, it is significantly better. If you plot the numbers generated by <code>Random</code> on a graph, for example, you should be able to recognise patterns, which is a strong sign of weakness. This is largely due to the fact that the algorithm simply uses a seeded lookup table of fixed size.</p> <h2>The Hard Way (for high quality theoretical randomness)</h2> <p>To generate <em>truly</em> random numbers, you need to make use of some natural phenomenon, such as nuclear decay, microscopic temperature fluctuations (CPU temperature is a comparatively conveient source), to name a few. This however is much more difficult and requires additional hardware, of course. I suspect the practical solution (<code>RNGCryptoServiceProvider</code> or such) should do the job perfectly well for you.</p> <p>Now, note that if you <em>really do require truly random numbers</em>, you could use a service such as <a href="http://www.random.org/" rel="noreferrer"><em>Random.org</em></a>, which generates numbers with very high randomness/entropy (based on <em>atmospheric noise</em>). Data is freely available for download. This may nonetheless be unnecessarily complicated for your situation, although it certainly gives you data suitable for scientific study and whatnot.</p> <p>The choice is yours in the end, but at least you should now be able to make an informative decision, being aware of the various types and levels of RNGs.</p>
327,223
Memory Efficient Alternatives to Python Dictionaries
<p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, <code>topDict[word1][word2][word3]</code> returns the number of times these words appear in the text, <code>topDict[word1][word2]</code> returns a dictionary with all the words that appeared following words 1 and 2, etc.</p> <p>This functions correctly, but it is very memory intensive. In my initial tests it used something like 20 times the memory of just storing the triplets in a text file, which seems like an overly large amount of memory overhead.</p> <p>My suspicion is that many of these dictionaries are being created with many more slots than are actually being used, so I want to replace the dictionaries with something else that is more memory efficient when used in this manner. I would strongly prefer a solution that allows key lookups along the lines of the dictionaries.</p> <p>From what I know of data structures, a balanced binary search tree using something like red-black or AVL would probably be ideal, but I would really prefer not to implement them myself. If possible, I'd prefer to stick with standard python libraries, but I'm definitely open to other alternatives if they would work best.</p> <p>So, does anyone have any suggestions for me?</p> <p>Edited to add:</p> <p>Thanks for the responses so far. A few of the answers so far have suggested using tuples, which didn't really do much for me when I condensed the first two words into a tuple. I am hesitant to use all three as a key since I want it to be easy to look up all third words given the first two. (i.e. I want something like the result of <code>topDict[word1, word2].keys()</code>). </p> <p>The current dataset I am playing around with is the most recent version of <a href="http://www.soschildrensvillages.org.uk/charity-news/wikipedia-for-schools.htm" rel="noreferrer">Wikipedia For Schools</a>. The results of parsing the first thousand pages, for example, is something like 11MB for a text file where each line is the three words and the count all tab separated. Storing the text in the dictionary format I am now using takes around 185MB. I know that there will be some additional overhead for pointers and whatnot, but the difference seems excessive.</p>
327,295
12
1
null
2008-11-29 05:33:26.607 UTC
30
2022-01-03 07:45:31.433 UTC
2017-06-28 10:00:36.287 UTC
null
1,685,157
null
121
null
1
48
python|memory|data-structures
21,981
<p>Some measurements. I took 10MB of free e-book text and computed trigram frequencies, producing a 24MB file. Storing it in different simple Python data structures took this much space in kB, measured as RSS from running ps, where d is a dict, keys and freqs are lists, and a,b,c,freq are the fields of a trigram record:</p> <pre><code>295760 S. Lott's answer 237984 S. Lott's with keys interned before passing in 203172 [*] d[(a,b,c)] = int(freq) 203156 d[a][b][c] = int(freq) 189132 keys.append((a,b,c)); freqs.append(int(freq)) 146132 d[intern(a),intern(b)][intern(c)] = int(freq) 145408 d[intern(a)][intern(b)][intern(c)] = int(freq) 83888 [*] d[a+' '+b+' '+c] = int(freq) 82776 [*] d[(intern(a),intern(b),intern(c))] = int(freq) 68756 keys.append((intern(a),intern(b),intern(c))); freqs.append(int(freq)) 60320 keys.append(a+' '+b+' '+c); freqs.append(int(freq)) 50556 pair array 48320 squeezed pair array 33024 squeezed single array </code></pre> <p>The entries marked [*] have no efficient way to look up a pair (a,b); they're listed only because others have suggested them (or variants of them). (I was sort of irked into making this because the top-voted answers were not helpful, as the table shows.)</p> <p>'Pair array' is the scheme below in my original answer (&quot;I'd start with the array with keys being the first two words...&quot;), where the value table for each pair is represented as a single string. 'Squeezed pair array' is the same, leaving out the frequency values that are equal to 1 (the most common case). 'Squeezed single array' is like squeezed pair array, but gloms key and value together as one string (with a separator character). The squeezed single array code:</p> <pre><code>import collections def build(file): pairs = collections.defaultdict(list) for line in file: # N.B. file assumed to be already sorted a, b, c, freq = line.split() key = ' '.join((a, b)) pairs[key].append(c + ':' + freq if freq != '1' else c) out = open('squeezedsinglearrayfile', 'w') for key in sorted(pairs.keys()): out.write('%s|%s\n' % (key, ' '.join(pairs[key]))) def load(): return open('squeezedsinglearrayfile').readlines() if __name__ == '__main__': build(open('freqs')) </code></pre> <p>I haven't written the code to look up values from this structure (use bisect, as mentioned below), or implemented the fancier compressed structures also described below.</p> <p><strong>Original answer:</strong> A simple sorted array of strings, each string being a space-separated concatenation of words, searched using the bisect module, should be worth trying for a start. This saves space on pointers, etc. It still wastes space due to the repetition of words; there's a standard trick to strip out common prefixes, with another level of index to get them back, but that's rather more complex and slower. (The idea is to store successive chunks of the array in a compressed form that must be scanned sequentially, along with a random-access index to each chunk. Chunks are big enough to compress, but small enough for reasonable access time. The particular compression scheme applicable here: if successive entries are 'hello george' and 'hello world', make the second entry be '6world' instead. (6 being the length of the prefix in common.) Or maybe you could get away with using <a href="http://www.python.org/doc/2.5.2/lib/module-zlib.html" rel="nofollow noreferrer">zlib</a>? Anyway, you can find out more in this vein by looking up dictionary structures used in full-text search.) So specifically, I'd start with the array with keys being the first two words, with a parallel array whose entries list the possible third words and their frequencies. It might still suck, though -- I think you may be out of luck as far as batteries-included memory-efficient options.</p> <p>Also, binary tree structures are <em>not</em> recommended for memory efficiency here. E.g., <a href="https://dl.acm.org/doi/abs/10.1145/506309.506312" rel="nofollow noreferrer">this paper</a> tests a variety of data structures on a similar problem (unigrams instead of trigrams though) and finds a hashtable to beat all of the tree structures by that measure.</p> <p>I should have mentioned, as someone else did, that the sorted array could be used just for the wordlist, not bigrams or trigrams; then for your 'real' data structure, whatever it is, you use integer keys instead of strings -- indices into the wordlist. (But this keeps you from exploiting common prefixes except in the wordlist itself. Maybe I shouldn't suggest this after all.)</p>
1,126,880
How can I auto increment the C# assembly version via our CI platform (Hudson)?
<p>Myself and my group are horrendous at incrementing assembly version numbers and we frequently ship assemblies with 1.0.0.0 versions. Obviously, this causes a lot of headaches.</p> <p>We're getting a lot better with our practices via our <a href="http://en.wikipedia.org/wiki/Continuous_integration" rel="noreferrer">CI</a> platform and I'd really like to set it up to auto increment the values within the <code>assemblyinfo.cs</code> file so that the versions of our assemblies are auto updated with the code changes in that assembly.</p> <p>I had previously setup (before we found <a href="http://en.wikipedia.org/wiki/Hudson_%28software%29" rel="noreferrer">Hudson</a>) a way to increment the value through either <code>msbuild</code> or the command line (can't remember), but with Hudson, that will update the SVN repository and trigger ANOTHER build. That would result in a slow infinite loop as Hudson polls SVN every hour.</p> <p>Is having Hudson increment the version number a bad idea? What would be an alternative way to do it?</p> <p>Ideally, my criteria for a solution would be one that:</p> <ul> <li>Increments the build number in <code>assemblyinfo.cs</code> before a build</li> <li>Only increments the build number in assemblies that have changed. This may not be possible as Hudson wipes out the project folder every time it does a build</li> <li>Commits the changed assemblyinfo.cs into the code repository (currently <a href="http://en.wikipedia.org/wiki/VisualSVN" rel="noreferrer">VisualSVN</a>)</li> <li>Does not cause Hudson to trigger a new build the next time it scans for changes</li> </ul> <p>Working this out in my head, I could easily come up with a solution to most of this through batch files / commands, but all of my ideas would cause Hudson to trigger a new build the next time it scans. I'm not looking for someone to do everything for me, just point me in the right direction, maybe a technique to get Hudson to ignore certain SVN commits, etc.</p> <p>Everything I've found so far is just an article explaining how to get the version number automatically incremented, nothing takes into account a CI platform that could be spun into an infinite loop.</p>
1,126,895
12
0
null
2009-07-14 17:35:47.39 UTC
52
2016-04-25 16:38:32.43 UTC
2011-09-14 18:55:38.517 UTC
null
10,755
null
49,885
null
1
116
.net|msbuild|continuous-integration|hudson|versioning
120,126
<p>A simple alternative is to let the C# environment increment the assembly version for you by setting the version attribute to <code>major.minor.*</code> (as described in the AssemblyInfo file template.)</p> <p>You may be looking for a more comprehensive solution, though.</p> <p><strong>EDIT</strong> (Response to the question in a comment):</p> <p>From <code>AssemblyInfo.cs</code>:</p> <pre><code>// Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] </code></pre>
832,620
Stripping HTML tags in Java
<p>Is there an existing Java library which provides a method to strip all HTML tags from a String? I'm looking for something equivalent to the <code>strip_tags</code> function in PHP. </p> <p>I know that I can use a regex as described in <a href="https://stackoverflow.com/questions/44078/strip-all-html-tags-except-links">this Stackoverflow question</a>, however I was curious if there may already be a <code>stripTags()</code> method floating around somewhere in the Apache Commons library that can be used.</p>
17,703,395
13
1
null
2009-05-07 02:22:51.747 UTC
12
2018-12-03 09:38:02.033 UTC
2017-05-23 12:26:10.267 UTC
null
-1
null
53,036
null
1
44
java|html
63,261
<p>Use <a href="http://jsoup.org/" rel="noreferrer">JSoup</a>, it's well documented, available on Maven and after a day of spending time with several libraries, for me, it is the best one i can imagine.. My own opinion is, that a job like that, parsing html into plain-text, should be possible in one line of code -> otherwise the library has failed somehow... just saying ^^ So here it is, the one-liner of JSoup - in Markdown4J, something like that is not possible, in Markdownj too, in htmlCleaner this is pain in the ass with somewhat about 50 lines of code...</p> <pre><code>String plain = new HtmlToPlainText().getPlainText(Jsoup.parse(html)); </code></pre> <p>And what you got is real plain-text (not just the html-source-code as a String, like in other libs lol) -> he really does a great job on that. It is more or less the same quality as Markdownify for PHP....</p>
858,181
How to check a not-defined variable in JavaScript
<p>I wanted to check whether the variable is defined or not. For example, the following throws a not-defined error </p> <pre><code>alert( x ); </code></pre> <p>How can I catch this error?</p>
858,193
15
4
null
2009-05-13 14:09:45.407 UTC
320
2022-02-01 20:09:08.63 UTC
2017-03-03 19:35:58.86 UTC
null
2,680,216
null
104,003
null
1
1,024
javascript|variables|undefined
1,322,148
<p>In JavaScript, <code>null</code> is an object. There's another value for things that don't exist, <code>undefined</code>. The DOM returns <code>null</code> for almost all cases where it fails to find some structure in the document, but in JavaScript itself <code>undefined</code> is the value used.</p> <p>Second, no, there is not a direct equivalent. If you really want to check for specifically for <code>null</code>, do:</p> <pre><code>if (yourvar === null) // Does not execute if yourvar is `undefined` </code></pre> <p>If you want to check if a variable exists, that can only be done with <code>try</code>/<code>catch</code>, since <code>typeof</code> will treat an undeclared variable and a variable declared with the value of <code>undefined</code> as equivalent.</p> <p>But, to check if a variable is declared <em>and</em> is not <code>undefined</code>:</p> <pre><code>if (yourvar !== undefined) // Any scope </code></pre> <p>Previously, it was necessary to use the <code>typeof</code> operator to check for undefined safely, because it was possible to reassign <code>undefined</code> just like a variable. The old way looked like this:</p> <pre><code>if (typeof yourvar !== 'undefined') // Any scope </code></pre> <p>The issue of <code>undefined</code> being re-assignable was fixed in ECMAScript 5, which was released in 2009. You can now safely use <code>===</code> and <code>!==</code> to test for <code>undefined</code> without using <code>typeof</code> as <code>undefined</code> has been read-only for some time.</p> <p>If you want to know if a member exists independent but don't care what its value is:</p> <pre><code>if ('membername' in object) // With inheritance if (object.hasOwnProperty('membername')) // Without inheritance </code></pre> <p>If you want to to know whether a variable is <a href="https://developer.mozilla.org/en-US/docs/Glossary/Truthy" rel="noreferrer">truthy</a>:</p> <pre><code>if (yourvar) </code></pre> <p><a href="http://lists.evolt.org/archive/Week-of-Mon-20050214/099714.html" rel="noreferrer">Source</a></p>
205,945
Why does the C++ STL not provide any "tree" containers?
<p>Why does the C++ STL not provide any "tree" containers, and what's the best thing to use instead?</p> <p>I want to store a hierarchy of objects as a tree, rather than use a tree as a performance enhancement...</p>
205,985
15
4
null
2008-10-15 18:52:42.11 UTC
112
2022-01-28 23:05:33.51 UTC
2020-07-29 00:23:08.957 UTC
Roddy
3,197,387
Roddy
1,737
null
1
417
c++|data-structures|tree|stl
248,869
<p>There are two reasons you could want to use a tree:</p> <p>You want to mirror the problem using a tree-like structure:<br> For this we have <a href="https://www.boost.org/doc/libs/1_70_0/libs/graph/doc/index.html" rel="noreferrer">boost graph library</a></p> <p>Or you want a container that has tree like access characteristics For this we have</p> <ul> <li><a href="https://en.cppreference.com/w/cpp/container/map" rel="noreferrer"><code>std::map</code></a> (and <a href="https://en.cppreference.com/w/cpp/container/multimap" rel="noreferrer"><code>std::multimap</code></a>)</li> <li><a href="https://en.cppreference.com/w/cpp/container/set" rel="noreferrer"><code>std::set</code></a> (and <a href="https://en.cppreference.com/w/cpp/container/multiset" rel="noreferrer"><code>std::multiset</code></a>)</li> </ul> <p>Basically the characteristics of these two containers is such that they practically have to be implemented using trees (though this is not actually a requirement).</p> <p>See also this question: <a href="https://stackoverflow.com/questions/181630/whats-a-good-and-stable-c-tree-implementation">C tree Implementation</a></p>
1,097,522
Select elements by attribute
<p>I have a collection of checkboxes with generated ids and some of them have an extra attribute. Is it possible to use JQuery to check if an element has a specific attribute? For example, can I verify if the following element has the attribute "myattr"? The value of the attribute can vary.</p> <pre><code>&lt;input type="checkbox" id="A" myattr="val_attr"&gt;A&lt;/input&gt; </code></pre> <p>For example how can I get a collection of all checkboxes that have this attribute without checking one by one? Is this possible?</p>
1,097,559
17
3
null
2009-07-08 11:39:24.843 UTC
55
2022-03-21 22:12:54.503 UTC
2015-10-09 10:15:17.25 UTC
null
3,545,094
null
105,992
null
1
253
jquery|attributes
259,293
<p>Do you mean can you select them? If so, then yes:</p> <pre><code>$(":checkbox[myattr]") </code></pre>
1,288,046
How can I get my webapp's base URL in ASP.NET MVC?
<p>How can I quickly determine what the root URL is for my ASP.NET MVC application? I.e., if IIS is set to serve my application at <a href="http://example.com/foo/bar" rel="noreferrer">http://example.com/foo/bar</a>, then I'd like to be able to get that URL in a reliable way that doesn't involve getting the current URL from the request and chopping it up in some fragile way that breaks if I re-route my action.</p> <p>The reason that I need the base URL is that this web application calls another one that needs the root to the caller web application for callback purposes.</p>
1,288,383
27
0
null
2009-08-17 13:47:41.693 UTC
79
2020-09-17 17:03:15.373 UTC
null
null
null
null
2,354
null
1
328
.net|asp.net|asp.net-mvc|iis
361,675
<p>Assuming you have a Request object available, you can use:</p> <pre><code>string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~")); </code></pre> <p>If it's not available, you can get to it via the context:</p> <pre><code>var request = HttpContext.Current.Request </code></pre>
6,678,411
Javascript - Ternary Operator with Multiple Statements
<p>Is this valid JavaScript? I saw an example where someone used commas in the ternary operator conditions, and it was marked as an error in my editor, and the example didn't run in Chrome. However, it did run in Firefox. Once I converted all the ternary statements to if/else statements, the app ran on Chrome. </p> <pre><code>a!==b ? (a=1, b=2) : (a=2, b=1) </code></pre> <p>Edit:</p> <p>This is the actual statement in the code:</p> <pre><code>a!==0?b&lt;0?(h=b/a,e=h-1,f=-2*b+2*a*e,i=-2*b+2*a*h,d=2*h*a-2*b-2*a):(h=b/a,e=h+1,f=2*b-2*a*e,i=2*b-2*a*h,d=-2*h*a+2*b):d=h=e=f=i=0 </code></pre>
6,678,457
5
0
null
2011-07-13 11:53:11.31 UTC
29
2020-10-26 20:53:49.783 UTC
2011-07-13 12:16:22.4 UTC
null
131,640
null
131,640
null
1
76
javascript
108,759
<p>Yes, it's valid, and it runs fine in Chrome:</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var a, b, c; a = 6; b = 7; c = a !== b ? (a = 1, b = 2) : (a = 2, b = 1); console.log("a = " + a); console.log("b = " + b); console.log("c = " + c);</code></pre> </div> </div> </p> <p>I'm not saying it's a remotely good idea in code <em>humans</em> are meant to read. :-) I expect jamietre is correct in the comments when he/she says it looks like the result of minification.</p> <p>The <a href="http://www.ecma-international.org/ecma-262/7.0/index.html#sec-comma-operator" rel="noreferrer">comma operator</a> is a binary operator (an operator accepting two operands). It evaluates its left-hand operand (thus causing any side-effects it has, such as assignment), throws that result away, then evalutes its right-hand operand (thus causing its side-effects if any) and takes that result as its result value. If you have multiple comma operators in a row, the overall expression is evaluated in order, left-to-right, with the final result being the value resulting from the right-most operand evaluation.</p> <p>And of course, you know the conditional operator (a ternary operator&nbsp;&mdash; one accepting three operands) is used to pick one of two sub-expressions to evaluate, on the basis of an initial expression.</p> <p>So that line is very...expressive...what with a total of <em>seven</em>* different expressions inside it.</p> <p>So in that example, the result of the overall expression is 2 if <code>a !== b</code> initially, or <code>1</code> if <code>a === b</code> initially, with the side-effects of setting <code>a</code> and <code>b</code>.</p> <p>It's the side effects that make it, in my view, a questionable choice. And of course, there's no reason to use the comma operator if the left-hand operand <em>doesn't</em> have side effects.</p> <hr> <p>* Yes, <em>seven</em> of 'em packed into that overall ternary:</p> <ul> <li><code>a !== b</code></li> <li>the first comma expression</li> <li><code>a = 1</code></li> <li><code>b = 2</code></li> <li>the second comma expression</li> <li><code>a = 2</code></li> <li><code>b = 1</code></li> </ul> <hr> <p>Re your edit with the actual statement, that one works too:</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function test(a) { var b = 7, d = 1, e = 2, f = 3, g = 4, h = 5, i = 6; a!==0?b&lt;0?(h=b/a,e=h-1,f=-2*b+2*a*e,i=-2*b+2*a*h,d=2*h*a-2*b-2*a):(h=b/a,e=h+1,f=2*b-2*a*e,i=2*b-2*a*h,d=-2*h*a+2*b):d=h=e=f=i=0; console.log("a = " + a); console.log("b = " + b); console.log("d = " + d); console.log("e = " + e); console.log("f = " + f); console.log("g = " + g); console.log("h = " + h); console.log("i = " + i); } test(0); test(1);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; }</code></pre> </div> </div> </p> <p>But wow, I hope this is minified, because if a person wrote that, they must <em>really</em> have a thing against anyone who's supposed to maintain it later... ;-)</p>
6,859,348
How do assembly languages depend on operating systems?
<p>As An assembly language implements a symbolic representation of CPU instructions which are independent on OSes while assemblers are always running under some OS, I was wondering how assembly languages depend on operating systems? For example, will assembly languages be the same for the same CPU with different OSes? Thanks!</p>
6,859,572
8
0
null
2011-07-28 12:59:42.543 UTC
9
2022-03-31 09:48:52.227 UTC
null
null
null
null
156,458
null
1
13
assembly|operating-system
8,086
<p>As others have pointed out, system calls and interrupts are different. I can think of another few differences.</p> <p>The instruction set is the same across all OSes on a given processor, but the executable file format might not be. For example, on the x86, Windows uses the PE format, Linux uses ELF, and MacOS uses Mach-O. That means that assemblers on those platforms must produce their output in those formats, which is a difference.</p> <p>Relatedly, the calling convention could also be different across different OSes. That probably only matters where you are writing assembly code that calls or is called by compiled-code routines, or perhaps where you are writing inline assembler in some compiled code. The calling convention governs which registers are used for what purposes during a function call, so different conventions require different use of registers by calling and called code. They also put constraints on the position of the stack pointer, and various other things. As it happens, calling conventions have historically been a rare example of consistency across OSes in many cases: i believe the Windows and UNIX calling conventions are the same on the x86 (and are all based on the venerable UNIX System V ABI specification), and are consistent across OSes on most other architectures. However, the conventions are now different between Windows and UNIX on the x86_64.</p> <p>In addition, there may be differences in the syntax used by the assembly language. Again on the x86, the Windows and Linux assemblers used to use different syntax, with the Windows assembler using a syntax invented by Intel, and the Linux assembler (really, the GNU assembler) using a traditional UNIX syntax invented by AT&amp;T. These syntaxes describe the same instruction set, but are written differently. Nowadays, the GNU assembler can also understand the Intel syntax, so there is less of a difference.</p>
6,317,750
How to measure the a time-span in seconds using System.currentTimeMillis()?
<p>How to convert <code>System.currentTimeMillis();</code> to seconds?</p> <pre><code>long start6=System.currentTimeMillis(); System.out.println(counter.countPrimes(100000000)+" for "+start6); </code></pre> <p>The console shows me <code>5761455 for 1307816001290</code>. I can't read how many seconds that is.</p> <p>Any help?</p>
6,317,765
9
2
null
2011-06-11 18:27:57.523 UTC
19
2021-01-14 14:21:48.017 UTC
2017-04-25 21:22:58.793 UTC
null
193,282
null
760,288
null
1
57
java|milliseconds
263,832
<pre><code>long start = System.currentTimeMillis(); counter.countPrimes(1000000); long end = System.currentTimeMillis(); System.out.println("Took : " + ((end - start) / 1000)); </code></pre> <p><strong>UPDATE</strong></p> <p>An even more accurate solution would be:</p> <pre><code>final long start = System.nanoTime(); counter.countPrimes(1000000); final long end = System.nanoTime(); System.out.println("Took: " + ((end - start) / 1000000) + "ms"); System.out.println("Took: " + (end - start)/ 1000000000 + " seconds"); </code></pre>
6,842,687
The remote end hung up unexpectedly while git cloning
<p>My <code>git</code> client repeatedly fails with the following error after trying to clone the repository for some time.</p> <p>What could be the issue here? </p> <p><strong>Note:</strong> I have registered my SSH key with the GIT hosting provider</p> <pre><code>Receiving objects: 13% (1309/10065), 796.00 KiB | 6 KiB/s fatal: The remote end hung up unexpectedly </code></pre>
6,849,424
41
12
null
2011-07-27 10:12:13.78 UTC
167
2022-01-25 11:43:48.7 UTC
2014-06-19 02:27:26.47 UTC
null
1,075,324
null
136,088
null
1
370
git
516,305
<h3>Quick solution:</h3> <p>With this kind of error, I usually start by raising the <code>postBuffer</code> size by:</p> <pre><code>git config --global http.postBuffer 524288000 </code></pre> <p>(some comments below report having to double the value):</p> <pre><code>git config --global http.postBuffer 1048576000 </code></pre> <p>(For <code>npm publish</code>, <a href="https://stackoverflow.com/users/1540350/martin-braun">Martin Braun</a> reports <a href="https://stackoverflow.com/questions/6842687/the-remote-end-hung-up-unexpectedly-while-git-cloning/6849424#comment113682102_6849424">in the comments</a> setting it to no more than 50 000 000 instead of the default 1 000 000)</p> <p>###More information:</p> <p>From the <a href="https://git-scm.com/docs/git-config" rel="noreferrer"><code>git config</code> man page</a>, <code>http.postBuffer</code> is about:</p> <blockquote> <p>Maximum size in bytes of the buffer used by smart HTTP transports when POSTing data to the remote system.<br /> For requests larger than this buffer size, HTTP/1.1 and <code>Transfer-Encoding: chunked</code> is used to avoid creating a massive pack file locally. Default is 1 MiB, which is sufficient for most requests.</p> </blockquote> <p>Even for the clone, that can have an effect, and in this instance, the <a href="https://stackoverflow.com/users/136088/joe">OP Joe</a> reports:</p> <blockquote> <p>[clone] works fine now</p> </blockquote> <hr /> <p>Note: if something went wrong on the server side, and if the server uses Git 2.5+ (Q2 2015), the error message might be more explicit.<br /> See &quot;<a href="https://stackoverflow.com/a/30696906/6309">Git cloning: remote end hung up unexpectedly, tried changing <code>postBuffer</code> but still failing</a>&quot;.</p> <hr /> <p><a href="https://stackoverflow.com/users/1538225/kulai">Kulai</a> (<a href="https://stackoverflow.com/questions/6842687/the-remote-end-hung-up-unexpectedly-while-git-cloning/6849424#comment52420161_6849424">in the comments</a>) points out to <a href="https://confluence.atlassian.com/pages/viewpage.action?pageId=693897332" rel="noreferrer">this Atlassian Troubleshooting Git page</a>, which adds:</p> <blockquote> <p><code>Error code 56</code> indicates a curl receive the error of <code>CURLE_RECV_ERROR</code> which means there was some issue that prevented the data from being received during the cloning process.<br /> Typically this is caused by a network setting, firewall, VPN client, or anti-virus that is terminating the connection before all data has been transferred.</p> </blockquote> <p>It also mentions the following environment variable, order to help with the debugging process.</p> <pre><code># Linux export GIT_TRACE_PACKET=1 export GIT_TRACE=1 export GIT_CURL_VERBOSE=1 #Windows set GIT_TRACE_PACKET=1 set GIT_TRACE=1 set GIT_CURL_VERBOSE=1 </code></pre> <hr /> <p>With Git 2.25.1 (Feb. 2020), you know more about this <code>http.postBuffer</code> &quot;solution&quot;.</p> <p>See <a href="https://github.com/git/git/commit/7a2dc95cbc25b4b82cff35931f69f8a5aafeb878" rel="noreferrer">commit 7a2dc95</a>, <a href="https://github.com/git/git/commit/1b13e9032f039c8cdb1994dd092ff2ed32af5cf5" rel="noreferrer">commit 1b13e90</a> (22 Jan 2020) by <a href="https://github.com/bk2204" rel="noreferrer">brian m. carlson (<code>bk2204</code>)</a>.<br /> <sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/53a83299c7cf7d101342400a6fcc6ba7650e3612" rel="noreferrer">commit 53a8329</a>, 30 Jan 2020)</sup><br /> (<a href="https://public-inbox.org/git/[email protected]/T/#u" rel="noreferrer">Git Mailing list discussion</a>)</p> <blockquote> <h2><a href="https://github.com/git/git/commit/7a2dc95cbc25b4b82cff35931f69f8a5aafeb878" rel="noreferrer"><code>docs</code></a>: mention when increasing http.postBuffer is valuable</h2> <p><sup>Signed-off-by: brian m. carlson</sup></p> </blockquote> <blockquote> <p>Users in a wide variety of situations find themselves with HTTP push problems.</p> <p>Oftentimes these issues are due to antivirus software, filtering proxies, or other man-in-the-middle situations; other times, they are due to simple unreliability of the network.</p> <p>However, a common solution to HTTP push problems found online is to increase http.postBuffer.</p> <p><strong>This works for none of the aforementioned situations and is only useful in a small, highly restricted number of cases: essentially, when the connection does not properly support HTTP/1.1.</strong></p> <p>Document when raising this value is appropriate and what it actually does, and discourage people from using it as a general solution for push problems, since it is not effective there.</p> </blockquote> <p>So the documentation for <a href="https://github.com/git/git/blob/7a2dc95cbc25b4b82cff35931f69f8a5aafeb878/Documentation/config/http.txt#L195-L209" rel="noreferrer"><code>git config http.postBuffer</code></a> now includes:</p> <blockquote> <h2><code>http.postBuffer</code></h2> </blockquote> <blockquote> <p>Maximum size in bytes of the buffer used by smart HTTP transports when POSTing data to the remote system.<br /> For requests larger than this buffer size, HTTP/1.1 and Transfer-Encoding: chunked is used to avoid creating a massive pack file locally.<br /> Default is 1 MiB, which issufficient for most requests.</p> <p>Note that raising this limit is only effective for disabling chunked transfer encoding and therefore should be used only where the remote server or a proxy only supports HTTP/1.0 or is noncompliant with the HTTP standard.<br /> <strong>Raising this is not, in general, an effective solution for most push problems, but can increase memory consumption significantly since the entire buffer is allocated even for small pushes</strong>.</p> </blockquote>
41,243,355
Visual Studio 2015 generate UML from code
<ul> <li>Windows 10 64-bit </li> <li>Microsoft Visual Studio Enterprise 2015 Version:14.0.25431.01 Update 3</li> </ul> <p>I have a almost finished project and now I need to write a documentation. I found some information in the www which tells to "simply" generate UML from the existing code. </p> <p>At the top Menu is a section with <strong>Architecture</strong> and there I can create <em>new</em> UML diagrams, but I can't import the classes which the project have. In all the other forum entries they was talking about a <strong>Architecture Explorer</strong> where you can simply drag and drop the needed classes and the dependencies are automatically created, but in my case this view is missing.</p> <p>If you have some good advise how to document the software differently, you're welcome.</p>
41,244,428
2
2
null
2016-12-20 13:20:37.517 UTC
3
2017-05-14 16:47:51.303 UTC
2016-12-20 13:24:43.31 UTC
null
13,302
null
4,802,448
null
1
16
c#|visual-studio-2015|uml|class-diagram
44,802
<p>In solution explorer right click and:</p> <p>add > item.. > General > class diagram </p> <p>Then you can fairly easy make a domain model by dragging entity classes in and right click on a few properties and choose: "Show as association"</p>
15,790,501
Why cv2.so missing after opencv installed?
<p>Today I installed opencv 2.4.4 to Ubuntu 12.10</p> <p>But import cv2 not works.</p> <pre><code>root@-:~# python Python 2.7.3 (default, Sep 26 2012, 21:53:58) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import cv2 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named cv2 &gt;&gt;&gt; </code></pre> <p>As I understand cv2.so missed, so python don't see where opencv</p> <pre><code>root@-:~# find / -name "cv.py" /root/opencv-2.4.4/modules/python/src2/cv.py root@-:~# find / -name "cv2.so" root@-:~# </code></pre> <p>My setup steps look like</p> <pre><code>wget http://downloads.sourceforge.net/project/opencvlibrary/opencv-unix/2.4.4/OpenCV-2.4.4a.tar.bz2 tar -xjf OpenCV-2.4.4a.tar.bz2 cd opencv-2.4.4 mkdir release cd release cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_PYTHON_SUPPORT=ON .. make &amp;&amp; make install echo "/usr/local/lib" &gt;&gt; /etc/ld.so.conf.d/opencv.conf ldconfig echo "PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig" &gt;&gt; /etc/bash.bashrc echo "export PKG_CONFIG_PATH" &gt;&gt; /etc/bash.bashrc </code></pre> <p>Where is cv2.so ? And why it was missed ?</p>
16,003,545
9
4
null
2013-04-03 14:42:51.92 UTC
15
2019-01-16 23:38:07.34 UTC
null
null
null
null
1,603,227
null
1
21
opencv
94,936
<p><strong>How to install opencv(cv2) with python bindings in Linux - Ubuntu/Fedora</strong></p> <ol> <li><p>Install gcc, g++/gcc-c++, cmake (apt-get or yum, in case of yum use gcc-c++)</p> <pre><code>apt-get install gcc, g++, cmake </code></pre></li> <li><p>Downlaod latest opencv from <a href="https://opencv.org/" rel="nofollow noreferrer">openCV's website</a></p></li> <li><p>Untar it with</p> <pre><code>tar -xvf opencv-* </code></pre></li> <li><p>Inside the untarred folder make a new folder called <code>release</code></p> <pre><code>mkdir release cd release </code></pre> <p>(or any folder name) and run this command in it</p> <pre><code>cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_NEW_PYTHON_SUPPORT=ON -D BUILD_EXAMPLES=ON .. </code></pre> <p>the <code>..</code> will pull files from the parents folder and will get the system ready for installation on your platform.</p></li> <li><p>in the release folder run</p> <pre><code>make </code></pre></li> <li><p>After about 2-3 mins of make processing when its finished run</p> <pre><code>sudo make install </code></pre></li> <li><p>Export python path</p> <pre><code>export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/site-packages </code></pre></li> </ol> <p>That's it, now go to python and try </p> <pre><code>&gt;&gt;&gt; import cv2 </code></pre> <p>you should not get any error message.</p> <p>Tested on python 2.7, should be virtually similar to python 3.x.</p>
15,763,091
Do these members have unspecified ordering?
<p>A colleague told me that, in the following type, all members have unspecified ordering in memory (relative to one another).</p> <p>I doubt this, because they all have the same access level.</p> <p>Who is correct?</p> <pre><code>struct foo { public: int x; public: int y; public: int z; }; </code></pre>
15,763,092
1
0
null
2013-04-02 11:35:44.37 UTC
5
2013-04-08 12:58:18.827 UTC
null
null
null
null
560,648
null
1
29
c++|c++11|c++03
958
<p>Your colleague is correct for C++03:</p> <blockquote> <p><code>[C++03: 9.2/12]:</code> Nonstatic data members of a (non-union) class declared <strong>without an intervening access-specifier</strong> are allocated so that later members have higher addresses within a class object. The order of allocation of nonstatic data members separated by an access-specifier is unspecified (11.1). <em>[..]</em></p> </blockquote> <p>But you are correct for C++11:</p> <blockquote> <p><code>[C++11: 9.2/14]:</code> Nonstatic data members of a (non-union) class <strong>with the same access control</strong> (Clause 11) are allocated so that later members have higher addresses within a class object. The order of allocation of non-static data members with different access control is unspecified (11). <em>[..]</em></p> </blockquote> <p>(Spot the difference.)</p>
15,651,488
How to pass a template function in a template argument list
<p>Suppose I have a <code>template</code> function:</p> <pre><code>template&lt;typename T&gt; T produce_5_function() { return T(5); } </code></pre> <p>How can I pass this entire <code>template</code> to another <code>template</code>?</p> <p>If <code>produce_5_function</code> was a functor, there would be no problem:</p> <pre><code>template&lt;typename T&gt; struct produce_5_functor { T operator()() const { return T(5); } }; template&lt;template&lt;typename T&gt;class F&gt; struct client_template { int operator()() const { return F&lt;int&gt;()(); } }; int five = client_template&lt; produce_5_functor &gt;()(); </code></pre> <p>but I want to be able to do this with a raw function template:</p> <pre><code>template&lt;??? F&gt; struct client_template { int operator()() const { return F&lt;int&gt;(); } }; int five = client_template&lt; produce_5_function &gt;()(); </code></pre> <p>I suspect the answer is "you cannot do this".</p>
15,651,770
2
0
null
2013-03-27 03:36:47.193 UTC
8
2013-03-27 04:57:11.153 UTC
null
null
null
null
1,774,667
null
1
35
c++|templates|c++11|function-templates
9,899
<blockquote> <p>I suspect the answer is "you cannot do this".</p> </blockquote> <p>Yes, that is the case, you cannot pass a function template as a template argument. From 14.3.3:</p> <blockquote> <p>A template-argument for a template template-parameter shall be the name of a class template or an alias template, expressed as id-expression.</p> </blockquote> <p>The template function needs to be instantiated <em>before</em> you pass it to the other template. One possible solution is to pass a class type that holds a static <code>produce_5_function</code> like so:</p> <pre><code>template&lt;typename T&gt; struct Workaround { static T produce_5_functor() { return T(5); } }; template&lt;template&lt;typename&gt;class F&gt; struct client_template { int operator()() const { return F&lt;int&gt;::produce_5_functor(); } }; int five = client_template&lt;Workaround&gt;()(); </code></pre> <p>Using alias templates, I could get a little closer:</p> <pre><code>template &lt;typename T&gt; T produce_5_functor() { return T(5); } template &lt;typename R&gt; using prod_func = R(); template&lt;template&lt;typename&gt;class F&gt; struct client_template { int operator()(F&lt;int&gt; f) const { return f(); } }; int five = client_template&lt;prod_func&gt;()(produce_5_functor); </code></pre>
25,304,439
Show part of next and previous items with Owl Carousel 2.0
<p>I'm using <a href="https://github.com/OwlFonk/OwlCarousel2" rel="noreferrer">Owl Carousel 2.0</a>. I would like to show one item, a half (or less) of the previous item (left side) and a half (or less) of the next item (right side). Just putting a part of them out on the right and on the left side:</p> <p><img src="https://i.stack.imgur.com/aFk4v.jpg" alt="enter image description here"></p> <p>I've been trying using just CSS (<code>padding</code> and <code>margin</code> negative with the <code>owl-stage-outer</code>) but obviously Javascript override them.</p> <p>Here's my code so far:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('.owl-carousel').owlCarousel({ loop: true, margin: 10, nav: true, responsive: { 0: { items: 1 }, 600: { items: 3 } } })</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.owl-carousel .item h4 { color: #FFF; font-weight: 400; margin-top: 0em; } .owl-carousel .item { height: 10em; background: #4DC7A0; padding: 1em; } .wrapper { width: 40em; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;link href="//cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.carousel.min.css" rel="stylesheet" /&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/owl.carousel.min.js"&gt;&lt;/script&gt; &lt;div class="wrapper"&gt; &lt;div class="owl-carousel"&gt; &lt;div class="item"&gt; &lt;h4&gt;1&lt;/h4&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;h4&gt;2&lt;/h4&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;h4&gt;3&lt;/h4&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;h4&gt;4&lt;/h4&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;h4&gt;5&lt;/h4&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;h4&gt;6&lt;/h4&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;h4&gt;7&lt;/h4&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;h4&gt;8&lt;/h4&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;h4&gt;9&lt;/h4&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;h4&gt;10&lt;/h4&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;h4&gt;11&lt;/h4&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;h4&gt;12&lt;/h4&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
25,348,677
4
4
null
2014-08-14 09:17:51.477 UTC
6
2020-02-10 08:09:24.82 UTC
2017-10-06 16:50:17.973 UTC
null
924,299
null
3,940,627
null
1
30
jquery|css|carousel|owl-carousel|owl-carousel-2
49,052
<p>The easiest way to do this is by using <a href="https://owlcarousel2.github.io/OwlCarousel2/demos/stagepadding.html" rel="noreferrer"><code>stagePadding</code></a>. Demo below:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() { $('.owl-carousel').owlCarousel({ margin: 10, loop: true, items: 1, stagePadding: 100 }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;link href="//cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.carousel.min.css" rel="stylesheet" /&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/owl.carousel.min.js"&gt;&lt;/script&gt; &lt;div class="owl-carousel"&gt; &lt;div class="item"&gt;&lt;img src="//placehold.it/350x150&amp;text=1" /&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;img src="//placehold.it/350x150&amp;text=2" /&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;img src="//placehold.it/350x150&amp;text=3" /&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;img src="//placehold.it/350x150&amp;text=4" /&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;img src="//placehold.it/350x150&amp;text=5" /&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;img src="//placehold.it/350x150&amp;text=6" /&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;img src="//placehold.it/350x150&amp;text=7" /&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;img src="//placehold.it/350x150&amp;text=8" /&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
50,455,988
Facebook pages API: "Page Public Content Access" review screencast
<p>My website uses Facebook Page API to pull public content from a Facebook page, published by the page owner, to create a dynamic blog with a clear link to the Facebook page.</p> <p>You can see it here in action: <a href="https://kc-hrubeho.cz" rel="noreferrer">https://kc-hrubeho.cz</a> (ctrl+F "Facebook"). Yellow button "Načíst další" works as an AJAX pagination. Sorry for the Czech language, this website unfortunately does not have an English version.</p> <p>I'm using this URL to get JSON object of the page content: <code>https://graph.facebook.com/&lt;PAGE-ID&gt;/feed?access_token=&lt;TOKEN&gt;&amp;limit=10&amp;fields=message,link,attachments,created_time,full_picture,picture,timeline_visibility</code></p> <p>Right now it <strong>works</strong>, but <a href="https://developers.facebook.com/docs/apps/review/faqs/#graph-api-3-0" rel="noreferrer">App review FAQ</a> states this:</p> <blockquote> <p><em>My app used to access public content on pages, am I affected by the v3.0 changes?</em></p> <p>Yes. Apps that access content of public pages need to request Page Public Content Access feature and require review by Facebook.</p> </blockquote> <p>Also, there is this notice:</p> <blockquote> <p>In order to maintain your current API access, your app will need to be submitted for review by August 1, 2018.</p> </blockquote> <p>I've filled out the form for review. One of the required items is "the screencast".</p> <blockquote> <p>We need to see your app using Page Public Content Access so we can see that it doesn't violate our policies. Upload a video screencast walkthrough using any method, (even recording with your phone). You must show:</p> <ol> <li>How a person logs in with Facebook</li> <li>How a person sees this feature used in your app</li> </ol> </blockquote> <p>More detailed instructions about the screencast state this however:</p> <blockquote> <p>You do not need to submit your app if it will only be used by you or by a reduced number of people. Any account listed in the Roles tab in your App Dashboard, such as admins, developers and testers, can access all permissions and generate a user or page access token.</p> <p>You can use any of these accounts to test your app and create a screencast.</p> </blockquote> <p>This is incredibly confusing. My questions are:</p> <ol> <li><p>If my code access the Pages API and shows the result on my website, is it "used by reduced number of people"? </p></li> <li><p>If I <em>do not need</em> to create a screencast, how can I apply for a review? Do I even need it (meaning "will my token work after 1st August")?</p></li> <li><p>If I <em>do need</em> a review with a screencast, what exactly should I record in my case? Should I just stitch a few screencasts of my code and the website to a single video? That, imho, sounds just bonkers. :)</p></li> <li><p>Is there a different endpoint all together (which would not require a review <em>or</em> the screencast) that I should use, if I only need to read the data of my own page?</p></li> <li><p>My old applications are working right now (not sure about August 1, see above). For applications with the same purpose (just to read public content of FB page owned by the owner of application) created <em>after</em> all the fuss with reviews, will there be the same rulset as is for the old ones?</p></li> </ol> <p>Thanks in advance!</p> <h2>Edit</h2> <p>This is what I've heard from the group moderator of official FB support group <a href="https://www.facebook.com/groups/fbdevelopers" rel="noreferrer">Facebook Developer Community</a>:</p> <blockquote> <p>You can use an app in dev mode to retrieve the feed for pages you are admin of. [...] I don't know if August 1 will change the current behavior or if the current behavior is even the intended behavior. [...] Actually I never met a person that was able to predict what will happen in 90+ days ... most experts even fail to predict tomorrow's weather ;) Seriously, I don't know ...</p> </blockquote> <p>Very frustrating, but so far the most specific answer I got.</p>
50,608,472
5
10
null
2018-05-21 20:12:37.81 UTC
26
2020-06-30 10:28:12.72 UTC
2018-05-30 13:58:51.28 UTC
null
1,872,494
null
1,872,494
null
1
58
facebook|facebook-opengraph|facebook-page
42,709
<blockquote> <p>If my code access the Pages API and shows the result on my website, is it "used by [a] reduced number of people"?</p> </blockquote> <p>You are most likely the only consumer of the API in your application. Since it's an AJAX call in the background and not a login based application, the "reduced number" situation should apply. </p> <blockquote> <p>If I do not need to create a screencast, how can I apply for a review? Do I even need it (meaning "will my token work after 1st August")?</p> </blockquote> <p>As long as the app developer and page admin roles are shared, switching the app to development mode will ensure it will keep working. </p> <hr> <p><em>"If your app is in dev mode you should be able to get page access tokens with any permission for anybody who has a role on your app. If you just want to manage posts on your own page or the pages of users who have roles on your app, you'll be able to do so in development mode without submitting for app review." - Response from Facebook Developer Support at <a href="https://developers.facebook.com/support/bugs/2029233277148530/" rel="noreferrer">https://developers.facebook.com/support/bugs/2029233277148530/</a> (private report by me)</em></p> <hr> <blockquote> <p>If I do need a review with a screencast, what exactly should I record in my case? Should I just stitch a few screencasts of my code and the website to a single video? That, imho, sounds just bonkers. :)</p> </blockquote> <p>See previous.</p> <blockquote> <p>Is there a different endpoint all together (which would not require a review or the screencast) that I should use, if I only need to read the data of my own page?</p> </blockquote> <p>Using the page feed endpoint (/PAGE_ID/feed), while having a user who both is a developer on the app and has a role on the page should work, as long as the app is in development mode.</p> <blockquote> <p>My old applications are working right now (not sure about August 1, see above). For applications with the same purpose (just to read public content of FB page owned by the owner of application) created after all the fuss with reviews, will there be the same rul[e]set as is for the old ones?</p> </blockquote> <p>The August 1st deadline is for a specific set of permissions </p> <ul> <li>user_friends </li> <li>user_link </li> <li>user_gender</li> <li>user_age_range</li> </ul> <p>It should work the same since these aren't needed to show the page posts. </p> <p>Use a user or page token with manage_pages access, since the app token cannot identify whether you have a role on the page. </p> <p>Yes, this will mean you will have to implement a way to either refresh the user token or ensure the extended page token doesn't invalidate in the background.</p> <pre><code>HTTP GET /page__id_owned/feed?access_token=APP|TOKEN Response #10) To use 'Page Public Content Access'... HTTP GET /page__id_owned/feed?access_token=access_token_no_manage_pages Response #10) To use 'Page Public Content Access'... HTTP GET /page__id_owned/feed?access_token=access_token_manage_pages Response { "data": [ { "created_time": "2018... HTTP GET /page__id_NOT_owned/feed?access_token=access_token_manage_pages #10) To use 'Page Public Content Access'... </code></pre> <p>Public Page Content is not directly related to your use case, that is, you do not use "Public Page Content". This is for a scenario where you are analyzing public content as a data firehose, see the common usage section at <a href="https://developers.facebook.com/docs/apps/review/feature#reference-PAGES_ACCESS" rel="noreferrer">https://developers.facebook.com/docs/apps/review/feature#reference-PAGES_ACCESS</a>.</p> <hr> <p><em>"Page Public Content Access, on the other hand, is an <strong>app-level</strong> feature for <strong>read-only access to anonymized public data</strong> including business metadata, public comments, posts and reviews for a public page (not owned by any developer on your app). <a href="https://developers.facebook.com/docs/apps/review/feature#reference-PAGES_ACCESS" rel="noreferrer">https://developers.facebook.com/docs/apps/review/feature#reference-PAGES_ACCESS</a>" - Response from Facebook Developer Support at <a href="https://developers.facebook.com/support/bugs/2029233277148530/" rel="noreferrer">https://developers.facebook.com/support/bugs/2029233277148530/</a> (private report by me)</em></p> <hr>
22,624,379
How to convert letters to numbers with Javascript?
<p>How could I convert a letter to its corresponding number in JavaScript?</p> <p>For example:</p> <pre class="lang-none prettyprint-override"><code>a = 0 b = 1 c = 2 d = 3 </code></pre> <p>I found this question on <a href="https://stackoverflow.com/questions/8240637/javascript-convert-numbers-to-letters-beyond-the-26-character-alphabet">converting numbers to letters beyond the 26 character alphabet</a>, but it is asking for the opposite. </p> <p>Is there a way to do this without a huge array?</p>
22,624,453
8
2
null
2014-03-25 02:27:55.347 UTC
17
2020-07-19 08:33:27.317 UTC
2017-05-23 10:31:06.357 UTC
null
-1
null
1,799,136
null
1
77
javascript
143,848
<p>You can get a codepoint* from any index in a string using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt"><code>String.prototype.charCodeAt</code></a>. If your string is a single character, you’ll want index <code>0</code>, and the code for <code>a</code> is 97 (easily obtained from JavaScript as <code>'a'.charCodeAt(0)</code>), so you can just do:</p> <pre><code>s.charCodeAt(0) - 97 </code></pre> <p>And in case you wanted to go the other way around, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode"><code>String.fromCharCode</code></a> takes Unicode codepoints* and returns a string.</p> <pre><code>String.fromCharCode(97 + n) </code></pre> <p>* <a href="https://mathiasbynens.be/notes/javascript-unicode">not quite</a></p>
13,544,985
Merge multiple arrays from one array
<p>How to merge multiple arrays from a single array variable ? lets say i have this in <b>one</b> array variable </p> <p><b>Those are in one variable .. </b><br> <code>$array = array(array(1), array(2));</code></p> <pre><code>Array ( [0] =&gt; 1 ) Array ( [0] =&gt; 2 ) </code></pre> <p>how to end up with this </p> <pre><code>Array ( [0] =&gt; 1 [1] =&gt; 2 ) </code></pre>
13,545,109
7
0
null
2012-11-24 19:53:20.773 UTC
1
2017-09-27 21:40:32.137 UTC
2012-11-24 20:00:44.687 UTC
null
749,090
null
749,090
null
1
7
php|arrays|function|merge
42,666
<p>This is the PHP equivalent of javascript <code>Function#apply</code> (generate an argument list from an array):</p> <pre><code>$result = call_user_func_array("array_merge", $input); </code></pre> <p>demo: <a href="http://3v4l.org/nKfjp">http://3v4l.org/nKfjp</a></p>
13,591,334
What actions do I need to take to get a crash dump in ALL error scenarios?
<p>We're on Windows and we want to get a crash dump (possibly using <code>MiniDumpWriteDump</code>) for <em>all</em> scenarios where our application exit's unexpectedly.</p> <p>So far we have identified, and set up, the following:</p> <ul> <li><code>SetUnhandledExceptionFilter</code> for unhandled exception (Win32 as well as "normal" C++ ones.)</li> <li><code>_set_invalid_parameter_handler</code> for the CRT invalid argument handling</li> <li><code>_set_abort_behavior</code>plus a <code>SIGABRT</code> handler to account for calls to <code>abort()</code></li> </ul> <p>Is there anything we missed? (Modulo some code non-legitimately calling <code>ExitProcess</code>, <code>TerminateProcess</code> or one of the <code>exit</code> variants.)</p> <hr> <p>I'll note that this question here is orthogonal to <em>how</em> a crash dump is then obtained. E.g., if you want a crash dump in case of <code>abort</code>, you always must use <code>_set_abort_behaviour</code> because otherwise abort just <code>exit</code>s.</p> <p>I'll also note that on Windows7+, <em>not</em> setting <code>SetUHEF</code> and just setting up the <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb787181(v=vs.85).aspx" rel="nofollow noreferrer">"correct" WER dump settings in the registry</a> is often a viable way.</p>
17,989,985
6
4
null
2012-11-27 19:11:09.73 UTC
8
2018-02-16 07:37:05.087 UTC
2018-02-16 07:37:05.087 UTC
null
321,013
null
321,013
null
1
14
c++|windows|visual-c++|crash-dumps
4,994
<p>I use exactly the ones you've listed, plus <code>_set_purecall_handler</code>, plus this handy snippet of code:</p> <pre><code>void EnableCrashingOnCrashes() { typedef BOOL (WINAPI *tGetPolicy)(LPDWORD lpFlags); typedef BOOL (WINAPI *tSetPolicy)(DWORD dwFlags); static const DWORD EXCEPTION_SWALLOWING = 0x1; const HMODULE kernel32 = LoadLibraryA("kernel32.dll"); const tGetPolicy pGetPolicy = (tGetPolicy)GetProcAddress(kernel32, "GetProcessUserModeExceptionPolicy"); const tSetPolicy pSetPolicy = (tSetPolicy)GetProcAddress(kernel32, "SetProcessUserModeExceptionPolicy"); if(pGetPolicy &amp;&amp; pSetPolicy) { DWORD dwFlags; if(pGetPolicy(&amp;dwFlags)) { // Turn off the filter pSetPolicy(dwFlags &amp; ~EXCEPTION_SWALLOWING); } } } </code></pre> <p>Source: <a href="http://randomascii.wordpress.com/2012/07/05/when-even-crashing-doesnt-work/">http://randomascii.wordpress.com/2012/07/05/when-even-crashing-doesnt-work/</a></p> <p>These other articles on his site also helped me understand this: <a href="http://randomascii.wordpress.com/2011/12/07/increased-reliability-through-more-crashes/">http://randomascii.wordpress.com/2011/12/07/increased-reliability-through-more-crashes/</a> <a href="http://randomascii.wordpress.com/2012/07/22/more-adventures-in-failing-to-crash-properly/">http://randomascii.wordpress.com/2012/07/22/more-adventures-in-failing-to-crash-properly/</a></p>
13,394,201
Why does rake db:migrate sometimes add trailing whitespace to structure.sql?
<p>On some of our developer machines <code>rake db:migrate</code> adds trailing whitespace to <code>structure.sql</code> which is really annoying because every time a change is made to the database we have to first remove all trailing whitespace from the file.</p> <p>Anyone know what could be up with that? Where would the whitespace come from? Has it to do with PostgreSQL or is it something else?</p>
55,917,577
6
8
null
2012-11-15 09:01:14.093 UTC
1
2019-06-24 09:42:52.283 UTC
2015-07-28 04:09:33.227 UTC
null
168,143
null
61,249
null
1
28
ruby-on-rails|postgresql
2,185
<p>It is the best day of my life, and maybe yours:</p> <p>In <strong>PG 11</strong>, this error is not here anymore since <code>Tablespace</code> is not written to the dump. So you can upgrade your PG version and get rid of the hook you had for space deletion.</p>
13,573,384
how to post arbitrary json object to webapi
<p>How do I / is it possible to pass in a json object to a webapi controller (POST) and <em>not</em> have a class to map it to, but rather handle it as arbitrary content?</p> <p>So if I pass in from my client like so:</p> <pre><code> createRecord: function (model, data, callback, callbackParams) { var request = jQuery.ajax({ type: "POST", // default = GET, url: '/api/' + model + '/', data: data, contentType: 'application/json', success: function (msg) { $('#results').text(msg); if (callback) // only fire a callback if it has been specified callback(msg, callbackParams); }, error: function (jqXHR, textStatus) { alert('Request failed: ' + textStatus); } }); } </code></pre> <p>and data is something like:</p> <pre><code>{ "_id" : ObjectId("5069f825cd4c1d590cddf206"), "firstName" : "John", "lastName" : "Smith", "city" : "Vancouver", "country" : "Canada" } </code></pre> <p>My controller will be able to parse it? And next time the data may not match that signature (eg:</p> <pre><code>{ "_id" : ObjectId("5069f825cd4c1d56677xz6"), "company" : "Acme" } </code></pre> <p>In my controller, I have tried:</p> <pre><code>public HttpResponseMessage Post([FromBody]JObject value) </code></pre> <p>and:</p> <pre><code>public HttpResponseMessage Post([FromBody]string value) </code></pre> <p>and (because this is actually to work with a mongo db):</p> <pre><code>public HttpResponseMessage Post([FromBody]BsonDocument value) </code></pre> <p>but it looks like the object mapper wants to map to something other than string...</p>
13,574,011
4
0
null
2012-11-26 21:23:20.487 UTC
8
2017-02-16 00:48:34.4 UTC
null
null
null
null
190,042
null
1
31
c#|json|mongodb|asp.net-web-api
30,191
<p>You can have your post method that takes in a HttpRequestMessage to by pass the model binding logic and you can read the content of the request directly:</p> <pre><code> public HttpResponseMessage Post(HttpRequestMessage req) { var data = req.Content.ReadAsStringAsync().Result; // using .Result here for simplicity... ... } </code></pre> <p>By the way, the reason why the action that takes in JObject doesn't work is because of 'ObjectId("...")' that is used as the value of "_id" in your data...</p>
13,516,476
long double (GCC specific) and __float128
<p>I'm looking for detailed information on <code>long double</code> and <code>__float128</code> in GCC/x86 (more out of curiosity than because of an actual problem).</p> <p>Few people will probably ever need these (I've just, for the first time ever, <em>truly</em> needed a <code>double</code>), but I guess it is still worthwile (and interesting) to know what you have in your toolbox and what it's about.</p> <p>In that light, please excuse my somewhat open questions:</p> <ol> <li>Could someone explain the implementation rationale and intended usage of these types, also in comparison of each other? For example, are they "embarrassment implementations" because the standard allows for the type, and someone might complain if they're only just the same precision as <code>double</code>, or are they intended as first-class types? </li> <li>Alternatively, does someone have a good, usable web reference to share? A Google search on <code>"long double" site:gcc.gnu.org/onlinedocs</code> didn't give me much that's truly useful.</li> <li>Assuming that the common mantra <em>"if you believe that you need double, you probably don't understand floating point"</em> does not apply, i.e. you <em>really</em> need more precision than just <code>float</code>, and one doesn't care whether 8 or 16 bytes of memory are burnt... is it reasonable to expect that one can as well just jump to <code>long double</code> or <code>__float128</code> instead of <code>double</code> without a significant performance impact?</li> <li>The "extended precision" feature of Intel CPUs has historically been source of nasty surprises when values were moved between memory and registers. If actually 96 bits are stored, the <code>long double</code> type should eliminate this issue. On the other hand, I understand that the <code>long double</code> type is mutually exclusive with <code>-mfpmath=sse</code>, as there is no such thing as "extended precision" in SSE. <code>__float128</code>, on the other hand, should work just perfectly fine with SSE math (though in absence of quad precision instructions certainly not on a 1:1 instruction base). Am I right in these assumptions?</li> </ol> <p>(3. and 4. can probably be figured out with some work spent on profiling and disassembling, <em>but maybe someone else had the same thought previously and has already done that work</em>.)</p> <p><strong>Background (this is the TL;DR part):</strong><br> I initially stumbled over <code>long double</code> because I was looking up <code>DBL_MAX</code> in <code>&lt;float.h&gt;</code>, and incidentially <code>LDBL_MAX</code> is on the next line. "Oh look, GCC actually has 128 bit doubles, not that I need them, but... cool" was my first thought. Surprise, surprise: <code>sizeof(long double)</code> returns 12... wait, you mean 16?</p> <p>The C and C++ standards unsurprisingly do not give a very concrete definition of the type. C99 (6.2.5 10) says that the numbers of <code>double</code> are a subset of <code>long double</code> whereas C++03 states (3.9.1 8) that <code>long double</code> has at least as much precision as <code>double</code> (which is the same thing, only worded differently). Basically, the standards leave everything to the implementation, in the same manner as with <code>long</code>, <code>int</code>, and <code>short</code>.</p> <p>Wikipedia says that GCC uses <em>"80-bit extended precision on x86 processors regardless of the physical storage used"</em>.</p> <p>The GCC documentation states, all on the same page, that the size of the type is 96 bits because of the i386 ABI, but no more than 80 bits of precision are enabled by any option (huh? what?), also Pentium and newer processors want them being aligned as 128 bit numbers. This is the default under 64 bits and can be manually enabled under 32 bits, resulting in 32 bits of zero padding.</p> <p>Time to run a test:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;cfloat&gt; int main() { #ifdef USE_FLOAT128 typedef __float128 long_double_t; #else typedef long double long_double_t; #endif long_double_t ld; int* i = (int*) &amp;ld; i[0] = i[1] = i[2] = i[3] = 0xdeadbeef; for(ld = 0.0000000000000001; ld &lt; LDBL_MAX; ld *= 1.0000001) printf("%08x-%08x-%08x-%08x\r", i[0], i[1], i[2], i[3]); return 0; } </code></pre> <p>The output, when using <code>long double</code>, looks somewhat like this, with the marked digits being constant, and all others eventually changing as the numbers get bigger and bigger:</p> <pre><code>5636666b-c03ef3e0-00223fd8-deadbeef ^^ ^^^^^^^^ </code></pre> <p>This suggests that it is <strong>not</strong> an 80 bit number. An 80-bit number has 18 hex digits. I see 22 hex digits changing, which looks much more like a 96 bits number (24 hex digits). It also isn't a 128 bit number since <code>0xdeadbeef</code> isn't touched, which is consistent with <code>sizeof</code> returning 12.</p> <p>The output for <code>__int128</code> looks like it's really just a 128 bit number. All bits eventually flip.</p> <p>Compiling with <code>-m128bit-long-double</code> does <strong>not</strong> align <code>long double</code> to 128 bits with a 32-bit zero padding, as indicated by the documentation. It doesn't use <code>__int128</code> either, but indeed seems to align to 128 bits, padding with the value <code>0x7ffdd000</code>(?!).</p> <p>Further, <code>LDBL_MAX</code>, seems to work as <code>+inf</code> for both <code>long double</code> and <code>__float128</code>. Adding or subtracting a number like <code>1.0E100</code> or <code>1.0E2000</code> to/from <code>LDBL_MAX</code> results in the same bit pattern.<br> Up to now, it was my belief that the <code>foo_MAX</code> constants were to hold the largest representable number that is <em>not</em> <code>+inf</code> (apparently that isn't the case?). I'm also not quite sure how an 80-bit number could conceivably act as <code>+inf</code> for a 128 bit value... maybe I'm just too tired at the end of the day and have done something wrong.</p>
16,360,980
4
3
null
2012-11-22 16:07:20.237 UTC
15
2018-05-31 22:22:14.53 UTC
2017-03-22 17:57:33.817 UTC
null
107,409
null
572,743
null
1
38
gcc|long-double
35,733
<p>Ad 1. </p> <p>Those types are designed to work with numbers with huge dynamic range. The long double is implemented in a native way in the x87 FPU. The 128b double I suspect would be implemented in software mode on modern x86s, as there's no hardware to do the computations in hardware.</p> <p>The funny thing is that it's quite common to do many floating point operations in a row and the intermediate results are not actually stored in declared variables but rather stored in FPU registers taking advantage of full precision. That's why comparison:</p> <pre><code>double x = sin(0); if (x == sin(0)) printf("Equal!"); </code></pre> <p>Is not safe and cannot be guaranteed to work (without additional switches).</p> <p>Ad. 3.</p> <p>There's an impact on the speed depending what precision you use. You can change used the precision of the FPU by using:</p> <pre><code>void set_fpu (unsigned int mode) { asm ("fldcw %0" : : "m" (*&amp;mode)); } </code></pre> <p>It will be faster for shorter variables, slower for longer. 128bit doubles will be probably done in software so will be much slower.</p> <p>It's not only about RAM memory wasted, it's about cache being wasted. Going to 80 bit double from 64b double will waste from 33% (32b) to almost 50% (64b) of the memory (including cache).</p> <p>Ad 4.</p> <blockquote> <p>On the other hand, I understand that the long double type is mutually exclusive with -mfpmath=sse, as there is no such thing as "extended precision" in SSE. __float128, on the other hand, should work just perfectly fine with SSE math (though in absence of quad precision instructions certainly not on a 1:1 instruction base). Am I right under these assumptions?</p> </blockquote> <p>The FPU and SSE units are totally separate. You can write code using FPU at the same time as SSE. The question is what will the compiler generate if you constrain it to use only SSE? Will it try to use FPU anyway? I've been doing some programming with SSE and GCC will generate only single SISD on its own. You have to help it to use SIMD versions. __float128 will probably work on every machine, even the 8-bit AVR uC. It's just fiddling with bits after all.</p> <p>The 80 bit in hex representation is actually 20 hex digits. Maybe the bits which are not used are from some old operation? On my machine, I compiled your code and only 20 bits change in long mode: 66b4e0d2-ec09c1d5-00007ffe-deadbeef</p> <p>The 128-bit version has all the bits changing. Looking at the <code>objdump</code> it looks as if it was using software emulation, there are almost no FPU instructions.</p> <blockquote> <p>Further, LDBL_MAX, seems to work as +inf for both long double and __float128. Adding or subtracting a number like 1.0E100 or 1.0E2000 to/from LDBL_MAX results in the same bit pattern. Up to now, it was my belief that the foo_MAX constants were to hold the largest representable number that is not +inf (apparently that isn't the case?). </p> </blockquote> <p>This seems to be strange...</p> <blockquote> <p>I'm also not quite sure how an 80-bit number could conceivably act as +inf for a 128-bit value... maybe I'm just too tired at the end of the day and have done something wrong.</p> </blockquote> <p>It's probably being extended. The pattern which is recognized to be +inf in 80-bit is translated to +inf in 128-bit float too.</p>
24,369,602
Using an NSTimer in Swift
<p>In this scenario, timerFunc() is never called. What am I missing?</p> <pre><code>class AppDelegate: NSObject, NSApplicationDelegate { var myTimer: NSTimer? = nil func timerFunc() { println("timerFunc()") } func applicationDidFinishLaunching(aNotification: NSNotification?) { myTimer = NSTimer(timeInterval: 5.0, target: self, selector:"timerFunc", userInfo: nil, repeats: true) } } </code></pre>
24,369,735
10
3
null
2014-06-23 15:22:21.167 UTC
8
2019-07-25 10:57:31.823 UTC
null
null
null
null
1,419,236
null
1
48
swift|nstimer
54,331
<p>You can create a scheduled timer which automatically adds itself to the runloop and starts firing:</p> <p><strong>Swift 2</strong></p> <pre><code>NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "timerDidFire:", userInfo: userInfo, repeats: true) </code></pre> <p><strong>Swift 3, 4, 5</strong></p> <pre><code>Timer.scheduledTimer(withTimeInterval: 0.5, target: self, selector: #selector(timerDidFire(_:)), userInfo: userInfo, repeats: true) </code></pre> <p>Or, you can keep your current code, and add the timer to the runloop when you're ready for it:</p> <p><strong>Swift 2</strong></p> <pre><code>let myTimer = NSTimer(timeInterval: 0.5, target: self, selector: "timerDidFire:", userInfo: nil, repeats: true) NSRunLoop.currentRunLoop().addTimer(myTimer, forMode: NSRunLoopCommonModes) </code></pre> <p><strong>Swift 3, 4, 5</strong></p> <pre><code>let myTimer = Timer(timeInterval: 0.5, target: self, selector: #selector(timerDidFire(_:)), userInfo: nil, repeats: true) RunLoop.current.add(myTimer, forMode: RunLoop.Mode.common) </code></pre>
3,842,481
Problem with TemporaryKey.pfx I don't have the password
<p>A client of mine has a problem. He had a Microsoft CRM developper and he left. Now the project remains uncomplete. I've downloaded the source code of the custom applications and I'm not trying to continue the development. I've tried the ClickOne deployment and it pops me with a password input box related to the myapp_TemporaryKey.pfx. I've tried to install on a computer on the network and launch in debugging mode, and I get the same problem, it says :</p> <p>"Cannot import the following key file: . The key file may be password protected. To correct this, try to import the certificate again or import the certificate manually into the current user's personal certificate store."</p> <p>And a second error is: "Importing key file "myapp_TemporaryKey.pfx" was canceled</p> <p>Do you know what can be done to fix that? I have the .PFX file, but not the password. </p>
8,653,563
2
0
null
2010-10-01 19:38:33.98 UTC
3
2020-09-15 06:00:05.58 UTC
null
null
null
null
457,500
null
1
17
c#|visual-studio-2010|dynamics-crm|pfx
40,513
<p>I went to Project Properties --> Signing tab--> then signed my app using the certificate in the ClickOnce section. In my case, the build was successful.</p>
16,313,320
How to call function of another block Magento
<p>I am trying to change the reference block of contact us link..I created all the phtml file and all.. Now in Phtml file when i am calling </p> <pre><code>&lt;?php $_links = $this-&gt;getLinks(); ?&gt; </code></pre> <p>I am getting number of links as 0..because it cant get the object of links.php.. I want to know how can I have reference object of contacts.phtml</p>
16,317,436
4
0
null
2013-05-01 05:41:28.287 UTC
8
2019-01-17 19:40:02.67 UTC
null
null
null
null
2,300,526
null
1
14
magento
40,562
<p>Hi you can do it by creating reference to that Block.Like </p> <pre><code> $cpBlock = $this-&gt;getLayout()-&gt;getBlockSingleton('your block class'); //ect Mage_Catalog_Block_Product_List_Toolbar </code></pre> <p>Than you can easily call every function of that class like <code>$cpBlock-&gt;getLinks();</code>.Other way is using XML block code.Add contact us xml reference just like user2338443 mentioned to your custom xml and than access functions of that block.</p>
16,322,896
TimeZoneInfo.ConvertTimeToUtc issue
<p>We had an issue where one developer creates the below code and it works on his DEV environment. But when it's checked into QA, the code breaks with the below error message:</p> <pre><code>myRecord.UTCStartTime = TimeZoneInfo.ConvertTimeToUtc(myRecord.StartTime, myTimeZone); </code></pre> <blockquote> <p>The conversion could not be completed because the supplied DateTime did not have the Kind property set correctly. For example, when the Kind property is DateTimeKind.Local, the source time zone must be TimeZoneInfo.Local.</p> </blockquote> <p>On my DEV environment, the above code generates the same error as the QA server. I applied the below change to fix the problem:</p> <pre><code>DateTime utcStart = DateTime.SpecifyKind(myRecord.StartTime, DateTimeKind.Unspecified); myRecord.UTCStartTime = TimeZoneInfo.ConvertTimeToUtc(utcStart, myTimeZone); </code></pre> <p>Why does the first code example work on DEV1's environment but break on my DEV environment and on our QA server?</p>
16,323,450
6
0
null
2013-05-01 17:09:57.133 UTC
14
2021-11-28 11:21:55.963 UTC
2013-05-01 17:56:11.983 UTC
null
238,688
null
937,554
null
1
70
c#|.net|datetime
47,607
<p>It depends on how the <code>myRecord.StartTime</code> was originated.</p> <ul> <li>If you got it from <code>DateTime.Now</code>, then it will have a <code>Local</code> kind.</li> <li>If you got it from <code>DateTime.UtcNow</code> then it will have an <code>Utc</code> kind.</li> <li>If you got it from <code>new DateTime(2013,5,1)</code> then it will have an <code>Unspecified</code> kind.</li> </ul> <p>It also depends on where you got <code>myTimeZone</code> from. For example:</p> <ul> <li><code>TimeZoneInfo.Local</code></li> <li><code>TimeZoneInfo.Utc</code></li> <li><code>TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time")</code></li> </ul> <p>The <code>TimeZoneInfo.ConvertTimeToUtc</code> function will only operate if it can match the zone to the kind you give it. If both are local, or both are UTC, then it will work. If you are giving it a specific zone, then the kind should be unspecified. This behavior is <a href="http://msdn.microsoft.com/en-us/library/vstudio/bb495915.aspx">documented on MSDN</a>.</p> <p>You can easily reproduce the exception consistently:</p> <pre><code>var tz = TimeZoneInfo.FindSystemTimeZoneById("Fiji Standard Time"); var utc = TimeZoneInfo.ConvertTimeToUtc(DateTime.Now, tz); </code></pre> <p>Assuming you don't live in Fiji, this will error every time. You basically said, "convert my local time, in some other zone, to utc" - which doesn't make sense.</p> <p>It probably works in your dev environment because the value you're testing for <code>myTimeZone</code> happens to be the local zone for the developer.</p> <p>Regarding your change - sure you can force the kind to be unspecified, and that changes the meaning of what you are doing such that it makes sense. But are you sure this is what you want? What is the <code>.Kind</code> of the date before hand? If it's not already <code>Unspecified</code>, then it is carrying some intent. You should probably go back to the source of this data and make sure it is what you expect.</p> <p>If all of this sounds crazy, mad, frustrating, and bizarre, it's because the <code>DateTime</code> object stinks. Here's some additional reading:</p> <ul> <li><a href="http://noda-time.blogspot.com/2011/08/what-wrong-with-datetime-anyway.html">What's wrong with DateTime anyway?</a></li> <li><a href="http://codeofmatt.com/2013/04/25/the-case-against-datetime-now/">The case against DateTime.Now</a></li> </ul> <p>You might consider using <a href="http://nodatime.org">NodaTime</a> instead. Its API will prevent you from making these types of common mistakes.</p>
17,581,910
How to switch to edit mode of vi on mac terminal
<p>I am new to mac, trying to edit a .gitignore file from the macbook terminal, I type </p> <pre><code> vi .gitignore </code></pre> <p>it opens the file but not letting me switch to edit mode. How does vi switches mode on mac ?</p>
17,581,948
2
3
null
2013-07-10 22:17:37.89 UTC
5
2016-08-13 23:27:29.723 UTC
2013-07-10 22:22:35.963 UTC
null
425,756
null
1,185,422
null
1
15
macos|vim
54,953
<p>On Mac you can more correctly type <code>vim</code> (Vi Improved) instead :)</p> <p>Same as everywhere, <code>i</code> switches to "INSERT" mode and <code>ESC</code> switches back to command mode.</p> <p>A good learning resource for Vim is included in Mac. Simply type <code>vimtutor</code> and it will teach you quickly how to use vim effectively.</p> <p>Another editing option on mac is <code>nano</code> it is a command line text editor that is much easier for those familiar with TextEdit/Notepad.</p>
24,690,357
Add tags around selected text in an element
<p>How can I add <code>&lt;span&gt;</code> tags around selected text within an element?</p> <p>For example, if somebody highlights "John", I would like to add span tags around it.</p> <p>HTML</p> <pre><code>&lt;p&gt;My name is Jimmy John, and I hate sandwiches. My name is still Jimmy John.&lt;/p&gt; </code></pre> <p>JS</p> <pre><code>function getSelectedText() { t = (document.all) ? document.selection.createRange().text : document.getSelection(); return t; } $('p').mouseup(function(){ var selection = getSelectedText(); var selection_text = selection.toString(); console.log(selection); console.log(selection_text); // How do I add a span around the selected text? }); </code></pre> <p><a href="http://jsfiddle.net/2w35p/" rel="noreferrer">http://jsfiddle.net/2w35p/</a></p> <p>There is a identical question here: <a href="https://stackoverflow.com/questions/2236982/jquery-select-text-and-add-span-to-it-in-an-paragraph">jQuery select text and add span to it in an paragraph</a>, but it uses outdated jquery methods (e.g. live), and the accepted answer has a bug.</p>
24,691,115
4
4
null
2014-07-11 04:55:59.277 UTC
13
2014-07-11 06:41:10.95 UTC
2017-05-23 12:32:14.287 UTC
null
-1
null
3,093,497
null
1
20
javascript|jquery
10,643
<p>I have a solution. Get the <code>Range</code> of the selecion and deleteContent of it, then insert a new <code>span</code> in it .</p> <pre><code>$('body').mouseup(function(){ var selection = getSelectedText(); var selection_text = selection.toString(); // How do I add a span around the selected text? var span = document.createElement('SPAN'); span.textContent = selection_text; var range = selection.getRangeAt(0); range.deleteContents(); range.insertNode(span); }); </code></pre> <p>You can see the <a href="http://jsfiddle.net/edisonator/2w35p/35/" rel="noreferrer">DEMO here</a></p> <p><strong>UPDATE</strong></p> <p>Absolutly, the selection will be delete at the same time. So you can add the selection range with js code if you want.</p>
22,233,532
Why does heap sort have a space complexity of O(1)?
<p>I understand that both quick sort and merge sort need <code>O(n)</code> auxiliary space for the temporary sub-arrays that are constructed, and in-place quick sort requires <code>O(log n)</code> auxiliary space for the recursive stack frames. But for heap sort, it seems like it also has a worst case of <code>O(n)</code> auxiliary space to build the temporary heap, even if the nodes are just pointers to the actual elements. </p> <p>I came across this <a href="https://code.google.com/p/combsortcs2p-and-other-sorting-algorithms/wiki/HeapSort#Description_of_the_heap_sort_algorithm" rel="noreferrer">explanation</a> : </p> <blockquote> <p>Only O(1) additional space is required because the heap is built inside the array to be sorted.</p> </blockquote> <p>But I think this means the original array necessarily already had to be implemented as some sort of tree? If the original array was just a vector, it seems memory for a heap would still have to be allocated.</p>
22,234,095
4
2
null
2014-03-06 19:00:13.63 UTC
15
2019-10-20 01:53:34.187 UTC
2014-10-09 20:15:06.177 UTC
null
3,440,545
null
2,450,607
null
1
36
sorting|complexity-theory|time-complexity
26,091
<p>Data in an array can be rearranged into a heap, in place. The algorithm for this is actually surprisingly simple., but I won't go into it here. </p> <p>For a heap sort, you arrange the data so that it forms a heap in place, with the smallest element at the back (<code>std::make_heap</code>). Then you swap the last item in the array (smallest item in the heap), with the first item in the array (a largish number), and then shuffle that large element down the heap until it's in a new proper position and the heap is again a new min heap, with the smallest remaining element in the last element of the array. (<code>std::pop_heap</code>)</p> <pre><code>data: 1 4 7 2 5 8 9 3 6 0 make_heap: [8 7 9 3 4 5 6 2 1 0] &lt;- this is a min-heap, smallest on right pop_heap(1): [0 7 9 3 4 5 6 2 1 8] &lt;- swap first and last elements pop_heap(2): 0 [7 9 3 4 8 6 2 5 1] &lt;- shuffle the 8 down the heap pop_heap(1): 0 1 [9 3 4 8 6 2 5 7] &lt;- swap first and last elements pop_heap(2): 0 1 [9 7 4 8 6 3 5 2] &lt;- shuffle the 7 down the heap etc </code></pre> <p>So no data actually needs to be stored anywhere else, except maybe during the swap step.</p> <p>For visualization, here's that original heap shown in a standard form</p> <pre><code>make_heap 0 2 1 3 4 5 6 8 7 9 pop_heap 8 1 1 2 1 2 8 2 5 3 4 5 6 -&gt; 3 4 5 6 -&gt; 3 4 8 6 7 9 7 9 7 9 </code></pre>
37,358,423
How to redirect page after click on Ok button on sweet alert?
<p>I am able to display sweet alert after the page refresh but I have to click on Ok button which I am getting on sweet alert to redirect the page.Please help me in this.</p> <pre><code>&lt;?php echo '&lt;script type="text/javascript"&gt;'; echo 'setTimeout(function () { swal("WOW!","Message!","success");'; echo '}, 1000);' echo 'window.location.href = "index.php";'; echo '&lt;/script&gt;'; ?&gt; </code></pre>
37,358,510
17
2
null
2016-05-21 02:57:08.723 UTC
7
2022-03-19 23:59:11.1 UTC
2017-05-31 06:56:35.707 UTC
null
5,076,266
user6930268
null
null
1
34
javascript|jquery|sweetalert
202,977
<p>To specify a callback function, you have to use an object as the first argument, and the callback function as the second argument.</p> <pre><code>echo '&lt;script&gt; setTimeout(function() { swal({ title: "Wow!", text: "Message!", type: "success" }, function() { window.location = "redirectURL"; }); }, 1000); &lt;/script&gt;'; </code></pre>
27,158,812
Does this code from "The C++ Programming Language" 4th edition section 36.3.6 have well-defined behavior?
<p>In Bjarne Stroustrup's <em><a href="https://en.wikipedia.org/wiki/The_C%2B%2B_Programming_Language" rel="nofollow noreferrer">The C++ Programming Language</a></em> 4th edition section <code>36.3.6</code> <em>STL-like Operations</em> the following code is used as an example of <a href="http://en.wikipedia.org/wiki/Method_chaining" rel="nofollow noreferrer">chaining</a>:</p> <pre><code>void f2() { std::string s = "but I have heard it works even if you don't believe in it" ; s.replace(0, 4, "" ).replace( s.find( "even" ), 4, "only" ) .replace( s.find( " don't" ), 6, "" ); assert( s == "I have heard it works only if you believe in it" ) ; } </code></pre> <p>The assert fails in <code>gcc</code> (<em><a href="http://coliru.stacked-crooked.com/a/d3d81ff98cab2f5c" rel="nofollow noreferrer">see it live</a></em>) and <code>Visual Studio</code> (<em><a href="http://rextester.com/IFNX5880" rel="nofollow noreferrer">see it live</a></em>), but it does not fail when using <a href="http://en.wikipedia.org/wiki/Clang" rel="nofollow noreferrer">Clang</a> (<em><a href="http://coliru.stacked-crooked.com/a/e6facaa9f18e252f" rel="nofollow noreferrer">see it live</a></em>).</p> <p>Why am I getting different results? Are any of these compilers incorrectly evaluating the chaining expression or does this code exhibit some form of <a href="http://en.wikipedia.org/wiki/Unspecified_behavior" rel="nofollow noreferrer">unspecified</a> or <a href="http://en.wikipedia.org/wiki/Undefined_behavior" rel="nofollow noreferrer">undefined behavior</a>?</p>
27,158,813
2
4
null
2014-11-26 21:02:34.74 UTC
23
2018-12-13 07:55:08.43 UTC
2018-12-13 07:55:08.43 UTC
null
1,708,801
null
1,708,801
null
1
95
c++|c++11|language-lawyer|operator-precedence|unspecified-behavior
11,248
<p>The code exhibits unspecified behavior due to unspecified order of evaluation of sub-expressions although it does not invoke undefined behavior since all side effects are done within functions <a href="http://en.cppreference.com/w/cpp/language/eval_order" rel="nofollow noreferrer">which introduces a sequencing relationship</a> between the side effects in this case.</p> <p>This example is mentioned in the proposal <a href="http://open-std.org/JTC1/SC22/WG21/docs/papers/2014/n4228.pdf" rel="nofollow noreferrer">N4228: Refining Expression Evaluation Order for Idiomatic C++</a> which says the following about the code in the question:</p> <blockquote> <p>[...]This code has been reviewed by C++ experts world-wide, and published (The C++ Programming Language, 4<sup>th</sup> edition.) Yet, its vulnerability to unspecified order of evaluation has been discovered only recently by a tool[...]</p> </blockquote> <p><B>Details</B></p> <p>It may be obvious to many that arguments to functions have an unspecified order of evaluation but it is probably not as obvious how this behavior interacts with chained functions calls. It was not obvious to me when I first analyzed this case and apparently not to all the <em>expert reviewers</em> either. </p> <p>At first glance it may appear that since each <code>replace</code> has to be evaluated from left to right that the corresponding function argument groups must be evaluated as groups from left to right as well. </p> <p>This is incorrect, function arguments have an unspecified order of evaluation, although chaining function calls does introduce a left to right evaluation order for each function call, the arguments of each function call are only sequenced before with respect to the member function call they are part of. In particular this impacts the following calls:</p> <pre><code>s.find( "even" ) </code></pre> <p>and:</p> <pre><code>s.find( " don't" ) </code></pre> <p>which are indeterminately sequenced with respect to:</p> <pre><code>s.replace(0, 4, "" ) </code></pre> <p>the two <code>find</code> calls could be evaluated before or after the <code>replace</code>, which matters since it has a side effect on <code>s</code> in a way that would alter the result of <code>find</code>, it changes the length of <code>s</code>. So depending on when that <code>replace</code> is evaluated relative to the two <code>find</code> calls the result will differ.</p> <p>If we look at the chaining expression and examine the evaluation order of some of the sub-expressions:</p> <pre><code>s.replace(0, 4, "" ).replace( s.find( "even" ), 4, "only" ) ^ ^ ^ ^ ^ ^ ^ ^ ^ A B | | | C | | | 1 2 3 4 5 6 </code></pre> <p>and:</p> <pre><code>.replace( s.find( " don't" ), 6, "" ); ^ ^ ^ ^ D | | | 7 8 9 </code></pre> <p>Note, we are ignoring the fact that <code>4</code> and <code>7</code> can be further broken down into more sub-expressions. So:</p> <ul> <li><code>A</code> is sequenced before <code>B</code> which is sequenced before <code>C</code> which is sequenced before <code>D</code></li> <li><code>1</code> to <code>9</code> are indeterminately sequenced with respect to other sub-expressions with some of the exceptions listed below <ul> <li><code>1</code> to <code>3</code> are sequenced before <code>B</code></li> <li><code>4</code> to <code>6</code> are sequenced before <code>C</code></li> <li><code>7</code> to <code>9</code> are sequenced before <code>D</code></li> </ul></li> </ul> <p>The key to this issue is that:</p> <ul> <li><code>4</code> to <code>9</code> are indeterminately sequenced with respect to <code>B</code></li> </ul> <p>The potential order of evaluation choice for <code>4</code> and <code>7</code> with respect to <code>B</code> explains the difference in results between <code>clang</code> and <code>gcc</code> when evaluating <code>f2()</code>. In my tests <code>clang</code> evaluates <code>B</code> before evaluating <code>4</code> and <code>7</code> while <code>gcc</code> evaluates it after. We can use the following test program to demonstrate what is happening in each case:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; std::string::size_type my_find( std::string s, const char *cs ) { std::string::size_type pos = s.find( cs ) ; std::cout &lt;&lt; "position " &lt;&lt; cs &lt;&lt; " found in complete expression: " &lt;&lt; pos &lt;&lt; std::endl ; return pos ; } int main() { std::string s = "but I have heard it works even if you don't believe in it" ; std::string copy_s = s ; std::cout &lt;&lt; "position of even before s.replace(0, 4, \"\" ): " &lt;&lt; s.find( "even" ) &lt;&lt; std::endl ; std::cout &lt;&lt; "position of don't before s.replace(0, 4, \"\" ): " &lt;&lt; s.find( " don't" ) &lt;&lt; std::endl &lt;&lt; std::endl; copy_s.replace(0, 4, "" ) ; std::cout &lt;&lt; "position of even after s.replace(0, 4, \"\" ): " &lt;&lt; copy_s.find( "even" ) &lt;&lt; std::endl ; std::cout &lt;&lt; "position of don't after s.replace(0, 4, \"\" ): " &lt;&lt; copy_s.find( " don't" ) &lt;&lt; std::endl &lt;&lt; std::endl; s.replace(0, 4, "" ).replace( my_find( s, "even" ) , 4, "only" ) .replace( my_find( s, " don't" ), 6, "" ); std::cout &lt;&lt; "Result: " &lt;&lt; s &lt;&lt; std::endl ; } </code></pre> <p>Result for <code>gcc</code> (<em><a href="http://coliru.stacked-crooked.com/a/a6035cb6e64f038f" rel="nofollow noreferrer">see it live</a></em>)</p> <pre><code>position of even before s.replace(0, 4, "" ): 26 position of don't before s.replace(0, 4, "" ): 37 position of even after s.replace(0, 4, "" ): 22 position of don't after s.replace(0, 4, "" ): 33 position don't found in complete expression: 37 position even found in complete expression: 26 Result: I have heard it works evenonlyyou donieve in it </code></pre> <p>Result for <code>clang</code> (<em><a href="http://coliru.stacked-crooked.com/a/84408d788238bacd" rel="nofollow noreferrer">see it live</a></em>):</p> <pre><code>position of even before s.replace(0, 4, "" ): 26 position of don't before s.replace(0, 4, "" ): 37 position of even after s.replace(0, 4, "" ): 22 position of don't after s.replace(0, 4, "" ): 33 position even found in complete expression: 22 position don't found in complete expression: 33 Result: I have heard it works only if you believe in it </code></pre> <p>Result for <code>Visual Studio</code> (<em><a href="http://rextester.com/VKFPX23982" rel="nofollow noreferrer">see it live</a></em>):</p> <pre><code>position of even before s.replace(0, 4, "" ): 26 position of don't before s.replace(0, 4, "" ): 37 position of even after s.replace(0, 4, "" ): 22 position of don't after s.replace(0, 4, "" ): 33 position don't found in complete expression: 37 position even found in complete expression: 26 Result: I have heard it works evenonlyyou donieve in it </code></pre> <p><B>Details from the standard</B></p> <p>We know that unless specified the evaluations of sub-expressions are unsequenced, this is from the <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf" rel="nofollow noreferrer">draft C++11 standard</a> section <code>1.9</code> <em>Program execution</em> which says:</p> <blockquote> <p>Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced.[...]</p> </blockquote> <p>and we know that a function call introduces a sequenced before relationship of the function calls postfix expression and arguments with respect to the function body, from section <code>1.9</code>:</p> <blockquote> <p>[...]When calling a function (whether or not the function is inline), every value computation and side effect associated with any argument expression, or with the postfix expression designating the called function, is sequenced before execution of every expression or statement in the body of the called function.[...]</p> </blockquote> <p>We also know that class member access and therefore chaining will evaluate from left to right, from section <code>5.2.5</code> <em>Class member access</em> which says:</p> <blockquote> <p>[...]The postfix expression before the dot or arrow is evaluated;<sup>64</sup> the result of that evaluation, together with the id-expression, determines the result of the entire postfix expression.</p> </blockquote> <p>Note, in the case where the <em>id-expression</em> ends up being a non-static member function it does not specify the order of evaluation of the <em>expression-list</em> within the <code>()</code> since that is a separate sub-expression. The relevant grammar from <code>5.2</code> <em>Postfix expressions</em>:</p> <pre><code>postfix-expression: postfix-expression ( expression-listopt) // function call postfix-expression . templateopt id-expression // Class member access, ends // up as a postfix-expression </code></pre> <h3>C++17 changes</h3> <p>The proposal <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0145r3.pdf" rel="nofollow noreferrer">p0145r3: Refining Expression Evaluation Order for Idiomatic C++</a> made several changes. Including changes that give the code well specified behavior by strengthening the order of evaluation rules for <em>postfix-expressions</em> and their <em>expression-list</em>.</p> <p><a href="https://timsong-cpp.github.io/cppwp/n4659/expr.call#5" rel="nofollow noreferrer">[expr.call]p5</a> says:</p> <blockquote> <p><strong>The postfix-expression is sequenced before each expression in the expression-list and any default argument</strong>. The initialization of a parameter, including every associated value computation and side effect, is indeterminately sequenced with respect to that of any other parameter. [ Note: All side effects of argument evaluations are sequenced before the function is entered (see 4.6). —end note ] [ Example:</p> <pre><code>void f() { std::string s = "but I have heard it works even if you don’t believe in it"; s.replace(0, 4, "").replace(s.find("even"), 4, "only").replace(s.find(" don’t"), 6, ""); assert(s == "I have heard it works only if you believe in it"); // OK } </code></pre> <p>—end example ]</p> </blockquote>
26,640,250
Using Bootstrap and my own CSS together
<p>I know basic CSS, but I'm not experienced. I want to use bootstrap's CSS file, but I want to add my own style codes too. What should I do for that? Should I add Bootstrap styles first and then mine? Is that the best way?</p>
26,640,525
5
3
null
2014-10-29 20:40:12.603 UTC
8
2015-08-10 10:16:11.027 UTC
2015-08-10 10:16:11.027 UTC
null
2,302,862
null
4,195,834
null
1
26
css|twitter-bootstrap
97,627
<p>You will have the stylesheets order like this, first you will include bootstrap css, then your stylesheet file. Why is that? Because that way you can overwrite the classes from the framework without using !important. You can write your own classes and include them in your layout, you can use bootstrap classes and make adjustments to them as you need. When you mix your classes and bootstrap classes check what attributes are added from their classes, do you need them or not etc...</p> <p>Example</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/&gt; &lt;style&gt; /* Your external css file will go here. This is just for testing :) */ .mycustombtn{ background: #000; } &lt;/style&gt; &lt;button type="button" class="btn btn-danger mycustombtn"&gt;Danger&lt;/button&gt;</code></pre> </div> </div> </p>
19,730,806
access data frame column using variable
<p>Consider the following code</p> <pre><code>a = "col1" b = "col2" d = data.frame(a=c(1,2,3),b=c(4,5,6)) </code></pre> <p>This code produces the following data frame</p> <pre><code> a b 1 1 4 2 2 5 3 3 6 </code></pre> <p>However the desired data frame is</p> <pre><code> col1 col2 1 1 4 2 2 5 3 3 6 </code></pre> <p>Further, I'd like to be able to do something like <code>d$a</code> which would then grab <code>d$col1</code> since <code>a = "col1"</code></p> <p>How can I tell R that <code>"a"</code> is a variable and not a name of a column?</p>
19,730,864
2
5
null
2013-11-01 16:16:04.06 UTC
5
2019-10-16 06:47:07.183 UTC
2019-10-16 06:47:07.183 UTC
null
1,563,960
null
412,082
null
1
35
r|dataframe
67,741
<p>After creating your data frame, you need to use <a href="http://stat.ethz.ch/R-manual/R-devel/library/base/html/colnames.html" rel="noreferrer">?colnames</a>. For example, you would have: </p> <pre><code>d = data.frame(a=c(1,2,3), b=c(4,5,6)) colnames(d) &lt;- c("col1", "col2") </code></pre> <p>You can also name your variables when you create the data frame. For example: </p> <pre><code>d = data.frame(col1=c(1,2,3), col2=c(4,5,6)) </code></pre> <p>Further, if you have the names of columns stored in variables, as in</p> <pre><code>a &lt;- "col1" </code></pre> <p>you can't use <code>$</code> to select a column via <code>d$a</code>. R will look for a column whose name is <code>a</code>. Instead, you can do either <code>d[[a]]</code> or <code>d[,a]</code>.</p>
44,942,851
Install User Certificate Via ADB
<p>Is there a way to install CA certificate (<code>.crt</code> file) under the <code>Security -&gt; Trusted Credential -&gt; User tab</code> via ADB? or any other "scriptable" way.</p>
46,569,793
6
4
null
2017-07-06 07:51:17.567 UTC
9
2022-06-01 14:32:34.653 UTC
null
null
null
null
6,028,746
null
1
20
android|certificate|adb|x509certificate
34,715
<p>I figured out a way to do this, thus i was able to trust charles proxy certificate. it will be added as trusted SSL root certificate.</p> <p>First you need to get the certificate hash</p> <pre><code>openssl x509 -inform PEM -subject_hash_old -in charles-proxy-ssl-proxying-certificate.pem | head -1&gt;toto </code></pre> <p>i use windows, store it in a var in a matter to automate the process <code>set /p totoVar=&lt;toto</code></p> <pre><code>set totoVar=%totoVar%.0 &amp;&amp; DEL toto cat charles-proxy-ssl-proxying-certificate.pem &gt; %totoVar% openssl x509 -inform PEM -text -in charles-proxy-ssl-proxying-certificate.pem -out nul &gt;&gt; %totoVar% adb shell mount -o rw,remount,rw /system adb push %totoVar% /system/etc/security/cacerts/ adb shell mount -o ro,remount,ro /system adb reboot </code></pre>
17,548,569
Where can I set headers in laravel
<p>I want to set headers as <code>array('Cache-Control'=&gt;'no-cache, no-store, max-age=0, must-revalidate','Pragma'=&gt;'no-cache','Expires'=&gt;'Fri, 01 Jan 1990 00:00:00 GMT');</code> for all my views, currently I'm doing this in all controllers while returning views, like </p> <pre><code>$headers=array('Cache-Control'=&gt;'no-cache, no-store, max-age=0, must-revalidate','Pragma'=&gt;'no-cache','Expires'=&gt;'Fri, 01 Jan 1990 00:00:00 GMT'); Redirect::to('/',301,$headers);` </code></pre> <p>So instead of writing this for each and every route can it be done in global scope, so that headers are set for every view.</p> <p>I tried setting headers by creating after filter, but didn't get it to work.</p> <p>Can anyone tell me where can I set the headers for all my views? </p> <p><strong>UPDATE</strong> One of my view file meta content</p> <pre><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt; </code></pre> <p>Now when i use <code>Redirect::to('/',301,$headers)</code> The header in firebug is</p> <pre><code>Cache-Control max-age=0, must-revalidate, no-cache, no-store, private Connection Keep-Alive Content-Type text/html; charset=UTF-8 Date Tue, 09 Jul 2013 14:52:08 GMT Expires Fri, 01 Jan 1990 00:00:00 GMT </code></pre> <p>And when I use <code>Redirect::to('/');</code></p> <p>The header in firebug is</p> <pre><code>Cache-Control no-cache Connection Keep-Alive Content-Type text/html; charset=UTF-8 Date Tue, 09 Jul 2013 14:52:08 GMT </code></pre>
17,550,224
7
1
null
2013-07-09 12:48:09.15 UTC
21
2016-06-10 05:07:46.52 UTC
2013-10-07 03:45:26.607 UTC
null
1,959,747
null
1,112,120
null
1
58
laravel|laravel-4
121,142
<p>There are a couple of different ways you could do this - all have advantages/disadvantages.</p> <p><strong>Option 1 (simple):</strong> Since the array is just static data - just manually put the headers in your view layouts directly - i.e. dont pass it from anywhere - code it straight in your view.</p> <pre><code>&lt;?php //set headers to NOT cache a page header("Cache-Control: no-cache, must-revalidate"); //HTTP 1.1 header("Pragma: no-cache"); //HTTP 1.0 header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past ?&gt; </code></pre> <p><strong>Option 2:</strong> Use <a href="http://four.laravel.com/docs/responses#view-composers" rel="noreferrer">view composers</a>. You can use an App before filter to bind the header to all views in your app.</p> <pre><code>App::before(function($request) { $headers=array('Cache-Control'=&gt;'no-cache, no-store, max-age=0, must-revalidate','Pragma'=&gt;'no-cache','Expires'=&gt;'Fri, 01 Jan 1990 00:00:00 GMT'); View::share('headers', $headers); }); </code></pre> <p>Then just echo out the $headers in your view(s).</p> <p>Note: you must let the view set your headers - that is why we are 'passing' the header into view for Laravel to handle. If you try and output the header itself from within a filter or something, you'll cause issues.</p> <p><strong>Edit Option 3:</strong> I just found out about this - you could try this</p> <pre><code>App::before(function($request) { Response::header('Cache-Control', 'nocache, no-store, max-age=0, must-revalidate'); Response::header('Pragma', 'no-cache'); Response::header('Expires', 'Fri, 01 Jan 1990 00:00:00 GMT'); }); </code></pre>
17,516,930
How to create an instance of anonymous class of abstract class in Kotlin?
<p>Assume that <code>KeyAdapter</code> is an abstract class with several methods that can be overridden.</p> <p>In java I can do:</p> <pre><code>KeyListener keyListener = new KeyAdapter() { @Override public void keyPressed(KeyEvent keyEvent) { // ... } }; </code></pre> <p>How to do the same in Kotlin?</p>
17,516,998
2
9
null
2013-07-07 22:14:28.627 UTC
16
2021-07-20 16:35:29.373 UTC
2016-06-16 06:13:52.677 UTC
null
1,148,030
null
312,708
null
1
154
java|abstract-class|kotlin
63,536
<p>From <a href="http://kotlinlang.org/docs/reference/object-declarations.html" rel="noreferrer">the official Kotlin language documentation</a>:</p> <pre class="lang-kotlin prettyprint-override"><code>window.addMouseListener(object : MouseAdapter() { override fun mouseClicked(e : MouseEvent) { // ... } </code></pre> <p>Applied to your problem at hand:</p> <pre class="lang-kotlin prettyprint-override"><code>val keyListener = object : KeyAdapter() { override fun keyPressed(keyEvent : KeyEvent) { // ... } </code></pre> <p>As Peter Lamberg has pointed out - if the anonymous class is actually an implementation of a functional interface (<em>i.e. not of an abstract class</em>), <a href="https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions" rel="noreferrer" title="SAM Conversions">SAM Conversions</a> can be used to simplify this statement even further:</p> <pre class="lang-kotlin prettyprint-override"><code>val keyListener = KeyAdapter { keyEvent -&gt; // ... } </code></pre> <p>Please also note <a href="https://discuss.kotlinlang.org/t/kotlin-and-sam-interface-with-two-parameters/293" rel="noreferrer">this discussion</a> about the different usage of interfaces defined in Java and Kotlin.</p>
30,745,411
Open two instances of Notepad++
<p>I would like to have two Notepad++ shortcuts in desktop, imagine to have two Notepad++ installed each with their exe icon shortcut, that is what I want, so I will can work in two projects,</p> <p>I have tried all with instances, and "multiins" or "atl + f6", but it does not work as I want, </p> <p>again, this is different to another questions with the same title, I want to have two shortcut icons of notepad++, each one opening their files opened,</p> <p>if it is not possible, I will need to use notepad++ and sublime-text at the same time, but that will be a very ugly option</p> <p>Thanks, I am using notepad++ 5.9.6</p> <p>(imagine to open notepad++ and sublimetext, working different project in each one, I want to do that but only with notepad++ opening two notepads++, :P)</p>
30,745,537
6
3
null
2015-06-10 01:07:10.007 UTC
3
2021-07-18 06:22:49.903 UTC
2015-06-10 03:17:06.983 UTC
null
106,224
null
1,657,457
null
1
30
notepad++
39,103
<p>When you open the second file, whilst it opens as a second tab you can just grab the tab and drag it out of Notepad++ to open it in a second session. Sort of like how Firefox, Chrome and IE do it with tabs.</p>
18,452,885
Building a 4 corners-colors CSS3 gradient
<p>Is it possible to produce the following gradient in CSS :</p> <p><img src="https://i.stack.imgur.com/aGiVE.png" alt="enter image description here"></p>
18,453,171
4
1
null
2013-08-26 20:57:11.187 UTC
14
2020-02-16 22:51:38.6 UTC
null
null
null
null
769,551
null
1
29
css|web
24,108
<p>in your case</p> <p><img src="https://i.stack.imgur.com/loRcM.png" alt="enter image description here"></p> <p><strong>Method 1:</strong></p> <p><a href="http://jsfiddle.net/ejEzy/2/" rel="noreferrer">jsFiddle Demo</a></p> <pre><code>div{ overflow: hidden; background: #f06; background: linear-gradient(45deg, #fff722, #ff26f9); min-height: 100%; width: 256px; height: 256px; position: relative; z-index: 1; box-shadow: inset -20px 0 38px -18px #ff26f9,inset -3px -13px 65px -18px yellow; } div:before,div:after{ content:''; position:absolute; width:100%; height:100%; } div:before{ background: red; box-shadow: 0 0 140px 64px red; z-index:2; top: -96%; left: -72%; opacity: 0.8; } div:after { background: white; z-index: 3; bottom: -96%; right: -72%; box-shadow: 0 0 140px 64px white; opacity: 1; border-radius: 100%; } </code></pre> <p><strong>Method 2:</strong></p> <p><img src="https://i.stack.imgur.com/DExsr.png" alt="enter image description here"></p> <pre><code>div{ overflow: hidden; background: #f06; background: linear-gradient(45deg, #fff722, #ff26f9); min-height: 100%; width:256px; height:256px; position:relative; z-index:1; } div:before,div:after{ content:''; position:absolute; width:100%; height:100%; } div:before{ background: red; box-shadow: 0 0 140px 64px red; z-index:2; top: -96%; left: -72%; opacity: 0.8; } div:after { background: white; z-index: 3; bottom: -96%; right: -72%; box-shadow: 0 0 140px 64px white; opacity: 1; border-radius: 100%; } </code></pre> <p><a href="http://jsfiddle.net/ejEzy/1/" rel="noreferrer">jsFiddle Demo</a></p> <p><strong>Method 3:</strong> multiple background:</p> <p><img src="https://i.stack.imgur.com/Cc3ZO.png" alt="enter image description here"></p> <pre><code>div{ background: #f06; background: linear-gradient(45deg, #fff722, #ff26f9),linear-gradient(142deg, transparent, white),linear-gradient(108deg, red, transparent); min-height: 100%; width:256px; height:256px; position:relative; z-index:1; } </code></pre> <p><a href="http://jsfiddle.net/vjcLD/1/" rel="noreferrer">jsFiddle Demo</a></p> <p><strong>Method 4:</strong> pseudo element</p> <pre><code>div{ background: #f06; background: linear-gradient(45deg, #fff722, #ff26f9); min-height: 100%; width:256px; height:256px; position:relative; z-index:1; } div:before,div:after{ content:''; position:absolute; width:100%; height:100%; opacity: 0.8; } div:before{ background: linear-gradient(108deg, red, transparent); z-index:2; top:0; left:0; } div:after{ background: linear-gradient(142deg, transparent, white); z-index:3; bottom:0; right:0; } </code></pre> <p>the markup:</p> <pre><code>&lt;div&gt;&lt;/div&gt; </code></pre> <p><a href="http://jsfiddle.net/vjcLD/" rel="noreferrer">jsFiddle Demo</a></p> <p><strong>Method 5:</strong></p> <pre><code>div{ overflow: hidden; background: #f06; background: linear-gradient(45deg, #fff722, #ff26f9); min-height: 100%; width:256px; height:256px; position:relative; z-index:1; } div:before,div:after{ content:''; position:absolute; width:100%; height:100%; } div:before{ background: linear-gradient(108deg, red, transparent); z-index:2; top:0; left:0; opacity: 0.8; } div:after { background: white; z-index: 3; bottom: -96%; right: -72%; box-shadow: 0 0 110px 54px white; opacity: 1; border-radius: 100%; } </code></pre> <p><a href="http://jsfiddle.net/ejEzy/" rel="noreferrer">jsFiddle Demo</a></p> <p>Update: many thanks to <strong><a href="http://about.me/thebabydino" rel="noreferrer">Ana-Maria Tudor</a></strong> &lt;3</p> <pre><code>body{ position:fixed; top:0; right:0; bottom:0; left:0; } body:before { content: ''; position:absolute; top:0; right:0; bottom:0; left:0; display: block; width: 100%; height: 600px; border-radius: 0%; background: radial-gradient(circle at 50% 0, rgba(255,0,0,.5), rgba(255,0,0,0) 70.71%), radial-gradient(circle at 6.7% 75%, rgba(0,0,255,.5), rgba(0,0,255,0) 70.71%), radial-gradient(circle at 93.3% 75%, rgba(0,255,0,.5), rgba(0,255,0,0) 70.71%); } </code></pre> <p><a href="http://dabblet.com/gist/9467973" rel="noreferrer">jsFiddle Demo</a></p>
23,202,146
"pkg-config script could not be found" on OSX
<p>I am trying to install some software on my mac; however I keep receiving the same error:</p> <pre><code>configure: error: The pkg-config script could not be found or is too old. Make sure it is in your PATH or set the PKG_CONFIG environment variable to the full path to pkg-config. Alternatively, you may set the environment variables XMEDCON_GLIB_CFLAGS and XMEDCON_GLIB_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details. To get pkg-config, see &lt;http://pkg-config.freedesktop.org/&gt;. See `config.log' for more details </code></pre> <p>I am not quite sure how to go about adding the pkg-config to the PATH. I have seen online (see link) that I should add the following:</p> <p><a href="http://www.fantageek.com/318/install-pkg-config-for-mac-osx/">Link showing how to direct PATH variable</a></p> <pre><code>export PATH=$PATH:/opt/local/bin # Fixed typo as mentioned in comment </code></pre> <p>which is where I have placed pkg-config. I still keep getting the error though every time I try to configure the files using ./configure. Any help would be super appreciated!</p>
23,217,948
6
4
null
2014-04-21 17:13:26.757 UTC
19
2022-05-13 10:28:55.723 UTC
2022-05-13 10:28:55.723 UTC
null
1,202,172
null
1,507,574
null
1
95
linux|macos
211,278
<p>Answer to my question (after several Google searches) revealed the following:</p> <pre><code>$ curl https://pkgconfig.freedesktop.org/releases/pkg-config-0.29.tar.gz -o pkgconfig.tgz $ tar -zxf pkgconfig.tgz &amp;&amp; cd pkg-config-0.29 $ ./configure &amp;&amp; make install </code></pre> <p>from the following link: <a href="https://github.com/LearnBoost/node-canvas/wiki/Installation---OSX" rel="noreferrer">Link showing above</a></p> <p>Thanks to everyone for their comments, and sorry for my linux/OSX ignorance!</p> <p>Doing this fixed my issues as mentioned above.</p>