pid
int64
2.28k
41.1M
label
int64
0
1
text
stringlengths
1
28.3k
13,604,607
0
<p>User-agents define the <code>&lt;a /&gt;</code> tag as interactive, but this element was only designed to make an hypertext reference without any idea of click.</p> <p>This user-agent behavior became a standard, which is not the same with the longdesc attribute of the <code>&lt;img /&gt;</code> tag.</p> <p>Because HTML was designed to structure information and contents, not to make interactions, the new version of HTML (5) tries to "palliate" this lack and introduces the <code>&lt;command /&gt;</code> tag to have interactions on HTML non-informative contents as "read more" anchors in example.</p> <p>Note that "A command can be explicitly part of a context menu or toolbar" should also say that the <code>&lt;command /&gt;</code> can be used in another context and does not require <code>&lt;form /&gt;</code> tag instead of <code>&lt;input /&gt;</code> or <code>&lt;button /&gt;</code>.</p> <p><sub>Thank you to Spontifixus &amp; Daniel Kutik for correcting this answer</sub></p>
35,699,448
0
<p>The following regex <a href="https://regex101.com/r/nQ6oJ1/1" rel="nofollow">does what you're looking for</a>:</p> <pre><code>\d+(?:\s?(?:\$|euro)) </code></pre> <p>In <code>PHP</code> code, this would be:</p> <pre><code>$string ="i have 300 $, 1000$ ,500 euro in my account"; $regex = '~\d+(?:\s?(?:\$|euro))~'; preg_match_all($regex, $string, $matches); print_r($matches); </code></pre> <p>See <a href="http://ideone.com/BCha1a" rel="nofollow">a demo on ideone.com</a>.<br> To actually get the digits (300,1000,500 in your case), you could use a capturing group like so:</p> <pre><code>$regex = '~(\d+)(?:\s?(?:\$|euro))~'; preg_match_all($regex, $string, $matches); print_r($matches); </code></pre> <p>To match other currencies as well (as @Wiktor pointed out), add these to the non-capturing group:</p> <pre><code>(\d+)(?:\s?(?:\$|euro|¥|yen)) </code></pre> <p>To allow <strong>float</strong> values, change the pattern as follows:</p> <pre><code>([\d.]+)(?:\s?(?:\$|euro|¥|yen)) </code></pre>
6,396,117
0
<p>Use Psyco, for python2:</p> <pre><code>import psyco psyco.full() </code></pre> <p>Also, enable doublebuffering. For example:</p> <pre><code>from pygame.locals import * flags = FULLSCREEN | DOUBLEBUF screen = pygame.display.set_mode(resolution, flags, bpp) </code></pre> <p>You could also turn off alpha if you don't need it:</p> <pre><code>screen.set_alpha(None) </code></pre> <p>Instead of flipping the entire screen every time, keep track of the changed areas and only update those. For example, something roughly like this (main loop):</p> <pre><code>events = pygame.events.get() for event in events: # deal with events pygame.event.pump() my_sprites.do_stuff_every_loop() rects = my_sprites.draw() activerects = rects + oldrects activerects = filter(bool, activerects) pygame.display.update(activerects) oldrects = rects[:] for rect in rects: screen.blit(bgimg, rect, rect) </code></pre> <p>Most (all?) drawing functions return a rect.</p> <p>You can also set only some allowed events, for more speedy event handling:</p> <pre><code>pygame.event.set_allowed([QUIT, KEYDOWN, KEYUP]) </code></pre> <p>Also, I would not bother with creating a buffer manually and would not use the HWACCEL flag, as I've experienced problems with it on some setups.</p> <p>Using this, I've achieved reasonably good FPS and smoothness for a small 2d-platformer.</p>
2,345,527
0
<p>There's a <a href="http://svn.collab.net/repos/svn/trunk/contrib/hook-scripts/remove-zombie-locks.py" rel="nofollow noreferrer">Python</a> script (referenced here: <a href="http://subversion.tigris.org/ds/viewMessage.do?dsForumId=1065&amp;dsMessageId=2369399" rel="nofollow noreferrer">http://subversion.tigris.org/ds/viewMessage.do?dsForumId=1065&amp;dsMessageId=2369399</a>). I'd either use that, or translate it to .NET if you needed to.</p>
27,160,869
0
<p>You can get content from articles easy with the follow "tools":</p> <ol> <li>scrapy (recommended, but have greater learning curve)</li> <li>newspaper (gives you immediately title, author, text, images, videos, etc. )</li> <li>goose-extractor (is like newspaper)</li> </ol>
9,830,013
0
<p>If you will never have dots, you can use this</p> <pre><code>PARSENAME(REPLACE(ColumnName,':','.'),1) </code></pre> <p>example</p> <pre><code>DECLARE @v VARCHAR(100) = 'DT:CSDF' SELECT PARSENAME(REPLACE(@v,':','.'),1) </code></pre> <p>otherwise use PATINDEX and RIGHT</p> <pre><code>SELECT RIGHT(ColumnName,LEN(ColumnName) -PATINDEX('%:%',ColumnName)) </code></pre> <p>Example</p> <pre><code>DECLARE @v VARCHAR(100) = 'DT:CSDF' SELECT RIGHT(@v,LEN(@v) -PATINDEX('%:%',@v)) </code></pre>
21,417,690
0
<p>The short answer is the operator needs to be at the end of the line in order to tell Ruby to continue reading the next line as part of the statement, so this would work:</p> <pre><code>if ( (aa != nil &amp;&amp; self.prop1 == aa.decrypt) || (bb != nil &amp;&amp; self.prop2 == bb.decrypt) ) &amp;&amp; (self.id.nil? || self.id != id) return true end </code></pre> <p>That being said, you can probably reduce the logic by throwing exceptions based on input values, and removing some redundant checks (I'm making some jumps here about what your variables will look like, but you get the idea.)</p> <pre><code>raise 'aa must support decrypt' unless aa.respond_to? :decrypt raise 'bb must support decrypt' unless bb.respond_to? :decrypt if prop1 == aa.decrypt || prop2 == bb.decrypt if self.id != id return true end end </code></pre>
842,967
0
<p>I have now switched from <code>wsDualHttpBinding</code> to <code>NetTcpBinding</code> and for some reason, everything is working fine. </p> <p>I have used <a href="http://www.singingeels.com/Articles/Duplex_WCF_Services_Hosted_in_IIS_Using_NetTcp.aspx" rel="nofollow noreferrer">this article</a> to help me set up hosting on IIS, and thankully everything is working as expected, with callbacks.</p>
38,371,187
1
Color sequence game in Python <p>The code below is for color sequence guessing in python.</p> <pre><code>import random import time def colorgame(): r='red' b='blue' g='green' y='yellow' v='violet' bl='black' o='orange' w='white' m='magenta' colors = [r, b, g, y, v, bl, o, w, m] sequence=[] win = True while win == True: else: win=False </code></pre> <p>In the first iteration say <code>sequence = 'red'</code> user enters <code>red</code> and it prints <code>"Correct"</code>. But, when it comes to the second iteration (say) <code>sequence = ['red', 'green']</code> and user enters <code>'red' 'green'</code> It is not returning correct. Please help me in correcting the code so that the user input is accepted as list and compared to the existing list (<code>sequence</code>)</p>
33,267,366
0
<p>Here is my modified mulerequester as per Ryan's suggestion. It uses both connector and selector as Uri params.</p> <pre><code> &lt;mulerequester:request config-ref="Mule_Requester" resource="wmq://REPLY.QUEUE?connector=wmqConnector&amp;amp;selector=JMSCorrelationID%3D'#[sessionVars.myCorrelationId]'" doc:name="Mule Requester" timeout="120000"/&gt; </code></pre>
17,936,157
0
<p>Either make plot space annotations for the second labels or create a second plot. Have the second plot only display data labels but no plot data (set all line styles and fills to <code>nil</code>).</p>
34,134,911
0
<p><code>String#to_i</code> returns a new Object (which is the only sensible implementation; think a moment about what would happen if <code>String#to_i</code> magically changed the object's class).</p> <p>So, to assign the integer value to your <code>sum</code> variable, use</p> <pre><code> sum = sum.to_i </code></pre> <p>or (better) introduce a new variable for your integer value:</p> <pre><code> sum_as_integer = sum.to_i </code></pre>
5,740,505
0
<p>As other people have said, you need to implement a comparison function yourself.</p> <p>There is a proposed way to ask the compiler to generate the obvious/naive(?) implementation: see <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2014/n4126.htm" rel="nofollow">here</a>.</p> <p>It may seem a bit unhelpful of C++ not to have already Standardised this, but often structs/classes have some <strong>data members to exclude</strong> from comparison (e.g. counters, cached results, container capacity, last operation success/error code, cursors), as well as <strong>decisions to make</strong> about myriad things including but not limited to:</p> <ul> <li>which fields to compare first, e.g. comparing a particular <code>int</code> member might eliminate 99% of unequal objects very quickly, while a <code>map&lt;string,string&gt;</code> member might often have identical entries and be relatively expensive to compare - if the values are loaded at runtime, the programmer may have insights the compiler can't possibly</li> <li>in comparing strings: case sensitivity, equivalence of whitespace and separators, escaping conventions...</li> <li>precision when comparing floats/doubles</li> <li>whether NaN floating point values should be considered equal</li> <li>comparing pointers or pointed-to-data (and if the latter, how to know how whether the pointers are to arrays and of how many objects/bytes needing comparison)</li> <li>whether order matters when comparing unsorted containers (e.g. <code>vector</code>, <code>list</code>), and if so whether it's ok to sort them in-place before comparing vs. using extra memory to sort temporaries each time a comparison is done</li> <li>how many array elements currently hold valid values that should be compared (is there a size somewhere or a sentinel?)</li> <li>which member of a <code>union</code> to compare</li> <li>normalisation: for example, date types may allow out-of-range day-of-month or month-of-year, or a rational/fraction object may have 6/8ths while another has 3/4ers, which for performance reasons they correct lazily with a separate normalisation step; you may have to decide whether to trigger a normalisation before comparison</li> <li>what to do when weak pointers aren't valid</li> <li>how to handle members and bases that don't implement <code>operator==</code> themselves (but might have <code>compare()</code> or <code>operator&lt;</code> or <code>str()</code> or getters...)</li> <li>what locks must be taken while reading/comparing data that other threads may want to update</li> </ul> <p>So, it's kind of <strong>nice to have an error</strong> until you've explicitly thought about what comparison should mean for your specific structure, <strong>rather than letting it compile but not give you a meaningful result at run-time</strong>.</p> <p>All that said, it'd be good if C++ let you say <code>bool operator==() const = default;</code> when you'd decided a "naive" member-by-member <code>==</code> test <em>was</em> ok. Same for <code>!=</code>. Given multiple members/bases, "default" <code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;=</code> implementations seem hopeless though - cascading on the basis of order of declaration's possible but very unlikely to be what's wanted, given conflicting imperatives for member ordering (bases being necessarily before members, grouping by accessibility, construction/destruction before dependent use). To be more widely useful, C++ would need a new data member/base annotation system to guide choices - that would be a great thing to have in the Standard though, ideally coupled with AST-based user-defined code generation... I expect it'll happen one day.</p> <h2>Typical implementation of equality operators</h2> <h3>A plausible implementation</h3> <p>It's <em>likely</em> that a reasonable and efficient implementation would be:</p> <pre><code>inline bool operator==(const MyStruct1&amp; lhs, const MyStruct1&amp; rhs) { return lhs.my_struct2 == rhs.my_struct2 &amp;&amp; lhs.an_int == rhs.an_int; } </code></pre> <p>Note that this needs an <code>operator==</code> for <code>MyStruct2</code> too.</p> <p>Implications of this implementation, and alternatives, are discussed under the heading <em>Discussion of specifics of your MyStruct1</em> below.</p> <h3>A consistent approach to ==, &lt;, &gt; &lt;= etc</h3> <p>It's easy to leverage <code>std::tuple</code>'s comparison operators to compare your own class instances - just use <code>std::tie</code> to create tuples of references to fields in the desired order of comparison. Generalising my example from <a href="http://stackoverflow.com/a/37269108/410767">here</a>:</p> <pre><code>inline bool operator==(const MyStruct1&amp; lhs, const MyStruct1&amp; rhs) { return std::tie(lhs.my_struct2, lhs.an_int) == std::tie(rhs.my_struct2, rhs.an_int); } inline bool operator&lt;(const MyStruct1&amp; lhs, const MyStruct1&amp; rhs) { return std::tie(lhs.my_struct2, lhs.an_int) &lt; std::tie(rhs.my_struct2, rhs.an_int); } // ...etc... </code></pre> <p>When you "own" (i.e. can edit, a factor with corporate and 3rd party libs) the class you want to compare, and especially with C++14's preparedness to deduce function return type from the <code>return</code> statement, it's often nicer to add a "tie" member function to the class you want to be able to compare:</p> <pre><code>auto tie() const { return std::tie(my_struct1, an_int); } </code></pre> <p>Then the comparisons above simplify to:</p> <pre><code>inline bool operator==(const MyStruct1&amp; lhs, const MyStruct1&amp; rhs) { return lhs.tie() == rhs.tie(); } </code></pre> <p>If you want a fuller set of comparison operators, I suggest <a href="http://www.boost.org/doc/libs/1_60_0/libs/utility/operators.htm" rel="nofollow">boost operators</a> (search for <code>less_than_comparable</code>). If it's unsuitable for some reason, you may or may not like the idea of support macros <a href="http://coliru.stacked-crooked.com/a/957768e47b82c2c9" rel="nofollow">(online)</a>:</p> <pre><code>#define TIED_OP(STRUCT, OP, GET_FIELDS) \ inline bool operator OP(const STRUCT&amp; lhs, const STRUCT&amp; rhs) \ { \ return std::tie(GET_FIELDS(lhs)) OP std::tie(GET_FIELDS(rhs)); \ } #define TIED_COMPARISONS(STRUCT, GET_FIELDS) \ TIED_OP(STRUCT, ==, GET_FIELDS) \ TIED_OP(STRUCT, !=, GET_FIELDS) \ TIED_OP(STRUCT, &lt;, GET_FIELDS) \ TIED_OP(STRUCT, &lt;=, GET_FIELDS) \ TIED_OP(STRUCT, &gt;=, GET_FIELDS) \ TIED_OP(STRUCT, &gt;, GET_FIELDS) </code></pre> <p>...that can then be used a la...</p> <pre><code>#define MY_STRUCT_FIELDS(X) X.my_struct2, X.an_int TIED_COMPARISONS(MyStruct1, MY_STRUCT_FIELDS) </code></pre> <p>(C++14 member-tie version <a href="http://coliru.stacked-crooked.com/a/8a9990f1339df20c" rel="nofollow">here</a>)</p> <h2>Discussion of specifics of your MyStruct1</h2> <p>There are implications to the choice to provide a free-standing versus member <code>operator==()</code>...</p> <p><strong>Freestanding implementation</strong></p> <p>You have an interesting decision to make. As your class can be implicitly constructed from a <code>MyStruct2</code>, a free-standing / non-member <code>bool operator==(const MyStruct2&amp; lhs, const MyStruct2&amp; rhs)</code> function would support...</p> <pre><code>my_MyStruct2 == my_MyStruct1 </code></pre> <p>...by first creating a temporary <code>MyStruct1</code> from <code>my_myStruct2</code>, then doing the comparison. This would definitely leave <code>MyStruct1::an_int</code> set to the constructor's default parameter value of <code>-1</code>. Depending on whether you include <code>an_int</code> comparison in the implementation of your <code>operator==</code>, a <code>MyStruct1</code> might or might not compare equal to a <code>MyStruct2</code> that itself compares equal to the <code>MyStruct1</code>'s <code>my_struct_2</code> member! Further, creating a temporary <code>MyStruct1</code> can be a very inefficient operation, as it involves copying the existing <code>my_struct2</code> member to a temporary, only to throw it away after the comparison. (Of course, you could prevent this implicit construction of <code>MyStruct1</code>s for comparison by making that constructor <code>explicit</code> or removing the default value for <code>an_int</code>.)</p> <p><strong>Member implementation</strong></p> <p>If you want to avoid implicit construction of a <code>MyStruct1</code> from a <code>MyStruct2</code>, make the comparison operator a member function:</p> <pre><code>struct MyStruct1 { ... bool operator==(const MyStruct1&amp; rhs) const { return tie() == rhs.tie(); // or another approach as above } }; </code></pre> <p>Note the <code>const</code> keyword - only needed for the member implementation - advises the compiler that comparing objects doesn't modify them, so can be allowed on <code>const</code> objects.</p> <h2>Comparing the visible representations</h2> <p>Sometimes the easiest way to get the kind of comparison you want can be...</p> <pre><code> return lhs.to_string() == rhs.to_string(); </code></pre> <p>...which is often very expensive too - those <code>string</code>s painfully created just to be thrown away! For types with floating point values, comparing visible representations means the number of displayed digits determines the tolerance within which nearly-equal values are treated as equal during comparison.</p>
26,487,614
0
storing transformed BufferedImage in Java <p>In Java, instead of using photoshop to transform my images(that I use in the program), I want to use code to transform and save them.</p> <p>I have created an AffineTransform object "at" and called the <code>rotate()</code> method. I have a BufferedImage called "image". </p> <p>I can draw the image on the screen with the desired transformation with this code:</p> <pre><code>g2d.drawImage(image, at, null); </code></pre> <p>What I want to do is to store the combination of at and image in a new BufferedImage image2. How can I do this so that<code>g2d.drawImage(image2,50,50, null);</code> will show the rotated version of image?</p> <p>edit: I've tweaked Ezequiel's answer a bit to get the effect I wanted. This did the trick:</p> <pre><code>BufferedImage image2= null; AffineTransformOp affineTransformOp = new AffineTransformOp(at,AffineTransformOp.TYPE_BILINEAR); image2 = affineTransformOp.filter(image, image2); g2d.drawImage(image2, 50, 50, null); </code></pre>
31,916,705
0
<p>Got it!</p> <p>It seems that <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1192763" rel="nofollow">the debugger has issues with internationalized domain names (IDN)</a>.</p>
40,628,904
0
<p>Change Swift Compiler optimization Level to </p> <blockquote> <p>Fast, Single File Optimization</p> </blockquote> <p>instead of whole module! <a href="https://i.stack.imgur.com/eJxcl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eJxcl.png" alt="see the highlighted"></a> Something seems unusual with whole module optimization and Alamofire!</p>
30,789,596
0
How to save resource assignments on Bryntum's Gantt? <p>I have an resource assignment column on my Gantt. I can change the assignments but I want to know how to save them ? Also can I change the assignment default unit of percentage tot hours. </p>
33,927,174
1
Django reverse url to onetoonefield on success <p>Good day SO!</p> <p>Recently I've started working on Django, got myself a situation which I can't find the right solution on the web to solve it. So I've got a little question about URL reversing on a success. Currently when an user successfully creates an account, the user gets reversed to a profile based on the user_id which just got created: </p> <pre><code>class Create(CreateView): form_class = UserCreateForm # inherits from django's UserCreationForm def get_success_url(self): return reverse('users:profile', kwargs={'pk': self.object.pk}) </code></pre> <p>This is working properly. Now I created a profile module with a OneToOneField to the django.auth.models User model. When creating a new account, a signal is send to the create_profile_on_registration method.</p> <pre><code>@receiver(post_save, sender=User) def create_profile_on_registration(sender, created, instance, **kwargs): ... </code></pre> <p>This is also working properly, a new profile is created on user account registration. Now I would like to reverse the user to the new created profile_id instead of the user_id. However, I cant figure out exactly how to get this properly to work. Can you give me a little push in the right direction on how to approach this issue? I can't match up the right google search words or find any examples which explains or shows how to achieve this properly.</p> <p>Thanks in advance!</p>
6,019,294
0
Loading a cookie and posting data with curl <p>If I load in a cookie, I am able to get to the page that requires cookies, like this:</p> <pre><code>$cookie = ".ASPXAUTH=Secret"; curl_setopt($ch, CURLOPT_COOKIE, $cookie); </code></pre> <p>No problem here, I can run <code>curl_exec</code>, and see the page that requires cookies. </p> <p>If I also want to send some post data, I can do like this:</p> <pre><code>$data = array( 'index' =&gt; "Some data is here" ); $cookie = ".ASPXAUTH=Secret"; curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_COOKIE, $cookie); </code></pre> <p>I have set up a <a href="http://pastebin.com/37mDNNHr" rel="nofollow">dump script</a> on my local server, to see if it is working. If i send <strong>only</strong> the cookie, I can see it in the http headers, and if I send <strong>only</strong> the post data, I can see the post data.</p> <p>When I send both, I see only the cookie. </p> <p>Why?</p>
15,175,243
0
Grouping elements under a new node in xslt <p>I need to group some elements together and pull them together under a new element. </p> <p>Below is a sample record, I would like to group together the address information into an additional layer.</p> <p>Here is the original record -</p> <pre><code> &lt;Records&gt; &lt;People&gt; &lt;FirstName&gt;John&lt;/FirstName&gt; &lt;LastName&gt;Doe&lt;/LastName&gt; &lt;Middlename /&gt; &lt;Age&gt;20&lt;/Age&gt; &lt;Smoker&gt;Yes&lt;/Smoker&gt; &lt;Address1&gt;11 eleven st&lt;/Address1&gt; &lt;Address2&gt;app 11&lt;/Address2&gt; &lt;City&gt;New York&lt;/City&gt; &lt;State&gt;New York&lt;/State&gt; &lt;Status&gt;A&lt;/Status&gt; &lt;/People&gt; &lt;/Records&gt; </code></pre> <p>expected Result: I need to group address data under a new element as such -</p> <pre><code> &lt;Records&gt; &lt;People&gt; &lt;FirstName&gt;John&lt;/FirstName&gt; &lt;LastName&gt;Doe&lt;/LastName&gt; &lt;Middlename /&gt; &lt;Age&gt;20&lt;/Age&gt; &lt;Smoker&gt;Yes&lt;/Smoker&gt; &lt;Address&gt; &lt;Address1&gt;11 eleven st&lt;/address1&gt; &lt;Address2&gt;app 11&lt;/address2&gt; &lt;City&gt;New York&lt;/City&gt; &lt;State&gt;New York&lt;/State&gt; &lt;/Address&gt; &lt;Status&gt;A&lt;/Status&gt; &lt;/People&gt; &lt;/Records&gt; </code></pre> <p>Any help would be great! Thank you</p>
36,690,802
0
<p>You simply need to set the <code>Foreground</code> property:</p> <pre><code>marker.ToolTip.Foreground = Brushes.Green; </code></pre>
13,354,692
0
<p>If you are thinking about compilation time purpose IF CONDITION is always preferable. If conditions do faster checking than switch case.</p> <p>But if you thin programatically then If condition is just a series of boolean checks. For program to work efficiently switch case should be used(Although it consumes time).</p>
6,520,737
0
<p><code>[]</code> notation will make it possible to transmit array data in a form.</p> <p>Name the checkboxes in the form like this:</p> <pre><code>&lt;input name="area[]" type="checkbox" value="51-75"&gt; </code></pre> <p>this should build an array of all selected check boxes. </p>
19,419,101
0
<p>Can't tell you how frustrated I am trying to narrow down the cause of this one. Took me hours. Trial and error here and there.. all leads to nothing until one comment in one of the threads relating to this mentioned about "Executable". Boom! I remember the plist key "Executable file" in my project plist (PROJECT-info.plist). So I got there and found out that that entry was missing. I filled it in with whatever default you see when creating new project, "Executable file" paired with "${EXECUTABLE_NAME}". Build + Run. Then it finally worked! </p> <p>Btw, I did try all those deleting/resetting stuff found all over SO. None of them works. </p>
23,765,162
0
<p>I’ve noticed occasionally that ASP.NET will cache the old SPROC in Visual Studio even after a change is made on SQL Server. So for example you changed custUPDATE by adding a parameter, and also added the parameter to your ASP.NET code, but are still receiving the “too many arguemtns specified” error because the old SPROC is being cached.</p> <p>If this is the case I would try the following:</p> <p>Change the SPROC name in your ASP.NET page from custUPDATE to [custUPDATE] and then try running it.</p>
2,783,555
0
where can I get these kind of exercises to solve? <p>Recently I did a Java programming exercise successfully which was sent by a recruiting firm, The problem statement goes like this 'There are two text files FI(records abt files and directory information) and FS(containing blocks of data) which represent a file Index and file System respectively and I was supposed to write a static read method in a class which will read the file from the FS depending upon the path string provided using FI' My question is where can I get these kind of exercises to solve, the complexity should be above average to tough.</p>
3,531,190
0
<p>You can know when it's postback with a function such as:</p> <pre><code>import javax.faces.bean.ManagedBean; import javax.faces.context.FacesContext; @ManagedBean public class HelperBean { public boolean isPostback() { FacesContext context = FacesContext.getCurrentInstance(); return context.getRenderKit().getResponseStateManager().isPostback(context); } } </code></pre> <p>If for every refresh the default constructor is called, that means that your bean is <code>RequestScoped</code>. A refresh (GET) or a postback (POST) are considered as requests, so the bean will be created for every request. There are other instantiation options such as <code>SessionScoped</code> or <code>ApplicationScoped</code> or just instantiate it when a <strong>postback</strong> occurs, with the above function.</p> <p>Setting the scope a-la-JSF1.2</p> <p>Edit your <code>faces-config.xml</code> file located under <code>/WEB-INF</code>:</p> <pre><code> &lt;managed-bean&gt; &lt;managed-bean-name&gt;myBean&lt;/managed-bean-name&gt; &lt;managed-bean-class&gt;com.mypackage.myBean&lt;/managed-bean-class&gt; &lt;managed-bean-scope&gt;request&lt;/managed-bean-scope&gt; &lt;/managed-bean&gt; </code></pre> <p>you can use <code>request</code>, <code>session</code> or <code>application</code></p>
21,741,803
0
Powershell SecureString Encrypt/Decrypt To Plain Text Not Working <p>We are trying to store a user password in the registry as a secure string but we can not seem to find a way to convert it back to plain text. Is this possible with SecureString?</p> <p>Here is the simple test script we are trying to use...</p> <pre><code>Write-Host "Test Start..." $PlainPassword = "@SomethingStupid" | ConvertTo-SecureString -AsPlainText -Force $BSTR = ` [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($PlainPassword) $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) Write-Host "Password is: " $PlainPassword Read-Host </code></pre> <p>This is the error we are getting...</p> <pre><code>The term ' [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At C:\test.ps1:4 char:71 + $BSTR = ` [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR &lt;&lt;&lt;&lt; ($PlainPassword) + CategoryInfo : ObjectNotFound: ( [System.Runtim...ureStringToBSTR:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Cannot find an overload for "PtrToStringAuto" and the argument count: "1". At C:\test.ps1:5 char:75 + $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto &lt;&lt;&lt;&lt; ($BSTR) + CategoryInfo : NotSpecified: (:) [], MethodException + FullyQualifiedErrorId : MethodCountCouldNotFindBest </code></pre>
24,930,555
0
<p>I don't understand what exactly you are trying to do. If you want to get an array of pointers from your array of structs, you will need to make a loop. It would look like this (i did not try it)</p> <pre><code>person * friends_ptrs[NUM_OF_FRIENDS]; for (int i = 0; i &lt; NUM_OF_FRIENDS; i++) friends_ptrs[i] = friends + i; </code></pre>
24,840,539
0
if statement to check number of days in a month <p>I am writing a simple program in asp.net mvc5 that will display a calendar. I have an array that stores the months and days 1-31. I would like to use an if statement to check for the month to allow only the appropriate number of days. I am really new to mvc and would appreciate any suggestions on how to accomplish this.</p>
31,680,592
0
what is the maximum limit that svnadmin load/dump file execute <p>I am migrating cvs and Subversion 1.6 repos to new subversion 1.8 server. I use cvs2svn for CVS dump and svnadmin dump to create dump files and load in new subversion server. My CVS repositories maximum size is 8 GB and Subversion repos 15 GB in size. 1. <strong>Can I use cvs2svn to dump 8 gb cvs repository</strong>. cvs2svn will create dumpfile for 8 gb repository and will this dump can be loaded in subversion server. 2. <strong>can I use svnadmin dump (not delta) for 15 gb repository</strong> and <strong>will I be able to load in the new server.</strong> Is there any size limit or limitations on running cvs2svn conversion and svnadmin load and dump commands. Please share your approach and suggestions that I can follow.</p>
39,664,115
0
Produce an APK for multiple architectures for Qt projects <p>In 3d party APK files I notice there are folders for different architectures - armv7, arm64, x86, mips - so a single APK works for multiple architectures, supported by Android.</p> <p>However, I don't seem to find a way to do that with Qt projects. I have a project that targets multiple architectures, but I can only produce an APK for an architecture at a time, only for the currently active project kit.</p> <p>Is it possible to produce such a muti-arch APK for a Qt projects?</p>
14,533,682
0
User Registration using Slim Rest server and android client <p>I am working on a simple app where I sign up new users. - I am using SLIM PHP framework with MySQL on apache local host - I have a MySQL database with table called tbl_user. I have tested my SLIM implementation using CURL - On Client side, I have three EditView fields named fname, email and password and a sign up button - Its simple, when user click sign up button, the db connection should be made and new user should be added in database. Registration is simple w/o any checks. That I am going to implement once I resolve this issue.</p> <p>Please help. I have searched a lot and could not resolve the errors.</p> <p>I am getting following errors:</p> <p>ERROR</p> <p>This is my actual error now<br> 01-27 08:42:14.981: D/URL read(6739): Slim Application Errorbody{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{display:inline-block;width:65px;}<h1>Slim Application Error</h1><p>The application could not run because of the following error:</p><h2>Details:</h2><strong>Message:</strong> error_log(/var/tmp/php.log) [function.error-log]: failed to open stream: No such file or directory<br/><strong>File:</strong> C:\xampp\htdocs\api\index.php<br/><strong>Line:</strong> 105<br/><h2>Stack Trace:</h2>#0 [internal function]: Slim::handleErrors(2, 'error_log(/var/...', 'C:\xampp\htdocs...', 105, Array)<br /> 01-27 08:42:14.981: D/URL read(6739): #1 C:\xampp\htdocs\api\index.php(105): error_log('SQLSTATE[23000]...', 3, '/var/tmp/php.lo...')<br /> 01-27 08:42:14.981: D/URL read(6739): #2 [internal function]: register()<br /> 01-27 08:42:14.981: D/URL read(6739): #3 C:\xampp\htdocs\api\Slim\Route.php(392): call_user_func_array('register', Array)<br /> 01-27 08:42:14.981: D/URL read(6739): #4 C:\xampp\htdocs\api\Slim\Slim.php(1052): Slim_Route->dispatch()<br /> 01-27 08:42:14.981: D/URL read(6739): #5 C:\xampp\htdocs\api\index.php(26): Slim->run()<br /> 01-27 08:42:14.981: D/URL read(6739): #6 {main}</p> <p>RegisterActivity.java(partial)</p> <pre><code> class CreateNewUser extends AsyncTask&lt;String, String, String&gt; { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(RegisterActivity.this); pDialog.setMessage("Signing Up.."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } /** * Creating User * */ protected String doInBackground(String... args) { String fname = mUsername.getText().toString(); String email = mEmail.getText().toString(); String password = mPassword.getText().toString(); // Building Parameters List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;(); params.add(new BasicNameValuePair("email", email)); params.add(new BasicNameValuePair("password", password)); params.add(new BasicNameValuePair("fname", fname)); // getting JSON Object // Note that create user url accepts POST method JSONObject json = jsonParser.makeHttpRequest(url_create_product, "POST", params); // check log cat from response //Log.d("Create Response", json.toString()); // check for success tag try { int success = json.getInt(TAG_SUCCESS); if (success == 1) { // successfully created USER Intent i = new Intent(getApplicationContext(), UserHome.class); startActivity(i); // closing this screen // finish(); } else { // failed to create USER // Log.d("No Sign Up.", json.toString()); } } catch(JSONException e){ // Log.e("log_tag", "Error parsing data "+e.toString()); // Log.e("log_tag", "Failed data was:\n" + TAG_SUCCESS); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog once done pDialog.dismiss(); } } </code></pre> <p>jsonParser.java(partial)</p> <pre><code> public JSONObject makeHttpRequest(String url, String method, List&lt;NameValuePair&gt; params) { // Making HTTP request try { // check for request method if(method == "POST"){ // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); }else if(method == "GET"){ // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } </code></pre> <p>SLIM :index.php</p> <pre><code>&lt;?php session_start(); require 'Slim/Slim.php'; $app = new Slim(); $app-&gt;post('/login', 'login'); $app-&gt;post('/register', 'register'); $app-&gt;response()-&gt;header('Content-Type', 'application/json'); $app-&gt;get('/users', 'getUsers'); $app-&gt;get('/users/:id', 'getUser'); $app-&gt;get('/users/search/:query', 'findByName'); $app-&gt;post('/users', 'addUser'); $app-&gt;put('/users/:id', 'updateUser'); $app-&gt;delete('/users/:id', 'deleteUser'); $app-&gt;get('/gametype', 'getgameType'); $app-&gt;run(); // AUTHENTICATION START function login() { $request = Slim::getInstance()-&gt;request(); $user = json_decode($request-&gt;getBody()); $email= $user-&gt;email; $password= $user-&gt;password; // echo $email; // echo $password; if(!empty($email)&amp;&amp;!empty($password)) { $sql="SELECT email, fname, role FROM tbl_user WHERE email='$email' and password='$password'"; $db = getConnection(); try { $result=$db-&gt;query($sql); if (!$result) { // add this check. die('Invalid query: ' . mysql_error()); } $row["user"]= $result-&gt;fetchAll(PDO::FETCH_OBJ); $db=null; echo json_encode($row); } catch(PDOException $e) { error_log($e-&gt;getMessage(), 3, '/var/tmp/php.log'); echo '{"error":{"text":'. $e-&gt;getMessage() .'}}'; } } } // AUTHENTICATION END //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ // Register START function register() { $request = Slim::getInstance()-&gt;request(); $user = json_decode($request-&gt;getBody()); $sql = "INSERT INTO tbl_user (email, password, fname) VALUES (:email, :password, :fname)"; try { $db = getConnection(); $stmt = $db-&gt;prepare($sql); $stmt-&gt;bindParam("fname", $user-&gt;fname); $stmt-&gt;bindParam("password", $user-&gt;password); $stmt-&gt;bindParam("email", $user-&gt;email); $stmt-&gt;execute(); $user-&gt;id = $db-&gt;lastInsertId(); $db = null; print('{"success":1}'); } catch(PDOException $e) { error_log($e-&gt;getMessage(), 3, '/var/tmp/php.log'); echo '{"error":{"text":'. $e-&gt;getMessage() .'}}'; } } // Register END </code></pre> <p>Behavior of APP: After clickng signup buttom...app gets stuck here and crashes as "Unfortunately, yourapp has stopped."..</p> <p><img src="https://i.stack.imgur.com/Kbwsx.jpg" alt="AppSCREEN"></p>
19,725,382
0
<p>You can use <code>$.proxy</code> to set the context within which a function should be called. try this:</p> <pre><code>beforeShowDay: $.proxy(this._processDate, this), </code></pre> <p>Now, within your <code>_processDate</code> function the <code>this</code> keyword will refer to your widget. You can get access to the element the event was raised on using <code>this.element</code>.</p>
5,358,680
0
<p>Yes, that is a much more complicated task. You're going to have to store the last modified time into a database (since you're saying users can modify their profile content I'll assume you already have a database). The easiest way to get the last time the user modified their profile depends on your schema.</p> <p>To put it another way... what the user is actually modifying isn't "profile.php", it's some data that lives elsewhere, e.g. a MySQL database; so the system that's going to know when the user last modified it is that external data source.</p>
16,070,455
0
<p>Why wouldn't be corrupted? You are opening a document, getting all of the child elements, and writing them to the same document. I am not sure what is that supposed to do.</p>
22,663,157
0
<p>Overdispersion isn't really a useful concept in the normal model because it is already fitting a variance for the variability at the observation level. So the error message is telling you that you can't have a grouping factor at the observation level. In that sense, yes, you are trying to overfit your model.</p> <p>In a poisson (or other glm) model, however, it does make sense, because the variability at the observation level is fixed according to whatever the variance term in the glm is, so it does make sense to add an additional variance term to the model to account for any extra variability at the observation level. Hence <code>glmer</code> does not do the same check that <code>lmer</code> does.</p>
3,944,136
0
<p>I <em>think</em> you want this:</p> <pre><code>$('#term').load('fetchcourses.php?', function() { $('[name=s2]').change(function() { $('#dept').load('fetchcourses.php?term='+$(this).val()); }); }); </code></pre> <p>The function passed to <code>load()</code> gets executed once the data is loaded. So if <code>$('[name=s2]')</code> actually refers to elements that are contained in the HTML returned from <code>fetchcourses.php</code>, then this should work.<br> But without telling more about the structure it is difficult to tell...</p>
34,716,062
0
<p>Try this code :</p> <pre><code>&lt;div ng-init="setFromDiv = 'green'" ng-click="setFromDiv = 'green'"class="box green"&gt;&lt;/div&gt; &lt;div ng-click="setFromDiv = 'blue'" class="box blue"&gt;&lt;/div&gt; &lt;div ng-click="setFromDiv = 'red'" class="box red"&gt;&lt;/div&gt; &lt;div ng-click="setFromDiv = 'yellow'" class="box yellow"&gt;&lt;/div&gt; &lt;div class="mainBox" ng-class="setFromDiv"&gt;&lt;/div&gt; </code></pre>
3,161,587
0
SSRS - How can I conditionally send a report to a mail address <p>Let me specify the environment. The client has UI for entering orders in SQL Server database. A Windows Service one another machine is processing these orders from database at particular intervals. Sometimes the Windows service is stopped then orders piles up. To avoid that I have created a SQL Server Report which is run at an interval of 5mins. It checks how many orders are processed and creates a status report. What I want, if count of processed order is zero then the report be mailed to system administrator. Then he will check the machine where the service is hosted and restart the service, so that all rework is avoided. So the question is how to implement this conditional delivery of report. In short, if count is zero no report be mailed otherwise it must.</p>
35,399,107
0
<p>Got it! Incredibly simple when you add a container node. The following seems to work for any positions in any quadrants.</p> <pre><code> // pointAt_c is a container node located at, and child of, the originNode // pointAtNode is its child, position coincident with pointAt_c (and originNode) // get deltas (positions of target relative to origin) let dx = targetNode.position.x - originNode.position.x let dy = targetNode.position.y - originNode.position.y let dz = targetNode.position.z - originNode.position.z // rotate container node about y-axis (pointAtNode rotated with it) let y_angle = atan2(dx, dz) pointAt_c.rotation = SCNVector4(0.0, 1.0, 0.0, y_angle) // now rotate the pointAtNode about its z-axis let dz_dx = sqrt((dz * dz) + (dx * dx)) // (due to rotation the adjacent side of this angle is now a hypotenuse) let x_angle = atan2(dz_dx, dy) pointAtNode.rotation = SCNVector4(1.0, 0.0, 0.0, x_angle) </code></pre> <p>I needed this to replace lookAt constraints which cannot, easily anyway, be archived with a node tree. I'm pointing the y-axis because that's how SCN cylinders and capsules are directed.</p> <p>If anyone knows how to obviate the container node please do tell. Everytime I try to apply sequential rotations to a single node, the last overwrites the previous one. I haven't the knowledge to formulate a rotation expression to do it in one shot.</p>
16,555,300
0
<p>This question has been answered already, but I want to point out that form_open() <strong>without</strong> any arguments would do exactly what you want (creating an action=""). </p> <p>So you can simply use the snippet below:</p> <pre class="lang-php prettyprint-override"><code>&lt;?php echo form_open(); ?&gt; </code></pre> <p>Here is a reference from the CodeIgniter's Source:</p> <pre class="lang-php prettyprint-override"><code>function form_open($action = '', $attributes = '', $hidden = array()) </code></pre>
498,526
0
Native vs. Protothreads, what is easier? <p>I just stumbled on Protothreads. They seems superior to native threads since context switch are explicit. </p> <p>My question is. Makes this multi-threaded programming an easy task again?</p> <p>(I think so. But have I missed something?)</p>
28,657,676
0
Bash EXIT trap with command substitution <p>I want a bash function to start a background process and set a trap to kill it when exiting. Something like:</p> <pre><code>function start { &lt;&lt;&lt;run process&gt;&gt;&gt; &amp; local pid="$!" trap "kill -9 $pid" EXIT echo $pid } </code></pre> <p>Now, if I just call this function directly, it works, but if I use command substitution to store pid for later use:</p> <pre><code>local pid=$(start) </code></pre> <p>Then apparently this starts another bash process and the trap is executed in it right after the function returns.</p> <p>Any way to make this work?</p>
25,328,659
0
<p>Maybe..</p> <pre><code>public void Delete_Bus(String bus_num) { SQLiteDatabase db=this.getWritableDatabase(); db.execSQL("DELETE FROM "+TABLE_BUS+" WHERE "+KEY_BUS_NUM+"='"+bus_num+"'"); db.close(); } </code></pre>
11,283,508
0
How to fetch records using predicate from A having relationship with A<-->B<-->C with coredata <p>I have three entities A,B,C. EntityA: Properties: Id,Name Relationships: ABRelation(A-->>B)</p> <p>EntityB: Properties: Id,Name Relationships: BARelation(B-->A) BCRelation(B-->>C)</p> <p>EntityC: RoleId CBRelation(C-->>B)</p> <p>Now I need to fetch records from Entity A having some RoleId = 23 which is contain in C.</p> <p>Could you please help me quickly.Thanks in Advance.</p>
18,232,552
0
Create Custom Action tab bar <p>I am trying to create a custom tabbar using <a href="http://www.androidbegin.com/tutorial/implementing-actionbarsherlock-side-menu-navigation-with-fragment-tabs-tutorial/" rel="nofollow noreferrer">this tutorial</a> for android 2.3.3 and above,but the title bar is disabled(Refer the image attached app deployed on Android 2.3.3 ).</p> <p><img src="https://i.stack.imgur.com/LLItU.png" alt="enter image description here"></p> <p>Also, how do I customize the titlebar. Please guide me for the same.</p>
36,799,704
0
<p>Here's an ersatz LR lexer/parser (in Python, but porting should be easy). Valid input is assumed.</p> <pre><code>#!/usr/bin/env python3 import re def parse(s): children = {} stack = [] for token in re.findall('[+-]?[0-9]+|.', s): if token == '[': stack.append(n) elif token == ']': del stack[-1] elif token != ',': n = int(token) children[n] = [] if stack: children[stack[-1]].append(n) return children &gt;&gt;&gt; print(parse('2[5],3[6,12[15,16]]')) {16: [], 2: [5], 3: [6, 12], 5: [], 6: [], 12: [15, 16], 15: []} </code></pre>
28,188,596
0
<p>You forgot to override among others the <a href="http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#size--" rel="nofollow"><code>size()</code></a> and <a href="http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#isEmpty--" rel="nofollow"><code>isEmpty()</code></a> methods. Moreover, you're never delegating to <code>ArrayList</code> superclass, but keeping an internal <code>ArrayList</code> instance. One would wonder why you extend from <code>ArrayList</code> at all instead of <a href="http://docs.oracle.com/javase/8/docs/api/java/util/AbstractList.html" rel="nofollow"><code>AbstractList</code></a> or even <a href="http://docs.oracle.com/javase/8/docs/api/java/util/List.html" rel="nofollow"><code>List</code></a>, which would in turn automatically force you to implement the right methods. An alternative would thus be to delegate to the <code>ArrayList</code> superclass instead of having an internal instance, so that the <code>size()</code> and <code>isEmpty()</code> calls would "automagically" return the right values.</p>
14,654,124
0
<p>You can use as mentioned below. You need a structure with an array of int.</p> <pre><code> struct Player { public int[] cards = new int[13]; }; </code></pre> <p>Then your while loop goes something like below</p> <pre><code>Palyer []player = new Palyer[4]; int random; int i = 1; while (i &lt;= 4) { cout &lt;&lt; "Card of Player " &lt;&lt; i &lt;&lt; " : "; int j = 0; while (j &lt; 13) { random = rand() % 52; if (player[i].cards[random] == NULL) { cards[random] = i; cout &lt;&lt; cardName(random) &lt;&lt; " , "; player[i].cards[j] = random; /* That's what I'm doubt with */ j++; } } i++; } </code></pre> <p>//Like the answer if it is helpful</p>
5,124,361
0
<p>"onSaveInstanceState only seems to support primitives"</p> <p>onSaveInstanceState supports objects, as long as they are declared serializable.</p> <pre><code>// ON_SAVE_INSTANCE_STATE // save instance data (5) on soft kill such as user changing phone orientation protected void onSaveInstanceState(Bundle outState){ password= editTextPassword.getText().toString(); try { ConfuseTextStateBuilder b= ConfuseTextState.getBuilder(); b.setIsShowCharCount(isShowCharCount); b.setTimeExpire(timeExpire); b.setTimeoutType(timeoutType); b.setIsValidKey(isValidKey); b.setPassword(password); state= b.build(); // may throw } catch(InvalidParameterException e){ Log.d(TAG,"FailedToSaveState",e); // will be stripped out of runtime } outState.putSerializable("jalcomputing.confusetext.ConfuseTextState", state); // save non view state super.onSaveInstanceState(outState); // save view state //Log.d(TAG,"onSaveInstance"); } </code></pre>
15,692,565
0
<p>I would suggest to create an Items constructor</p> <pre><code>Items(string weapon, string armour, int gold); </code></pre> <p>And change your player constructor to</p> <pre><code>Player(int health, int stamina, int keys, Items items); </code></pre> <p>You can then aggregate <code>Items</code> in <code>Player</code>.</p>
28,085,866
0
SQL Update to increment existing fields <p>I have an SQL table called 'Sales'</p> <p>I have the fields</p> <pre><code>ShopID int TotalSalesValue numeric(18.2) </code></pre> <p>Contents</p> <pre><code>ShopID | TotalSalesValue 1 | 10.34 2 | 100 </code></pre> <p>I have a stored procedure where I pass in the ShopID and addistion sales. What this does is check if the Shop ID exists in the table and if it does not, then it INSERTS into the table. If it goes exists I issue the UPDATE command. However, It update comment replaces the existing value, what I want to do it add onto the existing TotalSalesValue, a += if you may.</p> <p>Can anyone suggest a way to do this.</p> <p>Thanks in advance</p>
6,404,464
0
<p>If you look at the source code in <a href="http://webtimingdemo.appspot.com/" rel="nofollow">http://webtimingdemo.appspot.com/</a> it runs the code AFTER onload (setTimeout('writeTimings()', 0)), your code runs in $(document).ready() which runs before onload as it runs on DOMContentLoaded in Chrome.</p> <p>I have put a setTimeout into your code and now it works: See <a href="http://jsbin.com/acabo4/8" rel="nofollow">http://jsbin.com/acabo4/8</a></p> <pre><code>var performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {}; var timing = performance.timing || {}; function getTiming(timingStr) { if (!timing) return 0; var time = timing[timingStr]; return time; } var loadTime = (new Date().getTime() - getTiming("navigationStart"))/1000; $(document).ready(function() { setTimeout(function(){ var perflist = '&lt;ul id=perflist&gt;'; for(var performer in timing){ var j = getTiming(performer); perflist += '&lt;li&gt;' + performer + ' is: ' + j + '&lt;/li&gt;'; } perflist += '&lt;/ul&gt;'; $("body").prepend(perflist); $("#adminmenu").prepend("&lt;li&gt;Load time : " + loadTime + " seconds&lt;/li&gt;") }, 100); }); </code></pre>
5,172,616
0
How to parse one text file to multiple files based on data contained within <p>I have an enormous text file that I'd like to parse into other files - I think the only thing I have on this box (company computer) to use is VBS, so here's my question:</p> <p>I have text file with a bunch of network configurations that looks like this:</p> <p>"Active","HostName","IPAddress"<br> !<br> .......<br> end<br></p> <p>This repeats itself throughout the file, but obviously for each configuration different data will occur within the "..." It always says "Active" for each configuration as well.</p> <p>I want to create save files of the type HostName.cfg for each configuration and save all of the text between and including the ! and "end" . The line with the three quoted attributes doesn't need to be copied.</p> <p>I'm still learning VBS so I'd appreciate any help in the matter. Thanks!</p>
6,401,393
0
<p>You should probably write your application as a Home application. There is an example in the developer docs here:</p> <p><a href="http://developer.android.com/resources/samples/Home/index.html" rel="nofollow">http://developer.android.com/resources/samples/Home/index.html</a></p> <p>Then you'd be able to switch the default Home application for your one.</p>
12,011,482
0
<p>Whatever is not implemented in the Linux kernel, you have to implement yourself or borrow from another open source kernel module. However, you'll find that <code>strcat</code> is implemented in the kernel.</p> <p>See the <a href="http://www.kernel.org/doc/htmldocs/kernel-api/">kernel API</a> documentation. Specifically the <a href="http://www.kernel.org/doc/htmldocs/kernel-api/libc.html">Basic C Library Functions</a> section for your general question, and the <a href="http://www.kernel.org/doc/htmldocs/kernel-api/ch02s02.html">String Manipulation</a> section for your specific question about <code>strcat</code>.</p> <p>You'll want to include <code>linux/string.h</code>.</p> <p>I don't know why the kernel API documentation doesn't actually show the header file that you have to include to get the function. But if you're looking for something, you can restrict your search to <code>/include/linux</code> because that is where header files go if they have functions that are shared amongst different parts of the kernel.</p> <p>Header files outside <code>/include/linux</code> contain definitions only for source files residing in the same directory as the header. The exception is <code>/arch/.../include</code>, which will contain architecture-specific headers instead of platform independent ones.</p>
33,730,659
0
<p>With all the hints I found out that <code>DataGridTextColumn</code> is neither part of the visual tree nor of the logical tree. That should be the reason why <code>ElementName</code> and <code>RelativeSource</code> do not work. This answer regarding <code>DataGridTextColumn</code> explains that and gives a possible solution with <code>Source</code> and <code>x:Reference</code>: <a href="http://stackoverflow.com/questions/8847661/datagridtextcolumn-visibility-binding">DataGridTextColumn Visibility Binding</a></p> <p>The answer of @Anand Murali works but cannot be applied to <code>Visibility</code> - that was not part of the question because I minimalized that away. So I accept that one and will give more information in this one.</p> <p>Using <code>x:Reference</code> for <code>Visibility</code> it can turn out like:</p> <pre><code>&lt;DataGridTextColumn Binding="{Binding Data.OrderNumber}" Header="Order Number" Visibility="{Binding DataContext.ShowColumnOrderNumber, Source={x:Reference LayoutRoot}, Converter={StaticResource BooleanToVisibilityConverter}}" /&gt; </code></pre> <p>But: I my example I use a <code>ControlTemplate</code> and to have <code>x:Reference</code> to work this template must be within a <code>.Resources</code> XAML part in the same file and cannot be in an external <code>ResourceDictionary</code>. In the latter case the reference will not work because it cannot be resolved. (If someone knows a solution to that it would be welcome)</p>
30,140,030
0
How to check if Graph is connected <p>I have a un-directed graph, and wanted to know a node is connected to another node or not?</p> <p>for example </p> <pre><code>0 1 0 1 0 1 0 1 0 </code></pre> <p>In this node 1 is connected to node 3 ( because there is a path from 1 to 2 and 2 to 3 hence 1-3 is connected )</p> <p>I have written programs which is using DFS, but i am unable to figure out why is is giving wrong result.</p> <p><em>I don't want to keep any global variable</em> and want my method to return true id node are connected using <em>recursive</em> program</p> <pre><code>public static boolean isConnectedGraph(int[][] graph, int start, int end, int visited[]) { visited[start] = 1; if (graph[start][end] == 1) { System.out.println("Yes connected...."); return true; } for (int i = 0; i &lt; graph[0].length; i++) { if (graph[start][i] == 1 &amp;&amp; visited[i] == 0) { visited[i] =1; isConnectedGraph(graph, i, end, visited); } } return false; } </code></pre>
549,600
0
Is there a fundamental difference between backups and version control? <p>How does version control differ from plain backups?</p> <p>Let's forget about the feature decoration, and concentrate on the soul of version control. Is there a clear line that backups must cross before they can be called a VCS? Or are they, at heart, the same thing with different target markets?</p> <p>If there is a fundamental difference, what is the absolute minimum requirement for something to reach the status of version control?</p> <p><em>When you answer, please don't just list features (such as delta compression, distributed/central repositories, and concurrent access solutions) that most version control systems have or should have, unless they actually are necessary for a VCS by definition.</em></p>
16,611,423
0
Send picture from android phone to a local web server <p>I've been searching all over and found a bunch of examples of ways to send a picture to a web server. So far none have quite worked for me. Maybe I started in the wrong end but I've already written the code for the controller which is to take care of the received picture.</p> <p>I'm using a Tomcat web server and written all the code on the server side with Spring Tool Suite with the MVC Framework. The controller is written like this:</p> <pre><code>@RequestMapping(value = "/upload", method = RequestMethod.POST) public String handleFormUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) throws IOException { if (!file.isEmpty()) { byte[] bytes = file.getBytes(); // store the bytes somewhere return "redirect:uploadSuccess"; } else { return "redirect:uploadFailure"; } } </code></pre> <p>The .jsp is written like this:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Upload a file please&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Please upload a file&lt;/h1&gt; &lt;form method="post" action="/form" enctype="multipart/form-data"&gt; &lt;input type="text" name="name"/&gt; &lt;input type="file" name="file"/&gt; &lt;input type="submit"/&gt; &lt;/form&gt; &lt;/body&gt; </code></pre> <p></p> <p>So basically what I'd like to know: <br/> How can I write a class/method that sends a picture from my phone to the web server?</p> <p>I appreciate all the help I can get!</p>
37,355,029
0
<p>One thing you could do is take advantage of the <code>std::minmax</code> overload that takes a <code>std::initializer_list&lt;T&gt;</code> and returns a <code>std::pair&lt;T,T&gt;</code>. Using that you could have</p> <pre><code>int main() { const int a = 10, b = 20; static_assert(std::minmax({2, 1}) == std::make_pair(1, 2)); static_assert(std::minmax({a, b}) == std::make_pair(a, b)); } </code></pre> <p>Which <a href="http://coliru.stacked-crooked.com/a/d4630df7a71f182f">will compile</a> and allows you to get rid of <code>make_cref_pair</code>. It does call <code>std::minmax_element</code> so I am not sure if this decreases the efficiency or not.</p>
7,029,215
0
<p>oh, I just got what you mean by total revenue going down, weird...</p> <p>I suppose total revenue is only shown for the period of time selected, if you view a 30 or 90 days window, total revenue going down means the revenue over that period is lower than it was for the previous same-length period.</p> <p>Check "pending earning"s to see the all-time total amount on your account.</p>
29,153,431
0
<p>You should add a tap gesture recognizer to your table view that closes the keyboard when it's fired:</p> <pre><code>//Somewhere in setup UITapGestureRecognizer *viewTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyboard)]; viewTap.cancelsTouchesInView = FALSE; [myTableView addGestureRecognizer:viewTap]; //Somewhere else in your class -(void)closeKeyboard { [self.view endEditing:TRUE]; } </code></pre>
35,662,520
0
<p>Remove the Chr from every item in the first column (you can go through every line and only keep </p> <pre><code> [3:] </code></pre> <p>of each line, means everything but the first 3 chars. Then sort the lines by the first column and you should almost be finished?</p>
19,869,231
0
Opening multiple programs on a HTA <p>I'm using a HTA and I want to make various buttons to open different programs on the system.</p> <p>I've managed to get one program to run via the runfile command but how do I write to open another program using a separate button such as MS Word for example.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Start Screen&lt;/title&gt; &lt;HTA:APPLICATION ID="startscreen" APPLICATIONNAME="startscreen" BORDER="thin" BORDERSTYLE="normal" CAPTION="yes" ICON="ss.ico" MAXIMIZEBUTTON="no" MINIMIZEBUTTON="yes" SCROLL="no" SHOWINTASKBAR="yes" SINGLEINSTANCE="yes" SYSMENU="yes" VERSION="1.0" Navigable ="yes" WINDOWSTATE="normal" contextmenu="no" /&gt; &lt;script type="text/javascript" language="javascript"&gt; function RunFile() { WshShell = new ActiveXObject("WScript.Shell"); WshShell.Run("c:/windows/system32/notepad.exe", 1, false); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;input type="button" value="Run Notepad" onclick="RunFile();"/&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
30,614,683
0
matching login info to external file php <p>I have html registration form with username and password inputs. Usernames and passwords are stored in <code>.txt</code> file like this:</p> <pre><code>username1,password1 username2,password2 </code></pre> <p>I need to match entered username and password with the stored ones. This is my code, but something is not working, can somebody advise? </p> <pre><code>&lt;form action = "./get_form.php" method = "post" name = "form" &gt; Username: &lt;input type= "text" name = "username" &gt; Password: &lt;input type= "text" name = "passwords" &gt; Remember me: &lt;input type= "checkbox" name = "remember" value = "checked" &gt; &lt;input type = "submit" name = "submit" value= "Submit Query" &gt; &lt;/form&gt; &lt;?php $username= $_POST["username"]; $password= $_POST["password"]; $contents = file("passwords.txt"); $found = false; foreach ($contents as $line) { $data = explode(',', $line); if (($username === $data[0]) &amp;&amp; ($password === $data[1])) { $found = true; } } ?&gt; </code></pre>
15,074,850
0
<p>It's not that you can't access "primitive values" by reference. The problem is that some data types in Python are mutable (lists, dictionaries) while others are immutable (integers, strings, tuples). Whenever you try to modify an immutable object, you always get back a new object with the new value. The original object remains untouched. So...</p> <pre><code>a = 3 # create a new object with the value 3 and bind it to the variable 'a' b = a # bind the variable 'b' to the same object as 'a' </code></pre> <p>Here both 'a' and 'b' are referencing the same object at the same location in memory. However, because the object is immutable, modifying 'b' does not have the "expected" result...</p> <pre><code>b = 4 print a # displays "3" </code></pre> <p>Those of us coming from C/C++ aren't used to "immutable objects". In C, you would expect "b = 4" to modify the "object" b is pointing to, setting its value to 4. In Python, this isn't the case. "b = 4" creates a new object whose value is 4 and modifies b so that it points to this new object.</p>
11,144,267
0
<p>If you use Three20, you can try this extension:</p> <p><a href="https://github.com/RIKSOF/three20/tree/development/src/extThree20Facebook" rel="nofollow">https://github.com/RIKSOF/three20/tree/development/src/extThree20Facebook</a></p> <p>It allows you to use all Graph API features with just a few line of code.</p>
10,511,836
0
<pre><code>var f = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory,'example.txt'); var contents = f.read(); Ti.API.info('Output text of the file: '+contents.text); </code></pre> <p>This will give you the text. You can't simply put the text on the scroll view, you will need a label / textbox etc. set the value of one of those controls to the above print out.</p> <p>Here is a link to the API, this has every method and sample pieces of code, you will need to research / learn you can't just ask for everything you need.</p> <p>Would also recommend downloading the kitchen sink demo app as it has just about an example of everthing</p>
19,270,053
0
php str_replace not works <p>I have a html code putted in a variable. I want to replace any relative image src to absolute aby using str_replace. like this:</p> <pre><code>$export = 'some html codes' $repthis = 'src="/images'; $reptothis = 'src="http://images.site.com'; $export = str_replace($repthis, $reptothis, $export); </code></pre> <p>but this code is not working for me. I tried this code for test and it is working:</p> <pre><code>$export = 'some html codes' $repthis = "text1"; $reptothis = "text2"; $export = str_replace($repthis, $reptothis, $export); </code></pre> <p>this code is replacing text1 by text2 in my html code correctly. please help me.</p>
8,827,607
0
<p>Use <a href="http://php.net/manual/en/function.strftime.php" rel="nofollow"><code>strftime()</code></a> in conjunction with <a href="http://www.php.net/manual/en/function.setlocale.php" rel="nofollow"><code>setlocale()</code></a>. Seems like it's what you're looking for.</p>
16,750,242
0
<p>This is because you are effectively only using <code>data1</code>.</p> <p>The first loop can be expanded to</p> <pre><code>data1 = read.table('data1_lambda.dat', ...) data2 = read.table('data2_lambda.dat', ...) data3 = read.table('data3_lambda.dat', ...) </code></pre> <p>whereas your second loop is a bit buggy and the cause of the fault. If I expand the loop, what happens is:</p> <pre><code>plot(data.frame(data1[1], data1[2]), ...) lines(data.frame('data2[1]', 'data2[2]', ...) lines(data.frame('data3[1]', 'data3[2]', ...) </code></pre> <p>i.e. what you think is fetching <code>data2</code> and <code>data3</code>, you are really only using the strings <code>'data2'</code> and <code>'data3'</code> (note the quotation marks).</p> <p>Without assuming too much of your data and restructuring you entire code, this should do the trick (for the second loop). Since you only have three data-files, looping seems a bit extensive contra the problems they are introducing.</p> <pre><code>plot(data.frame(data1[1], data1[2]), xlim=c(-0.2, -7), ylim=c(0.31, 0.35), yaxt="n", type="l", xlab="", ylab="",lty="solid", col="red2", lwd=4, axes=TRUE) lines(data.frame(data2[1], data2[2]) ,lty="twodash", col="deepskyblue4", lwd=4) lines(data.frame(data3[1], data3[2]) ,lty="twodash", col="deepskyblue4", lwd=4) </code></pre> <p>If you insist on looping, we could do:</p> <pre><code>for(i in 1:3){ if(i==1){ plot(data.frame(data1[1], data1[2]), xlim=c(-0.2, -7), ylim=c(0.31, 0.35), yaxt="n", type="l", xlab="", ylab="",lty="solid", col="red2", lwd=4, axes=TRUE) } else { dat &lt;- get(paste('data', i, sep='')) lines(data.frame(dat[1], dat[2]) ,lty="twodash", col="deepskyblue4", lwd=4) } } </code></pre> <p>To further comment your code, in your <code>read.table</code> call, you have two nested <code>paste</code> calls, which in this case is unnecessary.</p> <p>paste(paste("data", i, sep=""),"_lambda.dat",sep="") # could be done with paste(paste("data", i, "_lambda.dat",sep="")</p>
35,098,118
0
How to create report table in sql? <p>I am creating In-patient management system desktop application in javafx as my mini project of MCA, which has some data about patient admitted in hospital.</p> <p>I have to save all the records of patient test &amp; test reports in a database.</p> <p>So, I have created <code>Test</code> table with following attributes </p> <pre><code>-&gt;(T_ID, P_ID, T_NAME, T_DATE), </code></pre> <p><code>Report</code> table with following attributes </p> <pre><code>-&gt;(R_ID, P_ID, P_NAME, T_DATE, REF_BY) </code></pre> <p>So, there are multiple types of Test Report like,</p> <pre><code>eg. CBC_REPORT, LFT_REPORT etc. </code></pre> <p>then how should I create the relationship between this table.</p> <p>I tried but I am facing problem in user interface for inputing values in table.</p>
18,564,726
0
<p>I have found in the past that there are 3 dlls you need to have the correct version of for debugging .Net.</p> <p>sos.dll mscorwks.dll mscordacwks.dll</p> <p>here's how I usually go about getting these dll's <a href="http://sjbdeveloper.blogspot.com.au/" rel="nofollow">http://sjbdeveloper.blogspot.com.au/</a>, although it sounds as though you are using a server based application which means you could possibly just grab them from your production box, assuming you have access to it, or a staging box if you don't.</p>
35,667,576
0
<p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() { //----- OPEN $('[data-popup-open]').on('click', function(e) { var targeted_popup_class = jQuery(this).attr('data-popup-open'); $('[data-popup="' + targeted_popup_class + '"]').fadeIn(350); setTimeout(function(){ $('.newsletter-popup').fadeOut(); }, 2000); e.preventDefault(); }); //----- CLOSE $('[data-popup-close]').on('click', function(e) { var targeted_popup_class = jQuery(this).attr('data-popup-close'); $('[data-popup="' + targeted_popup_class + '"]').fadeOut(); e.preventDefault(); }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>/* Outer */ .newsletter-popup { width:100%; height:100%; display:none; position:fixed; top:0px; left:0px; background:rgba(0,0,0,0.75); } /* Inner */ .popup-inner { max-width:700px; width:90%; padding:40px; position:absolute; top:50%; left:50%; -webkit-transform:translate(-50%, -50%); transform:translate(-50%, -50%); box-shadow:0px 2px 6px rgba(0,0,0,1); border-radius:3px; background:#fff; } /* Close Button */ .popup-close { width:30px; height:30px; padding-top:4px; display:inline-block; position:absolute; top:0px; right:0px; transition:ease 0.25s all; -webkit-transform:translate(50%, -50%); transform:translate(50%, -50%); border-radius:1000px; background:rgba(0,0,0,0.8); font-family:Arial, Sans-Serif; font-size:20px; text-align:center; line-height:100%; color:#fff; text-decoration:none; } .popup-close:hover { -webkit-transform:translate(50%, -50%) rotate(180deg); transform:translate(50%, -50%) rotate(180deg); background:rgba(0,0,0,1); text-decoration:none; } #popup-inner-content { text-align: center; font-size: 2em; color: #2a2a2a; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"&gt;&lt;/script&gt; &lt;a class="btn" data-popup-open="popup-1" href="#"&gt;Open Popup #1&lt;/a&gt; &lt;div class="newsletter-popup" data-popup="popup-1"&gt; &lt;div class="popup-inner"&gt; &lt;div id="popup-inner-content"&gt;Thanks for subscribing to our newsletter!&lt;/div&gt; &lt;!-- &lt;p&gt;&lt;a data-popup-close="popup-1" href="#"&gt;Close&lt;/a&gt;&lt;/p&gt; --&gt; &lt;a class="popup-close" data-popup-close="popup-1" href="#"&gt;x&lt;/a&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
9,979,801
0
<h2>PROBLEM:</h2> <p>I'm betting that you have a one-dimensional array with strings stored in each. So your array actually looks like:</p> <pre><code>array ( [0] =&gt; '...', [1] =&gt; '.X.', [2] =&gt; '...' ) </code></pre> <p>When this is what you want:</p> <pre><code>array ( [0] =&gt; array ( [0] =&gt; '.', [1] =&gt; '.', [2] =&gt; '.' ), [1] =&gt; array ( [0] =&gt; '.', [1] =&gt; 'X', [2] =&gt; '.' ), [2] =&gt; array ( [0] =&gt; '.', [1] =&gt; '.', [2] =&gt; '.' ) ) </code></pre> <p><br /></p> <h2>SOLUTION:</h2> <p>When constructing your 2D array, make sure you explicitly declare each entry in <code>board</code> as an array. So to construct it, your code might look something like this:</p> <pre><code>board = new Array(); rows = 3; for (var i = 0; i &lt; rows; i++) board[i] = new Array('.', '.', '.'); </code></pre>
17,344,168
0
Using SQL "Tree Branch" shortcut to Join Tables <p>To add more clarity to my question, I've seen a way in which by right clicking in the object explorer (or somewhere within) we had the option of selecting a checkbox from one table and then another to have it autogenerate the JOIN query beneath. </p> <p>I'm unsure of where this is, or if it even still exisits. I did a quick search online, and through SQL Server myself but have yet to find anything. </p> <p>Does this ring a bell to anyone? Ideally I could see the tables that are connected to one another in a "Tree Branch" form and can click on directly to join those two (or atleast populate the query)...</p> <p>Let me know, thanks!</p>
29,657,155
0
<p>in my case using <code>width="100%"</code> in table caused the problem, removing width solved it.</p> <p><strong>working code</strong></p> <pre><code>&lt;table id="dt_table"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;column1&lt;/th&gt; &lt;th&gt;column2&lt;/th&gt; &lt;th&gt;column3&lt;/th&gt; &lt;th&gt;column4&lt;/th&gt; &lt;th&gt;column5&lt;/th&gt; &lt;th&gt;column6&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;/table&gt; </code></pre>
12,489,854
0
How can I prevent both the keyboard and the menu from being shown together? <p>Here's a screenshot of my application. When the search box is clicked, the soft-keyboard automatically pops up, which is fine, but, if I also press the "Menu" button, the menu appears on top of the soft-keyboard. </p> <p>How can I show the menu but collapse the <code>SearchView</code> if it is in focus and also hide the soft-keyboard. I probably need to check and do something in the <code>onPrepareOptionsMenu</code> method of my <code>Activity</code>, right?</p> <p>It doesn't cause any real harm to me but it seems like an ugly implementation to the user when this happens.</p> <p><img src="https://i.stack.imgur.com/FQckf.jpg" alt="enter image description here"></p>
33,260,553
1
Using PyperClip on web app <p>I am using pyperclip.py to grab a list of E-Mail Addresses in my web app using a form so a user can paste it locally via clipboard. It works perfect locally. However, while running it on a server (Linux 14.04 with Apache2) and accessed from a client system through the browser it doesn't copy. How can I get it to copy to the clipboard of the client's system? </p> <p>Right now I'm just trying to get it to work and as such I'm only using a single line. I'm using pyperclip 1.5.15 with xclip and Python 3.4. The server is running Linux 14.04 and the client has noticed issues on Windows 8 and Windows 10 using Google Chrome and IE. No other os has currently been tested. </p> <pre><code>pyperclip.copy("HELLO") </code></pre>
34,459,670
0
Convert Library to JavaScript closure <p>I have an external library of JavaScript functions that I need to pull into my server-side Google Apps Script project. I'm doing this mainly for performance reasons, but also because <a href="https://developers.google.com/apps-script/guide_libraries" rel="nofollow">Google now recommends against using external libs</a>.</p> <p>In the current configuration, functions in the external library are referenced by <code>&lt;Libname&gt;.funcName()</code>, and any globals in the library are likewise contained, e.g. <code>&lt;Libname&gt;.globA</code>. If I just copy the library into a file in my project, those functions (and "globals") would be referenced as <code>funcName()</code> alone. I've got hundreds of such references in my project that potentially need to change. That's fine; it's something a global search &amp; replace can address. However, I have worries about "namespace" problems... Since the library is third-party code, I've had no control over it, and now I'm running into name collisions, as objects and functions in the library have the same names as some of my code.</p> <p>How can I pull this code into my project in a way that will keep its internal details separate from my code? Is there a way to do that and retain the current naming convention, <code>&lt;Libname&gt;.funcName()</code>? I believe that JavaScript closures are the right solution, but don't know enough about them.</p> <h3>My project, <code>Code.gs</code></h3> <pre><code>var globA = { key: 'aKey', value: 'valA' }; function myFunction() { var a = MyLib.getValue(); Logger.log( JSON.stringify( a ) ); // { key: 'libKey', value: 'valLibA' }; } function getValue() { return globA; } </code></pre> <h3>Library "MyLib", <code>Code.gs</code></h3> <pre><code>var globA = { key: 'libKey', value: 'valLibA' }; function getValue( ) { return globA; } </code></pre>
28,298,046
0
Filter not working with laravel commands <p>Can we use filters with Laravel commands. It works fine with controllers. But when use with commands it shows error "call to undefined method". I have this filter customAuth. It works fine in controller by calling <code>$this-&gt;beforeFilter('podioAuth');</code></p> <p>But when I use this with Laravel commands it shows error. Are filters designed only to work with controllers?</p>
24,266,037
0
<p>The following code should help. You should split each subject into a separate array within your query. Once your query is complete, you should iterate through the subject array, and then within each staff id.</p> <pre><code>$subjects = array(); $q = mysql_query("Select staff_id from my_table"); while($row = mysql_fetch_array($q)){ if ($subjects[$row['SUBJECT']] == nil) { $subjects[$row['SUBJECT']] = array(); } array_push($subjects[$row['SUBJECT']], $row['STAFF_ID']); } foreach ($subjects as $key=&gt;$value) { echo $key . '&lt;br&gt;; foreach ($vaue as &amp;$staff) { echo $staff . '&lt;br&gt;'; } } </code></pre>
15,134,325
0
<p>Call <code>moment.utc()</code> the same way you're calling <code>Date.UTC</code>: </p> <pre><code>var withMoment = moment.utc([now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes(), now.getSeconds()]).valueOf(); </code></pre> <p>I think calling <code>moment.utc(now)</code> will make it assume <code>now</code> lives in the local timezone, and it will convert it to UTC first, hence the difference.</p>
21,927,147
0
How to serialize ArrayList of float arrays <p>I have an ArrayList, and each object consists of an array of two floats representing coordinates. I found that I could serialize the ArrayList by calling the .toString() method on it, but this did not serialize the float arrays within the ArrayList. How can I go about serializing those as well?</p> <p>Here is basically what I did:</p> <pre><code>private ArrayList&lt;float[]&gt; pointsList = new ArrayList&lt;float[]&gt;(); </code></pre> <p>In an onTouch method, I add coordinates to the list:</p> <pre><code>float[] thisPosition = new float[2]; thisPosition[0] = touchX; thisPosition[1] = touchY; pointsList.add(thisPosition); </code></pre> <p>Then I serialize the ArrayList like this:</p> <p>pointsList.toString();</p> <p>But each item in the list is turned into F@426d51d8 and other strings like that. How can I serialize these sub-arrays and preserve their numeric values? I have searched forums here on StackOverflow and elsewhere, but other similar questions address how to make an ArrayList of String arrays or other ArrayLists.</p>
32,950,452
0
<p>Copy and paste this into notepad and remove all <code>\</code> characters so that you get one long line. Then paste in cmd. Should work. And the message you are seeing usually means that you try to run <code>mvn</code> from a folder which does not contain <code>pom.xml</code></p>
23,621,173
0
<p>How about writing 2 servlets, one to take in the image and write it to the database and another one to get the image and pass it back in the response output stream which you can call from the webpage via an ajax call.</p>
18,536,407
0
Keep `this` on prototype's object <p>I am trying to build a small javascript library for study purposes. I have an object inside a prototype that has some functions inside. I would like to access <code>this</code> (the one that has <code>valueOf</code> and stuff) from inside the functions, but <code>this</code> now brings me only the object parent to the functions.</p> <p>My code (coffee):</p> <pre><code>HTMLElement.prototype.on = click: (action) -&gt; @valueOf().addEventListener('click', action, false) # I'd like this to work, # but `this` here refers to the `on` object </code></pre> <p>Is this possible? I know I'm kinda reinventing the wheel, but as I said, it's for study purposes, so that's the idea.</p>
25,439,285
0
<p>I ended up implementing a custom version of the parsing algorithm used by JISON's compiled parsers, which takes an immutable state object, and a token, and performs as much work as possible with the token before returning. I am then able to use this implementation to check if a token will produce a parse error, and easily roll back to previous states of the parser.</p> <p>It works fairly well, although it is a bit of a hack right now. You can find the code here: <a href="https://github.com/mystor/myst/blob/cb9b7b7d83e5d00f45bef0f994e3a4ce71c11bee/compiler/layout.js" rel="nofollow">https://github.com/mystor/myst/blob/cb9b7b7d83e5d00f45bef0f994e3a4ce71c11bee/compiler/layout.js</a></p> <p>I tried doing what @augustss suggested, using the error production to fake the token's insertion, but it appears as though JISON doesn't have all of the tools which I need in order to get a reliable implementation, and re-implementing a stripped-down version of the parsing algorithm turned out to be easier, and lined up better with the original document.</p>
28,671,966
0
<p><strong>Function to get random integers where min, max are inclusive</strong></p> <pre><code>function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } </code></pre> <p><strong>Function to find Random Value from passed variable <code>plot</code></strong></p> <pre><code>function getRandomValue(plot) { var rN1 = getRandomInt(0,plot.length-1); var areaArray= plot[rN1].area.split(","); var rN2 = getRandomInt(0,areaArray.length-1); return areaArray[rN2]; } </code></pre> <p><strong>And use it like</strong></p> <pre><code>plot = [ { postcode: "MK1", area: "Denbigh, Mount Farm", }, { postcode: "MK2", area: "Brickfields, Central Bletchley, Fenny Stratford, Water Eaton" }, { postcode: "MK3", area: "Church Green, Far Bletchley, Old Bletchley, West Bletchley", }, { postcode: "MK4", area: "Emerson Valley, Furzton, Kingsmead, Shenley Brook End, Snelshall West, Tattenhoe, Tattenhoe Park, Westcroft, Whaddon, Woodhill", }, { postcode: "MK5", area: "Crownhill, Elfield Park, Grange Farm, Oakhill, Knowlhill, Loughton, Medbourne, Shenley Brook End, Shenley Church End, Shenley Lodge, Shenley Wood", } ] console.log(getRandomValue(plot)) </code></pre>
40,550,961
0
<p>Those specific pieces of information aren't necessarily available in any sort of direct way using the xAPI (Tin Can API). xAPI stores data points in a stream of statements, those statements <em>may</em> include some of that information depending on how and what generated them.</p> <p>To access the statement stream you would need to make xAPI requests to the <code>/statements</code> resource provided by the LRS. You would have to ask the individual vendors for the location of their xAPI "endpoint" and for information on credentials for accessing that endpoint. Once you have that information I would suggest using one of the open source libraries linked at <a href="http://experienceapi.com/libraries" rel="nofollow noreferrer">http://experienceapi.com/libraries</a> to interface with the LRS. A lot of additional information about what xAPI provides, how to use it, etc. is available at that site.</p>
7,504,180
0
<p>Maybe you could try this</p> <pre><code> double res = a / (b == 0 ? a : b); </code></pre>
11,236,200
0
Why do we need a static lock for synchronizing system.out.println()? <p>I am studying for java certification, and I see this example from Mughal's book:</p> <pre><code>public class Smiley extends Thread { @Override public void run() { while(true) { synchronized(this) { try { System.out.print(":"); Thread.sleep(100); System.out.print("-"); Thread.sleep(100); System.out.println(")"); Thread.sleep(100); } catch(InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) { new Smiley().start(); new Smiley().start(); } } </code></pre> <p>The purpose is to print one smiley :-) per line. My question is that why synchronizing on instance (this) doesn't achieve this? Why we need to synchronize on static level?</p> <p>Thanks,</p>
121,231
0
<p>In a word - No</p>
40,503,745
0
<p>how about </p> <pre><code>julia&gt; collect(b)[1] "A" </code></pre> <p><strong>edit</strong> </p> <p>as the legendary Dan Getz suggested, consider doing </p> <pre><code>julia&gt; collect(take(b,1))[1] "A" </code></pre> <p>if memory is an issue</p>
13,424,483
0
<p>When you open a MongoDB connection with the native driver, you're actually opening a pool of 5 connections (by default). So it's best to open that pool when your app starts and just leave it open rather than open and close the pool on each request.</p> <p>You're on the right track with closing out your HTTP response; just call <code>res.end();</code> when the response is complete (i.e. when <code>item</code> is <code>null</code> in the <code>cursor.each</code> callback).</p>
18,434,000
0
<p>Check your remote "origin" to ensure the URL looks correct:</p> <p><code>git remote -v</code></p> <p>Next, try listing out the contents of the remote:</p> <p><code>git ls-remote origin</code></p> <p>If all goes well with the steps above, Git is certainly connecting to the GitHub hosted repository. Try the <code>git push origin fefixex</code> again.</p>
14,747,579
0
<p>Your code is already working:</p> <p>for download as cvs add this code block:</p> <pre><code>Highcharts.getOptions().exporting.buttons.exportButton.menuItems.push({ text: 'Download CSV', onclick: function () { Highcharts.post('http://www.highcharts.com/studies/csv-export/csv.php', { csv: this.getCSV() }); } }); </code></pre> <p><a href="http://jsfiddle.net/gyf9y/1/" rel="nofollow">YOUR CODE DEMO</a></p>
31,346,733
0
How does mask affect stencil value according to stencil op? <p>The documentation in OpenGL reference pdf (both OpenGL 3.3 and 4.5 specs) is not much clear about what happens to the stored stencil value when a mask is applied.</p> <p>In example If I have the following mask:</p> <pre><code>glStencilMask( 0x06); </code></pre> <p>and stored in the stencil buffer there is already this value:</p> <pre><code>0x06 </code></pre> <p>If the stencil operation is <code>GL_INCR_WRAP</code></p> <p>what should happens when StencilOp is correctly invoked on that pixel?</p> <p>Basically I have the mask:</p> <pre><code>00000110 </code></pre> <p>and the value</p> <pre><code>00000110 </code></pre> <p>and I try to increment it, is it wrapped?</p> <pre><code>00000010 </code></pre> <p>or is it just zeroed? <code>(00000110 + 1) &amp; mask</code></p> <pre><code>00000000 </code></pre>