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
6,175,548
Array copy values to keys in PHP
<p>I have this array:</p> <pre><code>$a = array('b', 'c', 'd'); </code></pre> <p>Is there a simple method to convert the array to the following?</p> <pre><code>$a = array('b' =&gt; 'b', 'c' =&gt; 'c', 'd' =&gt; 'd'); </code></pre>
6,175,571
2
0
null
2011-05-30 11:14:20.363 UTC
26
2021-02-13 11:59:38.89 UTC
2017-06-18 08:29:43.303 UTC
null
63,550
null
276,640
null
1
184
php|arrays
121,445
<pre class="lang-php prettyprint-override"><code>$final_array = array_combine($a, $a); </code></pre> <p>Reference: <a href="http://php.net/array-combine" rel="noreferrer">http://php.net/array-combine</a></p> <p><strong>P.S.</strong> Be careful with source array containing duplicated keys like the following:</p> <pre class="lang-php prettyprint-override"><code>$a = ['one','two','one']; </code></pre> <p>Note the duplicated <code>one</code> element.</p>
30,972,574
Dagger 2 Custom Scope for each Fragment (or Activity etc...)
<p>I've looked at a couple different articles which seem to suggest two different ways of doing custom scoping in Dagger 2:</p> <ol> <li><p><a href="http://blog.bradcampbell.nz/mvp-presenters-that-survive-configuration-changes-part-2/">MVP Presenters that Survive Configuration Changes Part-2</a> (<a href="https://github.com/grandstaish/hello-mvp-dagger-2/tree/master/app/src/main/java/com/example/bradcampbell/app">Github repo</a>):</p> <ul> <li>Uses unique custom scopes for each fragment, e.g. <code>@Hello1Scope</code> and <code>@Hello2Scope</code> for <code>Hello1Fragment</code> and <code>Hello2Fragment</code> respectively</li> </ul></li> <li><p><a href="http://fernandocejas.com/2015/04/11/tasting-dagger-2-on-android/">Tasting Dagger 2 on Android</a>:</p> <ul> <li>Uses a single custom scope for all fragments, e.g. <code>@PerFragment</code>.</li> </ul></li> </ol> <p>From what I understand, it seems that, as in method 2, it should be okay to have a single scope defined that can be used for all fragments (i.e., <code>@PerFragment</code>). In fact (please correct me if I'm wrong), it seems like the name of the custom scope is irrelevant, and it's only where the subcomponent is created (i.e. in Application, Activity, or Fragment) that matters.</p> <p>Is there any use case for defining a unique scope for each fragment such as in case 1?</p>
30,984,952
2
0
null
2015-06-22 05:22:42.433 UTC
31
2016-02-08 18:09:33.067 UTC
2015-07-05 22:33:19.253 UTC
null
1,290,264
null
1,290,264
null
1
39
android|android-fragments|dagger-2
20,726
<p>After reading the answer by @vaughandroid, and <a href="https://stackoverflow.com/questions/28411352/what-determines-the-lifecycle-of-a-component-object-graph-in-dagger-2?rq=1">What determines the lifecycle of a component (object graph) in Dagger 2?</a> I think I understand custom scopes well enough to answer my own question.</p> <p>First, here are a couple rules when dealing with components, modules, and scoping annotations in dagger2.</p> <ul> <li>A <strong>Component</strong> <em>must</em> have a (single) scope annotation (e.g. <code>@Singleton</code> or <code>@CustomScope</code>).</li> <li>A <strong>Module</strong> <em>does not</em> have a scope annotation.</li> <li>A <strong>Module Method</strong> <em>may have</em> a (single) scope that matches its <strong>Component</strong> or no scope, where: <ul> <li><strong>Scoped</strong>: means a single instance is created for each instance of the component.</li> <li><strong>Unscoped</strong>: mean a new instance is created with each inject() or provider call</li> <li><strong>NOTE:</strong> Dagger2 reserves <code>@Singleton</code> for the root Component (and it's modules) only. Subcomponents must use a custom scope, but the functionality of that scope is exactly the same as <code>@Singleton</code>.</li> </ul></li> </ul> <p>Now, to answer the question: I would say create a new named scope for each conceptually different scope. For example, create a <code>@PerActivity</code>, <code>@PerFragment</code>, or <code>@PerView</code> annotation that indicates where the component should be instantiated, and thus indicating its lifetime.</p> <p><strong>Note</strong>: this is a compromise between two extremes. Consider the case of a root component and <em>n</em> subcomponents you will need:</p> <ul> <li><strong><em>at least</em></strong> 2 annotations (<code>@Singleton</code> and <code>@SubSingleton</code>), and</li> <li><strong><em>at most</em></strong> <em>n+1</em> annotations (<code>@Singleton</code>, <code>@SubSingleton1</code>, ... <code>@SubSingletonN</code>). </li> </ul> <hr> <h2>Example:</h2> <p><strong>Application:</strong></p> <pre><code>/** AppComponent.java **/ @Singleton @Component( modules = AppModule.class ) public interface AppComponent{ void inject(MainActivity mainActivity); } /** AppModule.java **/ @Module public class AppModule{ private App app; public AppModule(App app){ this.app = app; } // For singleton objects, annotate with same scope as component, i.e. @Singleton @Provides @Singleton public App provideApp() { return app; } @Provides @Singleton public EventBus provideBus() { return EventBus.getDefault(); } } </code></pre> <p><strong>Fragment:</strong></p> <pre><code>/** Fragment1Component.java **/ @PerFragment @Component( modules = {Fragment1Module.class}, dependencies = {AppComponent.class} ) public interface Fragment1Component { void inject(Fragment1 fragment1); } /** Fragment1Module.java **/ @Module public class Fragment1Module { // For singleton objects, annotate with same scope as component, i.e. @PerFragment @Provides @PerFragment public Fragment1Presenter providePresenter(){ return new Fragment1Presenter(); } } /** PerFragment.java **/ @Scope @Retention(RetentionPolicy.RUNTIME) public @interface PerFragment {} </code></pre>
41,191,424
Extract first character of each word from the sentence string
<p>I need to make a code that when you enter a text it takes the first letter from each word in the sentence you placed. </p> <p>For example, for sample string <code>"I like to play guitar and piano and drums"</code>, it should print <code>"Iltpgapad"</code></p>
41,191,463
3
1
null
2016-12-16 19:41:52.813 UTC
1
2019-03-27 14:49:03.64 UTC
2019-01-17 13:05:33.453 UTC
null
7,851,470
null
7,308,267
null
1
3
python|string
45,077
<p>Try something like this:</p> <pre><code>line = "I like to play guitar and piano and drums" words = line.split() letters = [word[0] for word in words] print "".join(letters) </code></pre>
21,194,294
Java Websocket Client without a Browser
<p>I am working on a project that requires real-time interaction between users. I want to have a HTML5 web client (simple enough) and also a local client (preferably Java) with both being able to connect to the server. I have done some research and have not found a conclusive answer to whether or not the local client can connect to the server without a browser.</p> <p>Question: Is there any way to connect from a local Java client to a websocket server without a browse? I have seen some browser wrappers in other languages that might make this possible. If not, I am open to suggestions.</p> <p>Thanks.</p>
21,231,344
4
1
null
2014-01-17 19:32:08.97 UTC
8
2017-07-18 12:44:44.283 UTC
null
null
null
null
1,787,241
null
1
11
java|html|websocket|client
12,491
<p>You might also consider using JSR 356 - <a href="https://www.jcp.org/en/jsr/detail?id=356" rel="noreferrer">Java API for WebSocket</a>. It is part of Java EE 7, but client can be run from plain Java SE without any issues. There are multiple implementations available right now and following will work in all of them:</p> <p>programmatic API:</p> <pre><code> final WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer(); Session session = webSocketContainer.connectToServer(new Endpoint() { @Override public void onOpen(Session session, EndpointConfig config) { // session.addMessageHandler( ... ); } }, URI.create("ws://some.uri")); </code></pre> <p>annotated API:</p> <pre><code>public static void main(String[] args) throws IOException, DeploymentException { final WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer(); webSocketContainer.connectToServer(MyEndpoint.class, URI.create("ws://some.uri")); } @ClientEndpoint public static class MyEndpoint { // text @OnMessage void onMessage(Session session, String message) { // ... } // binary @OnMessage void onMessage(Session session, ByteBuffer message) { // ... } // @OnClose, @OnOpen, @OnError } </code></pre> <p>please see linked page for further details (full specification).</p> <p>There are various implementations out here, basically every Java container has one. I am working on Glassfish/WebLogic implementation and its called <a href="https://tyrus.java.net" rel="noreferrer">Tyrus</a>, feel free to try it out (we provide easy to use all in one bundle, see <a href="http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22tyrus-standalone-client%22" rel="noreferrer">http://search.maven.org/...</a>).</p>
21,005,885
Export org-mode code block and result with different styles
<p>I am preparing a presentation using org-mode and babel, and want to export to beamer pdf.</p> <p>In the output, the source code and the results are with the same style (verbatim in latex). Thus it is difficult to distinguish them.</p> <p>Would it be possible to export source code and results with different styles (preferably different color)?</p> <p>Thanks a lot!</p>
21,007,117
1
1
null
2014-01-08 20:32:11.7 UTC
10
2021-01-19 16:49:53.083 UTC
null
null
null
null
1,858,984
null
1
14
emacs|org-mode|beamer|org-babel
6,094
<p>You could use the <code>minted</code> LaTeX package to syntax highlight the source code:</p> <p><code>C-h v org-latex-listings</code></p> <pre><code>... (setq org-latex-listings 'minted) causes source code to be exported using the minted package as opposed to listings. If you want to use minted, you need to add the minted package to `org-latex-packages-alist', for example using customize, or with (require 'ox-latex) (add-to-list 'org-latex-packages-alist '(&quot;&quot; &quot;minted&quot;)) In addition, it is necessary to install pygments (http://pygments.org), and to configure the variable `org-latex-pdf-process' so that the -shell-escape option is passed to pdflatex. The minted choice has possible repercussions on the preview of latex fragments (see `org-preview-latex-fragment'). If you run into previewing problems, please consult http://orgmode.org/worg/org-tutorials/org-latex-preview.html </code></pre> <p>I have this in my init file:</p> <pre><code>(require 'ox-latex) (add-to-list 'org-latex-packages-alist '(&quot;&quot; &quot;minted&quot;)) (setq org-latex-listings 'minted) (setq org-latex-pdf-process '(&quot;pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f&quot; &quot;pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f&quot; &quot;pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f&quot;)) </code></pre> <p>There are different color-themes you can use with minted, for example you could put this option into your org file to use &quot;monokai&quot;:</p> <pre><code>#+LaTeX_HEADER: \usemintedstyle{monokai} </code></pre> <p>to get a list of the supported styles from pygmentize:</p> <pre class="lang-sh prettyprint-override"><code>pygmentize -L styles </code></pre>
21,491,567
How to implement a writable stream
<p>I want to pipe data from an amazon kinesis stream to a an s3 log or a bunyan log.</p> <p>The sample works with a file write stream or stdout. How would I implmeny my own writable stream?</p> <pre><code>//this works var file = fs.createWriteStream('my.log') kinesisSource.pipe(file) </code></pre> <p>this doesn't work saying it has no method 'on'</p> <pre><code>var stream = {}; //process.stdout works however stream.writable = true; stream.write =function(data){ console.log(data); }; kinesisSource.pipe(stream); </code></pre> <p>what methods do I have to implement for my own custom writable stream, the docs seem to indicate I need to implement 'write' and not 'on'</p>
21,583,831
3
0
null
2014-01-31 22:55:21.85 UTC
29
2022-09-05 10:29:49.357 UTC
null
null
null
null
611,750
null
1
70
node.js|node.js-stream
69,521
<p>To create your own writable stream, you have three possibilities.</p> <h1>Create your own class</h1> <p>For this you'll need:</p> <ol> <li>To extend the <code>Writable</code> class.</li> <li>To call the Writable constructor in your own constructor.</li> <li>To define a <code>_write()</code> method in the prototype of your stream object.</li> </ol> <p>Here's an example:</p> <pre class="lang-js prettyprint-override"><code>var stream = require('stream'); var util = require('util'); function EchoStream () { // step 2 stream.Writable.call(this); }; util.inherits(EchoStream, stream.Writable); // step 1 EchoStream.prototype._write = function (chunk, encoding, done) { // step 3 console.log(chunk.toString()); done(); } var myStream = new EchoStream(); // instanciate your brand new stream process.stdin.pipe(myStream); </code></pre> <h1>Extend an empty Writable object</h1> <p>Instead of defining a new object type, you can instanciate an empty <code>Writable</code> object and implement the <code>_write()</code> method:</p> <pre class="lang-js prettyprint-override"><code>var stream = require('stream'); var echoStream = new stream.Writable(); echoStream._write = function (chunk, encoding, done) { console.log(chunk.toString()); done(); }; process.stdin.pipe(echoStream); </code></pre> <h1>Use the Simplified Constructor API</h1> <p>If you're using io.js, you can use the <a href="https://iojs.org/api/stream.html#stream_simplified_constructor_api" rel="nofollow noreferrer">simplified constructor API</a>:</p> <pre class="lang-js prettyprint-override"><code>var writable = new stream.Writable({ write: function(chunk, encoding, next) { console.log(chunk.toString()); next(); } }); </code></pre> <h1>Use an ES6 class in Node 4+</h1> <pre><code>class EchoStream extends stream.Writable { _write(chunk, enc, next) { console.log(chunk.toString()); next(); } } </code></pre>
8,959,593
How to display the VTABLE of a C++ class through GCC?
<p>I understand that a class will have a <code>VTABLE</code>, if it contains at-least one virtual function. I would like to see the contents of the <code>VTABLE</code>. Is there a way to display it ?</p> <p>Specifically, is there an option in <code>gcc</code> to display the <code>VTABLE</code> of a class?</p>
9,238,150
2
0
null
2012-01-22 07:04:10.897 UTC
9
2014-11-05 06:14:36.883 UTC
2014-11-05 06:14:36.883 UTC
null
462,608
null
1,220,250
null
1
12
c++|gcc|virtual-functions|vtable
7,084
<p>If the input file is say <code>layout.cpp</code>, the command <code>gcc -fdump-class-hierarchy layout.cpp</code> will produce a file <code>layout.cpp.class</code>. This file will display the VTABLE along with some other useful information.</p>
8,836,294
Remove Leading "0" in day of month SimpleDateFormat
<p>Is it possible to remove the "0" in January 04, 2012?</p> <p>I am currently using the following Java to get the date format like</p> <pre><code>Monday, January 04, 2012 </code></pre> <p>I would like for it to look like</p> <pre><code>Monday, January 4, 2012 Date anotherCurDate = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("EEEE', 'MMMM dd', ' yyyy"); final String formattedDateString = formatter.format(anotherCurDate); final TextView currentRoomDate = (TextView) this.findViewById(R.id.CurrentDate); </code></pre>
8,836,332
2
0
null
2012-01-12 14:01:17.657 UTC
0
2016-01-31 07:08:46.54 UTC
null
null
null
null
536,739
null
1
19
java|android|date|simpledateformat
40,958
<pre><code>SimpleDateFormat formatter = new SimpleDateFormat("EEEE', 'MMMM d', ' yyyy"); </code></pre> <p>Should do it (one 'd' instead of two)? </p> <p><a href="http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html" rel="noreferrer">http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html</a></p>
8,561,038
return new EmptyResult() VS return NULL
<p>in ASP.NET MVC when my action will not return anything I use <code>return new EmptyResult()</code> or <code>return null</code></p> <p>is there any difference?</p>
8,561,189
3
0
null
2011-12-19 12:00:55.843 UTC
5
2019-04-10 22:03:43.91 UTC
null
null
null
null
750,459
null
1
64
asp.net-mvc|asp.net-mvc-3|action
56,532
<p>You can return <code>null</code>. MVC will detect that and return an <code>EmptyResult</code>.</p> <blockquote> <p>MSDN: <strong>EmptyResult</strong> represents a result that doesn't do anything, like a controller action returning null</p> </blockquote> <h3>Source code of MVC.</h3> <pre><code>public class EmptyResult : ActionResult { private static readonly EmptyResult _singleton = new EmptyResult(); internal static EmptyResult Instance { get { return _singleton; } } public override void ExecuteResult(ControllerContext context) { } } </code></pre> <p>And the source from <code>ControllerActionInvoker</code> which shows if you return null, MVC will return <code>EmptyResult</code>.</p> <pre><code>protected virtual ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue) { if (actionReturnValue == null) { return new EmptyResult(); } ActionResult actionResult = (actionReturnValue as ActionResult) ?? new ContentResult { Content = Convert.ToString(actionReturnValue, CultureInfo.InvariantCulture) }; return actionResult; } </code></pre> <p>You can download the source code of the Asp.Net MVC Project on <a href="http://aspnet.codeplex.com/releases" rel="noreferrer">Codeplex</a>.</p>
26,788,854
Pandas get the age from a date (example: date of birth)
<p>How can I calculate the age of a person (based off the dob column) and add a column to the dataframe with the new value?</p> <p>dataframe looks like the following:</p> <pre><code> lname fname dob 0 DOE LAURIE 03011979 1 BOURNE JASON 06111978 2 GRINCH XMAS 12131988 3 DOE JOHN 11121986 </code></pre> <p>I tried doing the following:</p> <pre><code>now = datetime.now() df1['age'] = now - df1['dob'] </code></pre> <p>But, received the following error:</p> <p>TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'str'</p>
26,789,573
7
0
null
2014-11-06 20:31:41.033 UTC
13
2022-09-05 04:27:28.203 UTC
2017-09-08 16:36:26.187 UTC
null
1,736,542
null
2,201,603
null
1
26
python|pandas
72,324
<pre><code>import datetime as DT import io import numpy as np import pandas as pd pd.options.mode.chained_assignment = 'warn' content = ''' ssno lname fname pos_title ser gender dob 0 23456789 PLILEY JODY BUDG ANAL 0560 F 031871 1 987654321 NOEL HEATHER PRTG SRVCS SPECLST 1654 F 120852 2 234567891 SONJU LAURIE SUPVY CONTR SPECLST 1102 F 010999 3 345678912 MANNING CYNTHIA SOC SCNTST 0101 F 081692 4 456789123 NAUERTZ ELIZABETH OFF AUTOMATION ASST 0326 F 031387''' df = pd.read_csv(io.StringIO(content), sep='\s{2,}') df['dob'] = df['dob'].apply('{:06}'.format) now = pd.Timestamp('now') df['dob'] = pd.to_datetime(df['dob'], format='%m%d%y') # 1 df['dob'] = df['dob'].where(df['dob'] &lt; now, df['dob'] - np.timedelta64(100, 'Y')) # 2 df['age'] = (now - df['dob']).astype('&lt;m8[Y]') # 3 print(df) </code></pre> <p>yields</p> <pre><code> ssno lname fname pos_title ser gender \ 0 23456789 PLILEY JODY BUDG ANAL 560 F 1 987654321 NOEL HEATHER PRTG SRVCS SPECLST 1654 F 2 234567891 SONJU LAURIE SUPVY CONTR SPECLST 1102 F 3 345678912 MANNING CYNTHIA SOC SCNTST 101 F 4 456789123 NAUERTZ ELIZABETH OFF AUTOMATION ASST 326 F dob age 0 1971-03-18 00:00:00 43 1 1952-12-08 18:00:00 61 2 1999-01-09 00:00:00 15 3 1992-08-16 00:00:00 22 4 1987-03-13 00:00:00 27 </code></pre> <hr> <ol> <li>It looks like your <code>dob</code> column are currently strings. First, convert them to <code>Timestamps</code> using <code>pd.to_datetime</code>.</li> <li>The format <code>'%m%d%y'</code> converts the last two digits to years, but unfortunately assumes <code>52</code> means 2052. Since that's probably not Heather Noel's birthyear, let's subtract 100 years from <code>dob</code> whenever the <code>dob</code> is greater than <code>now</code>. You may want to subtract a few years to <code>now</code> in the condition <code>df['dob'] &lt; now</code> since it may be slightly more likely to have a 101 year old worker than a 1 year old worker...</li> <li>You can subtract<code>dob</code> from <code>now</code> to obtain <a href="http://docs.scipy.org/doc/numpy/reference/arrays.datetime.html#datetime-and-timedelta-arithmetic" rel="noreferrer">timedelta64[ns]</a>. To convert that to years, use <code>astype('&lt;m8[Y]')</code> or <code>astype('timedelta64[Y]')</code>.</li> </ol>
651
Checklist for IIS 6/ASP.NET Windows Authentication?
<p>I've been having trouble getting my ASP.NET application to automatically log users into the Intranet site I'm building. No matter the googling or the experimentation I applied, there is always a login box displayed by IE7.</p> <p>I've got Windows authentication mode set in the Web.config, disabled anonymous access and configured the correct default domain in IIS, but it's still asking the user to log in and, more annoyingly, the user is required to provide the domain too (<em>DOMAIN\auser</em>), which is causing problems with non-technical visitors. Thank Zeus for password remembering functionality.</p> <p>I'm not the network administrator so it's possible that something about Active Directory is set up incorrectly, or it could just be me missing something very simple. Please note that I don't want to impersonate the user, I just need to know that the IPrincipal.Name property matches that of a valid record in my user database, hence authenticating the user to my application.</p> <p>To this end, it would be very useful to have a checklist of all configuration requirements for AD, ASP.NET and IIS to work together in this manner as a reference for debugging and hopefully reducing some user friction.</p>
725
3
0
null
2008-08-03 11:21:54.52 UTC
1
2019-06-12 17:00:05.673 UTC
2009-03-10 03:47:54.46 UTC
Rich B
5,640
null
192
null
1
34
asp.net|iis|authentication|active-directory
6,806
<p>It sounds like you've covered all the server-side bases--maybe it's a client issue? I assume your users have integrated authentication enabled in IE7? (Tools -> Internet Options -> Advanced -> Security). This is enabled by default.</p> <p>Also, is your site correctly recognized by IE7 as being in the Local Intranet zone? The IE7 default is to allow automatic logon only in that zone, so users would be prompted if IE thinks your site is on the internet. I believe using a hostname with a dot in it causes IE to place the site into the Internet zone.</p>
36,638,756
Unable to build apk: The number of method references cannot exceed 64K
<p>I have been trying to build the apk file for my app, however, I am getting the error: The number of method references cannot exceed 64K.</p> <p>Here are the errors,</p> <p>Error:The number of method references in a .dex file cannot exceed 64K. Learn how to resolve this issue at <a href="https://developer.android.com/tools/building/multidex.html" rel="noreferrer">https://developer.android.com/tools/building/multidex.html</a></p> <p>Error:Execution failed for task ':app:transformClassesWithDexForDebug'.</p> <blockquote> <p>com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_15\bin\java.exe'' finished with non-zero exit value 2</p> </blockquote> <p>This is my gradle file,</p> <pre><code>apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.3" defaultConfig { applicationId "nikhilraghavendra.hopper" minSdkVersion 21 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { shrinkResources true minifyEnabled true useProguard true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } packagingOptions { exclude 'META-INF/LICENSE' exclude 'META-INF/LICENSE-FIREBASE.txt' exclude 'META-INF/NOTICE' } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.2.1' compile 'com.android.support:design:23.2.1' compile 'com.google.android.gms:play-services-identity:8.4.0' compile 'com.firebase:firebase-client-android:2.3.1' compile 'com.android.support:cardview-v7:23.2.1' compile 'com.google.android.gms:play-services:8.4.0' } </code></pre> <p>I want to build the apk file and deploy it without any issues, how do I do it?</p> <p><strong>Update</strong></p> <p>I also tried the following</p> <pre><code>apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.3" dexOptions { maxProcessCount = 4 // this is the default value } dataBinding{ enabled = true } defaultConfig { applicationId "nikhilraghavendra.hopper" minSdkVersion 21 targetSdkVersion 23 resConfigs "en", "fr" versionCode 1 versionName "1.0" } buildTypes { release { shrinkResources true minifyEnabled true useProguard true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } debug { minifyEnabled true useProguard false } } packagingOptions { exclude 'META-INF/LICENSE' exclude 'META-INF/LICENSE-FIREBASE.txt' exclude 'META-INF/NOTICE' } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.2.1' compile 'com.android.support:design:23.2.1' compile 'com.google.android.gms:play-services-identity:8.4.0' compile 'com.firebase:firebase-client-android:2.3.1' compile 'com.android.support:cardview-v7:23.2.1' compile 'com.google.android.gms:play-services:8.4.0' } </code></pre> <p>This is producing the message:</p> <p>Error:Execution failed for task ':app:transformClassesWithNewClassShrinkerForDebug'.</p> <blockquote> <p>Warnings found during shrinking, please use -dontwarn or -ignorewarnings to suppress them.</p> </blockquote> <p>How do I deal with this and build a proper apk? Please Help.</p>
36,638,920
3
2
null
2016-04-15 05:17:59.127 UTC
13
2017-06-27 11:08:03.023 UTC
2016-04-15 05:23:01.34 UTC
null
6,011,446
null
6,011,446
null
1
29
android|gradle|apk
51,488
<pre><code>android { compileSdkVersion 26 buildToolsVersion "26.0.0" defaultConfig { applicationId "com.try.app" minSdkVersion 21 targetSdkVersion 26 versionCode 1 versionName "1.0" multiDexEnabled true } </code></pre> <p>here <code>multiDexEnabled true</code> should do the game for you</p> <p><strong>UPDATE : To support latest Android version</strong><br> 1. If your <code>minSdkVersion</code> is set to <strong>21</strong> or higher, all you need to do is set multiDexEnabled to true in your module-level build.gradle file, as shown above.<br> 2. However, if your <code>minSdkVersion</code> is set to <strong>20</strong> or lower, then you must use the multidex support library along with above changes as follows:</p> <pre><code>dependencies { compile 'com.android.support:multidex:1.0.1' } </code></pre> <p>Apart from the above addition of support library, you need to make changes to your Application class as mentioned in this <a href="https://developer.android.com/studio/build/multidex.html" rel="noreferrer">Link</a>.</p> <p><strong>BEST PRACTICE:</strong><br> 1. Remove any unused code with proguard.<br> 2. Avoid adding unnecessary dependencies in your project.<br> 3. If limited number methods or classes of any open source library are needed, then its advisable to clone only those in your project as it not only gives you total control on them but also allows proguard to act on them and you don't have any unused methods in your code.</p> <p>Source : <a href="https://developer.android.com/studio/build/multidex.html" rel="noreferrer">Android Developers - Configure Apps with 64K Method count</a></p>
35,132,451
Call to a member function execute() on boolean in
<p>My html :</p> <pre><code> &lt;form action="rent.php" method="post"&gt;&lt;pre&gt; Email : &lt;input type="text" name="email"&gt; Message : &lt;input type="text" name="msg_text"&gt; &lt;input type="submit" value="Rent it"&gt; &lt;/pre&gt;&lt;/form&gt; </code></pre> <p>My rent.php file :</p> <pre><code>&lt;?php require_once 'login.php'; $conn = new mysqli($hn, $un, $pw, $db); if ($conn-&gt;connect_error) { die($conn-&gt;connect_error); } $query = "SET NAMES utf8"; $result = $conn-&gt;query($query); if (!$result) { die($conn-&gt;error); } $req = $conn-&gt;prepare('INSET INTO renter (email, msg_text) VALUES(?, ?)'); $req-&gt;execute(array($_POST['email'], $_POST['msg_text'])); header('Location: menu.php'); </code></pre> <p>My error when I try to submit, is : Fatal error: Call to a member function execute() on boolean in C:...\rent.php on line 18</p> <p>email, msg_text are in varchar type</p>
35,132,502
5
1
null
2016-02-01 14:01:46.073 UTC
0
2019-09-09 20:25:18.27 UTC
2016-02-01 14:12:05.99 UTC
null
4,662,759
null
5,843,691
null
1
15
php|mysql|mysqli
92,868
<p><code>mysqli-&gt;prepare</code> can also return <code>FALSE</code> (check <a href="http://php.net/manual/en/mysqli.prepare.php" rel="noreferrer">http://php.net/manual/en/mysqli.prepare.php</a>) if an error occurred. Your problem is that you have <code>INSET</code> instead of <code>INSERT</code>.</p>
24,087,791
Browserify - multiple entry points
<p>I am using Browserify within gulp. I am trying to compile down my tests to a single file as well. But unlike my main app, which I have working just fine, I am having trouble getting the tests to compile. The major difference is the tests have multiple entry points, there isn't one single entry point like that app. But I am getting errors fro Browserify that it can't find the entry point.</p> <pre><code>browserify = require 'browserify' gulp = require 'gulp' source = require 'vinyl-source-stream' gulp.task 'tests', -&gt; browserify entries: ['./app/js/**/*Spec.coffee'] extensions: ['.coffee'] .bundle debug: true .pipe source('specs.js') .pipe gulp.dest('./specs/') </code></pre>
24,443,634
4
0
null
2014-06-06 17:46:04.42 UTC
9
2016-06-06 10:05:04.67 UTC
2014-11-30 04:33:37.897 UTC
null
172,350
null
75,095
null
1
31
automated-tests|gulp|browserify
17,568
<p>Below is a task I was able to build that seems to solve the problem. Basically I use an outside library to gather the files names as an array. And then pass that array as the entry points</p> <pre><code>'use strict;' var config = require('../config'); var gulp = require('gulp'); var plumber = require('gulp-plumber'); var glob = require('glob'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); gulp.task('tests', function(){ var testFiles = glob.sync('./spec/**/*.js'); return browserify({ entries: testFiles, extensions: ['.jsx'] }) .bundle({debug: true}) .pipe(source('app.js')) .pipe(plumber()) .pipe(gulp.dest(config.dest.development)); }); </code></pre>
24,343,907
Changing active Bootstrap 3 tab using jQuery
<p>I was experimenting with programatically changing tabs using jQuery. I tried to implement the solution given by @MasterAM <a href="https://stackoverflow.com/questions/17830590/bootstrap-tab-activation-with-jquery">here</a>. However, the Chrome console shows the error <code>Uncaught TypeError: undefined is not a function</code></p> <p>Here is my HTML:</p> <pre><code>&lt;div id="click-me-div"&gt;Click Me&lt;/div&gt; &lt;ul class="nav nav-tabs"&gt; &lt;li class="active"&gt;&lt;a href="#fruits" data-toggle="tab"&gt;I like Fruits&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#veggies" data-toggle="tab"&gt;I like Veggies Too&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#samosas" data-toggle="tab"&gt;But Samosa's Rock&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div class="tab-content"&gt; &lt;div class="tab-pane active" id="fruits"&gt;Apple, Kiwi, Watermellon&lt;/div&gt; &lt;div class="tab-pane" id="veggies"&gt;Kale, Spinach, Pepper&lt;/div&gt; &lt;div class="tab-pane" id="samosas"&gt;Awesome, Spine Tingling, Explosive&lt;/div&gt; &lt;/div&gt; </code></pre> <p>And here is the jQuery:</p> <pre><code>$(document).ready(function() { $("#click-me-div").click(function() { alert('yes, the click actually happened'); ('.nav-tabs a[href="#samosas"]').tab('show'); }); }); </code></pre> <p>The desired outcome is that, if I click "Click Me", the active tab should change to the "samosas" tab.</p> <p>What am I doing wrong?</p>
24,343,998
2
0
null
2014-06-21 17:07:21.827 UTC
5
2017-09-26 08:20:55.63 UTC
2017-05-23 12:02:14.423 UTC
null
-1
null
2,066,468
null
1
23
javascript|jquery|html|twitter-bootstrap-3
49,891
<p>You left out the jQuery function </p> <pre><code>$(document).ready(function() { $("#click-me-div").click(function() { alert('yes, the click actually happened'); $('.nav-tabs a[href="#samosas"]').tab('show'); }); }); </code></pre> <p><a href="http://jsfiddle.net/k88Lf/">Fiddle</a></p>
42,757,924
What is the difference between Observable, Completable and Single in RxJava
<p>Can anyone please explain the difference between Observable, Completable and Single in RxJava with clear examples?</p> <p>In which scenario we use one over the others?</p>
42,759,432
3
1
null
2017-03-13 06:50:31.277 UTC
46
2020-09-01 19:57:55.033 UTC
2017-09-17 12:34:33.227 UTC
null
821,544
null
4,251,124
null
1
136
rx-java|rx-java2
37,493
<p><code>Observable</code> is the generic ReactiveX building block, of event source that emits values over time. (and thus exists in every language ReactiveX extended to)<br> in short Observable events are:<br> onNext* (onCompleted | onError)? /(* zero or more ? - zero or 1)</p> <p><a href="http://reactivex.io/documentation/single.html" rel="noreferrer"><code>Single</code></a> and <a href="http://reactivex.io/RxJava/javadoc/rx/Completable.html" rel="noreferrer"><code>Completable</code></a> are new types introduced exclusively at RxJava that represent reduced types of <code>Observable</code>, that have more concise API.</p> <p><code>Single</code> represent <code>Observable</code> that emit single value or error. </p> <p><code>Completable</code> represent <code>Observable</code> that emits no value, but only terminal events, either <code>onError</code> or <code>onCompleted</code></p> <p>You can think of the differences like the differences of a method that returns: </p> <ul> <li><p>Collection of Objects - Observable</p></li> <li><p>Single object - Single</p></li> <li><p>and method that returns no values (void method) - Completable.</p></li> </ul> <p><code>Single</code> can be appropriate when you have task oriented Observable and you expect single value, like Network request which is performed once and return value (or error), network call is operated in one time fashion, meaning you don't expect it to return additional values over time. Another example is DB fetch data operation.</p> <p><code>Completable</code>is appropriate when you have an <code>Observable</code> and you don't care about the value resulted from the operation, or there isn't any. Examples are updating a cache for instance, the operation can either succeed/fail, but there is no value. <br> Another example is some long running init operation that doesn't return anything. It can be UPDATE/PUT network call that resulted with success indication only.</p> <p>In any case, Completable and Single are not adding new capabilities but they are introducing more robust and concise APIs, that tells more about the operations behind the Observable that the API exposed.</p> <p><strong>Edit:</strong></p> <h2>RxJava2 <code>Maybe</code>:</h2> <p>RxJava2 added a new type called <code>Maybe</code>, <code>Maybe</code> is the combination of <code>Completable</code> and Single.</p> <p>In the same language like above, <code>Maybe</code> can be thought of as a method that returns <code>Optional</code> of some type, <code>Optional</code> is a wrapper around Object that explicitly tells whether we have some value in it - <code>Object</code> or not (instead of null).<br> With <code>Maybe</code> we can either have some value exactly like <code>Single</code> or have return nothing - just like <code>Completable</code>. Additionally, like both, we have the error.<br> <code>Maybe</code> is valuable when we want to mark that an <code>Observable</code> might not have a value and will just complete. <br> An example would be fetched from the cache, we'll not necessarily have a value in the cache, so in this case, we will complete, o.w. we will get <code>onNext</code> with the value from the cache.<br> This is also worthy to handle non-null values in a stream with RxJava2.</p> <h2>RxJava2 <code>Flowable</code>:</h2> <p>First, let's define backpressure. Backpressure is a means of handling the situation where data is generated faster than it can be processed. <code>Flowable</code> has backpressure support allowing downstream to request items. You can read more about the differences <a href="http://blog.jimbaca.com/essential-rxjava-guide-for-android-developers/#chapter6" rel="noreferrer">here</a>.</p>
42,695,866
access parent fragment by child fragment
<p>this is my child fragment and how to access my parent fragment from this fragment please help me to fix it </p> <pre><code>public class Profilefragmant extends Fragment { public Profilefragment(){} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.profile_layout, container, false); TextView VE = (TextView) rootView.findViewById(R.id.profile_view_enquiry); VE.setOnClickListener(new View.OnClickListener(){ public void onClick (View view){ Fragment fragment = null; fragment = new Enquiryfragment(); replaceFragment(fragment); } }); return rootView; } public void replaceFragment(Fragment someFragment) { android.support.v4.app.FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(R.id.containerView, someFragment); transaction.addToBackStack(null); transaction.commit(); } } </code></pre> <p>this is my error while run the project</p> <pre><code> java.lang.IllegalArgumentException: No view found for id 0x7f0c0099 (com.knrmarine.knr:id/containerView) for fragment EnquiryActivity{3754711 #2 id=0x7f0c0099} </code></pre> <p>This my <code>Enquiryfragment</code> code :</p> <pre><code>public class Enquiryfragmant extends Fragment { public Enquiryfragment(){} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.enquiry_layout, container, false); return rootView;}} </code></pre>
42,708,816
5
1
null
2017-03-09 12:50:04.8 UTC
6
2020-08-29 08:52:43.083 UTC
2017-03-10 01:48:16.903 UTC
null
7,357,837
null
7,357,837
null
1
34
android|android-layout|android-fragments
38,083
<p>You can get parent <code>Fragment</code>'s reference by :</p> <pre><code>ParentFragment parentFrag = ((ParentFragment)ChildFragment.this.getParentFragment()); parentFrag.someMethod(); </code></pre> <p>I used this in my ViewPager. If you have other requirement, <code>Interface</code> or <code>EventBus</code> are two of the general ones.</p>
42,884,087
How and when to use /dev/shm for efficiency?
<p>How is <code>/dev/shm</code> more efficient than writing the file on the regular file system? As far as I know, <code>/dev/shm</code> is also a space on the HDD so the read/write speeds are the same. </p> <p>My problem is, I have a 96GB file and only 64GB RAM (+ 64GB swap). Then, multiple threads from the same process need to read small random chunks of the file (about 1.5MB).</p> <p>Is <code>/dev/shm</code> a good use case for this?<br> Will it be faster than opening the file in read-only mode from <code>/home</code> and then passing over to the threads to do the reading the required random chunks?</p>
42,884,337
1
2
null
2017-03-19 07:35:14.95 UTC
9
2020-12-07 16:11:23.153 UTC
2019-06-19 05:04:03.14 UTC
null
371,539
null
371,539
null
1
21
linux|performance|io|filesystems|shared-memory
21,747
<p>You don't use <code>/dev/shm</code>. It exists so that the POSIX C library can provide shared memory support via the POSIX API. Not so you can poke at stuff in there.</p> <p>If you want an in-memory filesystem of your very own, you can mount one wherever you want it.</p> <p><code>mount -t tmpfs tmpfs /mnt/tmp</code>, for example.</p> <p>A Linux <code>tmpfs</code> is a temporary filesystem that only exists in RAM. It is implemented by having a file cache without any disk storage behind it. It will write its contents into the swap file under memory pressure. If you didn't want the swapfile you can use a <code>ramfs</code>. </p> <p>I don't know where you got the idea of using <code>/dev/shm</code> for efficiency in reading files, because that isn't what it does at all.</p> <p>Maybe you were thinking of using memory mapping, via the <code>mmap</code> system call?</p> <p>Read this answer here: <a href="https://superuser.com/a/1030777/4642">https://superuser.com/a/1030777/4642</a> it covers a lot of tmpfs information.</p>
41,443,987
Finding days between two dates in laravel
<p>I have to dates. Now, I need to find the difference between these two for further calculations. </p> <p>I tried different ways but I am not able to fix the issues. Can anyone tell me the best way to do it.</p> <p>My code is: </p> <pre><code>public function leaveRequest(request $request) { $fdate=$request-&gt;Fdate; $tdate=$request-&gt;Tdate; $start = Carbon::parse($fdate)-&gt;format('Y/m/d'); $end = Carbon::parse($tdate)-&gt;format('Y/m/d'); $days = $end-&gt;diffInDays($start); /*$days=date_diff($end,$start);*/ echo $days; exit; $user = User::findOrFail(Auth::user()-&gt;id); Mail::send('pages.leave', ['user' =&gt; $request,'userId'=&gt;$user], function ($m) use ($request) { $m-&gt;to($request-&gt;Email)-&gt;subject('Leave Request!'); }); DB::table('leaves')-&gt;insert( ['user' =&gt; Auth::user()-&gt;id, 'request_date' =&gt; Carbon::now(),'start' =&gt; $start,'end' =&gt; $end,'permissions' =&gt; "Pending",'leave_status' =&gt; "Active"] ); return redirect()-&gt;back()-&gt;with('message','Your request has sent'); } </code></pre> <p>If I can get the days then I can insert it into the leaves table.</p>
41,444,467
6
0
null
2017-01-03 12:53:16.167 UTC
4
2022-07-07 03:12:03.643 UTC
null
null
null
null
6,878,576
null
1
24
laravel-5
70,529
<p>You don't need Carbon, you can do that using simple PHP. Best is to use PHP OOP way. Like this:</p> <pre><code>$fdate = $request-&gt;Fdate; $tdate = $request-&gt;Tdate; $datetime1 = new DateTime($fdate); $datetime2 = new DateTime($tdate); $interval = $datetime1-&gt;diff($datetime2); $days = $interval-&gt;format('%a');//now do whatever you like with $days </code></pre> <p>PS : DateTime is not a function, it's a class, so don't forget to add : <code>use DateTime;</code> at top of your controller so that it can reference to right root class, or use <code>\DateTime()</code> instead when making its instance.</p>
20,144,529
Shifted colorbar matplotlib
<p>I am trying to make a filled contour for a dataset. It should be fairly straightforward:</p> <pre><code>plt.contourf(x, y, z, label = 'blah', cm = matplotlib.cm.RdBu) </code></pre> <p>However, what do I do if my dataset is not symmetric about 0? Let's say I want to go from blue (negative values) to 0 (white), to red (positive values). If my dataset goes from -8 to 3, then the white part of the color bar, which should be at 0, is in fact slightly negative. Is there some way to shift the color bar?</p>
20,146,989
1
0
null
2013-11-22 12:06:32.18 UTC
21
2022-08-29 08:39:37.957 UTC
null
null
null
null
2,625,540
null
1
29
python|colors|matplotlib
15,998
<p>First off, there's more than one way to do this. </p> <ol> <li>Pass an instance of <a href="https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.colors.DivergingNorm.html" rel="noreferrer"><code>DivergingNorm</code></a> as the <code>norm</code> kwarg.</li> <li>Use the <code>colors</code> kwarg to <code>contourf</code> and manually specify the colors</li> <li>Use a discrete colormap constructed with <code>matplotlib.colors.from_levels_and_colors</code>.</li> </ol> <p>The simplest way is the first option. It is also the only option that allows you to use a continuous colormap.</p> <p>The reason to use the first or third options is that they will work for any type of matplotlib plot that uses a colormap (e.g. <code>imshow</code>, <code>scatter</code>, etc).</p> <p>The third option constructs a discrete colormap and normalization object from specific colors. It's basically identical to the second option, but it will a) work with other types of plots than contour plots, and b) avoids having to manually specify the number of contours.</p> <p>As an example of the first option (I'll use <code>imshow</code> here because it makes more sense than <code>contourf</code> for random data, but <code>contourf</code> would have identical usage other than the <code>interpolation</code> option.):</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import DivergingNorm data = np.random.random((10,10)) data = 10 * (data - 0.8) fig, ax = plt.subplots() im = ax.imshow(data, norm=DivergingNorm(0), cmap=plt.cm.seismic, interpolation='none') fig.colorbar(im) plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/UrMEp.png" alt="first option result"></p> <p>As an example of the third option (notice that this gives a discrete colormap instead of a continuous colormap):</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import from_levels_and_colors data = np.random.random((10,10)) data = 10 * (data - 0.8) num_levels = 20 vmin, vmax = data.min(), data.max() midpoint = 0 levels = np.linspace(vmin, vmax, num_levels) midp = np.mean(np.c_[levels[:-1], levels[1:]], axis=1) vals = np.interp(midp, [vmin, midpoint, vmax], [0, 0.5, 1]) colors = plt.cm.seismic(vals) cmap, norm = from_levels_and_colors(levels, colors) fig, ax = plt.subplots() im = ax.imshow(data, cmap=cmap, norm=norm, interpolation='none') fig.colorbar(im) plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/GuGS5.png" alt="third option result"></p>
20,231,075
How to catch NetworkError in JavaScript?
<p>In Chrome's JavaScript console, if I run this:</p> <pre><code>var that = new XMLHttpRequest(); that.open('GET', 'http://this_is_a_bad_url.com', false); that.send(); </code></pre> <p>I get an intentionally expected error:</p> <pre><code>NetworkError: A network error occurred. </code></pre> <p>I want to catch this, so I use:</p> <pre><code>var that = new XMLHttpRequest(); that.open('GET', 'http://this_is_a_bad_url.com', false); try { that.send(); } catch(exception) { if(exception instanceof NetworkError) { console.log('There was a network error.'); } } </code></pre> <p>However, I get an error about NetworkError not being defined:</p> <pre><code>ReferenceError: NetworkError is not defined </code></pre> <p>How can I catch NetworkError?</p>
20,231,131
5
0
null
2013-11-27 01:03:16.39 UTC
6
2022-05-14 13:05:26.377 UTC
null
null
null
null
1,713,534
null
1
28
javascript|xmlhttprequest|referenceerror
61,888
<p>I think what you meant was:</p> <pre><code>if(exception.name == 'NetworkError'){ console.log('There was a network error.'); } </code></pre> <p>I don't believe the Error is an instance of <code>NetworkError</code>, but thrown in this manner:</p> <pre><code>throw { name: 'NetworkError', message: 'A network error occurred.' // etc... } </code></pre>
5,881,873
Python: find all classes which inherit from this one?
<p>Is there any way in python to query a namespace for classes which inherit from a particular class? Given a class <code>widget</code> I'd like to be able to call something like <code>inheritors(widget)</code> to get a list of all my different kinds of widget.</p>
5,883,218
4
1
null
2011-05-04 10:20:10.42 UTC
14
2013-01-28 14:47:23.43 UTC
null
null
null
null
99,876
null
1
52
python|inheritance
46,835
<p>You want to use <code>Widget.__subclasses__()</code> to get a list of all the subclasses. It only looks for direct subclasses though so if you want all of them you'll have to do a bit more work:</p> <pre><code>def inheritors(klass): subclasses = set() work = [klass] while work: parent = work.pop() for child in parent.__subclasses__(): if child not in subclasses: subclasses.add(child) work.append(child) return subclasses </code></pre> <p>N.B. If you are using Python 2.x this only works for new-style classes.</p>
2,334,787
How to match a Spring @RequestMapping having a @pathVariable containing "/"?
<p>I am doing the following request from the client:</p> <p><code>/search/hello%2Fthere/</code></p> <p>where the search term "hello/there" has been URLencoded.</p> <p>On the server I am trying to match this URL using the following request mapping:</p> <pre><code> @RequestMapping("/search/{searchTerm}/") public Map searchWithSearchTerm(@PathVariable String searchTerm) { // more code here } </code></pre> <p>But I am getting error 404 on the server, due I don't have any match for the URL. I noticed that the URL is decoded before Spring gets it. Therefore is trying to match /search/hello/there which does not have any match.</p> <p>I found a Jira related to this problem here: <a href="http://jira.springframework.org/browse/SPR-6780" rel="noreferrer">http://jira.springframework.org/browse/SPR-6780</a> .But I still don't know how to solve my problem.</p> <p>Any ideas?</p> <p>Thanks</p>
2,335,449
2
0
null
2010-02-25 14:44:11.523 UTC
10
2020-06-02 07:21:33.383 UTC
2010-02-25 20:37:14.173 UTC
null
21,234
null
233,026
null
1
16
java|spring|spring-mvc
18,925
<p>There are no good ways to do it (without dealing with <code>HttpServletResponse</code>). You can do something like this:</p> <pre><code>@RequestMapping("/search/**") public Map searchWithSearchTerm(HttpServletRequest request) { // Don't repeat a pattern String pattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); String searchTerm = new AntPathMatcher().extractPathWithinPattern(pattern, request.getServletPath()); ... } </code></pre>
29,670,586
how to fix Javac invalid flag error?
<p>I am trying to compile a an STK applet. </p> <p>Firstly, I would like to compile the <code>.java</code> class by using <code>javac</code>. I am getting an error (invalid flag); this is my command:</p> <pre><code>C:\Program Files (x86)\Java\jdk1.8.0_20\bin&gt;javac C:\Users\user\Desktop\ImsiManager Applet\2014-07-34_ImsiManager_src\2014-07-34_ImsiManager_src\ImsiManager\src\main\java\com\simulity\javacard\imsimanager\ImsiManager.java Javac: invalid flag: C:\Users\user\Desktop\ImsiManager Usage: javac &lt;options&gt; &lt;source files&gt; use -help for a list of possible options </code></pre>
29,670,772
1
0
null
2015-04-16 09:27:29.017 UTC
1
2015-11-03 20:53:26.273 UTC
2015-04-20 08:04:27.233 UTC
null
2,227,834
null
3,873,819
null
1
4
applet|javac
57,279
<p>The problem are the spaces, you should enclose it with quotes: </p> <pre><code>javac "C:\Users\user\Desktop\ImsiManager Applet\2014-07-34_ImsiManager_src\2014-07-34_ImsiManager_src\ImsiManager\src\main\java\com\simulity\javacard\imsimanager\ImsiManager.java" </code></pre>
5,611,233
jQuery $(this) selector function and limitations
<p>I need help understanding <code>$(this)</code>. Is it possible to narrow the focus of &quot;this&quot; within the parentheses or does &quot;this&quot; preclude the use of any other attributes?</p> <p>For example: I don't understand why this code:</p> <pre><code>$(this).children(&quot;div&quot;) </code></pre> <p>can't be rewritten like this:</p> <pre><code>$(this + &quot; div&quot;) </code></pre> <p>without having to resort to something like:</p> <pre><code>$('#'+$(this).attr(&quot;id&quot;)+ &quot; div&quot;) </code></pre> <p>Also, can you point me to 'this' in the jQuery documentation? It is difficult to use 'this' as a search term for obvious reasons.</p>
5,611,239
5
2
null
2011-04-10 10:45:37.79 UTC
10
2021-04-21 08:31:39.81 UTC
2021-04-21 08:31:39.81 UTC
null
12,632,699
null
321,813
null
1
12
jquery|selector|this
95,871
<p><a href="https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/this" rel="noreferrer"><code>this</code></a> isn't a jQuery "thing", but a <a href="https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/this" rel="noreferrer">basic JavaScript one</a>. It can't be re-written the way you have in examples because it's an object, in particular either a DOM element or a jQuery object (depending on what context you're in). So if you did this:</p> <pre><code> $(this + " div") </code></pre> <p>What you'd <em>really</em> be doing is calling <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/toString" rel="noreferrer"><code>.toString()</code></a> on <a href="https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/this" rel="noreferrer"><code>this</code></a> to concatenate the strings, resulting in:</p> <pre><code> $("[object Object] div") </code></pre> <p>....which isn't a valid selector.</p> <p>As for further reading, I believe <a href="http://www.digital-web.com/articles/scope_in_javascript/" rel="noreferrer">this article</a> continues to be one of the best references/resources to learn what <code>this</code> (a context keyword) means.</p> <hr> <p>Per comment requests, some examples of what <code>this</code> is in various places:</p> <ul> <li>Event handlers, for example: <code>$("selector").click(function() { alert(this); });</code> <ul> <li><code>this</code> refers to the DOM element the event handler is being triggered on.</li> </ul></li> <li>Inside a jQuery plugin, for example: <code>$.fn.myPlugin = function() { alert(this); });</code> <ul> <li><code>this</code> is the jQuery object the plugin was called/chained on, for example: <code>$("selector").myPlugin();</code>, <code>this</code> is that <code>$("selector")</code> jQuery object.</li> </ul></li> <li>Inside any generic function, for example: <code>function myFunc() { alert(this); };</code> <ul> <li><code>this</code> is the context you're in, whether it be an object or something else, a few examples:</li> <li><code>$("selector").click(myFunc);</code> - <code>this</code> is the DOM element, like above</li> <li><code>$("selector").click(function() { myFunc(); });</code> - <code>this</code> is the global content, <code>window</code></li> <li><code>myFunc.call(whatThisIs, arg1, arg2);</code> - <code>this</code> is <code>whatThisIs</code> <ul> <li>See <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call" rel="noreferrer"><code>Function.call()</code></a> and <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply" rel="noreferrer"><code>Function.apply()</code></a> for more info</li> </ul></li> </ul></li> </ul>
5,798,791
What is the difference when using flash :error, :alert, and :notice?
<p>As the title of the question asks, I am interested in knowing if there is any difference when using <code>flash[:error]</code>, <code>flash[:alert]</code>, and <code>flash[:notice]</code>. If so, when is it appropriate to use each, and why?</p>
5,801,088
5
0
null
2011-04-27 02:49:28.337 UTC
7
2013-05-07 16:39:07.477 UTC
2011-04-27 02:52:24.157 UTC
null
312,260
null
205,764
null
1
34
ruby-on-rails-3
16,295
<p>flash is a Rails mechanism to persist some information across 2 requests. You set something in flash hash in one request and it's available in the very next request you receive from that same client.</p> <p>Since flash is just a "hash" you can use it like one. Which means you can provide your preferred key (:alert/:error/:notice) and put whatever message string you wish as the value. </p> <p>The semantics of what or when to use :alert/:error/:notice are really up to you to manage. Having said that, the general best practice is to use :notice when things are OKAY and is displayed in a greenish hue, and use :error when things are NOT OKAY and is displayed in a reddish hue. It is completely okay if you want to use :alert for another type of message on your web app. I've used it before for informational purposes in a yellowish hue.</p>
6,172,020
OpenGL Rendering in a secondary thread
<p>I'm writing a 3D model viewer application as a hobby project, and also as a test platform to try out different rendering techniques. I'm using SDL to handle window management and events, and OpenGL for the 3D rendering. The first iteration of my program was single-threaded, and ran well enough. However, I noticed that the single-threaded program caused the system to become very sluggish/laggy. My solution was to move all of the rendering code into a different thread, thereby freeing the main thread to handle events and prevent the app from becoming unresponsive. </p> <p>This solution worked intermittently, the program frequently crashed due to a changing (and to my mind bizarre) set of errors coming mainly from the X window system. This led me to question my initial assumption that as long as all of my OpenGL calls took place in the thread where the context was created, everything should still work out. After spending the better part of a day searching the internet for an answer, I am thoroughly stumped. </p> <p>More succinctly: Is it possible to perform 3D rendering using OpenGL in a thread other than the main thread? Can I still use a cross-platform windowing library such as SDL or GLFW with this configuration? Is there a better way to do what I'm trying to do?</p> <p>So far I've been developing on Linux (Ubuntu 11.04) using C++, although I am also comfortable with Java and Python if there is a solution that works better in those languages.</p> <p><strong>UPDATE:</strong> As requested, some clarifications:</p> <ul> <li>When I say "The system becomes sluggish" I mean interacting with the desktop (dragging windows, interacting with the panel, etc) becomes much slower than normal. Moving my application's window takes time on the order of seconds, and other interactions are just slow enough to be annoying.</li> <li>As for interference with a compositing window manager... I am using the GNOME shell that ships with Ubuntu 11.04 (staying away from Unity for now...) and I couldn't find any options to disable desktop effects such as there was in previous distributions. I assume this means I'm not using a compositing window manager...although I could be very wrong. </li> <li>I believe the "X errors" are server errors due to the error messages I'm getting at the terminal. More details below. </li> </ul> <p>The errors I get with the multi-threaded version of my app:</p> <blockquote> <p>XIO: fatal IO error 11 (Resource temporarily unavailable) on X server ":0.0" after 73 requests (73 known processed) with 0 events remaining.</p> <p>X Error of failed request: BadColor (invalid Colormap parameter) Major opcode of failed request: 79 (X_FreeColormap) Resource id in failed request: 0x4600001 Serial number of failed request: 72 Current serial number in output stream: 73</p> <p>Game: ../../src/xcb_io.c:140: dequeue_pending_request: Assertion `req == dpy->xcb->pending_requests' failed. Aborted</p> </blockquote> <p>I always get one of the three errors above, which one I get varies, apparently at random, which (to my eyes) would appear to confirm that my issue does in fact stem from my use of threads. Keep in mind that I'm learning as I go along, so there is a very good chance that in my ignorance I've something rather stupid along the way.</p> <p><strong>SOLUTION:</strong> For anyone who is having a similar issue, I solved my problem by moving my call to <code>SDL_Init(SDL_INIT_VIDEO)</code> to the rendering thread, and locking the context initialization using a mutex. This ensures that the context is created in the thread that will be using it, and it prevents the main loop from starting before initialization tasks have finished. A simplified outline of the startup procedure:</p> <p>1) Main thread initializes <code>struct</code> which will be shared between the two threads, and which contains a mutex.<br> 2) Main thread spawns render thread and sleeps for a brief period (1-5ms), giving the render thread time to lock the mutex. After this pause, the main thread blocks while trying to lock the mutex.<br> 3) Render thread locks mutex, initializes SDL's video subsystem and creates OpenGL context.<br> 4) Render thread unlocks mutex and enters its "render loop".<br> 5) The main thread is no longer blocked, so it locks and unlocks the mutex before finishing its initialization step. </p> <p>Be sure and read the answers and comments, there is a lot of useful information there. </p>
6,173,817
6
6
null
2011-05-30 03:24:51.6 UTC
12
2015-02-08 16:59:39.203 UTC
2011-05-30 23:16:56.57 UTC
null
592,786
null
592,786
null
1
27
multithreading|opengl|sdl
20,752
<p>As long as the OpenGL context is touched from only one thread at a time, you should not run into any problems. You said even your single threaded program made your system sluggish. Does that mean the whole system or only your own application? The worst that should happen in a single threaded OpenGL program is, that processing user inputs for that one program gets laggy but the rest of the system is not affected.</p> <p>If you use some compositing window manager (Compiz, KDE4 kwin), please try out what happens if you disable all compositing effects.</p> <p>When you say <em>X errors</em> do you mean client side errors, or errors reported in the X server log? The latter case should not happen, because any kind of kind of malformed X command stream the X server must be able to cope with and at most emit a warning. If it (the X server) crashes this is a bug and should reported to X.org.</p> <p>If your program crashes, then there's something wrong in its interaction with X; in that case please provide us with the error output in its variations.</p>
49,613,127
Run Jest tests only for current folder
<p>I have Jest installed on my machine and typing <code>jest</code> from terminal results in tests from parent folers also getting executed. I want to run tests only from the current folder. </p> <p>For e.g. if I go to <code>c:/dev/app</code> in terminal and type <code>some-jest-command</code>, it should only run files with <code>.test.js</code> present in the <code>app</code> folder. Currently, running <code>jest</code> command from <code>app</code> folder runs tests in parent folders too, which is not my desired behaviour.</p>
49,614,002
5
2
null
2018-04-02 14:27:30.96 UTC
8
2022-06-07 18:07:49.683 UTC
null
null
null
null
3,706,051
null
1
54
javascript|npm|jestjs
61,106
<p>By default, Jest will try to recursively test everything from whatever folder <code>package.json</code> is located.</p> <p>Let's say you're in <code>c:/dev/app</code>, and your <code>package.json</code> is in <code>c:</code>. If your basic command to invoke Jest is <code>npm test</code>, then try with run <code>npm test dev/app</code>.</p>
25,384,761
Pure CSS star shape
<p>There are a lot of CSS shapes shown on <a href="http://css-tricks.com/examples/ShapesOfCSS/" rel="noreferrer">CSS Tricks</a>. I am particularly surprised by the star:</p> <p><img src="https://i.stack.imgur.com/XLwFS.png" alt="Star image"></p> <p>How does the CSS below create this shape? </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#star-five { margin: 50px 0; position: relative; display: block; color: red; width: 0px; height: 0px; border-right: 100px solid transparent; border-bottom: 70px solid red; border-left: 100px solid transparent; transform: rotate(35deg); } #star-five:before { border-bottom: 80px solid red; border-left: 30px solid transparent; border-right: 30px solid transparent; position: absolute; height: 0; width: 0; top: -45px; left: -65px; display: block; content: ''; transform: rotate(-35deg); } #star-five:after { position: absolute; display: block; color: red; top: 3px; left: -105px; width: 0px; height: 0px; border-right: 100px solid transparent; border-bottom: 70px solid red; border-left: 100px solid transparent; transform: rotate(-70deg); content: ''; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="star-five"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
25,385,379
2
2
null
2014-08-19 13:32:41.123 UTC
3
2015-09-02 14:50:02.3 UTC
2015-09-02 14:50:02.3 UTC
null
2,930,477
null
1,170,507
null
1
29
css|css-shapes
25,130
<p>Let's break it into pieces:</p> <p>The yellow borders are actually set as <code>transparent</code> in the final product so they don't show. They are yellow here to show how the borders look.</p> <p>As commented above, <a href="https://stackoverflow.com/questions/7073484/how-does-this-css-triangle-shape-work?rq=1">this answer</a> shows the idea behind the basic triangle shape.</p> <p>The div by itself:</p> <pre><code>&lt;div id="star-five"&gt;&lt;/div&gt; </code></pre> <p><img src="https://i.stack.imgur.com/gYYOL.png" alt="Piece one"></p> <p>Combining the <code>:before</code> pseudo element is the same as this:</p> <pre><code>&lt;div id="star-five"&gt; &lt;div id="before"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p><img src="https://i.stack.imgur.com/S9sex.png" alt="Piece two"></p> <p>Finally, combining the <code>:after</code> pseudo element is the same as this:</p> <pre><code>&lt;div id="star-five"&gt; &lt;div id="before"&gt;&lt;/div&gt; &lt;div id="after"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p><img src="https://i.stack.imgur.com/yfYqw.png" alt="Piece three"></p> <p>Now you overlap each element precisely using <code>position: absolute;</code> and rotate with <code>transform</code> as needed to get the final product:</p> <p><img src="https://i.stack.imgur.com/b4kkn.png" alt="Final product"></p> <p>Let's visualise it!</p> <p><img src="https://i.stack.imgur.com/9yEuM.gif" alt="Animation"></p>
9,189,338
How to extract content of html tags from a string using javascript or jquery?
<p>Maybe this is very basic, but I am all confused. I have a simple html page with many sections (div). I have a string containing html tags in javascript. The code is as follows:</p> <pre><code>&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; var str1="&lt;html&gt;&lt;body&gt;&lt;div id='item1'&gt;&lt;h2&gt;This is a heading1&lt;/h2&gt;&lt;p&gt;This is a paragraph1.&lt;/p&gt;&lt;/div&gt;&lt;div id='item2'&gt;&lt;h2&gt;This is a heading2&lt;/h2&gt;&lt;p&gt;This is another paragraph.&lt;/p&gt;&lt;/div&gt;&lt;div id='lastdiv'&gt;last&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;"; &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="title1"&gt;&lt;/div&gt; &lt;div id="new1"&gt;&lt;/div&gt; &lt;div id="title2"&gt;&lt;/div&gt; &lt;div id="new2"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I want to extract content of the html tags (from the string in javascript) and display that content in my html page in desired sections. </p> <p>i.e. I want "This is a heading1" displayed in <code>&lt;div id="title1"&gt;</code> and "This is a paragraph1." to be displayed in <code>&lt;div id="new1"&gt;</code> and same for the second pair of tags.</p> <p>I need all of this to work only on the client side. I have tried to use HTML DOM getElementByTagName method and its getting too complicated. I know very little of jquery. And I am confused. I dont understand how to go about it. Can you guide me what to use - javascript or jquery and how to use it? Is there a way to identify the from the string and iterate through it? </p> <p>How to extract "This is heading1" (and similar contents enclosed in the html tags) from str1?? I don't know the index of these hence cannot use substr() or substring() function in javascript.</p>
9,189,416
5
0
null
2012-02-08 07:32:59.103 UTC
3
2012-02-08 08:41:42.993 UTC
2012-02-08 08:41:42.993 UTC
null
74,214
null
1,196,522
null
1
9
javascript|jquery|html
48,998
<p>Using <a href="http://api.jquery.com/text/" rel="noreferrer">.text()</a> as both a 'getter' and a 'setter' we can just repeat the pattern of:</p> <ul> <li>target the element on the page we wish to fill </li> <li>give it content from the string</li> </ul> <p><a href="http://jsfiddle.net/rQdCz/10/" rel="noreferrer">jsFiddle</a></p> <pre><code>&lt;script type="text/javascript"&gt; var str1="&lt;html&gt;&lt;body&gt;&lt;div id='item1'&gt;&lt;h2&gt;This is a heading1&lt;/h2&gt;&lt;p&gt;This is a paragraph1.&lt;/p&gt;&lt;/div&gt;&lt;div id='item2'&gt;&lt;h2&gt;This is a heading2&lt;/h2&gt;&lt;p&gt;This is another paragraph.&lt;/p&gt;&lt;/div&gt;&lt;div id='lastdiv'&gt;last&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;"; $(function(){ var $str1 = $(str1);//this turns your string into real html //target something, fill it with something from the string $('#title1').text( $str1.find('h2').eq(0).text() ); $('#new1').text( $str1.find('p').eq(1).text() ); $('#title2').text( $str1.find('h2').eq(1).text() ); $('#new2').text( $str1.find('p').eq(1).text() ); }) &lt;/script&gt; </code></pre>
9,222,217
How does the fragment shader know what variable to use for the color of a pixel?
<p>I see a lot of different fragment shaders,</p> <pre><code>#version 130 out vec4 flatColor; void main(void) { flatColor = vec4(0.0,1.0,0.0,0.5); } </code></pre> <p>And they all use a different variable for the &quot;out color&quot; (in this case <code>flatColor</code>). So how does OpenGL know what you're trying to do?</p> <p>I'm guessing this works because <code>flatColor</code> is the only variable defined as <code>out</code>, but you're allowed to add more <code>out</code> variables aren't you? Or would that just crash?</p> <hr /> <p>Actually, as a test, I just ran this:</p> <pre><code>#version 330 in vec2 TexCoord0; uniform sampler2D TexSampler; out vec4 x; out vec4 y; void main() { y = texture2D(TexSampler, TexCoord0.xy); } </code></pre> <p>It worked fine whether I used <code>x</code> or <code>y</code>.</p> <p>(answer: the compiler is optimizing out the unused var, so the remaining var is assigned to location 0)</p> <hr /> <p>Furthermore, we have a predefined <code>gl_FragColor</code>. What's the difference, and why do people usually insist on using their own variables?</p>
9,222,588
2
0
null
2012-02-10 03:14:50.98 UTC
45
2021-12-01 07:56:59.793 UTC
2021-12-01 07:56:59.793 UTC
null
65,387
null
65,387
null
1
94
opengl|glsl
37,282
<blockquote> <p>Furthermore, we have a predefined gl_FragColor.</p> </blockquote> <p>Let's start with this. No, you <em>don't</em> have the predefined <code>gl_FragColor</code>. That was removed from core OpenGL 3.1 and above. Unless you're using compatibility (in which case, your 3.30 shaders should say <code>#version 330 compatibility</code> at the top), you should never use this.</p> <p>Now, back to user-defined fragment shader outputs. But first, a quick analogy.</p> <p>Remember how, in vertex shaders, you have inputs? And these inputs represent vertex attribute indices, the numbers you pass to <code>glVertexAttribPointer</code> and <code>glEnableVertexAttribArray</code> and so forth? You set up which input pulls from which attribute. In GLSL 3.30, you use this syntax:</p> <pre><code>layout(location = 2) in color; </code></pre> <p>This sets the <code>color</code> vertex shader input to come from attribute location 2. Before 3.30 (or without ARB_explicit_attrib_location), you would have to either set this up explicitly with <a href="http://www.opengl.org/wiki/GLAPI/glBindAttribLocation" rel="noreferrer"><code>glBindAttrbLocation</code></a> before linking or query the program for the attribute index with <a href="http://www.opengl.org/wiki/GLAPI/glGetAttribLocation" rel="noreferrer"><code>glGetAttribLocation</code></a>. If you don't explicitly provide an attribute location, GLSL will assign a location <em>arbitrarily</em> (ie: in an implementation-defined manner).</p> <p>Setting it in the shader is almost always the better option.</p> <p>In any case, fragment shader outputs work almost exactly the same way. Fragment shaders can write to <a href="https://www.khronos.org/opengl/wiki/Fragment#Fragment_shader_outputs" rel="noreferrer">multiple output colors</a>, which themselves get mapped to <a href="https://www.khronos.org/opengl/wiki/Framebuffer_Draw_Buffer" rel="noreferrer">multiple buffers in the framebuffer</a>. Therefore, you need to indicate which output goes to which fragment output color.</p> <p>This process begins with the fragment output location value. It's set very similarly to vertex shader input locations:</p> <pre><code>layout(location = 1) out secColor; </code></pre> <p>There are also the API functions <a href="http://www.opengl.org/wiki/GLAPI/glBindFragDataLocation" rel="noreferrer"><code>glBindFragDataLocation</code></a> and <a href="http://www.opengl.org/wiki/GLAPI/glGetFragDataLocation" rel="noreferrer"><code>glGetFragDataLocation</code></a>, which are analogous to <code>glBindAttribLocation</code> and <code>glGetAttribLocation</code>.</p> <p>If you don't do any explicit assignments, implementations usually will assign one of your output variables to location 0. However, the OpenGL standard does not <em>require</em> this behavior, so you should not depend on it either.</p> <p>Now to be fair, your program should have <em>failed</em> to link when you used two outputs that didn't get different output locations. What probably happened was that your compiler optimized the one you didn't write to out, so it kinda forgot about it when it came time to check for linker errors.</p>
29,893,578
Add inline CSS via jQuery
<p>I don't know jQuery very well so I don't know how to add CSS inline. This is my code:</p> <pre><code>&lt;div class="gm-style-iw" style="top: 9px; position: absolute; left: 15px; width: 23px;"&gt; &lt;div style="display: inline-block; overflow: hidden; max-height: 330px; max-width: 176px;"&gt; &lt;div style="overflow: auto"&gt; &lt;div id="iw-container"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I want to change the <code>max-width</code> of second div and add <code>overflow: none</code> to the div above <code>#iw-container</code>.</p> <p>I tried this but it did not work:</p> <pre><code>var iwOuter = $('.gm-style-iw'); iwOuter.children().css({max-width:'250px !important'}); iwOuter.children().children().css({overflow:'none'}); </code></pre> <p><strong>EDIT</strong> i want to customize infowindow Google and for me is important to change the value of max-width and overflow.... i think that your code maybe are good, but i don't understand why doesn't work...</p>
29,893,652
2
2
null
2015-04-27 10:46:48.117 UTC
3
2015-04-27 13:12:02.783 UTC
2015-04-27 11:13:49.463 UTC
null
4,487,487
null
4,487,487
null
1
8
jquery|html|css|dom
50,150
<p>In jQuery you can do something like this:</p> <pre><code>$('.gm-style-iw &gt; div').css('max-width', "250px !important"); $('#iw-container').parent().css('overflow', 'none');//css wasn't valid here </code></pre> <p>Using <code>&gt; div</code> means it gets the first div only, if you want all <code>div</code>s to have a <code>max-width</code>, use:</p> <pre><code>$('.gm-style-iw').children().css('max-width', "250px !important"); </code></pre> <p>Using the <code>.parent()</code> function means that it gets only the parent of the selected element. It's cleaner and easier to read and shorter to write.</p>
33,994,983
Assigning a cpu core to a process - Linux
<p>Is there any way to force a process with specific PID, to be executed and run on only one of the cpu s of a server? I know that there is a command like this</p> <pre><code>taskset -cp &lt;Cpu_Number&gt; &lt;Pid&gt; </code></pre> <p>but the above command does not work on my system. So please let me know if there is any other command. </p>
33,996,059
1
2
null
2015-11-30 09:14:23.007 UTC
5
2016-10-06 12:44:50.11 UTC
2016-10-06 12:44:50.11 UTC
null
265,954
null
5,595,353
null
1
22
bash|process|cpu|affinity
47,770
<p>There are two ways of assigning cpu core/cores to a running process.</p> <p><strong>First method:</strong></p> <pre><code>taskset -cp 0,4 9030 </code></pre> <p>Pretty clear ! assigning cpu cores 0 and 4 to the pid 9030.</p> <p><strong>Second Method:</strong></p> <pre><code>taskset -p 0x11 9030 </code></pre> <p>This is a bit more complex. The hexadecimal number that follows <code>-p</code> is a bitmask. An explanation can be found <a href="http://www.tutorialspoint.com/unix_commands/taskset.htm" rel="noreferrer">here</a>, an excerpt of which is given below :</p> <blockquote> <p>The CPU affinity is represented as a bitmask, with the lowest order bit corresponding to the first logical CPU and the highest order bit corresponding to the last logical CPU. Not all CPUs may exist on a given system but a mask may specify more CPUs than are present. A retrieved mask will reflect only the bits that correspond to CPUs physically on the system. If an invalid mask is given (i.e., one that corresponds to no valid CPUs on the current system) an error is returned. The masks are typically given in hexadecimal.</p> </blockquote> <p>Still confused? Look at the image below :</p> <p><a href="https://i.stack.imgur.com/ANscg.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ANscg.png" alt="enter image description here"></a></p> <p>I have added the binaries corresponding to the hexadecimal number and the processors are counted from left starting from zero. In the first example there is a <code>one</code> in the bitmask corresponding to the <code>zero</code>th processor, so that processor will be enabled for a process. All the processors which have <code>zero</code> to their corresponding position in the bitmask will be disabled. In fact this is the reason why it is called a mask.<br></p> <p>Having said all these, using taskset to change the processor affinity requires that :</p> <blockquote> <p>A user must possess CAP_SYS_NICE to change the CPU affinity of a process. Any user can retrieve the affinity mask.</p> </blockquote> <p>Please check the <a href="http://man7.org/linux/man-pages/man7/capabilities.7.html" rel="noreferrer">Capabalities Man Page</a>.</p> <p>You might be interested to look at this <a href="https://stackoverflow.com/questions/7635515/how-to-set-cap-sys-nice-capability-to-a-linux-user">SO Question</a> that deals with CAP_SYS_NICE.</p> <p><strong>My Resources</strong></p> <ol> <li><p><a href="http://www.tutorialspoint.com/unix_commands/taskset.htm" rel="noreferrer">Tutorials Point</a></p></li> <li><p><a href="http://xmodulo.com/run-program-process-specific-cpu-cores-linux.html" rel="noreferrer">XModulo</a></p></li> </ol>
7,207,894
Check a record IS NOT NULL in plsql
<p>I have a function which would return a record with type <code>my_table%ROWTYPE</code>, and in the caller, I could check if the returned record is null, but PL/SQL complains the if-statement that</p> <blockquote> <p>PLS-00306: wrong number or types of arguments in call to 'IS NOT NULL'</p> </blockquote> <p>Here is my code:</p> <pre class="lang-sql prettyprint-override"><code>v_record my_table%ROWTYPE; v_row_id my_table.row_id%TYPE := 123456; begin v_record := myfunction(v_row_id) if (v_record is not null) then -- do something end if; end; function myfunction(p_row_id in my_table.row_id%TYPE) return my_table%ROWTYPE is v_record_out my_table%ROWTYPE := null; begin select * into v_record_out from my_table where row_id = p_row_id; return v_record_out; end myfunction; </code></pre> <p>Thanks.</p>
7,207,923
2
0
null
2011-08-26 16:39:27.207 UTC
3
2014-11-26 17:30:26.877 UTC
null
null
null
null
185,977
null
1
23
plsql|notnull
45,938
<p>As far as I know, it's not possible. Checking the <code>PRIMARY KEY</code> or a <code>NOT NULL</code> column should be sufficient though.</p> <hr> <p>You can check for <code>v_record.row_id IS NULL</code>.</p> <p>Your function would throw a <code>NO_DATA_FOUND</code> exception though, when no record is found.</p>
23,383,001
Change public IP address of EC2 instance without stop/start or elastic IP
<p>I'm running an ubuntu AMI on EC2. Is it possible to assign/request a new public IP address for a running EC2 instance without terminating it and starting it again? Note that I'm not interested in using the Elastic IP feature here, I just want to use the regular random public IP addresses assigned by EC2.</p>
29,813,335
5
1
null
2014-04-30 08:16:25.853 UTC
8
2020-05-09 20:27:35.45 UTC
null
null
null
null
1,002,814
null
1
21
ubuntu|amazon-ec2|ip
20,430
<p><strong><em>Update</em></strong><br> As Alex B points out in the comments, AWS EC2 instances now have per-second billing, with a minimum billing period of 1 minute. That's a huge, and welcome improvement. It means that starting and stopping an instance should refresh the IP without racking up extra costs.</p> <p>The one important thing to keep in mind is that per-second billing only applies to <strong>Amazon Linux</strong> and <strong>Ubuntu</strong> instances. Other OSs are billed hourly as before. In those cases, the original method explained below is likely the best option.</p> <hr> <p>Stopping and starting an instance is one way to change your IP, but it isn't the fastest or even the cheapest, however it does meet your criteria of avoiding Elastic IPs.</p> <p>Stopping and starting an instance, from a billing perspective is the same as terminating/relaunching an instance.</p> <blockquote> <p>Pricing is per instance-hour consumed for each instance, from the time an instance is launched until it is terminated or stopped. Each partial instance-hour consumed will be billed as a full hour. <a href="http://aws.amazon.com/ec2/pricing/" rel="nofollow noreferrer">http://aws.amazon.com/ec2/pricing/</a></p> </blockquote> <p>This means that, if you start an instance, stop it half an hour later, then start it again and run it for half an hour then stop it again, for that one hour, you're actually going to be billed for two hours of usage.</p> <p>Elastic IPs are very likely a better solution in that scenario, but the added cost of Elastic IPs is something most people want to avoid. We don't actually want a fixed IP. We just want a new one. Paying for unique IPs per instance doesn't make sense for this. The interesting thing is, we don't need an EIP for each instance in order to release/renew the instance's external IP. We just need one for the entire VPC.</p> <p>When you assign an EIP to an instance, the old IP is completely gone, released into the void. When you remove the EIP from the instance, the instance is then forced to request a new external IP from the pool.</p> <p>Keeping a single Elastic IP attached to an instance in the Oregon region (us-west-2) is free, as long as it's attached to something. If it's not attached, it costs $0.05/hour to sit there.</p> <p>The first 100 IP remaps each month are free. To us, that works out to 50 free IP refreshes (1 remap for release, 1 for renew). If you break that 100 remap limit, the price jumps quickly, to $0.10/remap (or $0.20/IP refresh), so try to keep track. <a href="http://aws.amazon.com/ec2/pricing/" rel="nofollow noreferrer">http://aws.amazon.com/ec2/pricing/</a></p> <p><strong>TL;DR</strong></p> <p>The free EIP powered solution? A single EIP for your entire VPC, assigned to a single instance. When you want to release/renew, transfer that IP to the instance in need of a new IP, then transfer it back to the original instance. You can now quickly change an instance's IP up to 50 times a month at no extra cost.</p> <p>The IP shuffle, ladies and gentlemen :)</p>
23,377,533
python BeautifulSoup parsing table
<p>I'm learning python <code>requests</code> and BeautifulSoup. For an exercise, I've chosen to write a quick NYC parking ticket parser. I am able to get an html response which is quite ugly. I need to grab the <code>lineItemsTable</code> and parse all the tickets.</p> <p>You can reproduce the page by going here: <code>https://paydirect.link2gov.com/NYCParking-Plate/ItemSearch</code> and entering a <code>NY</code> plate <code>T630134C</code></p> <pre><code>soup = BeautifulSoup(plateRequest.text) #print(soup.prettify()) #print soup.find_all('tr') table = soup.find("table", { "class" : "lineItemsTable" }) for row in table.findAll("tr"): cells = row.findAll("td") print cells </code></pre> <p>Can someone please help me out? Simple looking for all <code>tr</code> does not get me anywhere.</p>
23,377,804
5
2
null
2014-04-30 00:17:58.867 UTC
70
2022-05-10 18:12:36.893 UTC
2017-01-02 20:58:00 UTC
null
875,915
null
650,424
null
1
128
python|beautifulsoup
233,777
<p>Here you go:</p> <pre><code>data = [] table = soup.find('table', attrs={'class':'lineItemsTable'}) table_body = table.find('tbody') rows = table_body.find_all('tr') for row in rows: cols = row.find_all('td') cols = [ele.text.strip() for ele in cols] data.append([ele for ele in cols if ele]) # Get rid of empty values </code></pre> <p>This gives you:</p> <pre><code>[ [u'1359711259', u'SRF', u'08/05/2013', u'5310 4 AVE', u'K', u'19', u'125.00', u'$'], [u'7086775850', u'PAS', u'12/14/2013', u'3908 6th Ave', u'K', u'40', u'125.00', u'$'], [u'7355010165', u'OMT', u'12/14/2013', u'3908 6th Ave', u'K', u'40', u'145.00', u'$'], [u'4002488755', u'OMT', u'02/12/2014', u'NB 1ST AVE @ E 23RD ST', u'5', u'115.00', u'$'], [u'7913806837', u'OMT', u'03/03/2014', u'5015 4th Ave', u'K', u'46', u'115.00', u'$'], [u'5080015366', u'OMT', u'03/10/2014', u'EB 65TH ST @ 16TH AV E', u'7', u'50.00', u'$'], [u'7208770670', u'OMT', u'04/08/2014', u'333 15th St', u'K', u'70', u'65.00', u'$'], [u'$0.00\n\n\nPayment Amount:'] ] </code></pre> <p>Couple of things to note: </p> <ul> <li>The last row in the output above, the Payment Amount is not a part of the table but that is how the table is laid out. You can filter it out by checking if the length of the list is less than 7.</li> <li>The last column of every row will have to be handled separately since it is an input text box.</li> </ul>
31,953,518
Start IPython notebook server without running web browser?
<p>I would like to use Emacs as main editor for iPython notebooks / Jupyter Notebook (with the package <a href="http://tkf.github.io/emacs-ipython-notebook/#install" rel="noreferrer">ein</a>). I want to ask you if there is a way to run the server without the need to open a web browser. </p>
31,953,548
2
1
null
2015-08-11 23:11:25.157 UTC
8
2018-09-30 04:32:58.883 UTC
2018-09-30 04:32:58.883 UTC
null
2,681,088
null
1,435,633
null
1
47
python|ipython|jupyter-notebook
33,251
<p>Is this what you want?</p> <pre><code>$ ipython notebook --no-browser </code></pre> <p><strong>Edit</strong></p> <p>Now you should use instead</p> <pre><code>$ jupyter notebook --no-browser </code></pre> <p>Since </p> <blockquote> <p><code>ipython notebook</code> is deprecated and will be removed in future versions. You likely want to use <code>jupyter notebook</code> in the future</p> </blockquote>
3,710,829
Paperclip image url
<pre><code>&lt;img alt=&quot;Phone_large&quot; src=&quot;/system/photos/1/small/phone_large.jpg?1238845838&quot; /&gt; </code></pre> <p>Why is &quot;?1238845838&quot; added to the image path?</p> <p>How can I get my path/url without it?</p>
3,711,129
1
0
null
2010-09-14 16:22:26.16 UTC
5
2022-04-25 07:49:35.427 UTC
2022-04-25 07:49:35.427 UTC
null
5,446,749
null
231,501
null
1
39
ruby-on-rails|paperclip
13,128
<p>It's commonly referred to as a "cache buster". Paperclip automatically appends the timestamp for the last time the file was updated.</p> <p>Say you were to remove the cache buster and use <code>/system/photos/1/small/phone_large.jpg</code> instead. The URL wouldn't change when you changed the image and your visitors would see the old image for as long as they had it cached.</p> <p>If you want to remove it just call <code>.url(:default, timestamp: false)</code>. Of course you can change <code>:default</code> to any other style you've defined.</p> <p>Or if you want to globally default them to off, just put this in a <code>config/initializers/paperclip.rb</code> file.</p> <pre><code>Paperclip::Attachment.default_options[:use_timestamp] = false </code></pre>
2,250,297
How to run a sql script using C#
<p>I have a sql script to create a new database which i need to create when our product is installed. For this i need to fire the script using c#. DB is sql-server 2005 express. Plz help....</p> <p>The sql script is as follows:</p> <pre><code>USE [master] GO /****** Object: Database [Jai] Script Date: 02/12/2010 11:01:25 ******/ CREATE DATABASE [Jai] ON PRIMARY ( NAME = N'Jai', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\Jai.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ) LOG ON ( NAME = N'Jai_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\Jai_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%) COLLATE SQL_Latin1_General_CP1_CI_AS GO EXEC dbo.sp_dbcmptlevel @dbname=N'Jai', @new_cmptlevel=90 GO IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')) begin EXEC [Jai].[dbo].[sp_fulltext_database] @action = 'disable' end GO ALTER DATABASE [Jai] SET ANSI_NULL_DEFAULT OFF GO ALTER DATABASE [Jai] SET ANSI_NULLS OFF GO ALTER DATABASE [Jai] SET ANSI_PADDING OFF GO ALTER DATABASE [Jai] SET ANSI_WARNINGS OFF GO ALTER DATABASE [Jai] SET ARITHABORT OFF GO ALTER DATABASE [Jai] SET AUTO_CLOSE OFF GO ALTER DATABASE [Jai] SET AUTO_CREATE_STATISTICS ON GO ALTER DATABASE [Jai] SET AUTO_SHRINK OFF GO ALTER DATABASE [Jai] SET AUTO_UPDATE_STATISTICS ON GO ALTER DATABASE [Jai] SET CURSOR_CLOSE_ON_COMMIT OFF GO ALTER DATABASE [Jai] SET CURSOR_DEFAULT GLOBAL GO ALTER DATABASE [Jai] SET CONCAT_NULL_YIELDS_NULL OFF GO ALTER DATABASE [Jai] SET NUMERIC_ROUNDABORT OFF GO ALTER DATABASE [Jai] SET QUOTED_IDENTIFIER OFF GO ALTER DATABASE [Jai] SET RECURSIVE_TRIGGERS OFF GO ALTER DATABASE [Jai] SET ENABLE_BROKER GO ALTER DATABASE [Jai] SET AUTO_UPDATE_STATISTICS_ASYNC OFF GO ALTER DATABASE [Jai] SET DATE_CORRELATION_OPTIMIZATION OFF GO ALTER DATABASE [Jai] SET TRUSTWORTHY OFF GO ALTER DATABASE [Jai] SET ALLOW_SNAPSHOT_ISOLATION OFF GO ALTER DATABASE [Jai] SET PARAMETERIZATION SIMPLE GO ALTER DATABASE [Jai] SET READ_WRITE GO ALTER DATABASE [Jai] SET RECOVERY FULL GO ALTER DATABASE [Jai] SET MULTI_USER GO ALTER DATABASE [Jai] SET PAGE_VERIFY CHECKSUM GO ALTER DATABASE [Jai] SET DB_CHAINING OFF </code></pre>
2,250,305
3
1
null
2010-02-12 07:48:13.32 UTC
5
2014-06-26 08:45:24.797 UTC
2011-05-03 23:54:59.847 UTC
null
10,936
null
238,779
null
1
12
c#|.net|sql-server|sql-server-2005
53,740
<p>Have a look at</p> <ul> <li><a href="http://social.msdn.microsoft.com/Forums/en/adodotnetdataproviders/thread/43e8bc3a-1132-453b-b950-09427e970f31" rel="nofollow noreferrer">Run a .sql script file in C#</a></li> <li><a href="https://stackoverflow.com/questions/650098/how-to-execute-an-sql-script-file-using-c">How to execute an .SQL script file using c#</a></li> </ul>
2,156,207
Polyvariadic Functions in Haskell
<p>After reading <a href="http://okmij.org/ftp/Haskell/vararg-fn.lhs" rel="noreferrer">this article on writing polyvariadic functions in Haskell</a>, I tried to write some of my own.</p> <p>At first I thought I'd try to generalize it - so I could have a function that returned variadic functions by collapsing arguments as given.</p> <pre><code>{-# OPTIONS -fglasgow-exts #-} module Collapse where class Collapse a r | r -&gt; a where collapse :: (a -&gt; a -&gt; a) -&gt; a -&gt; r instance Collapse a a where collapse _ = id instance (Collapse a r) =&gt; Collapse a (a -&gt; r) where collapse f a a' = collapse f (f a a') </code></pre> <p>However, the compiler didn't like that:</p> <pre><code>Collapse.hs:5:9: Functional dependencies conflict between instance declarations: instance Collapse a a -- Defined at Collapse.hs:5:9-20 instance (Collapse a r) =&gt; Collapse a (a -&gt; r) -- Defined at Collapse.hs:7:9-43 </code></pre> <p>If I went back and added a wrapper type for the final result, however, it worked:</p> <pre><code>module Collapse where class Collapse a r | r -&gt; a where collapse :: (a -&gt; a -&gt; a) -&gt; a -&gt; r data C a = C a instance Collapse a (C a) where collapse _ = C . id instance (Collapse a r) =&gt; Collapse a (a -&gt; r) where collapse f a a' = collapse f (f a a') sum :: (Num a, Collapse a r) =&gt; a -&gt; r sum = collapse (+) </code></pre> <p>Once I made this change, it compiled fine, and I could use the <code>collapse</code> function in <code>ghci</code>.</p> <pre><code>ghci&gt; let C s = Collapse.sum 1 2 3 in s 6 </code></pre> <p>I'm not sure why the wrapper type is required for the final result. If anyone could explain that, I'd highly appreciate it. I can see that the compiler's telling me that it's some issue with the functional dependencies, but I don't really grok the proper use of fundeps yet.</p> <p>Later, I tried to take a different tack, and try and define a variadic function generator for functions that took a list and returned a value. I had to do the same container trick, and also allow <code>UndecidableInstances</code>.</p> <pre><code>{-# OPTIONS -fglasgow-exts #-} {-# LANGUAGE UndecidableInstances #-} module Variadic where class Variadic a b r | r -&gt; a, r -&gt; b where variadic :: ([a] -&gt; b) -&gt; r data V a = V a instance Variadic a b (V b) where variadic f = V $ f [] instance (Variadic a b r) =&gt; Variadic a b (a -&gt; r) where variadic f a = variadic (f . (a:)) list :: Variadic a [a] r =&gt; r list = variadic . id foldl :: (Variadic b a r) =&gt; (a -&gt; b -&gt; a) -&gt; a -&gt; r foldl f a = variadic (Prelude.foldl f a) </code></pre> <p>Without allowing <code>UndecidableInstances</code> the compiler complained that my instance declarations were illegal:</p> <pre><code>Variadic.hs:7:0: Illegal instance declaration for `Variadic a b (V b)' (the Coverage Condition fails for one of the functional dependencies; Use -XUndecidableInstances to permit this) In the instance declaration for `Variadic a b (V b)' Variadic.hs:9:0: Illegal instance declaration for `Variadic a b (a -&gt; r)' (the Coverage Condition fails for one of the functional dependencies; Use -XUndecidableInstances to permit this) In the instance declaration for `Variadic a b (a -&gt; r)' </code></pre> <p>However, once it compiled, I could successfully use it in ghci:</p> <pre><code>ghci&gt; let V l = Variadic.list 1 2 3 in l [1,2,3] ghci&gt; let vall p = Variadic.foldl (\b a -&gt; b &amp;&amp; (p a)) True ghci&gt; :t vall vall :: (Variadic b Bool r) =&gt; (b -&gt; Bool) -&gt; r ghci&gt; let V b = vall (&gt;0) 1 2 3 in b True </code></pre> <p>I guess <strong>what I'm looking for is an explanation of why the container type for the final value is necessary, as well as why all the various functional dependencies are necessary</strong>.</p> <p>Also, this seemed odd:</p> <pre><code>ghci&gt; let vsum = Variadic.foldl (+) 0 &lt;interactive&gt;:1:10: Ambiguous type variables `a', `r' in the constraint: `Variadic a a r' arising from a use of `Variadic.foldl' at &lt;interactive&gt;:1:10-29 Probable fix: add a type signature that fixes these type variable(s) &lt;interactive&gt;:1:10: Ambiguous type variable `a'in the constraint: `Num a' arising from the literal `0' at &lt;interactive&gt;:1:29 Probable fix: add a type signature that fixes these type variable(s) ghci&gt; let vsum' = Variadic.foldl (+) ghci&gt; :t vsum' (Num a, Variadic a a r) =&gt; t -&gt; a -&gt; r ghci&gt; :t vsum' 0 (Num a, Variadic a a r) =&gt; a -&gt; r ghci&gt; let V s = vsum' 0 1 2 3 in s 6 </code></pre> <p>I'm guessing that's fallout from allowing <code>UndecidableInstances</code>, but I don't know, and I'd like to better understand what's going on.</p>
2,156,639
3
1
null
2010-01-28 16:45:14.467 UTC
9
2010-09-19 09:54:20.047 UTC
2010-09-19 09:54:20.047 UTC
null
417,501
null
9,859
null
1
15
haskell|polymorphism|polyvariadic
1,775
<p>The idea behind functional dependencies is that in a declaration like</p> <pre><code>class Collapse a r | r -&gt; a where ... </code></pre> <p>the <code>r -&gt; a</code> bit says that <code>a</code> is uniquely determined by <code>r</code>. So, you can't have <code>instance Collapse (a -&gt; r) (a -&gt; r)</code> and <code>instance Collapse a (a -&gt; r)</code>. Note that <code>instance Collapse (a -&gt; r) (a -&gt; r)</code> follows from <code>instance Collapse a a</code> for the complete picture.</p> <p>In other words, your code is trying to establish <code>instance Collapse t t</code> (the type variable's name is of course unimportant) and <code>instance Collapse a (a -&gt; r)</code>. If you substitute <code>(a -&gt; r)</code> for <code>t</code> in the first instance declaration, you get <code>instance Collapse (a -&gt; r) (a -&gt; r)</code>. Now <em>this is the only instance of <code>Collapse</code> with the second type parameter equal to <code>(a -&gt; r)</code> that you can have</em>, because the class declaration says that the first type parameter is to be deducible from the second. Yet next you try to establish <code>instance a (a -&gt; r)</code>, which would add another instance of <code>Collapse</code> with the second type parameter being <code>(a -&gt; r)</code>. Thus, GHC complains.</p>
1,859,385
Print out jQuery object as HTML
<p>Is there a good way of printing out a jQuery object as pure HTML?</p> <p>ex:</p> <pre><code>&lt;img src="example.jpg"&gt; &lt;script&gt; var img = $('img').eq(0); console.log(img.toString()); &lt;/script&gt; </code></pre> <p><code>toString()</code> doesn't work this way. I need the HTML equivalent string , i.e: </p> <p><code>&lt;img src="example.jpg"&gt;</code></p>
1,859,428
3
0
null
2009-12-07 11:16:29.153 UTC
5
2013-05-08 13:01:42.6 UTC
null
null
null
null
210,578
null
1
23
jquery
49,016
<p>If you need to print the object in HTML format, use this extension <a href="http://www.darlesson.com/jquery/outerhtml/" rel="noreferrer">outerHTML</a> or this <a href="https://gist.github.com/jboesch/889005" rel="noreferrer">outerHTML</a>.</p> <p><strong>Update</strong></p> <p>Update the link and include the code for second link:</p> <pre><code>$.fn.outerHTML = function(){ // IE, Chrome &amp; Safari will comply with the non-standard outerHTML, all others (FF) will have a fall-back for cloning return (!this.length) ? this : (this[0].outerHTML || ( function(el){ var div = document.createElement('div'); div.appendChild(el.cloneNode(true)); var contents = div.innerHTML; div = null; return contents; })(this[0])); } </code></pre>
2,106,820
Re-open files in Python?
<p>Say I have this simple python script:</p> <pre><code>file = open('C:\\some_text.txt') print file.readlines() print file.readlines() </code></pre> <p>When it is run, the first print prints a list containing the text of the file, while the second print prints a blank list. Not completely unexpected I guess. But is there a way to 'wind back' the file so that I can read it again? Or is the fastest way just to re-open it?</p>
2,106,825
3
4
null
2010-01-21 03:57:53.323 UTC
5
2010-01-21 07:32:26.037 UTC
2010-01-21 05:08:16.773 UTC
null
136,829
null
243,780
null
1
38
python|file
43,783
<p>You can reset the file pointer by calling <a href="http://docs.python.org/library/stdtypes.html#file.seek" rel="noreferrer"><code>seek()</code></a>:</p> <pre><code>file.seek(0) </code></pre> <p>will do it. You need that line after your first <code>readlines()</code>. Note that <code>file</code> has to support random access for the above to work.</p>
2,057,227
C# ASP.NET Send Email via TLS
<p>In order to comply with <a href="http://en.wikipedia.org/wiki/Health_Insurance_Portability_and_Accountability_Act" rel="noreferrer">HIPAA</a> regulations, we need to send email from an external site (outside the firewall) to an internal Exchange server (inside the firewall). Our Exchange admins tell us we need to use TLS encryption to send mail from the web server to the email server.</p> <p>I've never used TLS before and I'm not very familiar with it. Searching on Google as brought up numerous paid-for-use libraries. Is there anything native to .NET that will accomplish this? If so, how do I configure it? If not, is there something free or open source?</p> <p>Current Configuration:</p> <ul> <li>ASP.NET C# Web Application</li> <li>2.0 Framework</li> <li>Using System.Net.Mail to send email and attachments via SMTP</li> <li>IIS 6.0</li> </ul>
2,057,274
3
1
null
2010-01-13 14:18:50.557 UTC
10
2016-10-13 20:29:47.583 UTC
2013-02-05 14:54:57.88 UTC
null
205,245
null
249,861
null
1
70
asp.net|ssl|c#-2.0
128,054
<p>TLS (Transport Level Security) is the slightly broader term that has replaced SSL (Secure Sockets Layer) in securing HTTP communications. So what you are being asked to do is enable SSL.</p>
1,029,027
X11: move an existing window via command line?
<p>Given an X client window ID, is there a way to move that window or change its geometry from the command line?</p> <pre><code>$ xlsclients -a Window 0x3000001: Machine: ohm Name: Terminal Icon Name: foo Command: foo Instance/Class: foo/bar $ xmovewindow -id 0x3000001 --geometry +100+200 &lt;-- this is what I would like to do </code></pre>
1,029,302
1
1
null
2009-06-22 19:36:29.22 UTC
9
2013-11-25 04:08:41.943 UTC
2009-07-14 22:49:23.013 UTC
null
116
null
116
null
1
27
x11
25,278
<p>I think <a href="http://www.semicomplete.com/projects/xdotool/" rel="noreferrer">xdotool</a> will do the job. </p> <blockquote> <p>xdotool lets you programatically (or manually) simulate keyboard input and mouse activity, move and resize windows, etc. It does this using X11's XTEST extension and other Xlib functions.</p> </blockquote> <p>E.g.</p> <pre><code>$ xdotool windowfocus 0x1a00ad2 </code></pre> <p>will focus the window with id 0x1a00ad2. There's also a windowmove command which is probably the one you're looking for.</p> <p><a href="http://tripie.sweb.cz/utils/wmctrl/" rel="noreferrer">wmctrl</a> is slighty more advanced. It is compatible with EWMH/NetWM X window managers as you can read on <a href="http://tripie.sweb.cz/utils/wmctrl/" rel="noreferrer">their website</a>. I don't think you'll need it to be compatible with those though.</p>
165,105
How to disable Oracle XE component which is listening on 8080?
<p>After installing Oracle XE, something in Oracle is listening on port 8080. I am not sure if they have an Apache HTTPD, a Tomcat, or something else. But how can I disable it?</p>
165,124
1
0
null
2008-10-02 23:49:33.317 UTC
6
2016-08-09 22:09:16.883 UTC
2012-09-12 14:29:22.447 UTC
FerranB
869,458
Alessandro Vernet
5,295
null
1
28
oracle|oracle-xe
17,241
<p>It is Oracle XML DB HTTP Server; disable it as follows:</p> <pre><code>sqlplus '/ as sysdba' EXEC DBMS_XDB.SETHTTPPORT(0); commit; </code></pre> <p>You might have to restart Oracle XE (not just the listener).</p>
19,644,617
LINQ multiple join IQueryable modify result selector expression
<p>Imagine the following table structure</p> <pre><code>--------- TableA ID Name --------- TableB ID TableAID --------- TableC ID TableBID </code></pre> <p>I want to define a function that joins these three tables and accepts an <code>Expression&lt;Func&lt;TableA, TableB, TableC, T&gt;&gt;</code> as a selector.</p> <p>So I'd like something like the following:</p> <pre><code>public IQueryable&lt;T&gt; GetJoinedView&lt;T&gt;(Expression&lt;Func&lt;TableA, TableB, TableC, T&gt;&gt; selector) { return from a in DbContext.Set&lt;TableA&gt;() join b on DbContext.Set&lt;TableB&gt;() a.ID equals b.TableAID join c on DbContext.Set&lt;TableC&gt;() b.ID equals c.TableBID select selector; } </code></pre> <p>Now, obviously the above doesn't do what I want it to do, this will give me an <code>IQueryable</code> of the expression type. I could use method chaining syntax, but then I end up needing multiple selectors, one for each method chain invocation. Is there a way to take the selector and apply it to an anonymous type like in the following incomplete function:</p> <pre><code>public IQueryable&lt;T&gt; GetJoinedView&lt;T&gt;(Expression&lt;Func&lt;TableA, TableB, TableC, T&gt;&gt; selector) { var query = from a in DbContext.Set&lt;TableA&gt;() join b on DbContext.Set&lt;TableB&gt;() a.ID equals b.TableAID join c on DbContext.Set&lt;TableC&gt;() b.ID equals c.TableBID select new { A = a, B = b, C = c }; // I need the input selector to be modified to be able to operate on // the above anonymous type var resultSelector = ModifyInputSelectorToOperatorOnAnonymousType(selector); return query.Select(resultSelector); } </code></pre> <p>Any ideas on how this could be done?</p>
19,645,709
3
0
null
2013-10-28 20:35:24.073 UTC
4
2020-08-20 09:23:56.82 UTC
2013-10-28 22:48:00.303 UTC
null
1,159,478
null
1,582,922
null
1
7
c#|linq|entity-framework|expression
38,714
<p>You can define a throwaway intermediary object to select into instead of using an anonymous type:</p> <pre><code>public class JoinedItem { public TableA TableA { get; set; } public TableB TableB { get; set; } public TableC TableC { get; set; } } </code></pre> <p>New method:</p> <pre><code>public IQueryable&lt;T&gt; GetJoinedView&lt;T&gt;(Expression&lt;Func&lt;JoinedItem, T&gt;&gt; selector) { return DbContext.Set&lt;TableA&gt;() .Join(DbContext.Set&lt;TableB&gt;(), a =&gt; a.ID, b =&gt; b.TableAID, (a, b) =&gt; new { A = a, B = b}) .Join(DbContext.Set&lt;TableC&gt;(), ab =&gt; ab.B.ID, c =&gt; c.TableBID (ab, c) =&gt; new JoinedItem { TableA = ab.A, TableB = ab.B, TableC = c }) .Select(selector); } </code></pre> <p>Will you really be joining on these three tables enough to make the use of this method clearer than just expressing what you want to do directly in LINQ? I would argue that the extra lines needed to create this query every time would be clearer than using this method.</p>
19,539,303
Installing pg gem; ERROR: Failed to build gem native extension
<p>After updating to <strong>OS X 10.9 Mavericks</strong> I tried to start a Rails 3 app, but the connection to the PG database was not working. Checking on PGAdmin III, the database is still there and it works fine. So I tried to reinstall the pg gem:</p> <pre><code>gem uninstall pg gem install pg </code></pre> <p>But the last command doesn't succeed, and gives the following error:</p> <blockquote> <p>Building native extensions. This could take a while... ERROR: Error installing pg: </p> <p>ERROR: Failed to build gem native extension.</p> <pre><code> /Users/XXX/.rvm/rubies/ruby-1.9.3-p194/bin/ruby extconf.rb checking for pg_config... yes Using config values from </code></pre> <p>/usr/local/bin/pg_config <strong>* extconf.rb failed *</strong> Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options.</p> <p>/Users/XXX/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:381:in `try_do': The compiler failed to generate an executable file.</p> <p>(RuntimeError) You have to install development tools first. from /Users/XXX/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:461:in <code>try_link0' from /Users/XXX/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:476:in </code>try_link' from extconf.rb:39:in `'</p> </blockquote> <p>I guess the problem is related to the <strong>Xcode developer tools</strong>. I updated Xcode to the latest version, but that didn't solve the problem. Do you know how to fix it?</p>
19,545,788
8
0
null
2013-10-23 10:35:25.603 UTC
14
2019-04-05 15:04:38.07 UTC
2019-04-05 15:04:38.07 UTC
null
41,688
null
396,133
null
1
20
ruby-on-rails|postgresql|osx-mavericks|pg
15,953
<p>Using <a href="https://github.com/mxcl/homebrew">homebrew</a> fixed this for me:</p> <pre><code>gem uninstall pg brew install apple-gcc42 gem install pg </code></pre> <p>EDIT: I also manually installed "devtools"</p> <pre><code>xcode-select --install </code></pre>
45,341,721
Flutter - ListView inside on a TabBarView loses its scroll position
<p>I have a very simple Flutter app with a <strong>TabBarView</strong> with two views (<strong>Tab 1</strong> and <strong>Tab 2</strong>), one of them (<strong>Tab 1</strong>) has a ListView with many simple Text Widgets, the problem with this is that after I scroll down the ListView elements of <strong>Tab 1</strong>, if I swipe from <strong>Tab 1</strong> to <strong>Tab 2</strong> and finally I swipe from <strong>Tab 2</strong> to <strong>Tab 1</strong>, the previous scroll position in the ListView of <strong>Tab 1</strong> get lost.</p> <p>Here is the code:</p> <pre><code>import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override _MyHomePageState createState() =&gt; _MyHomePageState(); } class _MyHomePageState extends State&lt;MyHomePage&gt; with SingleTickerProviderStateMixin { late TabController controller; @override void initState() { super.initState(); controller = TabController( length: 2, vsync: this, ); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { var tabs = const &lt;Tab&gt;[ Tab(icon: Icon(Icons.home), text: 'Tab 1'), Tab(icon: Icon(Icons.account_box), text: 'Tab 2') ]; return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: TabBarView(controller: controller, children: &lt;Widget&gt;[ ListView(children: &lt;Widget&gt;[ Column(children: &lt;Widget&gt;[ for (int i = 0; i &lt; 48; i++) Text('Data $i'), ]) ]), const Center(child: Text('Tab 2')) ]), bottomNavigationBar: Material( color: Colors.deepOrange, child: TabBar(controller: controller, tabs: tabs), ), ); } } </code></pre> <p>I have even separated the <strong>TabBarView</strong> <strong>childrens</strong> (Tab 1 and Tab 2) in another classes and I have noticed that the</p> <pre><code>@override Widget build(BuildContext context) { ... } </code></pre> <p>method of each child (Tab 1 and Tab 2) is executed every time I swipe to its container tab.</p> <p>My questions are:</p> <p><strong>1.- How can I keep the scroll of the <em>ListView</em> even if I move from tab to tab?</strong></p> <p><strong>2.- Is there a way to execute the</strong></p> <pre><code>@override Widget build(BuildContext context) { } </code></pre> <p><strong>method only once if I separate the <em>TabBarView childrens</em> (Tab 1 and Tab 2) to another classes?</strong> I mean, if I have to retrieve data when the Tab 1 and Tab 2 are created I don't want to do this every time its Tab is swiped in. That would be expensive.</p> <p><strong>3.- In general, Is there a way to prevent that a tab view (including its variables, data, etc.) be rebuilt every time I swipe to that tab?</strong></p> <p><strong>Thank you in advance.</strong></p>
45,387,591
7
0
null
2017-07-27 04:56:04.087 UTC
22
2022-09-16 22:11:27.693 UTC
2022-09-16 22:11:27.693 UTC
null
712,558
null
6,172,868
null
1
59
flutter|dart|flutter-layout
33,320
<h2><a href="https://stackoverflow.com/a/51664759/7829326">Jordan Nelson's answer</a> is the correct one. Don't use mine.</h2> <hr /> <p><strong>1.- How can I keep the scroll of the ListView even if I move from tab to tab?</strong></p> <p>Ok, it wasn't so easy as I thought but I think I managed to do it.</p> <p>My idea is to keep listview's offset in HomePageState, and when we scroll listview we just get offset from notifier and set it via setter (please make it cleaner and share!).</p> <p>Then when we rebuild listview we just ask our main widget to give us saved offset and by ScrollController we initialize list with that offset.</p> <p>I also changed your listview since it had one column element with 50 texts to use 50 elements with one text each. Hope you don't mind :)</p> <p>The code:</p> <pre><code>import 'package:flutter/material.dart'; void main() { runApp(new MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter Demo', theme: new ThemeData( primarySwatch: Colors.blue, ), home: new MyHomePage(title: 'Flutter Demo Home Page'), ); } } typedef double GetOffsetMethod(); typedef void SetOffsetMethod(double offset); class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() =&gt; new _MyHomePageState(); } class _MyHomePageState extends State&lt;MyHomePage&gt; with SingleTickerProviderStateMixin { TabController controller; double listViewOffset=0.0; @override void initState() { super.initState(); controller = new TabController( length: 2, vsync: this, ); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { var tabs = &lt;Tab&gt;[ new Tab(icon: new Icon(Icons.home), text: 'Tab 1'), new Tab(icon: new Icon(Icons.account_box), text: 'Tab 2') ]; return new Scaffold( appBar: new AppBar( title: new Text(widget.title), ), body: new TabBarView( controller: controller, children: &lt;Widget&gt;[ new StatefulListView( getOffsetMethod: () =&gt; listViewOffset, setOffsetMethod: (offset) =&gt; this.listViewOffset = offset, ), new Center(child: new Text('Tab 2')) ]), bottomNavigationBar: new Material( color: Colors.deepOrange, child: new TabBar(controller: controller, tabs: tabs), ), ); } } class StatefulListView extends StatefulWidget { StatefulListView({Key key, this.getOffsetMethod, this.setOffsetMethod}) : super(key: key); final GetOffsetMethod getOffsetMethod; final SetOffsetMethod setOffsetMethod; @override _StatefulListViewState createState() =&gt; new _StatefulListViewState(); } class _StatefulListViewState extends State&lt;StatefulListView&gt; { ScrollController scrollController; @override void initState() { super.initState(); scrollController = new ScrollController( initialScrollOffset: widget.getOffsetMethod() ); } @override Widget build(BuildContext context) { return new NotificationListener( child: new ListView.builder( controller: scrollController, itemCount: 50, itemBuilder: (BuildContext context, int index) { return new Text(&quot;Data &quot;+index.toString()); }, ), onNotification: (notification) { if (notification is ScrollNotification) { widget.setOffsetMethod(notification.metrics.pixels); } }, ); } } </code></pre>
32,673,943
How to update Homebrew SHA256?
<p>This seems like a very noob question but I can't find an answer anywhere!</p> <p>I'm very new to developing packages for Homebrew but when I edit my formula and come to update my package I get the following error</p> <pre><code>Error: SHA256 mismatch </code></pre> <p>My question is, how do I generate the expected SHA256 value?</p>
32,753,064
2
0
null
2015-09-19 22:46:14.277 UTC
9
2020-09-14 20:09:02.33 UTC
2015-09-20 09:25:32.56 UTC
null
4,245,316
null
4,245,316
null
1
25
homebrew|sha
9,060
<p>After editing the formula, you can run <code>brew fetch your-formula --build-from-source</code> to fetch the tarball and display the new checksum. If you've already downloaded the tarball somewhere, you can calculate the hash with <code>openssl sha256 &lt; some_tarball.tar.gz</code> or <code>shasum -a 256 some_tarball.tar.gz</code>.</p>
39,577,920
Angular 2 unit testing components with routerLink
<p>I am trying to test my component with angular 2 final, but I get an error because the component uses the <code>routerLink</code> directive. I get the following error:</p> <blockquote> <p>Can't bind to 'routerLink' since it isn't a known property of 'a'.</p> </blockquote> <p>This is the relevant code of the <code>ListComponent</code> template</p> <pre><code>&lt;a *ngFor="let item of data.list" class="box" routerLink="/settings/{{collectionName}}/edit/{{item._id}}"&gt; </code></pre> <p>And here is my test.</p> <pre><code>import { TestBed } from '@angular/core/testing'; import { ListComponent } from './list.component'; import { defaultData, collectionName } from '../../config'; import { initialState } from '../../reducers/reducer'; const data = { sort: initialState.sort, list: [defaultData, defaultData], }; describe(`${collectionName} ListComponent`, () =&gt; { let fixture; beforeEach(() =&gt; { TestBed.configureTestingModule({ declarations: [ ListComponent, ], }).compileComponents(); // compile template and css; fixture = TestBed.createComponent(ListComponent); fixture.componentInstance.data = data; fixture.detectChanges(); }); it('should render 2 items in list', () =&gt; { const el = fixture.debugElement.nativeElement; expect(el.querySelectorAll('.box').length).toBe(3); }); }); </code></pre> <p>I looked at several answers to similar questions but could not find a solution that worked for me.</p>
39,579,009
3
0
null
2016-09-19 16:33:16.43 UTC
15
2018-05-25 09:47:36.243 UTC
2016-09-19 17:55:17.263 UTC
null
2,587,435
null
1,436,151
null
1
69
angular|typescript|angular2-routing|angular2-testing
59,171
<p>You need to configure all the routing. For testing, rather than using the <code>RouterModule</code>, you can use the <code>RouterTestingModule</code> from <code>@angular/router/testing</code>, where you can set up some mock routes. You will also need to import the <code>CommonModule</code> from <code>@angular/common</code> for your <code>*ngFor</code>. Below is a complete passing test</p> <pre><code>import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { By } from '@angular/platform-browser'; import { Location, CommonModule } from '@angular/common'; import { RouterTestingModule } from '@angular/router/testing'; import { TestBed, inject, async } from '@angular/core/testing'; @Component({ template: ` &lt;a routerLink="/settings/{{collName}}/edit/{{item._id}}"&gt;link&lt;/a&gt; &lt;router-outlet&gt;&lt;/router-outlet&gt; ` }) class TestComponent { collName = 'testing'; item = { _id: 1 }; } @Component({ template: '' }) class DummyComponent { } describe('component: TestComponent', function () { beforeEach(() =&gt; { TestBed.configureTestingModule({ imports: [ CommonModule, RouterTestingModule.withRoutes([ { path: 'settings/:collection/edit/:item', component: DummyComponent } ]) ], declarations: [ TestComponent, DummyComponent ] }); }); it('should go to url', async(inject([Router, Location], (router: Router, location: Location) =&gt; { let fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); fixture.debugElement.query(By.css('a')).nativeElement.click(); fixture.whenStable().then(() =&gt; { expect(location.path()).toEqual('/settings/testing/edit/1'); console.log('after expect'); }); }))); }); </code></pre> <h2>UPDATE</h2> <p>Another option, if you just want to test that the routes are rendered correctly, without trying to navigate...</p> <p>You an just import the <code>RouterTestingModule</code> without configuring any routes</p> <pre><code>imports: [ RouterTestingModule ] </code></pre> <p>then just check that the link is rendered with the correct URL path, e.g.</p> <pre><code>let href = fixture.debugElement.query(By.css('a')).nativeElement .getAttribute('href'); expect(href).toEqual('/settings/testing/edit/1'); </code></pre>
29,918,007
Compare dates between datetimes with Doctrine
<p>I have a Symfony2 application with a table that contains a date field, whose type is DateTime.<br /> I need to get all the entities where that field value is now.</p> <p>If I uses the following code, I get 0 results because Doctrine is comparing the DateTime object.</p> <pre class="lang-php prettyprint-override"><code>$now = new \DateTime(); data = $entityRepository-&gt;findByDate($now); </code></pre> <p>I need to only compare year, month, and day, not hours.</p> <p>How can I achieve this?</p>
29,918,391
3
0
null
2015-04-28 11:18:58.12 UTC
5
2022-01-12 10:24:35.84 UTC
2022-01-12 10:24:35.84 UTC
null
225,647
null
3,396,420
null
1
22
php|symfony|datetime|doctrine-orm|doctrine
59,032
<p>I see this simple way:</p> <pre><code>$now = new \DateTime(); $data = $entityRepository-&gt;getByDate($now); </code></pre> <p>then in your repository</p> <pre><code>public function getByDate(\Datetime $date) { $from = new \DateTime($date-&gt;format("Y-m-d")." 00:00:00"); $to = new \DateTime($date-&gt;format("Y-m-d")." 23:59:59"); $qb = $this-&gt;createQueryBuilder("e"); $qb -&gt;andWhere('e.date BETWEEN :from AND :to') -&gt;setParameter('from', $from ) -&gt;setParameter('to', $to) ; $result = $qb-&gt;getQuery()-&gt;getResult(); return $result; } </code></pre>
26,884,395
Ansible: Install tarball via HTTP
<p>I'd like to extend my ansible playbook to install/verify installation of phantomjs and wkhtmltopdf to my Debian 7 machine. Both programs are available as packed tarballs via HTTP. I know the get_url module, but it doesn't unpack stuff, and if I'd add some shell commands for unpacking and moving the binaries, I suspect each time I run ansible, the tarballs would be downloaded, unpacked and moved again, causing unnecessary network traffic.</p> <p>How can I solve this? Should I make a .deb file and run that using the apt command, or should I make a new ansible module for installing tarballs, or is there something that I'm overlooking?</p>
26,887,390
2
0
null
2014-11-12 10:14:52.053 UTC
8
2016-08-29 11:27:46.233 UTC
2015-06-29 20:39:48.89 UTC
null
22,404
null
22,404
null
1
12
http|installation|ansible
14,099
<p>If you download specific versions (e.g. <code>foo_1.2.3.tar.gz</code> and not <code>foo_latest.tar.gz</code>), you can do this by keeping the downloaded tarball :</p> <pre><code>- name: Gets tarball sudo: yes sudo_user: "{{ deploy_user }}" get_url: url="http://some.host/some_tarball-{{ tarball_version }}.tar.gz" dest="/home/{{ deploy_user }}/" register: new_archive - name: Unarchive source sudo: yes sudo_user: "{{ deploy_user }}" unarchive: src="/home/{{ deploy_user }}/some_tarball-{{ tarball_version }}.tar.gz" dest="/home/{{ deploy_user }}/app/" copy=no when: new_archive|changed </code></pre> <p>Change variables according to your environment.</p>
43,522,133
Using jq how can I replace the name of a key with something else
<p>This should be easy enough... I want to rename a few keys (ideally with jq), whatever I do seems to error though. Here is a json example below:</p> <pre><code>[ { "fruit": "strawberry", "veg": "apple", "worker": "gardener" } ] </code></pre> <p>I'd like to rename the veg key to fruit2 (or example, whatever is easiest) and also the worker key to job.</p> <p>I realize this is possible in sed, but I'm trying to get to grips with jq</p>
43,522,716
2
0
null
2017-04-20 14:17:57.033 UTC
3
2020-04-27 05:54:42.77 UTC
2020-04-27 05:54:42.77 UTC
null
6,782,707
null
486,670
null
1
40
json|key|jq
19,316
<p>Use the following <strong><em>jq</em></strong> approach:</p> <pre><code>jq '[.[] | .["fruit2"] = .veg | .["job"] = .worker | del(.veg, .worker)]' file </code></pre> <p>The output:</p> <pre><code>[ { "fruit": "strawberry", "fruit2": "apple", "job": "gardener" } ] </code></pre>
22,255,579
Homebrew brew doctor warning about /Library/Frameworks/Python.framework, even with brew's Python installed
<p>When I ran <strong>Homebrew's</strong> <code>brew doctor</code> (Mac OS X 10.9.2), I get the following warning message:</p> <blockquote> <p>Warning: Python is installed at /Library/Frameworks/Python.framework</p> <p>Homebrew only supports building against the System-provided Python or a brewed Python. In particular, Pythons installed to /Library can interfere with other software installs.</p> </blockquote> <p>Therefore, I ran <code>brew install</code> and followed the steps provided in the installation's caveats output to install Homebrew's version of <strong>Python</strong>. Running <code>which python</code> confirms that Homebrew's version of it is indeed at the top of my <em>PATH</em>. Output is <code>/usr/local/bin/python</code>.</p> <p>Despite all this, when I rerun <code>brew doctor</code>, I am still getting the <em>same warning message</em>. How do I suppress this warning? Do I need to delete the /Library/Frameworks/Python.framework directory from my computer? Am I just supposed to ignore it? Is there a different application on my computer that may be causing this warning to emit?</p> <p>Note that I don't have any applications in particular that are running into errors due to this warning from <code>brew doctor</code>. Also note that this warning message didn't always print out when I ran <code>brew doctor</code>, it was something that started to appear recently. Also, I am using Python 2.7 on my computer, trying to stay away from Python 3.</p>
22,265,200
6
0
null
2014-03-07 16:33:44.337 UTC
20
2018-03-21 10:11:49.323 UTC
null
null
null
null
814,576
null
1
73
python|macos|python-2.7|homebrew|brew-doctor
46,394
<p>I had the same problem. When I upgraded python3 through Homebrew, I started getting this:</p> <pre><code>-bash: python3: command not found </code></pre> <p>I had the same conflict with Python somehow being installed in <code>/Library/Framework/Python.framework</code>. I just did a <code>brew link overwrite</code> and everything is working fine now. There is some info about what to do with the Python version in the <code>/Library/Framework/Python.framework</code> <a href="https://github.com/Homebrew/homebrew/issues/27146" rel="noreferrer">here</a>.</p> <p>I guess you could try deleting that version as the link suggests, just make sure that version isn't being used. When I got into the Python.framework directory I was seeing some EPD version of Python, which I think is Enthought. You could delete it, but I if it isn't causing you any problems besides the unsightly Homebrew warning message, then I think you should just ignore it for now. </p> <p>Update:</p> <p>I did delete the Python.framework directory which, through some poking around inside that directory, I started seeing a few old versions of Python that I didn't install with Homebrew. One was from Enthought, and another was a distribution of Python3.3. I think some of these installs in the Framework directory are user installs. I installed R on my system, and there is also an R.framework directory, so I think most of these are user installs. After I deleted the directory, I just had to call brew prune to remove the old symlinks. I checked both brew versions of python 2.7.6 and 3.3.4, and they seem to be in good working order with all of my installed packages. I guess I leave the decision to remove that directory, or python version, to your discretion. </p>
40,408,096
What's the correct way to pass props as initial data in Vue.js 2?
<p>So I want to pass props to an Vue component, but I expect these props to change in future from inside that component e.g. when I update that Vue component from inside using AJAX. So they are only for initialization of component.</p> <p>My <code>cars-list</code> Vue component element where I pass props with initial properties to <code>single-car</code>:</p> <pre><code>// cars-list.vue &lt;script&gt; export default { data: function() { return { cars: [ { color: 'red', maxSpeed: 200, }, { color: 'blue', maxSpeed: 195, }, ] } }, } &lt;/script&gt; &lt;template&gt; &lt;div&gt; &lt;template v-for="car in cars"&gt; &lt;single-car :initial-properties="car"&gt;&lt;/single-car&gt; &lt;/template&gt; &lt;/div&gt; &lt;/template&gt; </code></pre> <p>The way I do it right now it that inside my <code>single-car</code> component I'm assigning <code>this.initialProperties</code> to my <code>this.data.properties</code> on <code>created()</code> initialization hook. And it works and is reactive.</p> <pre><code>// single-car.vue &lt;script&gt; export default { data: function() { return { properties: {}, } }, created: function(){ this.data.properties = this.initialProperties; }, } &lt;/script&gt; &lt;template&gt; &lt;div&gt;Car is in {{properties.color}} and has a max speed of {{properties.maxSpeed}}&lt;/div&gt; &lt;/template&gt; </code></pre> <p>But my problem with that is that I don't know if that's a correct way to do it? Won't it cause me some troubles along the road? Or is there a better way to do it?</p>
40,435,856
5
4
null
2016-11-03 17:46:53.573 UTC
39
2022-07-15 04:23:24.127 UTC
2020-08-04 12:11:35.377 UTC
null
1,970,470
null
3,143,704
null
1
139
javascript|vue.js|vuejs2
126,801
<p>Thanks to this <a href="https://github.com/vuejs/vuejs.org/pull/567" rel="nofollow noreferrer">https://github.com/vuejs/vuejs.org/pull/567</a> I know the answer now.</p> <h1>Method 1</h1> <p>Pass initial prop directly to the data. Like the example in updated docs:</p> <pre><code>props: ['initialCounter'], data: function () { return { counter: this.initialCounter } } </code></pre> <p>But have in mind if the passed prop is an object or array that is used in the parent component state any modification to that prop will result in the change in that parent component state.</p> <p><strong>Warning</strong>: this method is not recommended. It will make your components unpredictable. If you need to set parent data from child components either use state management like Vuex or use &quot;v-model&quot;. <a href="https://v2.vuejs.org/v2/guide/components.html#Using-v-model-on-Components" rel="nofollow noreferrer">https://v2.vuejs.org/v2/guide/components.html#Using-v-model-on-Components</a></p> <h1>Method 2</h1> <p>If your initial prop is an object or array and if you don't want changes in children state propagate to parent state then just use e.g. <code>Vue.util.extend</code> [1] to make a copy of the props instead pointing it directly to children data, like this:</p> <pre><code>props: ['initialCounter'], data: function () { return { counter: Vue.util.extend({}, this.initialCounter) } } </code></pre> <h1>Method 3</h1> <p>You can also use spread operator to clone the props. More details in the Igor answer: <a href="https://stackoverflow.com/a/51911118/3143704">https://stackoverflow.com/a/51911118/3143704</a></p> <p>But have in mind that spread operators are not supported in older browsers and for better compatibility you'll need to transpile the code e.g. using <code>babel</code>.</p> <h1>Footnotes</h1> <p>[1] Have in mind this is an internal Vue utility and it may change with new versions. You might want to use other methods to copy that prop, see &quot;https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object&quot;.</p> <p>My fiddle where I was testing it: <a href="https://jsfiddle.net/sm4kx7p9/3/" rel="nofollow noreferrer">https://jsfiddle.net/sm4kx7p9/3/</a></p>
1,117,332
How can I monitor outgoing email from Unix and Sendmail?
<p>I am running a FreeBSD server and I have been sent a warning that spam has been sent from my server. I do not have it set as an open relay and I have customized the sendmail configuration. I'd like to know who is sending what email along with their username, email subject line as well as a summary of how much mail they have been sending. I would like to run a report on a log similar to how it is done when processing Apache server logs.</p> <p>What are my options?</p>
1,117,371
4
1
null
2009-07-13 00:42:01.757 UTC
null
2016-02-09 11:14:15.6 UTC
null
null
null
null
10,366
null
1
6
unix|email|sendmail|freebsd
42,173
<p>One idea is to alias sendmail to be a custom script, which simply cats the sendmail arguments to the end of a log before calling sendmail in the usual manner.</p>
398,884
PostgreSQL HASH index
<p>Does anyone know a situation where a PostgreSQL HASH should be used instead of a B-TREE for it seems to me that these things are a trap. They are take way more time to CREATE or maintain than a B-TREE (at least 10 times more), they also take more space (for one of my table.columns, a B-TREE takes up 240 MB, while a HASH would take 4 GB) and I seem to have understood from my googling, that they do not SELECT faster than B-TREEs; yet the HASH may have recently been optimized or google was wrong. </p> <p>Anyway, I wanted you guy's opinions and experiences. If these HASHs are evil, people should know. </p> <p>Thanks<br> Also: what about MySQL's HASHs?</p>
398,921
4
0
null
2008-12-29 22:18:46.71 UTC
11
2015-12-22 08:11:25.987 UTC
2012-04-05 17:14:46.29 UTC
null
871,050
null
49,985
null
1
31
sql|postgresql|indexing|database
11,302
<p>Hashes are faster than B-Trees for cases where you have a known key value, especially a known unique value. </p> <p>Hashes should be used if the column in question is <em>never</em> intended to be scanned comparatively with <code>&lt;</code> or <code>&gt;</code> commands.</p> <p>Hashes are <code>O(1)</code> complexity, B-Trees are <code>O(log n)</code> complexity ( iirc ) , ergo, for large tables with unique entries, fetching an <code>ITEM="foo"</code>, they will be the most efficient way of looking it up. </p> <p>This is <em>especially</em> practical when these unique fields are used on a join condition.</p>
914,370
Where does a published RDL file sit?
<p>When publishing a reporting services report. Where does the actual .RDL file sit on the server?</p> <p>I can redownload the .RDL file via browsing through the report manager? But where is this file situated on the reporting services server?</p> <p>Thanks</p>
914,377
4
0
null
2009-05-27 07:14:56 UTC
9
2018-11-14 21:40:55.287 UTC
null
null
null
user110714
null
null
1
56
reporting-services|reporting|rdl
65,772
<p>It is not a file on the server. It stored as a BLOB in the ReportServer database.</p> <p>(In the Catalog table to be precise on SSRS 2005)</p> <p><a href="https://stackoverflow.com/a/17991798/6868683">Extended Answer</a></p>
40,097,590
Detect whether a Python string is a number or a letter
<p>How can I detect either numbers or letters in a string? I am aware you use the ASCII codes, but what functions take advantage of them?</p>
40,097,699
2
2
null
2016-10-18 00:15:58.513 UTC
16
2021-08-09 09:22:08.65 UTC
2016-10-18 00:18:56.96 UTC
null
603,977
null
6,902,080
null
1
76
python|string|ascii
195,815
<h2>Check if string is <em>nonnegative</em> digit (integer) and alphabet</h2> <p>You may use <a href="https://docs.python.org/2/library/stdtypes.html#str.isdigit" rel="noreferrer"><strong><code>str.isdigit()</code></strong></a> and <a href="https://docs.python.org/2/library/stdtypes.html#str.isalpha" rel="noreferrer"><strong><code>str.isalpha()</code></strong></a> to check whether a given string is a <em>nonnegative</em> integer (0 or greater) and alphabetical character, respectively.</p> <p>Sample Results:</p> <pre><code># For alphabet &gt;&gt;&gt; 'A'.isdigit() False &gt;&gt;&gt; 'A'.isalpha() True # For digit &gt;&gt;&gt; '1'.isdigit() True &gt;&gt;&gt; '1'.isalpha() False </code></pre> <h2>Check for strings as positive/negative - integer/float</h2> <p><code>str.isdigit()</code> returns <code>False</code> if the string is a <em>negative</em> number or a float number. For example:</p> <pre><code># returns `False` for float &gt;&gt;&gt; '123.3'.isdigit() False # returns `False` for negative number &gt;&gt;&gt; '-123'.isdigit() False </code></pre> <p>If you want to <strong>also check for the <em>negative</em> integers and <a href="https://docs.python.org/3/library/functions.html#float" rel="noreferrer"><code>float</code></a></strong>, then you may write a custom function to check for it as:</p> <pre><code>def is_number(n): try: float(n) # Type-casting the string to `float`. # If string is not a valid `float`, # it'll raise `ValueError` exception except ValueError: return False return True </code></pre> <p>Sample Run:</p> <pre><code>&gt;&gt;&gt; is_number('123') # positive integer number True &gt;&gt;&gt; is_number('123.4') # positive float number True &gt;&gt;&gt; is_number('-123') # negative integer number True &gt;&gt;&gt; is_number('-123.4') # negative `float` number True &gt;&gt;&gt; is_number('abc') # `False` for &quot;some random&quot; string False </code></pre> <h2>Discard &quot;NaN&quot; (not a number) strings while checking for number</h2> <p>The above functions will return <code>True</code> for the &quot;NAN&quot; (Not a number) string because for Python it is valid float representing it is not a number. For example:</p> <pre><code>&gt;&gt;&gt; is_number('NaN') True </code></pre> <p>In order to check whether the number is &quot;NaN&quot;, you may use <a href="https://docs.python.org/2/library/math.html#math.isnan" rel="noreferrer"><strong><code>math.isnan()</code></strong></a> as:</p> <pre><code>&gt;&gt;&gt; import math &gt;&gt;&gt; nan_num = float('nan') &gt;&gt;&gt; math.isnan(nan_num) True </code></pre> <p>Or if you don't want to import additional library to check this, then you may simply check it via comparing it with itself using <code>==</code>. Python returns <code>False</code> when <code>nan</code> float is compared with itself. For example:</p> <pre><code># `nan_num` variable is taken from above example &gt;&gt;&gt; nan_num == nan_num False </code></pre> <p>Hence, above <strong>function <code>is_number</code> can be updated to return <code>False</code> for <code>&quot;NaN&quot;</code></strong> as:</p> <pre><code>def is_number(n): is_number = True try: num = float(n) # check for &quot;nan&quot; floats is_number = num == num # or use `math.isnan(num)` except ValueError: is_number = False return is_number </code></pre> <p>Sample Run:</p> <pre><code>&gt;&gt;&gt; is_number('Nan') # not a number &quot;Nan&quot; string False &gt;&gt;&gt; is_number('nan') # not a number string &quot;nan&quot; with all lower cased False &gt;&gt;&gt; is_number('123') # positive integer True &gt;&gt;&gt; is_number('-123') # negative integer True &gt;&gt;&gt; is_number('-1.12') # negative `float` True &gt;&gt;&gt; is_number('abc') # &quot;some random&quot; string False </code></pre> <h2>Allow Complex Number like &quot;1+2j&quot; to be treated as valid number</h2> <p>The above function will still return you <code>False</code> for the <a href="https://docs.python.org/3/library/stdtypes.html#typesnumeric" rel="noreferrer"><em>complex numbers</em></a>. If you want your <strong><code>is_number</code> function to treat <em>complex numbers</em> as valid number</strong>, then you need to type cast your passed string to <a href="https://docs.python.org/3/library/functions.html#complex" rel="noreferrer"><strong><code>complex()</code></strong></a> instead of <a href="https://docs.python.org/3/library/functions.html#float" rel="noreferrer"><strong><code>float()</code></strong></a>. Then your <code>is_number</code> function will look like:</p> <pre><code>def is_number(n): is_number = True try: # v type-casting the number here as `complex`, instead of `float` num = complex(n) is_number = num == num except ValueError: is_number = False return is_number </code></pre> <p>Sample Run:</p> <pre><code>&gt;&gt;&gt; is_number('1+2j') # Valid True # : complex number &gt;&gt;&gt; is_number('1+ 2j') # Invalid False # : string with space in complex number represetantion # is treated as invalid complex number &gt;&gt;&gt; is_number('123') # Valid True # : positive integer &gt;&gt;&gt; is_number('-123') # Valid True # : negative integer &gt;&gt;&gt; is_number('abc') # Invalid False # : some random string, not a valid number &gt;&gt;&gt; is_number('nan') # Invalid False # : not a number &quot;nan&quot; string </code></pre> <p><em><strong>PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of <code>is_number</code> function which fits your requirement.</strong></em></p>
21,995,264
Attempt to invoke virtual method
<p>I am trying to get some <code>LinearLayouts</code>in my <code>onCreateView</code> but my App is crashing with the following message:</p> <pre><code>23430-23430/? W/System.err﹕ java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference </code></pre> <p>Here is the code:</p> <pre><code>@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); new Body().execute(); card01 = (LinearLayout) getView().findViewById(R.id.card01); card02 = (LinearLayout) getView().findViewById(R.id.card02); card03 = (LinearLayout) getView().findViewById(R.id.card03); card04 = (LinearLayout) getView().findViewById(R.id.card04); card05 = (LinearLayout) getView().findViewById(R.id.card05); card06 = (LinearLayout) getView().findViewById(R.id.card06); card01.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), "Card Clicked", Toast.LENGTH_SHORT).show(); } }); return rootView; } </code></pre> <p>This is a pure <code>Fragment</code> class. The <code>Activity</code> which calls this <code>Fragment</code> does not contain this <code>Fragment</code>. Am I doing it wrong? Should the <code>Fragment</code>always be within the <code>Activity</code>?</p> <p>As requested the whole <code>AsyncTask</code>:</p> <pre><code> // AsyncTask private class Body extends AsyncTask&lt;Void, Void, Void&gt; { @Override protected void onPreExecute() { super.onPreExecute(); mProgressDialog = new ProgressDialog(getActivity()); mProgressDialog.setTitle("Fetching your info"); mProgressDialog.setMessage("Loading..."); mProgressDialog.setIndeterminate(false); mProgressDialog.show(); } @Override protected Void doInBackground(Void... params) { Document doc; try { // Connect to the web site doc = Jsoup.connect(url).get(); // Using Elements to get the Meta data //Date of Event Elements dateElement = doc.select("span[class=date-display-single]"); //Headline of Event Elements titleElement = doc.select("h2[property=schema:name]"); //Description of Event Elements bodyElement = doc.select("div[class=field field-name-body field-type-text-with-summary field-label-hidden]"); // get the dates date1 = dateElement.eq(0).text(); date2 = dateElement.eq(1).text(); date3 = dateElement.eq(2).text(); date4 = dateElement.eq(3).text(); date5 = dateElement.eq(4).text(); date6 = dateElement.eq(5).text(); // get headlines head1 = titleElement.eq(0).text(); head2 = titleElement.eq(1).text(); head3 = titleElement.eq(2).text(); head4 = titleElement.eq(3).text(); head5 = titleElement.eq(4).text(); head6 = titleElement.eq(5).text(); // get description body1 = bodyElement.eq(0).toString(); body1 = Jsoup.parse(body1.replaceAll("&lt;br /&gt;", "br2n")).toString(); body1 = Jsoup.parse(body1.replaceAll("&lt;/p&gt;", "p2n")).text(); body1 = body1.replaceAll("br2n", "\n"); body1 = body1.replaceAll("p2n", "\n\n"); body2 = bodyElement.eq(1).toString(); body2 = Jsoup.parse(body2.replaceAll("&lt;br /&gt;", "br2n")).toString(); body2 = Jsoup.parse(body2.replaceAll("&lt;/p&gt;", "p2n")).text(); body2 = body2.replaceAll("br2n", "\n"); body2 = body2.replaceAll("p2n", "\n\n"); body3 = bodyElement.eq(2).toString(); body3 = Jsoup.parse(body3.replaceAll("&lt;br /&gt;", "br2n")).toString(); body3 = Jsoup.parse(body3.replaceAll("&lt;/p&gt;", "p2n")).text(); body3 = body3.replaceAll("br2n", "\n"); body3 = body3.replaceAll("p2n", "\n\n"); body4 = bodyElement.eq(3).toString(); body4 = Jsoup.parse(body4.replaceAll("&lt;br /&gt;", "br2n")).toString(); body4 = Jsoup.parse(body4.replaceAll("&lt;/p&gt;", "p2n")).text(); body4 = body4.replaceAll("br2n", "\n"); body4 = body4.replaceAll("p2n", "\n\n"); body5 = bodyElement.eq(4).toString(); body5 = Jsoup.parse(body5.replaceAll("&lt;br /&gt;", "br2n")).toString(); body5 = Jsoup.parse(body5.replaceAll("&lt;/p&gt;", "p2n")).text(); body5 = body5.replaceAll("br2n", "\n"); body5 = body5.replaceAll("p2n", "\n\n"); body6 = bodyElement.eq(5).toString(); body6 = Jsoup.parse(body6.replaceAll("&lt;br /&gt;", "br2n")).toString(); body6 = Jsoup.parse(body6.replaceAll("&lt;/p&gt;", "p2n")).text(); body6 = body6.replaceAll("br2n", "\n"); body6 = body6.replaceAll("p2n", "\n\n"); //cut out the date in the headlines (13 characters) if the String has something to cut //Let's hope the website stays like this if (head1.length() &gt; 0) { head1 = head1.substring(13); } if (head2.length() &gt; 0) { head2 = head2.substring(13); } if (head3.length() &gt; 0) { head3 = head3.substring(13); } if (head4.length() &gt; 0) { head4 = head4.substring(13); } if (head5.length() &gt; 0) { head5 = head5.substring(13); } if (head6.length() &gt; 0) { head6 = head6.substring(13); } //Get Event Labels AssetManager am = getActivity().getAssets(); bwe = BitmapFactory.decodeStream(am.open("label/bwe.jpg")); commaklar = BitmapFactory.decodeStream(am.open("label/commaklar.jpg")); // musica = BitmapFactory.decodeStream(am.open("label/musica.jpg")); doualatag = BitmapFactory.decodeStream(am.open("label/doualatag.jpg")); synestesia = BitmapFactory.decodeStream(am.open("label/synestesia.jpg")); douala = BitmapFactory.decodeStream(am.open("label/douala.jpg")); // tanzen = BitmapFactory.decodeStream(am.open("label/tanzen.jpg")); // nacht = BitmapFactory.decodeStream(am.open("label/nacht.jpg")); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { mProgressDialog.dismiss(); try { RobotoTextView date_widget1 = (RobotoTextView) getActivity().findViewById(R.id.date01); date_widget1.setText(date1); RobotoTextView head_widget1 = (RobotoTextView) getActivity().findViewById(R.id.head01); head_widget1.setText(head1); RobotoTextView body_widget1 = (RobotoTextView) getActivity().findViewById(R.id.body1); Whitelist.simpleText().addTags("br", "p"); body_widget1.setText(body1); ImageView label1 = (ImageView) getView().findViewById(R.id.label1); if (head1.contains("BLACKWHITE")) { label1.setImageBitmap(bwe); } if (date1.contains("Do")) { ; label1.setImageBitmap(doualatag); } if (head1.contains("COMMAKLAR")) { label1.setImageBitmap(commaklar); } if (head1.toLowerCase().contains("synestesia") | head1.contains("SYNESTESIA")) { label1.setImageBitmap(synestesia); } if (label1.getDrawable() == null) { label1.setImageBitmap(douala); } RobotoTextView date_widget2 = (RobotoTextView) getActivity().findViewById(R.id.date02); date_widget2.setText(date2); RobotoTextView head_widget2 = (RobotoTextView) getActivity().findViewById(R.id.head02); head_widget2.setText(head2); RobotoTextView body_widget2 = (RobotoTextView) getActivity().findViewById(R.id.body2); body_widget2.setText(body2); ImageView label2 = (ImageView) getView().findViewById(R.id.label2); if (head2.contains("BLACKWHITE")) { label2.setImageBitmap(bwe); } if (date2.contains("Do")) { label2.setImageBitmap(doualatag); } if (head2.contains("COMMAKLAR")) { label2.setImageBitmap(commaklar); } if (head2.toLowerCase().contains("synestesia")) { label2.setImageBitmap(synestesia); } if (label2.getDrawable() == null) { label2.setImageBitmap(douala); } RobotoTextView date_widget3 = (RobotoTextView) getActivity().findViewById(R.id.date03); date_widget3.setText(date3); RobotoTextView head_widget3 = (RobotoTextView) getActivity().findViewById(R.id.head03); head_widget3.setText(head3); RobotoTextView body_widget3 = (RobotoTextView) getActivity().findViewById(R.id.body3); body_widget3.setText(body3); ImageView label3 = (ImageView) getView().findViewById(R.id.label3); if (head3.contains("BLACKWHITE")) { label3.setImageBitmap(bwe); } if (date3.contains("Do")) { label3.setImageBitmap(doualatag); } if (head3.contains("COMMAKLAR")) { label3.setImageBitmap(commaklar); } if (head3.toLowerCase().contains("synestesia")) { label3.setImageBitmap(synestesia); } if (label3.getDrawable() == null) { label3.setImageBitmap(douala); } RobotoTextView date_widget4 = (RobotoTextView) getActivity().findViewById(R.id.date04); date_widget4.setText(date4); RobotoTextView head_widget4 = (RobotoTextView) getActivity().findViewById(R.id.head04); head_widget4.setText(head4); RobotoTextView body_widget4 = (RobotoTextView) getActivity().findViewById(R.id.body4); body_widget4.setText(body4); ImageView label4 = (ImageView) getView().findViewById(R.id.label4); if (head4.contains("BLACKWHITE")) { label4.setImageBitmap(bwe); } if (date4.contains("Do")) { label4.setImageBitmap(doualatag); } if (head4.contains("COMMAKLAR")) { label4.setImageBitmap(commaklar); } if (head4.toLowerCase().contains("synestesia")) { label4.setImageBitmap(synestesia); } if (label4.getDrawable() == null) { label4.setImageBitmap(douala); } if (!head5.equals("")) { RobotoTextView date_widget5 = (RobotoTextView) getActivity().findViewById(R.id.date05); date_widget5.setText(date5); RobotoTextView head_widget5 = (RobotoTextView) getActivity().findViewById(R.id.head05); head_widget5.setText(head5); RobotoTextView body_widget5 = (RobotoTextView) getActivity().findViewById(R.id.body5); body_widget5.setText(body5); ImageView label5 = (ImageView) getView().findViewById(R.id.label5); if (head5.contains("BLACKWHITE")) { label5.setImageBitmap(bwe); } if (date5.contains("Do")) { label5.setImageBitmap(doualatag); } if (head5.contains("COMMAKLAR")) { label5.setImageBitmap(commaklar); } if (head5.toLowerCase().contains("synestesia")) { label5.setImageBitmap(synestesia); } if (label5.getDrawable() == null) { label5.setImageBitmap(douala); } } if (!head6.equals("")) { RobotoTextView date_widget6 = (RobotoTextView) getActivity().findViewById(R.id.date06); date_widget6.setText(date6); RobotoTextView head_widget6 = (RobotoTextView) getActivity().findViewById(R.id.head06); head_widget6.setText(head6); RobotoTextView body_widget6 = (RobotoTextView) getActivity().findViewById(R.id.body6); body_widget6.setText(body6); ImageView label6 = (ImageView) getView().findViewById(R.id.label6); if (head6.contains("BLACKWHITE")) { label6.setImageBitmap(bwe); } if (date6.contains("Do")) { label6.setImageBitmap(doualatag); } if (head6.contains("COMMAKLAR")) { label6.setImageBitmap(commaklar); } if (head6.toLowerCase().contains("synestesia")) { label6.setImageBitmap(synestesia); } if (label6.getDrawable() == null) { label6.setImageBitmap(douala); } } } catch (NullPointerException e) { e.printStackTrace(); } } } </code></pre>
21,995,284
3
0
null
2014-02-24 17:54:50.187 UTC
2
2016-06-29 13:03:49.637 UTC
2014-02-24 18:09:28.357 UTC
null
2,100,269
null
2,100,269
null
1
12
java|android|android-fragments|android-activity|nullpointerexception
51,437
<p>Change to</p> <pre><code> card01 = (LinearLayout) rootView.findViewById(R.id.card01); card02 = (LinearLayout) rootView.findViewById(R.id.card02); card03 = (LinearLayout) rootView.findViewById(R.id.card03); card04 = (LinearLayout) rootView.findViewById(R.id.card04); card05 = (LinearLayout) rootView.findViewById(R.id.card05); card06 = (LinearLayout) rootView.findViewById(R.id.card06); </code></pre> <p>You inflate a layout. the views belong to the inflated layout. So use the view object to initialize views in <code>onCreateView</code></p> <p>Fragment is hosted by a Acitvity</p> <p>You can use <code>getView</code> in <code>onActivityCreated</code> and initialize views</p> <p>Initialize your TextView's also in <code>onCreateView</code>. Since Asynctask is a inner class you can update ui there</p> <p>Declare</p> <pre><code> RobotoTextView date_widget2; </code></pre> <p>as instance variable</p> <p>Then in onCreateView</p> <pre><code> date_widget2= (RobotoTextView) rootView.findViewById(R.id.date02); </code></pre>
25,891,342
Creating a video from a single image for a specific duration in ffmpeg
<p>How do I generate a movie using ffmpeg using a single image (image1.png) for a duration of 15 seconds with a specific resolution so when I play the video, the image will appear on screen for 15 seconds.</p>
25,895,709
4
1
null
2014-09-17 13:02:55.92 UTC
42
2022-08-25 11:07:27.523 UTC
2017-08-26 13:07:07.007 UTC
null
111,036
null
4,046,318
null
1
130
video|ffmpeg
94,634
<pre><code>ffmpeg -loop 1 -i image.png -c:v libx264 -t 15 -pix_fmt yuv420p -vf scale=320:240 out.mp4 </code></pre> <ul> <li>The -t 15 makes it 15 seconds long.</li> <li>The -vf scale=320:240 sets the width/height.</li> </ul> <p>Make sure to use the latest ffmpeg version e.g. <a href="http://johnvansickle.com/ffmpeg/" rel="noreferrer">http://johnvansickle.com/ffmpeg/</a></p>
30,667,122
Error: Call to a member function on array
<p>I'm trying to get the products from my selection in the Category object but I gives me the following error</p> <blockquote> <p>Error: Call to a member function getProducts() on array in /Users/jurrejan/Documents/projects/audsur2/src/Audsur/ShopBundle/Controller/DefaultController.php line 94</p> </blockquote> <p>Where am I going wrong?</p> <p>The object has multiple products</p> <pre><code>array(1) { [0]=&gt; object(stdClass)#329 (6) { ["__CLASS__"]=&gt; string(33) "Audsur\ShopBundle\Entity\Category" ["id"]=&gt; int(4) ["name"]=&gt; string(8) "Receiver" ["slug"]=&gt; string(8) "receiver" ["description"]=&gt; string(5) "descr" ["products"]=&gt; array(47) { [0]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [1]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [2]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [3]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [4]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [5]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [6]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [7]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [8]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [9]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [10]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [11]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [12]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [13]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [14]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [15]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [16]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [17]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [18]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [19]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [20]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [21]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [22]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [23]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [24]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [25]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [26]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [27]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [28]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [29]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [30]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [31]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [32]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [33]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [34]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [35]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [36]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [37]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [38]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [39]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [40]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [41]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [42]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [43]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [44]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [45]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" [46]=&gt; string(32) "Audsur\ShopBundle\Entity\Product" } } } </code></pre> <p>Controller</p> <pre><code>&lt;?php namespace Audsur\ShopBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Audsur\ShopBundle\Entity\Category; use Audsur\ShopBundle\Entity\Brand; use Audsur\ShopBundle\Entity\Product; use Symfony\Component\HttpFoundation\Response; class DefaultController extends Controller { /* removed irrelevant functions */ public function getGroupAction($slug, $type = null, $grouped = true) { $group = $this-&gt;getDoctrine() -&gt;getRepository('AudsurShopBundle:'.$type) -&gt;findBy(array( 'name' =&gt; $slug )) -&gt;getProducts(); return $this-&gt;render('AudsurShopBundle:Default:productOverview.html.twig', array( 'group' =&gt; $group ) ); } } </code></pre> <p>src/Audsur/ShopBundle/Entity/Category.php</p> <pre><code>&lt;?php namespace Audsur\ShopBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; /** * @ORM\Entity * @ORM\Table(name="category") */ class Category { /** * @ORM\Column(type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @ORM\Column(type="string", length=100, unique=true) */ protected $name; /** * @ORM\Column(type="string", length=255, nullable=false, unique=true) */ protected $slug; /** * @ORM\Column(type="text") */ protected $description; /** * @ORM\OneToMany(targetEntity="Product", mappedBy="category") */ protected $products; public function __construct() { $this-&gt;products = new ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this-&gt;id; } /** * Set name * * @param string $name * @return Category */ public function setName($name) { $this-&gt;name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this-&gt;name; } /** * Set slug * * @param string $slug * @return Category */ public function setSlug($slug) { $this-&gt;slug = $slug; return $this; } /** * Get slug * * @return string */ public function getSlug() { return $this-&gt;slug; } /** * Set description * * @param string $description * @return Category */ public function setDescription($description) { $this-&gt;description = $description; return $this; } /** * Get description * * @return string */ public function getDescription() { return $this-&gt;description; } /** * Add products * * @param \Audsur\ShopBundle\Entity\Product $products * @return Category */ public function addProduct(\Audsur\ShopBundle\Entity\Product $products) { $this-&gt;products[] = $products; return $this; } /** * Remove products * * @param \Audsur\ShopBundle\Entity\Product $products */ public function removeProduct(\Audsur\ShopBundle\Entity\Product $products) { $this-&gt;products-&gt;removeElement($products); } /** * Get products * * @return \Doctrine\Common\Collections\Collection */ public function getProducts() { return $this-&gt;products; } } </code></pre>
30,667,242
2
1
null
2015-06-05 12:55:58.757 UTC
null
2020-02-09 17:21:06.52 UTC
2015-06-05 13:03:32.72 UTC
null
158,477
null
158,477
null
1
8
symfony|doctrine
76,753
<p><code>findBy</code> returns an array of entities that satisfy the condition. If you are sure there is only one, you can just use <code>findOneBy</code> instead and you will get a single entity.</p>
20,365,286
Query WMI from Go
<p>I would like to run WMI queries from Go. There are ways to <a href="https://code.google.com/p/go-wiki/wiki/WindowsDLLs" rel="noreferrer">call DLL functions</a> from Go. My understanding is that there must be some DLL somewhere which, with the correct call, will return some data I can parse and use. I'd prefer to avoid calling into C or C++, especially since I would guess those are wrappers over the Windows API itself.</p> <p>I've examined the output of <code>dumpbin.exe /exports c:\windows\system32\wmi.dll</code>, and the following entry looks promising:</p> <p><code>WmiQueryAllDataA (forwarded to wmiclnt.WmiQueryAllDataA)</code></p> <p>However I'm not sure what to do from here. What arguments does this function take? What does it return? Searching for <code>WmiQueryAllDataA</code> is not helpful. And that name only appears in a comment of <code>c:\program files (x86)\windows kits\8.1\include\shared\wmistr.h</code>, but with no function signature.</p> <p>Are there better methods? Is there another DLL? Am I missing something? Should I just use a C wrapper?</p> <p>Running a WMI query in Linqpad with .NET Reflector shows the use of <code>WmiNetUtilsHelper:ExecQueryWmi</code> (and a <code>_f</code> version), but neither have a viewable implementation.</p> <p><strong>Update:</strong> use the <a href="http://github.com/StackExchange/wmi" rel="noreferrer">github.com/StackExchange/wmi</a> package which uses the solution in the accepted answer.</p>
20,366,574
4
1
null
2013-12-04 01:44:27.653 UTC
10
2021-11-19 03:51:38.747 UTC
2015-03-13 17:25:11.21 UTC
null
864,236
null
864,236
null
1
15
com|go|wmi
11,685
<p>Welcome to the wonderful world of <a href="http://en.wikipedia.org/wiki/Component_Object_Model" rel="noreferrer">COM</a>, Object Oriented Programming in C from when C++ was "a young upstart".</p> <p>On github <a href="https://github.com/mattn" rel="noreferrer">mattn</a> has thrown together a <a href="https://github.com/mattn/go-ole" rel="noreferrer">little wrapper in Go</a>, which I used to throw together a quick example program. "<em>This repository was created for experimentation and should be considered unstable.</em>" instills all sorts of confidence.</p> <p>I'm leaving out a lot of error checking. Trust me when I say, you'll want to add it back.</p> <pre><code>package main import ( "github.com/mattn/go-ole" "github.com/mattn/go-ole/oleutil" ) func main() { // init COM, oh yeah ole.CoInitialize(0) defer ole.CoUninitialize() unknown, _ := oleutil.CreateObject("WbemScripting.SWbemLocator") defer unknown.Release() wmi, _ := unknown.QueryInterface(ole.IID_IDispatch) defer wmi.Release() // service is a SWbemServices serviceRaw, _ := oleutil.CallMethod(wmi, "ConnectServer") service := serviceRaw.ToIDispatch() defer service.Release() // result is a SWBemObjectSet resultRaw, _ := oleutil.CallMethod(service, "ExecQuery", "SELECT * FROM Win32_Process") result := resultRaw.ToIDispatch() defer result.Release() countVar, _ := oleutil.GetProperty(result, "Count") count := int(countVar.Val) for i :=0; i &lt; count; i++ { // item is a SWbemObject, but really a Win32_Process itemRaw, _ := oleutil.CallMethod(result, "ItemIndex", i) item := itemRaw.ToIDispatch() defer item.Release() asString, _ := oleutil.GetProperty(item, "Name") println(asString.ToString()) } } </code></pre> <p>The real meat is the call to <a href="http://msdn.microsoft.com/en-us/library/aa393866%28v=vs.85%29.aspx" rel="noreferrer">ExecQuery</a>, I happen to grab <a href="http://msdn.microsoft.com/en-us/library/aa394372%28v=vs.85%29.aspx" rel="noreferrer">Win32_Process</a> from the <a href="http://msdn.microsoft.com/en-us/library/aa394554%28v=vs.85%29.aspx" rel="noreferrer">available classes</a> because it's easy to understand and print.</p> <p>On my machine, this prints:</p> <pre><code>System Idle Process System smss.exe csrss.exe wininit.exe services.exe lsass.exe svchost.exe svchost.exe atiesrxx.exe svchost.exe svchost.exe svchost.exe svchost.exe svchost.exe spoolsv.exe svchost.exe AppleOSSMgr.exe AppleTimeSrv.exe ... and so on go.exe main.exe </code></pre> <p>I'm not running it elevated or with UAC disabled, but some WMI providers are gonna require a privileged user.</p> <p>I'm also not 100% that this won't leak a little, you'll want to dig into that. COM objects are reference counted, so <code>defer</code> should be a pretty good fit there (provided the method isn't crazy long running) but go-ole may have some magic inside I didn't notice.</p>
66,338,549
WSL2 network unreachable
<p>A couple of weeks ago, WSL suddenly could not reach any IP addresses nor resolve any domains. Even internal network IPs are not reachable.</p> <pre><code>&gt;lsb_release -a Distributor ID: Ubuntu Description: Ubuntu 20.04.1 LTS Release: 20.04 Codename: focal ❯ neofetch .-/+oossssoo+/-. klewis@NOTEBOOK-KLEWIS `:+ssssssssssssssssss+:` ---------------------- -+ssssssssssssssssssyyssss+- OS: Ubuntu 20.04.1 LTS on Windows 10 x86_64 .ossssssssssssssssssdMMMNysssso. Kernel: 5.4.72-microsoft-standard-WSL2 /ssssssssssshdmmNNmmyNMMMMhssssss/ Uptime: 1 hour, 20 mins +ssssssssshmydMMMMMMMNddddyssssssss+ Packages: 1405 (dpkg) /sssssssshNMMMyhhyyyyhmNMMMNhssssssss/ Shell: zsh 5.8 .ssssssssdMMMNhsssssssssshNMMMdssssssss. Theme: Adwaita [GTK3] +sssshhhyNMMNyssssssssssssyNMMMysssssss+ Icons: Adwaita [GTK3] ossyNMMMNyMMhsssssssssssssshmmmhssssssso Terminal: Windows Terminal ossyNMMMNyMMhsssssssssssssshmmmhssssssso CPU: Intel i7-7820HK (8) @ 2.903GHz +sssshhhyNMMNyssssssssssssyNMMMysssssss+ Memory: 968MiB / 5942MiB .ssssssssdMMMNhsssssssssshNMMMdssssssss. Font: Cantarell 11 [GTK3] /sssssssshNMMMyhhyyyyhdNMMMNhssssssss/ +sssssssssdmydMMMMMMMMddddyssssssss+ /ssssssssssshdmNNNNmyNMMMMhssssss/ .ossssssssssssssssssdMMMNysssso. -+sssssssssssssssssyyyssss+- `:+ssssssssssssssssss+:` .-/+oossssoo+/-. </code></pre> <pre><code>❯ ifconfig ❯ ccat /etc/resolv.conf nameserver 9.9.9.9 nameserver 8.8.8.8 ❯ ccat /etc/wsl.conf [user] default=klewis # Now make it look like this and save the file when you're done: [automount] root = / options = &quot;metadata&quot; [network] generateResolvConf = false </code></pre> <pre><code>❯ ping 127.0.0.1 ping: connect: Network is unreachable ❯ ping 192.168.0.1 ping: connect: Network is unreachable ❯ ping 8.8.8.8 ping: connect: Network is unreachable ❯ ping google.com ping: google.com: Temporary failure in name resolution ❯ nslookup google.com 9.9.9.9 net.c:536: probing sendmsg() with IP_TOS=b8 failed: Network is unreachable ;; connection timed out; no servers could be reached ❯ ip route Error: ipv4: FIB table does not exist. Dump terminated ❯ ip addr show 1: lo: &lt;LOOPBACK&gt; mtu 65536 qdisc noop state DOWN group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 2: bond0: &lt;BROADCAST,MULTICAST,MASTER&gt; mtu 1500 qdisc noop state DOWN group default qlen 1000 link/ether 86:9a:be:53:f0:44 brd ff:ff:ff:ff:ff:ff 3: dummy0: &lt;BROADCAST,NOARP&gt; mtu 1500 qdisc noop state DOWN group default qlen 1000 link/ether 1e:ff:ad:a4:c4:a7 brd ff:ff:ff:ff:ff:ff 4: sit0@NONE: &lt;NOARP&gt; mtu 1480 qdisc noop state DOWN group default qlen 1000 link/sit 0.0.0.0 brd 0.0.0.0 5: eth0: &lt;BROADCAST,MULTICAST&gt; mtu 1500 qdisc noop state DOWN group default qlen 1000 link/ether 00:15:5d:b7:f4:da brd ff:ff:ff:ff:ff:ff </code></pre> <pre><code>C:\&gt; ipconfig Ethernet adapter vEthernet (WSL): Connection-specific DNS Suffix . : Description . . . . . . . . . . . : Hyper-V Virtual Ethernet Adapter #7 Physical Address. . . . . . . . . : 00-15-5D-E5-0C-1B DHCP Enabled. . . . . . . . . . . : No Autoconfiguration Enabled . . . . : Yes Link-local IPv6 Address . . . . . : fe80::1962:7d4e:a75e:8d62%78(Preferred) IPv4 Address. . . . . . . . . . . : 192.168.16.1(Preferred) Subnet Mask . . . . . . . . . . . : 255.255.240.0 Default Gateway . . . . . . . . . : DHCPv6 IAID . . . . . . . . . . . : 1308628317 DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-27-B3-1F-34-9C-B6-D0-DD-8C-CF DNS Servers . . . . . . . . . . . : fec0:0:0:ffff::1%1 fec0:0:0:ffff::2%1 fec0:0:0:ffff::3%1 NetBIOS over Tcpip. . . . . . . . : Enabled </code></pre> <pre><code>&gt;sudo ip route add default via 192.168.16.1 Error: Nexthop has invalid gateway. </code></pre> <p>I have looked through GH and found solutions that worked for others. Things I have tried:</p> <ul> <li> <pre><code>netsh winsock reset netsh int ip reset all netsh winhttp reset proxy ipconfig /flushdns </code></pre> </li> <li><p>deleted Hyper-V virtual adapters and restarting to let Windows rebuild</p> </li> <li><p>Changed where the Virtual Switch connects to in Hyper-V Virtual Switch Manager from Internal Network to External Network</p> </li> <li><p>Ensured %TEMP% is not compressed</p> </li> <li><p>Ensured no file nor folder under %TEMP% were compressed</p> </li> <li><p>Ensured no firewall was running</p> </li> <li><p><a href="https://github.com/microsoft/WSL/issues/4926" rel="noreferrer">https://github.com/microsoft/WSL/issues/4926</a></p> </li> <li><p><a href="https://github.com/microsoft/WSL/issues/4731" rel="noreferrer">https://github.com/microsoft/WSL/issues/4731</a></p> </li> <li><p>turned off Generation of resolv.conf and add gateway, 9.9.9.9 and 8.8.8.8 to resolv.conf</p> </li> </ul>
68,441,923
7
6
null
2021-02-23 17:56:39.323 UTC
10
2022-06-02 01:10:35.787 UTC
2021-05-10 13:37:41.483 UTC
null
1,282,988
null
1,282,988
null
1
24
windows-subsystem-for-linux|wsl-2|windows-networking
39,682
<p>As of build 19042.1052, this is working again with no changes from my end. I am unsure as to the actual cause, but since I can no longer reproduce it, further troubleshooting seems moot.</p>
32,398,006
IEnumerable<T> Skip on unlimited sequence
<p>I have a simple implementation of Fibonacci sequence using BigInteger:</p> <pre><code>internal class FibonacciEnumerator : IEnumerator&lt;BigInteger&gt; { private BigInteger _previous = 1; private BigInteger _current = 0; public void Dispose(){} public bool MoveNext() {return true;} public void Reset() { _previous = 1; _current = 0; } public BigInteger Current { get { var temp = _current; _current += _previous; _previous = temp; return _current; } } object IEnumerator.Current { get { return Current; } } } internal class FibonacciSequence : IEnumerable&lt;BigInteger&gt; { private readonly FibonacciEnumerator _f = new FibonacciEnumerator(); public IEnumerator&lt;BigInteger&gt; GetEnumerator(){return _f;} IEnumerator IEnumerable.GetEnumerator(){return GetEnumerator();} } </code></pre> <p>It is an <em>unlimited</em> sequence as the <code>MoveNext()</code> always returns true.</p> <p>When called using</p> <pre><code>var fs = new FibonacciSequence(); fs.Take(10).ToList().ForEach(_ =&gt; Console.WriteLine(_)); </code></pre> <p>the output is as expected (1,1,2,3,5,8,...)</p> <p>I want to select 10 items but starting at 100th position. I tried calling it via</p> <pre><code>fs.Skip(100).Take(10).ToList().ForEach(_ =&gt; Console.WriteLine(_)); </code></pre> <p>but this does not work, as it outputs ten elements from the beginning (i.e. the output is again 1,1,2,3,5,8,...).</p> <p>I <em>can</em> skip it by calling SkipWhile</p> <pre><code>fs.SkipWhile((b,index) =&gt; index &lt; 100).Take(10).ToList().ForEach(_ =&gt; Console.WriteLine(_)); </code></pre> <p>which correctly outputs 10 elements starting from the 100th element.</p> <p>Is there something else that needs/can be implemented in the enumerator to make the <code>Skip(...)</code> work?</p>
32,398,062
3
3
null
2015-09-04 12:24:27.12 UTC
5
2020-11-21 08:51:18.073 UTC
null
null
null
null
711,269
null
1
28
c#|linq|fibonacci|skip
1,424
<p><code>Skip(n)</code> doesn't access <code>Current</code>, it just calls <code>MoveNext()</code> <code>n</code> times. </p> <p>So you need to perform the increment in <code>MoveNext()</code>, which is <a href="https://msdn.microsoft.com/en-us/library/system.collections.ienumerator.current(v=vs.110).aspx" rel="noreferrer">the logical place for that operation anyway</a>:</p> <blockquote> <p>Current does not move the position of the enumerator, and consecutive calls to Current return the same object until either MoveNext or Reset is called.</p> </blockquote>
4,324,514
Horizontal UIScrollView inside a UITableViewCell
<p>I'm trying to create the exact same effect as in the AppStore app for viewing screenshots: inside a UITableView, I have custom subclasses of UITableViewCell's. One of them is designed to show previews of some product, say 4 images. I want them to show the same way as the AppStore presents screenshots of an app : inside a horizontal UIScrollView with its attached UIPageControl.</p> <p>So I add my UIScrollView and my UIPageControl to my UITableViewCell, just like that :</p> <pre><code>@implementation phVolumePreviewCell - (id)init { if (self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kVolumePreviewCellIdentifier]) { [self setAccessoryType:UITableViewCellAccessoryDisclosureIndicator]; [self setSelectionStyle:UITableViewCellSeparatorStyleNone]; previews = [[NSMutableArray alloc] initWithCapacity:4]; for (int i = 0; i &lt; 4; i++) { [previews addObject:@"dummy"]; } scrollView = [[UIScrollView alloc] initWithFrame:CGRectZero]; [scrollView setPagingEnabled:YES]; [scrollView setBackgroundColor:[UIColor grayColor]]; [scrollView setIndicatorStyle:UIScrollViewIndicatorStyleBlack]; [scrollView setShowsHorizontalScrollIndicator:YES]; [scrollView setBounces:YES]; [scrollView setScrollEnabled:YES]; [scrollView setDelegate:self]; [self.contentView addSubview:scrollView]; [scrollView release]; pageControl = [[UIPageControl alloc] initWithFrame:CGRectZero]; [pageControl setNumberOfPages:[previews count]]; [pageControl setBackgroundColor:[UIColor grayColor]]; [self.contentView addSubview:pageControl]; [pageControl release]; } return self; } </code></pre> <p>(note: I'm populating "previews" with dummy data here, just in order to have a [previews count] that works ; I want to view the scrollView's scroll indicator for test purposes only, I'll hide them later on).</p> <p>My problem is that I can scroll the whole UITableView containing this phVolumePreviewCell (subclass of UITableViewCell), but I can't scroll the UIScrollView. How can I achieve this?</p> <p>The only information I found is there: <a href="http://theexciter.com/articles/touches-and-uiscrollview-inside-a-uitableview.html" rel="noreferrer">http://theexciter.com/articles/touches-and-uiscrollview-inside-a-uitableview.html</a> But it talks of old SDKs (namely 2.2) and I'm sure there is a more "recent" approach to doing this.</p> <p>Some precisions :</p> <ul> <li>I can scroll the UIScrollView with two fingers. That's not what I want, I want it to be able to scroll with one finger only.</li> <li>When I scroll with two fingers, the TableView still intercepts the touches and scroll a little bit to the top or the bottom. I'd like the TableView to stick at its position when I touch the ScrollView.</li> </ul> <p>I believe I have to work out how to intercept touches on my TableView, and if the touch is on the phVolumePreviewCell (custom UITableViewCell subclass), pass it to the cell instead of handling it on the TableView.</p> <p>For the record, my TableView is created programmatically in a UITableViewController subclass:</p> <pre><code>@interface phVolumeController : UITableViewController &lt;UITableViewDelegate&gt; { LocalLibrary *lib; NSString *volumeID; LLVolume *volume; } - (id)initWithLibrary:(LocalLibrary *)newLib andVolumeID:(NSString *)newVolumeID; @end </code></pre> <p> </p> <pre><code>@implementation phVolumeController #pragma mark - #pragma mark Initialization - (id)initWithLibrary:(LocalLibrary *)newLib andVolumeID:(NSString *)newVolumeID { if (self = [super initWithStyle:UITableViewStylePlain]) { lib = [newLib retain]; volumeID = newVolumeID; volume = [(LLVolume *)[LLVolume alloc] initFromLibrary:lib forID:volumeID]; [[self navigationItem] setTitle:[volume title]]; } return self; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 1; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kVolumePreviewCellIdentifier]; if (cell == nil) { cell = [[[phVolumePreviewCell alloc] init] autorelease]; } [(phVolumePreviewCell *)cell setVolume:volume]; return (UITableViewCell *)cell; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return kVolumePreviewCellHeight; } </code></pre> <p>Thanks for any help!</p>
4,327,001
1
0
null
2010-12-01 12:49:01.253 UTC
23
2010-12-01 17:13:29.287 UTC
null
null
null
null
526,547
null
1
36
iphone|uitableview|uiscrollview|scroll
29,750
<p>I have found a workaround.</p> <p>Recreating from scratch a very simple UITableView (8 rows), and inserting a UIScrollView in just the second row, works perfectly. Nested scroll views (the TableView and the ScrollView) scroll independently as expected. All that was done in a single-file test project, in the AppDelegate.</p> <p>So... first I thought "this might be a delegation problem", so I told the scrollView that its delegate was the TableView, not my custom TableViewCell subclass. To no avail.</p> <p>Then instead of resorting to a custom, clean TableViewCell subclass that just adds the ScrollView and the PageControl, I resorted to creating a plain TableViewCell in the TableView's cellForRowAtIndexPath: method. Then, I create a UIScrollView right after initializing the TableViewCell, then add it to the TableViewCell, and shazam... it works!</p> <p>Before:</p> <pre><code>UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kVolumePreviewCellIdentifier]; if (cell == nil) { cell = [[[phVolumePreviewCell alloc] init] autorelease]; } [(phVolumePreviewCell *)cell setVolume:volume]; // That does the job of creating the cell's scrollView and pageControl return (UITableViewCell *)cell </code></pre> <p>After:</p> <pre><code>UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kvcPreviewRowIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kvcPreviewRowIdentifier] autorelease]; previewScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, kvcPreviewScrollViewHeight)]; [previewScrollView setContentSize:CGSizeMake(1000, kvcPreviewScrollViewHeight)]; [[cell contentView] addSubview:previewScrollView]; previewPageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, kvcPreviewScrollViewHeight, tableView.frame.size.width, kvcPreviewPageControlHeight)]; [previewPageControl setNumberOfPages:4]; [[cell contentView] addSubview:previewPageControl]; } return (UITableViewCell *)cell; </code></pre> <p>How the heck comes that when I create my scrollView from the TVCell subclass, it doesn't play nice ; but when I create the scrollView from the TableView right after creating a "classical" TVCell, it works?</p> <p>I might have found a solution, but I'm still puzzled by the reason.</p>
48,625,444
Calling a SOAP service in .net Core
<p>I´m porting a .net 4.6.2 code to a <strong>.net Core project</strong>, that calls a SOAP service. In the new code I´m using C# (because of some config reasons I just can´t remember why right now).</p> <p>But I´m getting the following exception.</p> <blockquote> <p>An error occurred while receiving the HTTP response to <a href="https://someurl.com/ws/Thing.pub.ws:Something" rel="noreferrer">https://someurl.com/ws/Thing.pub.ws:Something</a>. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.</p> </blockquote> <p>The code that is throwing it is</p> <pre><code>try { var binding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; var endpoint = new EndpointAddress(new Uri("https://someurl.com/ws/TheEndpoint.pub.ws:AService")); var thing= new TheEndpoint.AService_PortTypeClient(binding, endpoint); thing.ClientCredentials.UserName.UserName = "usrn"; thing.ClientCredentials.UserName.Password = "passw"; var response = await thing.getSomethingAsync("id").ConfigureAwait(false); } finally { await thing.CloseAsync().ConfigureAwait(false); } </code></pre> <p>Based on the old config where it works calling the service is like this, <strong>what am I missing</strong>?</p> <pre><code>&lt;bindings&gt; &lt;basicHttpsBinding&gt; &lt;binding name="TheEndpoint_pub_ws_AService_Binder" closeTimeout="00:02:00" openTimeout="00:02:00" receiveTimeout="00:03:00" sendTimeout="00:03:00"&gt; &lt;security mode="Transport"&gt; &lt;transport clientCredentialType="Basic" /&gt; &lt;message clientCredentialType="UserName" algorithmSuite="Default" /&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/basicHttpsBinding&gt; &lt;/bindings&gt; &lt;client&gt; &lt;endpoint address="https://someurl.com/ws/Thing.pub.ws:AService" binding="basicHttpsBinding" bindingConfiguration="TheEndpoint_pub_ws_AService_Binder" contract="TheEndpoint.AService_PortType" name="TheEndpoint_pub_ws_AService_Port" /&gt; &lt;/client&gt; </code></pre> <p>I´m just unable to find lot of information on this online. Hope you can help me.</p> <p><strong>UPDATE</strong> Per Sixto Saez suggestion I got the endpoint to reveal its error and it is</p> <blockquote> <p>The HTTP request is unauthorized with client authentication scheme 'Basic'. The authentication header received from the server was 'Basic realm="Integration Server", encoding="UTF-8"'.</p> </blockquote> <p>I´ll try to find out what to do and post the result here if successful.</p> <p><strong>UPDATE 2</strong></p> <p>Ok now I tried to move to the new syntax with this code here</p> <pre><code>ChannelFactory&lt;IAService&gt; factory = null; IAService serviceProxy = null; Binding binding = null; try { binding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport); factory = new ChannelFactory&lt;IAService&gt;(binding, new EndpointAddress(new Uri("https://someurl.com/ws/TheEndpoint.pub.ws:AService"))); factory.Credentials.UserName.UserName = "usrn"; factory.Credentials.UserName.Password = "passw"; serviceProxy = factory.CreateChannel(); var result = await serviceProxy.getSomethingAsync("id").ConfigureAwait(false); factory.Close(); ((ICommunicationObject)serviceProxy).Close(); } catch (MessageSecurityException ex) { //error caught here throw; } </code></pre> <p>but I still get the same (slightly different) error. It now has 'Anonymous' instead of 'Basic' and is now missing ", encoding="UTF-8" at the end.</p> <blockquote> <p>The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Basic realm="Integration Server"'.</p> </blockquote> <p><strong>Is the problem at my side or the servers?</strong></p> <p>Obviously my SOAP "skills" are greatly lacking now days, but I have just about tried every config combo I can think of with this new approach without luck. Hope somebody can point me in the right direction.</p>
48,660,543
7
3
null
2018-02-05 15:03:28.39 UTC
19
2021-04-19 06:42:46.93 UTC
2018-02-08 09:47:35.83 UTC
null
1,187,583
null
1,187,583
null
1
51
c#|wcf|soap|.net-core
131,703
<p>Ok this answer is for those who are trying to connect <strong>to a WCF</strong> service <strong>from a .net Core</strong> project.</p> <p>Here is the solution to <strong>my</strong> problem, using the new .net Core WCF syntax/library.</p> <pre><code>BasicHttpBinding basicHttpBinding = null; EndpointAddress endpointAddress = null; ChannelFactory&lt;IAService&gt; factory = null; IAService serviceProxy = null; try { basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; endpointAddress = new EndpointAddress(new Uri("https://someurl.com/ws/TheEndpoint.pub.ws:AService")); factory = new ChannelFactory&lt;IAService&gt;(basicHttpBinding, endpointAddress); factory.Credentials.UserName.UserName = "usrn"; factory.Credentials.UserName.Password = "passw"; serviceProxy = factory.CreateChannel(); using (var scope = new OperationContextScope((IContextChannel)serviceProxy)) { var result = await serviceProxy.getSomethingAsync("id").ConfigureAwait(false); } factory.Close(); ((ICommunicationObject)serviceProxy).Close(); } catch (MessageSecurityException ex) { throw; } catch (Exception ex) { throw; } finally { // *** ENSURE CLEANUP (this code is at the WCF GitHub page *** \\ CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } </code></pre> <p><strong>UPDATE</strong></p> <p>I got the following exception using the code above </p> <blockquote> <p>This OperationContextScope is being disposed out of order.</p> </blockquote> <p>Which seems to be <a href="https://github.com/dotnet/wcf/issues/2512" rel="noreferrer">something that is broken</a> (or needs addressing) by the WCF team.</p> <p>So I had to do the following to make it work (based on this <a href="https://github.com/dotnet/wcf/issues/2475" rel="noreferrer">GitHub issue</a>)</p> <pre><code>basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; factory = new ChannelFactory&lt;IAService_PortType&gt;(basicHttpBinding, new EndpointAddress(new Uri("https://someurl.com/ws/TheEndpoint.pub.ws:AService"))); factory.Credentials.UserName.UserName = "usern"; factory.Credentials.UserName.Password = "passw"; serviceProxy = factory.CreateChannel(); ((ICommunicationObject)serviceProxy).Open(); var opContext = new OperationContext((IClientChannel)serviceProxy); var prevOpContext = OperationContext.Current; // Optional if there's no way this might already be set OperationContext.Current = opContext; try { var result = await serviceProxy.getSomethingAsync("id").ConfigureAwait(false); // cleanup factory.Close(); ((ICommunicationObject)serviceProxy).Close(); } finally { // *** ENSURE CLEANUP *** \\ CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); OperationContext.Current = prevOpContext; // Or set to null if you didn't capture the previous context } </code></pre> <p>But your requirements will probably be different. So here are the resources you might need to help you connecting to your WCF service are here:</p> <ul> <li><a href="https://github.com/dotnet/wcf/" rel="noreferrer">WCF .net core at GitHub</a></li> <li><a href="https://github.com/dotnet/wcf/blob/master/src/System.Private.ServiceModel/tests/Scenarios/Binding/Http/BasicHttpBindingTests.4.0.0.cs" rel="noreferrer">BasicHttpBinding Tests</a> </li> <li><a href="https://github.com/dotnet/wcf/blob/master/src/System.Private.ServiceModel/tests/Scenarios/Security/TransportSecurity/Https/ClientCredentialTypeTests.4.1.0.cs" rel="noreferrer">ClientCredentialType Tests</a></li> </ul> <p>The tests helped me a lot but they where somewhat hard to find (I had help, thank you Zhenlan for <a href="https://github.com/dotnet/wcf/issues/2544" rel="noreferrer">answering my wcf github issue</a>)</p>
39,345,995
How does Python return multiple values from a function?
<p>I have written the following code:</p> <pre><code>class FigureOut: def setName(self, name): fullname = name.split() self.first_name = fullname[0] self.last_name = fullname[1] def getName(self): return self.first_name, self.last_name f = FigureOut() f.setName(&quot;Allen Solly&quot;) name = f.getName() print (name) </code></pre> <p>I get the following <strong>Output:</strong></p> <pre><code>('Allen', 'Solly') </code></pre> <p>Whenever multiple values are returned from a function in python, does it always convert the multiple values to a <strong>list of multiple values</strong> and then returns it from the function?</p> <p><em>Is the whole process same as converting the multiple values to a <code>list</code> explicitly and then returning the list, for example in Java, as one can return only one object from a function in Java?</em></p>
39,346,109
6
5
null
2016-09-06 09:54:25.127 UTC
8
2022-06-28 20:22:27.077 UTC
2022-06-28 20:22:27.077 UTC
null
523,612
null
6,354,622
null
1
28
python|function|return
108,097
<p>Since the return statement in <code>getName</code> specifies <em>multiple elements</em>:</p> <pre><code>def getName(self): return self.first_name, self.last_name </code></pre> <p>Python will return a container object that basically contains them. </p> <p>In this case, returning a <em>comma separated</em> set of elements creates <em>a tuple</em>. Multiple values <em>can only be returned inside containers</em>.</p> <p>Let's use a simpler function that returns multiple values:</p> <pre><code>def foo(a, b): return a, b </code></pre> <p>You can look at the byte code generated by using <a href="https://docs.python.org/3/library/dis.html#dis.dis" rel="noreferrer"><code>dis.dis</code></a>, a disassembler for Python bytecode. For comma separated values w/o any brackets, it looks like this:</p> <pre><code>&gt;&gt;&gt; import dis &gt;&gt;&gt; def foo(a, b): ... return a,b &gt;&gt;&gt; dis.dis(foo) 2 0 LOAD_FAST 0 (a) 3 LOAD_FAST 1 (b) 6 BUILD_TUPLE 2 9 RETURN_VALUE </code></pre> <p>As you can see the values are first loaded on the internal stack with <code>LOAD_FAST</code> and then a <a href="https://docs.python.org/3/library/dis.html#opcode-BUILD_TUPLE" rel="noreferrer"><code>BUILD_TUPLE</code></a> (grabbing the previous <code>2</code> elements placed on the stack) is generated. Python knows to create a tuple due to the commas being present.</p> <p>You could alternatively specify another return type, for example a list, by using <code>[]</code>. For this case, a <a href="https://docs.python.org/3/library/dis.html#opcode-BUILD_LIST" rel="noreferrer"><code>BUILD_LIST</code></a> is going to be issued following the same semantics as it's tuple equivalent:</p> <pre><code>&gt;&gt;&gt; def foo_list(a, b): ... return [a, b] &gt;&gt;&gt; dis.dis(foo_list) 2 0 LOAD_FAST 0 (a) 3 LOAD_FAST 1 (b) 6 BUILD_LIST 2 9 RETURN_VALUE </code></pre> <p>The type of object returned really depends on the presence of brackets (for tuples <code>()</code> can be omitted if there's at least one comma). <code>[]</code> creates lists and <code>{}</code> sets. Dictionaries need <code>key:val</code> pairs.</p> <p>To summarize, <em>one actual object is returned</em>. If that object is of a container type, it can contain multiple values giving the impression of multiple results returned. The usual method then is to unpack them directly:</p> <pre><code>&gt;&gt;&gt; first_name, last_name = f.getName() &gt;&gt;&gt; print (first_name, last_name) </code></pre> <hr> <p>As an aside to all this, your Java ways are leaking into Python :-) </p> <p>Don't use getters when writing classes in Python, use <code>properties</code>. Properties are the idiomatic way to manage attributes, for more on these, see a nice answer <a href="https://stackoverflow.com/questions/1554546/when-and-how-to-use-the-builtin-function-property-in-python">here</a>.</p>
6,529,177
Capturing reference variable by copy in C++0x lambda
<p>According to the answers and comments for <a href="https://stackoverflow.com/q/5470174/320418">this question</a>, when a reference variable is captured by value, the lambda object should make a copy of the referenced object, not the reference itself. However, GCC doesn't seem to do this.</p> <p>Using the following test: </p> <pre class="lang-c++ prettyprint-override"><code>#include &lt;stddef.h&gt; #include &lt;iostream&gt; using std::cout; using std::endl; int main(int argc, char** argv) { int i = 10; int&amp; ir = i; [=] { cout &lt;&lt; "value capture" &lt;&lt; endl &lt;&lt; "i: " &lt;&lt; i &lt;&lt; endl &lt;&lt; "ir: " &lt;&lt; ir &lt;&lt; endl &lt;&lt; "&amp;i: " &lt;&lt; &amp;i &lt;&lt; endl &lt;&lt; "&amp;ir: " &lt;&lt; &amp;ir &lt;&lt; endl &lt;&lt; endl; }(); [&amp;] { cout &lt;&lt; "reference capture" &lt;&lt; endl &lt;&lt; "i: " &lt;&lt; i &lt;&lt; endl &lt;&lt; "ir: " &lt;&lt; ir &lt;&lt; endl &lt;&lt; "&amp;i: " &lt;&lt; &amp;i &lt;&lt; endl &lt;&lt; "&amp;ir: " &lt;&lt; &amp;ir &lt;&lt; endl &lt;&lt; endl; }(); return EXIT_SUCCESS; } </code></pre> <p>Compiling with GCC 4.5.1, using <code>-std=c++0x</code>, and running gives the following output:</p> <pre class="lang-none prettyprint-override"><code>value capture i: 10 ir: -226727748 &amp;i: 0x7ffff27c68a0 &amp;ir: 0x7ffff27c68a4 reference capture i: 10 ir: 10 &amp;i: 0x7ffff27c68bc &amp;ir: 0x7ffff27c68bc </code></pre> <p>When captured by copy, <code>ir</code> just references junk data. But it correctly references <code>i</code> when captured by reference.</p> <p>Is this a bug in GCC? If so, does anyone know if a later version fixes it? What is the correct behavior?</p> <h3>EDIT</h3> <p>If the first lambda function is changed to</p> <pre class="lang-c++ prettyprint-override"><code>[i, ir] { cout &lt;&lt; "explicit value capture" &lt;&lt; endl &lt;&lt; "i: " &lt;&lt; i &lt;&lt; endl &lt;&lt; "ir: " &lt;&lt; ir &lt;&lt; endl &lt;&lt; "&amp;i: " &lt;&lt; &amp;i &lt;&lt; endl &lt;&lt; "&amp;ir: " &lt;&lt; &amp;ir &lt;&lt; endl &lt;&lt; endl; }(); </code></pre> <p>then the output looks correct:</p> <pre class="lang-none prettyprint-override"><code>explicit value capture i: 10 ir: 10 &amp;i: 0x7fff0a5b5790 &amp;ir: 0x7fff0a5b5794 </code></pre> <p>This looks more and more like a bug.</p>
6,587,917
2
4
null
2011-06-30 01:50:46.353 UTC
4
2011-07-05 19:37:05.273 UTC
2017-05-23 12:25:40.46 UTC
null
-1
null
320,418
null
1
32
c++|gcc|lambda|c++11|g++
9,158
<p>This has just been fixed in gcc-4.7 trunk and gcc-4.6 branch. These should be available in gcc-4.7.0 (a while from now - still in stage 1) and gcc-4.6.2 (alas 4.6.1 just came out.)</p> <p>But the intrepid could wait for the next snapshots or get a subversion copy.</p> <p>See <a href="http://gcc.gnu.org/bugzilla/show_bug.cgi?id=49598" rel="noreferrer">audit trail</a> for details.</p>
7,669,899
How to run Eclipse Indigo on JDK 1.7 OSX
<p>With the recently OSX JDK 7 ea release from Oracle. How to run Eclipse Indigo ?</p> <p>I get the following error msg:</p> <pre><code>$ echo $JAVA_HOME /Library/Java/JavaVirtualMachines/JDK 1.7.0 Developer Preview.jdk/Contents/Home $ java -version openjdk version "1.7.0-ea" OpenJDK Runtime Environment (build 1.7.0-ea-b211) OpenJDK 64-Bit Server VM (build 21.0-b17, mixed mode) $ /Applications/eclipse/Eclipse.app/Contents/MacOS/eclipse JavaVM: requested Java version ((null)) not available. Using Java at "" instead. JavaVM: Failed to load JVM: /bundle/Libraries/libserver.dylib JavaVM FATAL: Failed to load the jvm library. </code></pre>
11,074,151
3
3
null
2011-10-06 02:53:50.557 UTC
5
2013-02-22 15:33:07.143 UTC
2012-10-31 13:42:45.713 UTC
null
258,689
null
258,689
null
1
22
macos|java-7|eclipse-indigo
42,098
<p>I just tried this myself and had some complications so I thought I would share what ended up working for me:</p> <ol> <li>Download and install Mac OSX version of <a href="http://www.oracle.com/technetwork/java/javase/downloads/jdk-7u4-downloads-1591156.html" rel="noreferrer">Java SE Development Kit 7</a></li> <li>Under Eclipse -> Preferences -> Java -> Installed JREs, click Add, select Mac OS X VM, then click Next.</li> <li>Enter "/Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home" as the JRE home directory, enter something reasonable like "Java SE 7" as the JRE name, and then click Finish. (Note that you won't be able to navigate to the "../Contents/Home" folder. You will have to type it in manually.)</li> <li>After adding the new JRE to the list of Eclipse installed JREs, check the box next to the new JRE that you just added and then click OK.</li> <li>Now under Eclipse -> Preferences -> Java -> Compiler, select 1.7 from the "Compiler compliance level" dropdown and click Ok. </li> </ol> <p>Hope this helps someone who has problems figuring this out. The confusing part for me was selecting the JRE home directory in Eclipse, since I wasn't able to navigate to it.</p>
7,460,092
NSWindow makeKeyAndOrderFront makes window appear, but not Key or Front
<p><code>makeKeyAndOrderFront</code> is not making my NSWindow key or front.</p> <p>My app <strong>does not have a main window or menubar</strong>, which may be part of the problem?</p> <pre><code>IBOutlet NSWindow *loginWindow; //(connected in Interface Builder to the NSWindow) </code></pre> <p>The NSWindow has "visible at launch" and "release when closed" both unchecked.</p> <p>Then:</p> <pre><code>- (void) applicationDidFinishLaunching:(NSNotification *)aNotification { [loginWindow makeKeyAndOrderFront:self]; } </code></pre> <p>This <em>does</em> open the window. (commenting it out results in no window being opened).</p> <p>However:</p> <ul> <li><p>It appears behind the Xcode window (not front). </p></li> <li><p>It appears to recieve mouse focus, but will not take keypresses in the textfields the window contains. The keypresses are sent to Xcode.</p></li> <li><p>It appears in the Expose grid when Expose is activated. But I cannot click the window to select it in Expose... it won't come to the front.</p></li> </ul> <p>Why isn't my Window working?</p>
7,460,248
3
1
null
2011-09-18 07:22:04.793 UTC
10
2017-06-29 02:19:43.327 UTC
2011-09-18 08:01:31.403 UTC
null
106,761
null
106,761
null
1
24
objective-c|macos|cocoa
16,295
<p>Stab in the dark: You have <code>LSBackgroundOnly</code> set in your Info.plist. That's what makes this not work: A background-only application cannot come to the foreground, which is why your window does not come to the foreground.</p> <p>If you want your app to not show up in the Dock, set <code>LSUIElement</code> instead. This suppresses your app's Dock tile and keeps it from showing its own main menu in the menu bar, but preserves its ability to bring a window frontmost and make it key.</p>
7,696,633
How to set default Ruby version with RVM?
<p>Ubuntu 11.</p> <p>I do the following:</p> <p><code>$ rvm --default use 1.9.2</code> and I get:</p> <p><code>Using /home/md/.rvm/gems/ruby-1.9.2-p180</code> so that is good.</p> <p>but when I now open a new terminal window I still get:</p> <p><code>$ ruby -v</code></p> <p><code>ruby 1.8.7 (2010-08-16 patchlevel 302) [i686-linux]</code></p>
7,698,294
4
10
null
2011-10-08 11:57:31.257 UTC
16
2019-06-16 16:56:45.91 UTC
2013-07-21 07:59:45.267 UTC
null
31,671
null
631,619
null
1
54
ruby-on-rails|ruby|rvm|ruby-1.9.2
52,249
<p>If you put the RVM source line in your bashrc (in order to ensure that non-interactive shells have access to RVM), you will need to source .bashrc from your .bash_profile with the following as the last lines in your .bash_profile</p> <pre><code>if [ -f "$HOME/.bashrc" ]; then source $HOME/.bashrc fi </code></pre> <p>This pre-supposes that you have</p> <pre><code>[[ -s "$HOME/.rvm/scripts/rvm" ]] &amp;&amp; source "$HOME/.rvm/scripts/rvm" </code></pre> <p>in your $HOME/.bashrc. This is a good way to ensure that both interactive/login and non-interactive shells are able to find and load RVM correctly. Multi-User installs accomplish the same thing via the /etc/profile.d/rvm.sh file.</p> <p>After that, you should have no problems defining a default Ruby to use via</p> <pre><code>rvm 1.9.2 --default </code></pre> <p>or </p> <pre><code>rvm use 1.9.2@mygemset --default </code></pre> <p>Its better to define a default gemset to use so as not to pollute your 'default' or 'global' gemsets.</p> <p>If you are using non-interactive shells, be aware that they genereally operate in SH-compatibility mode which then requires you to set</p> <pre><code>BASH_ENV="$HOME/.bashrc" </code></pre> <p>in your $HOME/.profile in order you load RVM, or to set that within your script directly. The reason for this is that when bash is operating in SH mode it does not directly load .bash_profile or .bashrc as SH doesn't use those files, and bash is attempting to mimic the loading and execution process of the SH shell.</p>
66,922,379
'yield' expression implicitly results in an 'any' type because its containing generator lacks a return-type annotation
<p>The first snippet is the code im working with and below is the error it throws and it happens on every &quot;yield select&quot; portion that is in the code and im not sure what my next step is.</p> <pre><code>function* onLoadingDomainsresult() { const pathname = yield select(getPathname); interface Params { hastag: string; } 'yield' expression implicitly results in an 'any' type because its containing generator lacks a return-type annotation. TS7057 113 | 114 | function* onLoadingDomainsresult() { &gt; 115 | const pathname = yield select(getPathname); | ^ 116 | 117 | interface Params { 118 | hastag: string; </code></pre>
66,922,707
4
2
null
2021-04-02 16:31:37.093 UTC
8
2022-04-13 01:25:56.857 UTC
null
null
null
null
13,925,871
null
1
33
javascript|reactjs|typescript
33,555
<p>The literal type of <code>select(getPathname)</code> doesn't relate to the value you get back from the <code>yield</code>. <code>select(getPathname)</code> is the value yielded by your co-routine to its iterating context.</p> <p>The value injected into your generator by its running context (through the <code>next()</code> call) DOES matter to the type you get back from the <code>yield</code> expression.</p> <p>Either way, currently Typescript has no metadata about what it's going to get at all, since your generator function has no type annotation.</p> <p>I'm guessing this is redux-saga.</p> <p>A typical Generator function type annotation is something like...</p> <pre><code>type WhatYouYield=&quot;foo&quot; type WhatYouReturn=&quot;bar&quot; type WhatYouAccept=&quot;baz&quot; function* myfun(): Generator&lt; WhatYouYield, WhatYouReturn, WhatYouAccept &gt; { const myYield = &quot;foo&quot; //type of myYield is WhatYouYield const myAccepted = yield myYield; //type of myAccepted is WhatYouAccept return &quot;baz&quot; //type of this value is WhatYouReturn } </code></pre> <p>...and the error you're getting is from Typescript having to guess the <code>WhatYouAccept</code> type without the Generator type annotation on your function.</p>
21,436,831
How to write an Objective-C Completion Block
<p>I'm in a situation where need to call a class method from my view controller, have it do it's thing, but then perform some actions ONLY AFTER the class method has completed.</p> <p>(I think what I need is a completion block, but please correct me if I'm wrong.)</p> <p>Here is the situation:</p> <p>I'm using Parse.com for my apps back end. When a user signs up for an account, they enter their name, company and some other info in a popup then click submit. The submit button is linked to a class method (shown below) which takes their PFUser object, and company name and creates some database objects. After the function completes, the popup is dismissed using a delegate.</p> <p>The issue is I need the creation of these objects to happen in a specific order because they depend on each others objectId's to exist. The problem is, the delegate method to dismiss the popup is called right away after clicking submit as it's the next on the stack.</p> <p>When saving a Parse object one calls a method that looks something like this: (This is kind of what I'm hoping to write and I think would solve my issue)</p> <pre><code>[someParseObject saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) { // Code here runs AFTER the method completes. // This also happens on another thread which // I'd like to implement as well. }]; </code></pre> <p>So, What I need to figure out how to do something like the following: (Everything having to do with the block is completely wrong I'm sure)</p> <pre><code>SignUpViewController.m myUserOrg *userOrg = [myUserOrg object]; // myUserOrg = Custom PFObject Subclass // My method that takes in a user object and a string, creates // the database objects in order. [userOrg registerNewUserOrgWithUser:(PFUser*) andCompanyName:(NSString*) companyName withBlock(somethingHere)block { if(error) { NSLog(@"Unable to create org!"); } else { NSLog(@"Created Org!"); [self.delegate dismissSignupView]; } </code></pre> <p>Please let me know if you need additional information or clarification.</p> <p>Thank you in advance!</p> <p>--------- EDIT ONE ----------</p> <p>Alright, So several sizeable units of time later, this is what I've come up with. The whole implementation could be better simplified and make far fewer api calls but will work on that. Several other glaring issues with it as well but is a first step.</p> <p>Method Call:</p> <pre><code>[testOrg registerNewUserOrgWithUser:currentUser creatingOrgContactWithName:@"MyBigHappy Corp." withBlock:^(BOOL succeeded, NSError *error) { if (error) { NSLog(@"Not working"); } else { NSLog(@"Working!"); } }]; </code></pre> <p>Method Implementation:</p> <pre><code>@implementation MYUserOrg @dynamic orgContact; @dynamic orgDisplayName; @dynamic members; @dynamic contacts; + (NSString *)parseClassName { return @"MYUserOrg"; } dispatch_queue_t NewUserOrgRegistrationQueue; -(void)registerNewUserOrgWithUser:(MYUser*)user creatingOrgContactWithName:(NSString*) orgContactName withBlock:(MYBooleanResultBlock) block { NewUserOrgRegistrationQueue = dispatch_queue_create("com.myapp.initialOrgCreationQueue", NULL); dispatch_async(NewUserOrgRegistrationQueue, ^{ NSMutableArray *errors = [[NSMutableArray alloc] init]; // Initial org save to generate objectId NSError *orgSaveError = nil; [self save:&amp;orgSaveError]; if (orgSaveError) { [errors addObject:@"Initial Org save Failed"]; } // Create and Relate Org Contact NSError *saveOrgContactError = nil; MYontact *orgContact = [MYContact object]; [orgContact setContactType:MYContactTypeUserOrganization]; [orgContact setDisplayName:orgContactName]; [orgContact setParentOrg:self]; [orgContact save:&amp;saveOrgContactError]; if (saveOrgContactError) { [errors addObject:@"Saving Org Contact Failed"]; } else { // If Org contact saved, set it; [self setOrgContact:orgContact]; } // Create amd Relate User Contact NSError *saveUserContactError = nil; MYContact *userContact = [MYContact object]; [userContact setFirstName:user.firstName]; [userContact setLastName:user.lastName]; [userContact setContactType:MYcontactTypeUser]; [userContact setParentOrg:self]; [userContact save:&amp;saveUserContactError]; if (saveUserContactError) { [errors addObject:@"Saving user contact failed"]; } NSError *saveUserError = nil; [user setParentOrg:self]; [user setUserContact:userContact]; [user save:&amp;saveUserError]; if (saveUserError) { [errors addObject:@"Saving User failed"]; } // Return if block succeeded and any errors. NSError *error = nil; BOOL succeeded; if (errors.count &gt; 0) { NSDictionary *userInfo = @{@"error" : errors}; errors = [NSError errorWithDomain:@"MyAppErrorDomain" code:1 userInfo:userInfo]; succeeded = NO; } else { succeeded = YES; } block(succeeded, error); }); } @end </code></pre>
21,436,894
5
2
null
2014-01-29 16:26:44.867 UTC
15
2020-07-01 06:54:37.017 UTC
2018-03-28 14:29:25.44 UTC
null
8,561,766
null
2,103,259
null
1
45
ios|objective-c|objective-c-blocks
78,706
<p>I always use this when I want to write a block:</p> <p><a href="http://fuckingblocksyntax.com" rel="noreferrer">http://fuckingblocksyntax.com</a></p> <p><strong>EDIT</strong></p> <p>If you are writing Swift then use this:</p> <p><a href="http://fuckingswiftblocksyntax.com" rel="noreferrer">http://fuckingswiftblocksyntax.com</a></p> <p>If the above links are not opening because of the obscene language, use this one. </p> <p><a href="http://goshdarnblocksyntax.com/" rel="noreferrer">http://goshdarnblocksyntax.com/</a></p>
2,086,374
What is the difference between "image/png" and "image/x-png"?
<p>What is the difference between "image/png" and "image/x-png"?</p>
2,086,406
4
0
null
2010-01-18 13:45:09.897 UTC
3
2011-07-07 17:17:31.643 UTC
null
null
null
null
241,629
null
1
74
language-agnostic|mime-types
42,203
<p>The <code>x-</code> prefix is given to non-standard MIME types (i. e. not registered with IANA). So I assume that <code>image/x-png</code> would have been PNG before the MIME type was standardized.</p> <blockquote> <p><strong>6.3. New Content-Transfer-Encodings</strong></p> </blockquote> <blockquote> <p>Implementors may, if necessary, define private Content-Transfer-Encoding values, but must use an x-token, which is a name prefixed by “<code>X-</code>”, to indicate its non-standard status, e. g., “<code>Content-Transfer-Encoding: x-my-new-encoding</code>”. Additional standardized Content-Transfer-Encoding values must be specified by a standards-track RFC. The requirements such specifications must meet are given in <a href="https://www.rfc-editor.org/rfc/rfc2048" rel="nofollow noreferrer">RFC 2048</a>. As such, all content-transfer-encoding namespace except that beginning with “<code>X-</code>” is explicitly reserved to the IETF for future use.</p> </blockquote> <blockquote> <p>—<a href="https://www.rfc-editor.org/rfc/rfc2045#section-6.3" rel="nofollow noreferrer">RFC 2045 — Multipurpose Internet Mail Extensions, Section 6.3</a></p> </blockquote> <p>This is also documented in the PNG specification. See <a href="https://stackoverflow.com/questions/2086374/what-is-the-difference-between-image-png-and-image-x-png/2086413#2086413">FalseVinylShrub's answer</a>.</p>
49,309,797
RDLC Local report viewer for ASP.NET Core and Angular(>2.0)
<p>Is there any way to show RDLC Local ReportViewer control in asp.net core webpage?</p> <p>To show a ReportViewer, on a traditional WebForms application, the below code works.</p> <pre><code>&lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;asp:ScriptManager ID="ScriptManager1" runat="server"&gt; &lt;/asp:ScriptManager&gt; &lt;div style="height: 600px;"&gt; &lt;rsweb:ReportViewer ID="reportViewer" runat="server" Width="100%" Height="100%"&gt;&lt;/rsweb:ReportViewer&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; </code></pre> <p>I have already tried and tested the below components. The results are given below.</p> <ol> <li><a href="https://github.com/armanio123/ReportViewerForMvc" rel="noreferrer">ReportViewerForMvc</a> - Works for MVC, but not compatible with ASPNET Core.</li> <li><a href="https://github.com/ilich/MvcReportViewer" rel="noreferrer">MvcReportViewer</a> - Works for MVC, but not compatible with ASPNET Core(See this issue: <a href="https://github.com/ilich/MvcReportViewer/issues/121" rel="noreferrer">https://github.com/ilich/MvcReportViewer/issues/121</a>).</li> <li><a href="https://github.com/alanjuden/MvcReportViewer" rel="noreferrer">MvcReportViewer</a> - Does not use microsoft viewer control, thus supports aspnet core, but does not work with Local Reports(Need a report server url).</li> <li><a href="https://www.npmjs.com/package/ngx-ssrs-reportviewer" rel="noreferrer">ngx-ssrs-reportviewer</a> npm package - A wrapper over Remote Reports, does not supports Local reports.(Need a report server url)</li> </ol> <p>Q1. What is the best approach to use <code>&lt;rsweb:ReportViewer&gt;</code> in asp.net core application?</p>
50,009,151
5
5
null
2018-03-15 21:48:30.127 UTC
9
2021-06-18 04:33:25.037 UTC
2018-03-22 17:32:33.687 UTC
null
1,516,648
null
1,516,648
null
1
17
angular|reporting-services|asp.net-core|pdf.js|report-viewer2016
34,669
<p>Microsoft is not implementing or bringing RDLC report viewer into aspnet core. Instead they are purchasing a product to fill the void.</p> <p>Full link to news - <a href="https://blogs.msdn.microsoft.com/sqlrsteamblog/2018/04/02/microsoft-acquires-report-rendering-technology-from-forerunner-software/" rel="noreferrer">https://blogs.msdn.microsoft.com/sqlrsteamblog/2018/04/02/microsoft-acquires-report-rendering-technology-from-forerunner-software/</a></p> <p>Link to original issue - <a href="https://github.com/aspnet/Home/issues/1528" rel="noreferrer">https://github.com/aspnet/Home/issues/1528</a></p> <p>Here is the essence. "Microsoft acquires report rendering technology from Forerunner Software</p> <p>We’re pleased to announce that we’ve acquired technology from Forerunner Software to accelerate our investments in Reporting Services. This technology includes, among other things, client-side rendering of Reporting Services (*.rdl) reports, responsive UI widgets for viewing reports, and a JavaScript SDK for integrating reports into other apps – a testament to what our partners can achieve building on our open platform.</p> <p>This is great news for you, as we see opportunities to apply this technology to multiple points of feedback we’ve heard from you:</p> <p>You’re looking for cloud Software-as-a-Service (SaaS) or Platform-as-a-Service (PaaS) that can run SSRS reports. As you might’ve seen in our Spring ’18 Release Notes, we’re actively working on bringing SSRS reports to the Power BI cloud service, and we’re building on client-side rendering to make that possible. You want to view SSRS reports on your phone, perhaps using the Power BI app. We believe this technology will help us deliver better, more responsive UI for supplying report parameter values, navigating within reports, and possibly even viewing report content.</p> <p><strong><em>You love the Report Viewer control… but it’s an ASP.NET Web Forms control. You need something you can integrate into your ASP.NET Core/MVC app or non-ASP.NET app. With this technology, we hope to deliver a client-side/JavaScript-based Report Viewer you can integrate into any modern app.</em></strong></p> <p>These are large undertakings and we don’t yet have timeframes to share, but stay tuned over the coming months as we always strive to share our progress with you and hear your feedback as early and often as we can.</p> <p>Forerunner Software will continue to support existing customers for a limited period of time."</p>
7,134,238
Is there a Javascript library for Paint-like applications using canvas?
<p>Is there a Javascript library which has built-in features for quickly creating a Paint-like web application using the canvas element?</p> <p><strong>EDIT:</strong> So, far, I have found Javascript libraries that allow easy animation of canvas elements -- such as <a href="http://raphaeljs.com/">Raphael JS</a> -- and Javascript tutorials for creating simple Paint apps, but no robust libraries for Paint-like applications.</p> <p><strong>EDIT 2:</strong> I found a <a href="http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/#demo-complete">Javascript tutorial</a> on a pretty nice looking Paint app using the canvas element. I'd still like to see what others have found.</p>
7,134,310
6
6
null
2011-08-20 19:47:13.123 UTC
13
2021-05-15 21:28:25.233 UTC
2013-11-15 11:43:52.623 UTC
null
130,652
null
759,316
null
1
26
javascript|canvas|drawing
29,649
<p>There is <a href="http://processingjs.org/" rel="nofollow">processingJS</a>, but as it is port of the JAVA bassed processing you write your code in "javaish" processing language. But after all you could create what an paint like app. Another framework is <a href="https://github.com/kangax/fabric.js" rel="nofollow">fabricJS</a> which is also really great to work with canvas.</p>
7,170,746
Change the time zone in Codeigniter
<p>my project is hosted on shared server and i want to change the timezone to Asia/Kolkata. i have tried setting timezone using htaccess file but failed.</p>
7,171,398
7
6
null
2011-08-24 05:16:54.177 UTC
1
2016-12-23 10:05:21.873 UTC
null
null
null
null
887,267
null
1
14
php|codeigniter
46,968
<p>With CodeIgniter, the best place to set the timezone is inside the main <code>index.php</code> file. It's at the same level in your project structure as the <code>system/</code> and <code>application/</code> folders.</p> <p>Just add the following as the first line of code in the file after the opening <code>&lt;?php</code> tag:</p> <pre><code>date_default_timezone_set('Asia/Kolkata'); </code></pre> <p>That should do it for all your PHP code.</p> <p>Don't forget that if you're using a database, the timezone for the database will probably be different as well. If you're using MySQL, you'll want to do a <code>SET time_zone = "+05:30"</code> query as soon as you open a database connection.</p>
7,190,050
How do I compile the asm generated by GCC?
<p>I'm playing around with some asm code, and something is bothering me.</p> <p>I compile this:</p> <pre><code>#include &lt;stdio.h&gt; int main(int argc, char** argv){ printf("Hello World\n"); return 0; } </code></pre> <p>with <code>gcc file.c -S -o file.S</code> this generates a nice little piece of asm code:</p> <pre><code> .cstring LC0: .ascii "Hello World\0" .text .globl _main _main: LFB3: pushq %rbp LCFI0: movq %rsp, %rbp LCFI1: subq $16, %rsp LCFI2: movl %edi, -4(%rbp) movq %rsi, -16(%rbp) leaq LC0(%rip), %rdi call _puts movl $0, %eax leave ret LFE3: .section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support EH_frame1: .set L$set$0,LECIE1-LSCIE1 .long L$set$0 LSCIE1: .long 0x0 .byte 0x1 .ascii "zR\0" .byte 0x1 .byte 0x78 .byte 0x10 .byte 0x1 .byte 0x10 .byte 0xc .byte 0x7 .byte 0x8 .byte 0x90 .byte 0x1 .align 3 LECIE1: .globl _main.eh _main.eh: LSFDE1: .set L$set$1,LEFDE1-LASFDE1 .long L$set$1 LASFDE1: .long LASFDE1-EH_frame1 .quad LFB3-. .set L$set$2,LFE3-LFB3 .quad L$set$2 .byte 0x0 .byte 0x4 .set L$set$3,LCFI0-LFB3 .long L$set$3 .byte 0xe .byte 0x10 .byte 0x86 .byte 0x2 .byte 0x4 .set L$set$4,LCFI1-LCFI0 .long L$set$4 .byte 0xd .byte 0x6 .align 3 LEFDE1: .subsections_via_symbols </code></pre> <p>My next problem is really, how do I compile this output, and can I make GCC do it for me?</p>
7,190,391
7
0
null
2011-08-25 12:07:37.95 UTC
44
2017-04-13 13:27:29.163 UTC
2016-02-10 16:54:56.947 UTC
null
452,775
null
750,186
null
1
82
c|gcc|compiler-construction|assembly
170,056
<p>Yes, You can use gcc to compile your asm code. Use -c for compilation like this:</p> <pre><code>gcc -c file.S -o file.o </code></pre> <p>This will give object code file named file.o. To invoke linker perform following after above command:</p> <pre><code>gcc file.o -o file </code></pre>
7,086,990
how to know if a variable is a tuple, a string or an integer?
<p>I am trying to figure out a type mismatch while adding a string to another string in a concatenate operation.</p> <p>Basically the error returned is a <a href="https://docs.python.org/3/library/exceptions.html#TypeError" rel="noreferrer"><code>TypeError</code></a> (cannot concatenate string and tuple); so I would like to figure out where I assigned a value as tuple instead of string.</p> <p>All the values that I assign are strings, so I gotta figure out where the tuple is coming from, so I was hoping that there is a way in Python to find out what is contained inside a variable and what type is it.</p> <p>So far using <a href="https://docs.python.org/3/library/pdb.html" rel="noreferrer">pdb</a> I was able to check the content of the variables, and I get correctly the values that I would expect; but I would like to know also the type of the variable (by logic, if the compiler is able to raise a type error, it means that it knows what is inside a variable and if it is compatible with the operation to perform; so there must be a way to get that value/flag out).</p> <p>Is there any way to print out the type of a variable in python?</p> <p>BTW, I tried to change all my variables to be explicitly strings, but is not feasible to force <code>str (myvar)</code>, so I cannot just cast as string type everywhere I use strings.</p>
7,087,005
7
2
null
2011-08-17 01:21:37.53 UTC
6
2019-12-15 22:29:38.707 UTC
2018-07-23 11:16:53.093 UTC
user8554766
null
user393267
null
null
1
89
python
103,867
<p>You just use:</p> <pre><code>type(varname) </code></pre> <p>which will output int, str, float, etc...</p>
7,048,313
How to have multiple CSS transitions on an element?
<p>It's a pretty straightforward question but I can't find very good documentation on the CSS transition properties. Here is the CSS snippet:</p> <pre><code> .nav a { text-transform:uppercase; text-decoration:none; color:#d3d3d3; line-height:1.5 em; font-size:.8em; display:block; text-align:center; text-shadow: 0 -1.5em 0 rgba(255, 255, 255, 0.15); -webkit-transition: color .2s linear; -moz-transition: color .2s linear; -o-transition: color .2s linear; transition: color .2s linear; -webkit-transition: text-shadow .2s linear; -moz-transition: text-shadow .2s linear; -o-transition: text-shadow .2s linear; transition: text-shadow .2s linear; } .nav a:hover { color:#F7931E; text-shadow: 0 1.5em 0 rgba(247, 147, 30, 0.15); } </code></pre> <p>As you can see, the transition properties are overwriting eachother. As it stands, the text-shadow will animate, but not the color. How do I get them both to simultaneously animate? Thanks for any answers.</p>
7,048,326
9
1
null
2011-08-13 03:06:58.797 UTC
46
2021-06-30 07:05:48.447 UTC
2011-08-13 13:48:09.067 UTC
null
184,883
null
862,773
null
1
425
animation|css|css-transitions
392,273
<p>Transition properties are comma delimited in all browsers that support transitions:</p> <pre><code>.nav a { transition: color .2s, text-shadow .2s; } </code></pre> <p><code>ease</code> is the default timing function, so you don't have to specify it. If you really want <code>linear</code>, you will need to specify it:</p> <pre><code>transition: color .2s linear, text-shadow .2s linear; </code></pre> <p>This starts to get repetitive, so if you're going to be using the same times and timing functions across multiple properties it's best to go ahead and use the various <code>transition-*</code> properties instead of the shorthand:</p> <pre><code>transition-property: color, text-shadow; transition-duration: .2s; transition-timing-function: linear; </code></pre>
14,260,399
AngularJs ReferenceError: angular is not defined
<p>I trying to add a custom filter, but if I use the following code:</p> <pre><code>angular.module('myApp',[]).filter('startFrom', function() { return function(input, start) { start = +start; //parse to int return input.slice(start); } }); </code></pre> <p>But if I do so, I get: "ReferenceError: angular is not defined" in firebug.</p> <p>The rest of application is working fine, I am using ng-app in a tag div not in tag html, and <a href="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.js">https://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.js</a></p>
16,170,205
9
5
null
2013-01-10 14:40:54.277 UTC
2
2017-06-14 10:44:28.507 UTC
null
null
null
null
729,861
null
1
16
javascript|angularjs|singlepage
111,413
<p>Well in the way this is a single page application, the solution used was:</p> <p>load the content with AJAX, like any other controller, and then call:</p> <pre><code>angular.bootstrap($('#your_div_loaded_in_ajax'),["myApp","other_module"]); </code></pre>
29,003,118
Get driving distance between two points using Google Maps API
<p>I'm trying to get <strong>driving</strong> distance between two points using Google Maps API. Now, I have code which get direct distance:</p> <p>This function get lat and lng:</p> <pre><code>function get_coordinates($city, $street, $province) { $address = urlencode($city.','.$street.','.$province); $url = "http://maps.google.com/maps/api/geocode/json?address=$address&amp;sensor=false&amp;region=Poland"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_PROXYPORT, 3128); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $response = curl_exec($ch); curl_close($ch); $response_a = json_decode($response); $return = array('lat' =&gt; $response_a-&gt;results[0]-&gt;geometry-&gt;location-&gt;lat, 'long' =&gt; $long = $response_a-&gt;results[0]-&gt;geometry-&gt;location-&gt;lng); return $return; } </code></pre> <p>This function calculate distance between two points based on lat &amp; lng:</p> <pre><code>function getDistanceBetweenPoints($lat1, $lon1, $lat2, $lon2) { $theta = $lon1 - $lon2; $miles = (sin(deg2rad($lat1)) * sin(deg2rad($lat2))) + (cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta))); $miles = acos($miles); $miles = rad2deg($miles); $miles = $miles * 60 * 1.1515; $kilometers = $miles * 1.609344; return $kilometers; } </code></pre> <p>This function print distance by kilometers:</p> <pre><code>function get_distance($lat1, $lat2, $long1, $long2) { /* These are two points in New York City */ $point1 = array('lat' =&gt; $lat1, 'long' =&gt; $long1); $point2 = array('lat' =&gt; $lat2, 'long' =&gt; $long2); $distance = getDistanceBetweenPoints($point1['lat'], $point1['long'], $point2['lat'], $point2['long']); return $distance; } </code></pre> <p>Usage:</p> <pre><code>$coordinates1 = get_coordinates('Katowice', 'Korfantego', 'Katowicki'); $coordinates2 = get_coordinates('Tychy', 'Jana Pawła II', 'Tyski'); echo 'Distance: &lt;b&gt;'.round(get_distance($coordinates1['lat'], $coordinates2['lat'], $coordinates1['long'], $coordinates2['long']), 1).'&lt;/b&gt; km'; </code></pre> <p>But this code get direct distance. I need driving distance. How I can get driving distance using google maps API?</p> <p>Thanks for your help!</p>
29,003,839
5
2
null
2015-03-12 06:23:07.94 UTC
24
2019-08-02 13:08:17.307 UTC
null
null
null
null
4,580,209
null
1
42
php
103,095
<p>OK, I found solution using distance matrix: <a href="https://developers.google.com/maps/documentation/distancematrix/#DistanceMatrixRequests">https://developers.google.com/maps/documentation/distancematrix/#DistanceMatrixRequests</a></p> <p>This function get lat &amp; lng from city, adress, province:</p> <pre><code>function get_coordinates($city, $street, $province) { $address = urlencode($city.','.$street.','.$province); $url = "http://maps.google.com/maps/api/geocode/json?address=$address&amp;sensor=false&amp;region=Poland"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_PROXYPORT, 3128); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $response = curl_exec($ch); curl_close($ch); $response_a = json_decode($response); $status = $response_a-&gt;status; if ( $status == 'ZERO_RESULTS' ) { return FALSE; } else { $return = array('lat' =&gt; $response_a-&gt;results[0]-&gt;geometry-&gt;location-&gt;lat, 'long' =&gt; $long = $response_a-&gt;results[0]-&gt;geometry-&gt;location-&gt;lng); return $return; } } </code></pre> <p>This function calculate driving distance and travel time duration:</p> <pre><code>function GetDrivingDistance($lat1, $lat2, $long1, $long2) { $url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$lat1.",".$long1."&amp;destinations=".$lat2.",".$long2."&amp;mode=driving&amp;language=pl-PL"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_PROXYPORT, 3128); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $response = curl_exec($ch); curl_close($ch); $response_a = json_decode($response, true); $dist = $response_a['rows'][0]['elements'][0]['distance']['text']; $time = $response_a['rows'][0]['elements'][0]['duration']['text']; return array('distance' =&gt; $dist, 'time' =&gt; $time); } </code></pre> <p>Usage:</p> <pre><code>$coordinates1 = get_coordinates('Tychy', 'Jana Pawła II', 'Śląskie'); $coordinates2 = get_coordinates('Lędziny', 'Lędzińska', 'Śląskie'); if ( !$coordinates1 || !$coordinates2 ) { echo 'Bad address.'; } else { $dist = GetDrivingDistance($coordinates1['lat'], $coordinates2['lat'], $coordinates1['long'], $coordinates2['long']); echo 'Distance: &lt;b&gt;'.$dist['distance'].'&lt;/b&gt;&lt;br&gt;Travel time duration: &lt;b&gt;'.$dist['time'].'&lt;/b&gt;'; } </code></pre> <p>Return:</p> <p>Distance: 11,2 km Travel time duration: 15 min</p>
47,266,071
Android dependency '..' has different version for the compile (..) and runtime (..) classpath
<p>I migrated to Android Studio 3 and Gradle 4. Then I changed <code>compile</code> to <code>implementation</code> in my build.gradle files. But I get the error:</p> <pre><code>Error:Execution failed for task ':app:preDebugBuild'. &gt; Android dependency 'com.google.firebase:firebase-core' has different version for the compile (9.0.0) and runtime (11.6.0) classpath. You should manually set the same version via DependencyResolution </code></pre> <p>When I change <code>implementation</code> to <code>api</code> the error disappear. But this is not the solution. I have the app module and one library module. App build.gradle has only one dependency:</p> <pre><code>implementation project(':common-lib') </code></pre> <p>The <code>apply plugin: 'com.google.gms.google-services'</code> is correctly placed at the bottom of the app build.gradle file (the project worked before migration to Gradle 4)</p> <p>Dependencies from gradlew app:dependencies (clipping of text):</p> <p>Compile</p> <pre><code>debugAndroidTestCompileClasspath - Resolved configuration for compilation for variant: debugAndroidTest +--- com.google.firebase:firebase-core:9.0.0 | \--- com.google.firebase:firebase-analytics:9.0.0 | +--- com.google.android.gms:play-services-basement:9.0.0 | | \--- com.android.support:support-v4:23.0.0 | | \--- com.android.support:support-annotations:23.0.0 | +--- com.google.firebase:firebase-common:9.0.0 | | +--- com.google.android.gms:play-services-basement:9.0.0 (*) | | \--- com.google.android.gms:play-services-tasks:9.0.0 | | \--- com.google.android.gms:play-services-basement:9.0.0 (*) | \--- com.google.firebase:firebase-analytics-impl:9.0.0 | +--- com.google.android.gms:play-services-base:9.0.0 | | +--- com.google.android.gms:play-services-basement:9.0.0 (*) | | +--- com.google.firebase:firebase-common:9.0.0 (*) | | \--- com.google.android.gms:play-services-tasks:9.0.0 (*) | +--- com.google.android.gms:play-services-basement:9.0.0 (*) | +--- com.google.firebase:firebase-iid:9.0.0 | | +--- com.google.android.gms:play-services-basement:9.0.0 (*) | | \--- com.google.firebase:firebase-common:9.0.0 (*) | \--- com.google.firebase:firebase-common:9.0.0 (*) \--- project :common-lib (............) </code></pre> <p>Runtime</p> <pre><code>debugAndroidTestRuntimeClasspath - Resolved configuration for runtime for variant: debugAndroidTest +--- com.google.firebase:firebase-core:9.0.0 -&gt; 11.6.0 | \--- com.google.firebase:firebase-analytics:11.6.0 | +--- com.google.android.gms:play-services-basement:11.6.0 | | +--- com.android.support:support-v4:25.2.0 -&gt; 26.1.0 | | | +--- com.android.support:support-compat:26.1.0 | | | | +--- com.android.support:support-annotations:26.1.0 | | | | \--- android.arch.lifecycle:runtime:1.0.0 | | | | +--- android.arch.lifecycle:common:1.0.0 | | | | \--- android.arch.core:common:1.0.0 | | | +--- com.android.support:support-media-compat:26.1.0 | | | | +--- com.android.support:support-annotations:26.1.0 | | | | \--- com.android.support:support-compat:26.1.0 (*) | | | +--- com.android.support:support-core-utils:26.1.0 | | | | +--- com.android.support:support-annotations:26.1.0 | | | | \--- com.android.support:support-compat:26.1.0 (*) | | | +--- com.android.support:support-core-ui:26.1.0 | | | | +--- com.android.support:support-annotations:26.1.0 | | | | \--- com.android.support:support-compat:26.1.0 (*) | | | \--- com.android.support:support-fragment:26.1.0 | | | +--- com.android.support:support-compat:26.1.0 (*) | | | +--- com.android.support:support-core-ui:26.1.0 (*) | | | \--- com.android.support:support-core-utils:26.1.0 (*) | | \--- com.google.android.gms:play-services-basement-license:11.6.0 | +--- com.google.firebase:firebase-common:11.6.0 | | +--- com.google.android.gms:play-services-basement:11.6.0 (*) | | +--- com.google.android.gms:play-services-tasks:11.6.0 | | | +--- com.google.android.gms:play-services-basement:11.6.0 (*) | | | \--- com.google.android.gms:play-services-tasks-license:11.6.0 | | \--- com.google.firebase:firebase-common-license:11.6.0 | +--- com.google.firebase:firebase-analytics-impl:11.6.0 | | +--- com.google.android.gms:play-services-basement:11.6.0 (*) | | +--- com.google.firebase:firebase-iid:11.6.0 | | | +--- com.google.android.gms:play-services-basement:11.6.0 (*) | | | +--- com.google.firebase:firebase-common:11.6.0 (*) | | | +--- com.google.android.gms:play-services-tasks:11.6.0 (*) | | | \--- com.google.firebase:firebase-iid-license:11.6.0 | | +--- com.google.firebase:firebase-common:11.6.0 (*) | | +--- com.google.android.gms:play-services-tasks:11.6.0 (*) | | \--- com.google.firebase:firebase-analytics-impl-license:11.6.0 | \--- com.google.firebase:firebase-analytics-license:11.6.0 \--- project :common-lib (.............) </code></pre> <p>Edited:</p> <p>app dependencies</p> <pre><code>dependencies { implementation project(':common-lib') } </code></pre> <p>common-lib dependencies</p> <pre><code>dependencies { //android firebase implementation "com.google.firebase:firebase-core:$firebase_version" implementation "com.google.firebase:firebase-crash:$firebase_version" implementation "com.google.firebase:firebase-messaging:$firebase_version" implementation "com.google.firebase:firebase-ads:$firebase_version" //android support implementation "com.android.support:appcompat-v7:$support_version" implementation "com.android.support:design:$support_version" implementation "com.android.support:cardview-v7:$support_version" implementation "com.android.support:percent:$support_version" //others implementation 'com.google.code.gson:gson:2.8.0' implementation 'com.hannesdorfmann:adapterdelegates3:3.0.1' implementation 'net.danlew:android.joda:2.9.9' implementation 'org.ocpsoft.prettytime:prettytime:4.0.1.Final' implementation 'com.squareup.picasso:picasso:2.5.2' implementation 'com.github.simbiose:Encryption:2.0.1' //server implementation files('libs/xxx.jar') implementation files('libs/yyy.jar') implementation files('libs/zzz.jar') //tests testImplementation 'junit:junit:4.12' } </code></pre> <p>versions:</p> <pre><code>ext { firebase_version = '11.6.0' support_version = '26.1.0' } </code></pre>
47,268,500
5
3
null
2017-11-13 13:59:01.123 UTC
6
2019-11-15 01:33:00.233 UTC
2017-11-13 14:43:55.743 UTC
null
1,550,077
null
1,550,077
null
1
23
android|android-studio|firebase|gradle|android-gradle-plugin
38,339
<p>It appears that, previously, you were implicitly depending on the common-lib module to export Firebase SDKs to your app module. Now that you've changed from "compile" to "implementation", you're no longer exporting those SDKs. So, what's happening now is this: the google-services plugin is adding v9.0.0 of firebase-core to your app module since it no longer sees it present in the visible classpath of your app module.</p> <p>You should be able to work around this by manually adding firebase-core to your app module at the correct version. Or, you can continue to export Firebase SDKs from your library module to your app module by switching to an "api" dependency instead of an "implementation" dependency.</p>
43,424,095
How to unit test with ILogger in ASP.NET Core
<p>This is my controller:</p> <pre><code>public class BlogController : Controller { private IDAO&lt;Blog&gt; _blogDAO; private readonly ILogger&lt;BlogController&gt; _logger; public BlogController(ILogger&lt;BlogController&gt; logger, IDAO&lt;Blog&gt; blogDAO) { this._blogDAO = blogDAO; this._logger = logger; } public IActionResult Index() { var blogs = this._blogDAO.GetMany(); this._logger.LogInformation("Index page say hello", new object[0]); return View(blogs); } } </code></pre> <p>As you can see I have 2 dependencies, a <code>IDAO</code> and a <code>ILogger</code></p> <p>And this is my test class, I use xUnit to test and Moq to create mock and stub, I can mock <code>DAO</code> easy, but with the <code>ILogger</code> I don't know what to do so I just pass null and comment out the call to log in controller when run test. Is there a way to test but still keep the logger somehow ?</p> <pre><code>public class BlogControllerTest { [Fact] public void Index_ReturnAViewResult_WithAListOfBlog() { var mockRepo = new Mock&lt;IDAO&lt;Blog&gt;&gt;(); mockRepo.Setup(repo =&gt; repo.GetMany(null)).Returns(GetListBlog()); var controller = new BlogController(null,mockRepo.Object); var result = controller.Index(); var viewResult = Assert.IsType&lt;ViewResult&gt;(result); var model = Assert.IsAssignableFrom&lt;IEnumerable&lt;Blog&gt;&gt;(viewResult.ViewData.Model); Assert.Equal(2, model.Count()); } } </code></pre>
43,425,633
17
2
null
2017-04-15 08:51:22.64 UTC
34
2022-07-20 14:51:22.233 UTC
2019-05-22 22:38:01.18 UTC
null
38,461
null
5,667,162
null
1
216
c#|unit-testing|asp.net-core|moq|ilogger
165,598
<p>Just mock it as well as any other dependency:</p> <pre><code>var mock = new Mock&lt;ILogger&lt;BlogController&gt;&gt;(); ILogger&lt;BlogController&gt; logger = mock.Object; //or use this short equivalent logger = Mock.Of&lt;ILogger&lt;BlogController&gt;&gt;() var controller = new BlogController(logger); </code></pre> <p>You probably will need to install <code>Microsoft.Extensions.Logging.Abstractions</code> package to use <code>ILogger&lt;T&gt;</code>. </p> <p>Moreover you can create a real logger:</p> <pre><code>var serviceProvider = new ServiceCollection() .AddLogging() .BuildServiceProvider(); var factory = serviceProvider.GetService&lt;ILoggerFactory&gt;(); var logger = factory.CreateLogger&lt;BlogController&gt;(); </code></pre>
59,007,007
Is there an equivalent of "tools:layout=" for FragmentContainerView?
<p>In order to be able to see the content of a certain view inside a fragment when previewing a layout in Android Studio, it is possible to do <a href="https://developer.android.com/studio/write/tool-attributes#toolslayout" rel="noreferrer">this</a>:</p> <pre class="lang-xml prettyprint-override"><code>&lt;MainLayoutView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"&gt; &lt;fragment ... tools:layout="@layout/my_fragment_view"/&gt; &lt;/MainLayoutView&gt; </code></pre> <p>However, if you switch from <code>fragment</code> to <code>androidx.fragment.app.FragmentContainerView</code>, this handy tool stops working and the fragment just appears blank on the preview screen.</p> <p>Is there any way to show content inside a <code>FragmentContainerView</code> when previewing it in a layout in Android Studio?</p>
71,174,808
1
3
null
2019-11-23 11:12:24.32 UTC
2
2022-02-18 14:07:37.397 UTC
null
null
null
null
3,891,038
null
1
34
android|android-studio
2,218
<p>As stated in the <a href="https://stackoverflow.com/questions/59007007/is-there-an-equivalent-of-toolslayout-for-fragmentcontainerview#:%7E:text=tir38-,Sep%2016%2C%202020%20at%2019%3A49,-Add%20a%20comment">comment by tir38</a> <strong>this was fixed in later versions of Android Studio</strong>, you can now use the tools:layout attribute in the FragmentContainerView. In cases where you are using <a href="https://developer.android.com/guide/navigation/navigation-getting-started" rel="nofollow noreferrer">Navigation component</a>, if you define a startDestination for your <a href="https://developer.android.com/guide/navigation/navigation-design-graph" rel="nofollow noreferrer">Navigation graph</a> which uses the tools:layout attribute, this will automatically be reflected in your FragmentContainerView</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-html lang-html prettyprint-override"><code>&lt;androidx.fragment.app.FragmentContainerView ... app:navGraph="@navigation/nav_graph"/&gt; &lt;navigation ... app:startDestination="@id/someFragment"&gt; &lt;fragment ... android:id="@+id/someFragment" tools:layout="@layout/fragment_splash"/&gt; &lt;/navigation&gt;</code></pre> </div> </div> </p>
62,591,440
Webpack 5: devtool ValidationError, invalid configuration object
<p>While migrating from Webpack 4 to Webpack 5 I got an error when using <code>devtool</code> with empty value (only in production mode).</p> <pre><code>module.exports = { devtool: isProd ? '' : 'source-map', // entry: ... // output: ... // module: ... } </code></pre> <p>The message in the console:</p> <pre><code>ValidationError: Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema. - configuration.devtool should match pattern &quot;^(inline-|hidden-|eval-)?(nosources-)?(cheap-(module-)?)?source-map$&quot;. BREAKING CHANGE since webpack 5: The devtool option is more strict. Please strictly follow the order of the keywords in the pattern. </code></pre> <p>Any ideas how to avoid source maps in production mode? What to type in there?</p>
62,671,979
2
0
null
2020-06-26 09:02:32.43 UTC
2
2021-12-30 00:45:24.743 UTC
null
null
null
null
10,944,219
null
1
29
webpack|webpack-5
21,387
<p>Answer to own question! Spoiler: <code>false</code>.</p> <pre><code>module.exports = { devtool: isProd ? false : 'source-map', } </code></pre> <p>In Webpack 4 it was possible to value this with an empty string. webpack 5 is more strict. <a href="https://webpack.js.org/configuration/devtool/" rel="noreferrer">Webpacks devtool configuration</a>.</p>
19,810,940
Ubuntu - Linking boost.python - Fatal error: pyconfig cannot be found
<p>Having some issues, now I have read the following:</p> <p><a href="https://stackoverflow.com/questions/6007185/hello-world-python-extension-in-c-using-boost">hello world python extension in c++ using boost?</a></p> <p>I have tried installing boost onto my desktop, and, done as the posts suggested in terms of linking. I have the following code:</p> <pre><code>#include &lt;boost/python.hpp&gt; #include &lt;Python.h&gt; using namespace boost::python; </code></pre> <p>Now I have tried linking with the following:</p> <pre><code>g++ testing.cpp -I /usr/include/python2.7/pyconfig.h -L /usr/include/python2.7/Python.h -lpython2.7 </code></pre> <p>And I have tried the following as well:</p> <pre><code>g++ testing.cpp -I /home/username/python/include/ -L /usr/include/python2.7/Python.h -lpython2.7 </code></pre> <p>I keep getting the following error:</p> <pre><code>/usr/include/boost/python/detail/wrap_python.hpp:50:23: fatal error: pyconfig.h: No such file or directory # include &lt;pyconfig.h&gt; </code></pre> <p>I don't know where I am going wrong. I do have boost.python installed, there's just a problem linking?</p>
22,674,820
7
2
null
2013-11-06 11:30:06.08 UTC
15
2020-05-27 21:07:46.177 UTC
2017-05-23 12:18:13.22 UTC
null
-1
null
1,326,876
null
1
56
c++|ubuntu|gcc|boost|boost-python
65,782
<p>I just had the same error, the problem is g++ can't find pyconfig.h(shocking, I know). For me this file is located in <code>/usr/include/python2.7/pyconfig.h</code> so appending <code>-I /usr/include/python2.7/</code> should fix it, alternatively you can add the directory to your path with:</p> <pre><code>export CPLUS_INCLUDE_PATH="$CPLUS_INCLUDE_PATH:/usr/include/python2.7/" </code></pre> <p>You can also add this to your .bashrc and it will be added whenever you start your shell next(you will have to reopen your terminal to realize the changes).</p> <p>You can find your own python include path by using <code>find /usr/include -name pyconfig.h</code>, in my case this returns:</p> <pre><code>/usr/include/python2.7/pyconfig.h /usr/include/i386-linux-gnu/python2.7/pyconfig.h </code></pre>
572,962
Reading a Matrix txt file and storing as an array
<p>I'm currently writing a Simulated Annealing code to solve a traveling salesman problem and have run into difficulties with storing and using my read data from a txt file. Each row &amp; column in the file represents each city, with the distance between two different cities stored as a 15 x 15 matrix:</p> <pre><code>0.0 5.0 5.0 6.0 7.0 2.0 5.0 2.0 1.0 5.0 5.0 1.0 2.0 7.1 5.0 5.0 0.0 5.0 5.0 5.0 2.0 5.0 1.0 5.0 6.0 6.0 6.0 6.0 1.0 7.1 5.0 5.0 0.0 6.0 1.0 6.0 5.0 5.0 1.0 6.0 5.0 7.0 1.0 5.0 6.0 6.0 5.0 6.0 0.0 5.0 2.0 1.0 6.0 5.0 6.0 2.0 1.0 2.0 1.0 5.0 7.0 5.0 1.0 5.0 0.0 7.0 1.0 1.0 2.0 1.0 5.0 6.0 2.0 2.0 5.0 2.0 2.0 6.0 2.0 7.0 0.0 5.0 5.0 6.0 5.0 2.0 5.0 1.0 2.0 5.0 5.0 5.0 5.0 1.0 1.0 5.0 0.0 2.0 6.0 1.0 5.0 7.0 5.0 1.0 6.0 2.0 1.0 5.0 6.0 1.0 5.0 2.0 0.0 7.0 6.0 2.0 1.0 1.0 5.0 2.0 1.0 5.0 1.0 5.0 2.0 6.0 6.0 7.0 0.0 5.0 5.0 5.0 1.0 6.0 6.0 5.0 6.0 6.0 6.0 1.0 5.0 1.0 6.0 5.0 0.0 7.0 1.0 2.0 5.0 2.0 5.0 6.0 5.0 2.0 5.0 2.0 5.0 2.0 5.0 7.0 0.0 2.0 1.0 2.0 1.0 1.0 6.0 7.0 1.0 6.0 5.0 7.0 1.0 5.0 1.0 2.0 0.0 5.0 6.0 5.0 2.0 6.0 1.0 2.0 2.0 1.0 5.0 1.0 1.0 2.0 1.0 5.0 0.0 7.0 6.0 7.0 1.0 5.0 1.0 2.0 2.0 1.0 5.0 6.0 5.0 2.0 6.0 7.0 0.0 5.0 5.0 7.0 6.0 5.0 5.0 5.0 6.0 2.0 6.0 2.0 1.0 5.0 6.0 5.0 0.0 </code></pre> <p>To read this I have a LoadCities() function as shown below:</p> <pre><code>#include "iostream" #include "fstream" #include "string" using namespace std; double distances [15][15]; void LoadCities() { ifstream CityFile; if (!CityFile.is_open()) //check is file has been opened { CityFile.open ("Cities.txt", ios::in | ios::out); if (!CityFile) { cerr &lt;&lt; "Failed to open " &lt;&lt; CityFile &lt;&lt; endl; exit(EXIT_FAILURE); //abort program } } int length; char * buffer; string cities; CityFile.seekg(0, ios::end); length = CityFile.tellg(); CityFile.seekg (0, ios::beg); buffer = new char [length]; cities = CityFile.read (buffer,length); string rows = strtok(cities, "\n"); distances = new double[rows.length()][rows.length()]; for (int i = 0; i &lt; (string) rows.length(); i++) { string distance = strtok(rows[i], " "); for (int j = 0; j &lt; distance.length(); j++) { distances[i][j] = (double) Parse(distance[j]); } } CityFile.close(); } </code></pre> <p>I've attempted an alternative istreambuf_iterator method to get to the point of manipulating the read material into arrays, however I always seem to run into complications:</p> <pre><code>ifstream CityFile("Cities.txt"); string theString((std::istreambuf_iterator&lt;char&gt;(CityFile)), std::istreambuf_iterator&lt;char&gt;()); </code></pre> <p>Any help would be much appriciated. Been bashing my head against this with little success!</p> ################ EDIT / Update <p>@ SoapBox - Some Detail of the SA code, functions and main(). This is not clean, efficient, tidy and isn't ment to be at this stage, just needs to work for the moment. This version (below) works and is setup to solve polynomials (simplest problems). What needs to be done to convert it to a Traveling Salesman Problem is to:</p> <ol> <li><p>Write the LoadCities() function to gather the distance data. (Current)</p></li> <li><p>Change Initialise() to get the Total of the distances involved</p></li> <li><p>Change E() to the TSP function (e.g. Calculate distance of a random route)</p></li> </ol> <p>The latter two I know I can do, however I require LoadCities() to do it. Nothing else needs to be changed in the following script.</p> <pre><code>#include "math.h" #include "iostream" #include "fstream" #include "time.h" // Define time() #include "stdio.h" // Define printf() #include "randomc.h" // Define classes for random number generators #include "mersenne.cpp" // Include code for the chosen random number generator using namespace std; // For the use of text generation in application double T; double T_initial; double S; double S_initial; double S_current; double S_trial; double E_current; int N_step; // Number of Iterations for State Search per Temperature int N_max; //Number of Iterations for Temperature int Write; const double EXP = 2.718281828; //------------------------------------------------------------------------------ //Problem Function of Primary Variable (Debugged 17/02/09 - Works as intended) double E(double x) //ORIGNINAL { double y = x*x - 6*x + 2; return y; } //------------------------------------------------------------------------------ //Random Number Generation Function (Mod 19/02/09 - Generated integers only &amp; fixed sequence) double Random_Number_Generator(double nHigh, double nLow) { int seed = (int)time(0); // Random seed CRandomMersenne RanGen(seed); // Make instance of random number generator double fr; // Random floating point number fr = ((RanGen.Random() * (nHigh - nLow)) + nLow); // Generatres Random Interger between nLow &amp; nHigh return fr; } //------------------------------------------------------------------------------ //Initializing Function (Temp 17/02/09) void Initialize() //E.g. Getting total Distance between Cities { S_initial = Random_Number_Generator(10, -10); cout &lt;&lt; "S_Initial: " &lt;&lt; S_initial &lt;&lt; endl; } //------------------------------------------------------------------------------ //Cooling Schedule Function (make variables) (Completed 16/02/09) double Schedule(double Temp, int i) // Need to find cooling schedule { double CoolingRate = 0.9999; return Temp *= CoolingRate; } //------------------------------------------------------------------------------ //Next State Function (Mod 18/02/09) double Next_State(double T_current, int i) { S_trial = Random_Number_Generator(pow(3, 0.5), pow(3, 0.5)*-1); S_trial += S_current; double E_t = E(S_trial); double E_c = E(S_current); double deltaE = E_t - E_c; //Defines gradient of movement if ( deltaE &lt;= 0 ) //Downhill { S_current = S_trial; E_current = E_t; } else //Uphill { double R = Random_Number_Generator(1,0); //pseudo random number generated double Ratio = 1-(float)i/(float)N_max; //Control Parameter Convergence to 0 double ctrl_pram = pow(EXP, (-deltaE / T_current)); //Control Parameter if (R &lt; ctrl_pram*Ratio) //Checking { S_current = S_trial; //Expresses probability of uphill acceptance E_current = E_t; } else E_current = E_c; } return S_current; } //------------------------------------------------------------------------------ //Metropolis Function (Mod 18/02/09) double Metropolis(double S_start, double T_current, int N_Steps, int N_temperatures) { S_current = S_start; //Initialised S_initial equated to S_current for ( int i=1; i &lt;= N_step; i++ ) //Iteration of neighbour states S_current = Next_State(T_current, N_temperatures); //Determines acceptance of new states return S_current; } //------------------------------------------------------------------------------ //Write Results to Notepad (Completed 18/02/09) void WriteResults(double i, double T, double x, double y) { //This function opens a results file (if not already opened) //and stores results for one time step static ofstream OutputFile; const int MAXLENGTH = 80; if (!OutputFile.is_open()) //check is file has been opened { //no it hasn't. Get a file name and open it. char FileName[MAXLENGTH]; //read file name cout &lt;&lt; "Enter file name: "; do { cin.getline(FileName, MAXLENGTH); } while (strlen(FileName) &lt;= 0); //try again if length of string is 0 //open file OutputFile.open(FileName); // check if file was opened successfully if (!OutputFile) { cerr &lt;&lt; "Failed to open " &lt;&lt; FileName &lt;&lt; endl; exit(EXIT_FAILURE); //abort program } OutputFile &lt;&lt; "Iterations" &lt;&lt; '\t' &lt;&lt; "Temperatures" &lt;&lt; '\t' &lt;&lt; "X-Value" &lt;&lt; '\t' &lt;&lt; "Y-Value" &lt;&lt; endl; OutputFile &lt;&lt; endl; } //OutputFile.width(10); OutputFile &lt;&lt; i &lt;&lt; '\t' &lt;&lt; T &lt;&lt; '\t' &lt;&lt; x &lt;&lt; '\t' &lt;&lt; y &lt;&lt; endl; if (i == N_max) { OutputFile &lt;&lt; endl &lt;&lt; "Settings: " &lt;&lt; endl &lt;&lt; "Initial Temperature: " &lt;&lt; T_initial &lt;&lt; endl &lt;&lt; "Temperature Iterations: " &lt;&lt; N_max &lt;&lt; endl &lt;&lt; "Step Iterations: " &lt;&lt; N_step &lt;&lt; endl &lt;&lt; endl &lt;&lt; "Results: " &lt;&lt; endl &lt;&lt; "Final Temperature: " &lt;&lt; T &lt;&lt; endl &lt;&lt; "Minimum: " &lt;&lt; S &lt;&lt; endl; OutputFile.close(); } } //------------------------------------------------------------------------------ //Main SA Function (Mod 17/02/09) void SA(int W) { S = S_initial; T = T_initial; for ( int N_temperatures = 1 ; N_temperatures &lt;= N_max ; N_temperatures++ ) { S = Metropolis( S, T, N_step, N_temperatures); T = Schedule(T, N_temperatures); if (W == 1) WriteResults(N_temperatures, T, S, E_current); } cout &lt;&lt; "Result" &lt;&lt; endl &lt;&lt; "Y-value&gt; " &lt;&lt; S &lt;&lt; endl &lt;&lt; "Temperature&gt; " &lt;&lt; T &lt;&lt; endl; } //------------------------------------------------------------------------------ //Execution of Traveling Salesman Problem (Progress 18/02/09) int main() { cout &lt;&lt; "Quadratic Function" &lt;&lt; endl &lt;&lt; "Solving method: Simulated Annealing" &lt;&lt; endl; cout &lt;&lt; "" &lt;&lt; endl; cout &lt;&lt; "Select desired Initial Temperature:" &lt;&lt; endl &lt;&lt; "&gt; "; cin &gt;&gt; T_initial; cout &lt;&lt; "Select desired number of Temperature Iterations:" &lt;&lt; endl &lt;&lt; "&gt; "; cin &gt;&gt; N_max; cout &lt;&lt; "Select desired number of step Iterations:" &lt;&lt; endl &lt;&lt; "&gt; "; cin &gt;&gt; N_step; Initialize(); cout &lt;&lt; "Write to file: (1 / 0) " &lt;&lt; endl &lt;&lt; "&gt; "; cin &gt;&gt; Write; SA(Write); system ("PAUSE"); return 0; } </code></pre> <p>@ strager - I know its bad code, but unfortunatly with the time constraints involved for my project and the consiquental learning curve, results are what are needed! :) It'll be tidied up at latter stages.</p> <p>@ dirkgently - That was the initial reason for doing it this way, and hence why my first attempt is to go at it like so.</p>
573,042
5
7
null
2009-02-21 13:12:53.137 UTC
3
2016-09-27 16:34:28.793 UTC
2014-06-22 11:27:37.97 UTC
Temperedsoul
759,866
Temperedsoul
69,308
null
1
8
c++|matrix|ifstream
51,057
<p>How about this? (<a href="http://en.wikipedia.org/wiki/KISS_principle" rel="noreferrer">KISS</a> solution)</p> <pre><code>void LoadCities() { int x, y; ifstream in("Cities.txt"); if (!in) { cout &lt;&lt; "Cannot open file.\n"; return; } for (y = 0; y &lt; 15; y++) { for (x = 0; x &lt; 15; x++) { in &gt;&gt; distances[x][y]; } } in.close(); } </code></pre> <p>Works for me. Might not be that complex and perhaps isn't very performant, but as long as you aren't reading a 1000x1000 array, you won't see any difference.</p>
881,754
How to check the availability of a net.tcp WCF service
<p>My WCF server needs to go up and down on a regular basis, the client sometimes uses the server, but if it is down the client just ignore it. So each time I need to use the server services I check the connection state and if it's not open I open it. The problem is that if I attempt to open while the server is down there is a delay which hits performance. My question is, is there a way to do some kind of <code>myClient.CanOpen()</code>? so I'd know if there is any point to open the connection to the server.</p>
883,780
5
2
null
2009-05-19 09:19:05.173 UTC
8
2016-06-27 15:16:44.98 UTC
2009-05-19 10:22:41.737 UTC
null
30,729
null
30,729
null
1
16
c#|wcf|net.tcp
39,785
<p>There is an implementation of WS-Discovery that would allow you to listen for up/down announcements for your service. This is also a very convenient form of service address resolution because it utilizes UDP multicast messages to find the service, rather than configuring one set address on the client. <a href="http://www.codeproject.com/KB/WCF/ws-discovery.aspx" rel="nofollow noreferrer">WS-Discovery for WCF</a></p> <p>There's also an implementation done by a Microsoft employee: <a href="http://blogs.msdn.com/vipulmodi/archive/2006/12/21/ws-discovery-sample-implementation.aspx" rel="nofollow noreferrer">WS-Discovery Sample Implementation</a></p> <p>.NET 4.0 will include this natively. You can read about .NET 4.0's implementation on Jesus Rodriguez's blog. It has a great chart that details the ad-hoc communication that goes on in WS-Disco <a href="http://weblogs.asp.net/gsusx/archive/2009/02/13/using-ws-discovery-in-wcf-4-0.aspx" rel="nofollow noreferrer">Using WS-Discovery in WCF 4.0</a></p> <p>Another thing you might consider, especially if your messages are largely one-way, is a protocol that works natively disconnected, like MSMQ. I don't know what your design for your application looks like, but MSMQ would allow a client to send a message regardless of the state of the service and the service will get it when it comes back up. This way your client doesn't have to block quite so much trying to get confirmation that a service is up before communicating... it'll just fire and forget.</p> <p>Hope this helps.</p>
527,833
How to configure git to avoid accidental git push
<p>After git clone, the config in the new repo looks like:</p> <pre><code>remote.origin.url=&lt;some url&gt; remote.origin.fetch=+refs/heads/*:refs/remotes/origin/* branch.master.remote=origin branch.master.merge=refs/heads/master </code></pre> <p>Then, I can execute "git pull" and "git push". But I'm interested in only do "git pull", because I want to push into another repo.</p> <p>One thing I can do is:</p> <pre><code>git add remote repo-for-push &lt;some other url&gt; git push repo-for-push master </code></pre> <p>But I would like to configure git to use default and distinct repositories for pull and push, i.e:</p> <pre><code>git pull # pulls from origin git push # pushes into repo-for-push, avoiding accidental push into the origin </code></pre> <p>How can this be configured? Thanks in advance.</p> <p>EDIT:<br> Basically, I want to setup the default push repo to be different from the default fetch/pull repo.</p>
817,345
5
2
null
2009-02-09 11:44:40.1 UTC
18
2013-04-21 01:59:10.257 UTC
2009-02-09 15:13:17.54 UTC
Vlookward
16,135
Vlookward
16,135
null
1
34
git
12,076
<p>Looks like</p> <pre><code>git config remote.origin.receivepack /bin/false </code></pre> <p>Makes push to remote origin fail.</p>
951,509
Maintaining a common set of Eclipse preferences
<p>Whenever I switch workspaces/Eclipse installs I need to copy/redo the preferences:</p> <ul> <li>compiler settings;</li> <li>font sizes/families;</li> <li>code formatter;</li> <li>java code templates;</li> <li>editor templates;</li> <li>code clean-ups;</li> </ul> <p>I would like to maintain these settings in an unitary way, preferrably under source control. How can I do that?</p> <hr> <p>I know about 'copy settings' when creating a new workspace, but it does not keep updated copies.</p>
951,824
5
1
null
2009-06-04 16:09:03.453 UTC
14
2018-03-29 04:26:47.29 UTC
null
null
null
null
112,671
null
1
34
eclipse|settings|preferences
11,501
<p>You could of course <a href="https://stackoverflow.com/questions/881655/importing-exporting-project-preferences">export/import</a> those settings.</p> <p>The other approach is to enable project specific settings for some settings.</p> <p><img src="https://i.stack.imgur.com/hap0X.jpg" alt="http://www.peterfriese.de/wp-content/downloads/images/formatter_project_specific_settings.jpg"></p> <p>We have a very small Git repository with those kind of files:</p> <p><img src="https://i.stack.imgur.com/DsyzR.jpg" alt="http://www.mkyong.com/wp-content/uploads/2009/01/wicket-examples-7.jpg"></p> <ul> <li><code>.settings/org.eclipse.jdt.core.prefs</code> (compiler problem settings and formatter rules)</li> <li><code>.settings/org.eclipse.jdt.ui.pref</code> (cleanup rules, common code templates)</li> </ul> <p>The common settings are just copied/merged in each projects <code>.settings</code> directory, ensuring common rules amongst all projects, whatever the workspace.</p>
650,919
Using implicitly typed local variables
<p>I just installed a trial version of <a href="http://www.jetbrains.com/resharper/index.html" rel="noreferrer">ReSharper</a> and one of the first things I noticed is that it always suggests to replace explicitly typed local variables with implicitly typed ones, e.g:</p> <pre><code>public string SomeMethod(int aParam) { int aNumber = SomeOtherMethod(aParam); // should be changed to: var aNumber = SomeOtherMethod(aParam); } </code></pre> <p>I think explicitly typed variables are more readable (more explicit).</p> <p>What do you think about ReSharper's suggestion? Is there any advantage in using implicitly typed variables? When do you use implicit/explict vars?</p>
650,995
5
4
null
2009-03-16 15:32:55.277 UTC
11
2015-09-19 12:33:20.88 UTC
2014-09-24 19:58:37.813 UTC
null
1,043,380
Martin
19,635
null
1
65
c#|coding-style|implicit-typing
37,913
<p>I personally only use “var” when I can clearly distinguish the variable Type by just reading the declaration, for example:</p> <pre><code>var someVariable = new List&lt;int&gt;(); </code></pre> <p>In the example above, its evident that “var” refers to “List&lt;int&gt;”.</p> <p>I don’t like to use “var” when I have to go to some method definition to find out what variable type “var” represents or by having to rely on visual studio intelli-popup or whatever that is called, for example this in not ok to me:</p> <pre><code>var someVaraible = SomeMethod(); </code></pre> <p>I mean, what is the “SomeMethod” function supposed to return? Can you tell just by looking at the line of code? No you can’t, so that is why I avoid using “var” on those situations.</p>
435,721
Where to split Directrory Groupings? A-F | G-K | L-P
<p>I'm looking to build a "quick link" directory access widget. e.g. (option 1)</p> <pre><code>0-9 | A-F | G-K | L-P | Q-U | V-Z </code></pre> <p>Where each would be a link into sub-chunks of a directory starting with that character. The widget itself would be used in multiple places for looking up contacts, companies, projects, etc.</p> <p>Now, for the programming part... I want to know if I should split as above...</p> <pre><code>0-9 | A-F | G-K | L-P | Q-U | V-Z 10+ 6 5 5 5 5 </code></pre> <p>This split is fairly even and logically grouped, but what I'm interested to know is if there is a more optimal split based on the quantity of typical results starting with each letter. (option 2)</p> <p>e.g. very few items will start with "Q".</p> <p><em>(Note: this is currently for a "North American/English" deployment.)</em></p> <p>Does anyone have any stats that would backup reasons to split differently?</p> <p>Likewise, for usability how do users like/dislike this type of thing? I know mentally if I am looking for say: "S" it takes me a second to recall it falls in the Q-U section.</p> <p>Would it be better to do a big list like this? (option 3)</p> <pre><code>#|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z </code></pre>
435,733
6
0
null
2009-01-12 15:16:16.087 UTC
1
2009-01-13 00:31:39.18 UTC
2009-01-12 15:25:11.497 UTC
James Burgess
2,951
scunliffe
6,144
null
1
4
language-agnostic|user-interface|grouping|widget
111,464
<p>As a user I would most definitely prefer one link per letter.</p> <p>But better (for me as a user) would be a search box.</p>
1,111,501
@@ERROR and/or TRY - CATCH
<p>Will Try-Catch capture all errors that @@ERROR can? In the following code fragment, is it worthwhile to check for @@ERROR? Will RETURN 1111 ever occur?</p> <pre><code>SET XACT_ABORT ON BEGIN TRANSACTION BEGIN TRY --do sql command here &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; SELECT @Error=@@ERROR IF @Error!=0 BEGIN IF XACT_STATE()!=0 BEGIN ROLLBACK TRANSACTION END RETURN 1111 END END TRY BEGIN CATCH IF XACT_STATE()!=0 BEGIN ROLLBACK TRANSACTION END RETURN 2222 END CATCH IF XACT_STATE()=1 BEGIN COMMIT END RETURN 0 </code></pre>
1,111,550
6
0
null
2009-07-10 19:25:59.493 UTC
12
2019-05-08 12:11:53.183 UTC
2010-02-14 10:55:33.02 UTC
null
13,302
null
65,223
null
1
16
sql-server|sql-server-2005|tsql
31,806
<p>The following article is a must read by Erland Sommarskog, SQL Server MVP: <a href="http://www.sommarskog.se/error-handling-II.html" rel="nofollow noreferrer">Implementing Error Handling with Stored Procedures</a></p> <p>Also note that <a href="https://web.archive.org/web/20170910224651/http://sqlblog.com/blogs/alexander_kuznetsov/archive/2009/05/13/your-try-block-may-fail-and-your-catch-block-may-be-bypassed.aspx" rel="nofollow noreferrer">Your TRY block may fail, and your CATCH block may be bypassed</a></p> <p>One more thing: Stored procedures using old-style error handling and savepoints may not work as intended when they are used together with TRY … CATCH blocks.<a href="https://web.archive.org/web/20180414164120/http://sqlblog.com/blogs/alexander_kuznetsov/archive/2008/11/15/avoid-mixing-old-and-new-styles-of-error-handling.aspx" rel="nofollow noreferrer">Avoid mixing old and new styles of error handling.</a></p>
52,594,764
How to hot-reload properties in Java EE and Spring Boot?
<p>Many in-house solutions come to mind. Like having the properties in a database and poll it every N secs. Then also check the timestamp modification for a .properties file and reload it. </p> <p>But I was looking in Java EE standards and spring boot docs and I can't seem to find some best way of doing it.</p> <p>I need my application to read a properties file(or env. variables or DB parameters), then be able to re-read them. What is the best practice being used in production?</p> <p>A correct answer will at least solve one scenario (Spring Boot or Java EE) and provide a conceptual clue on how to make it work on the other</p>
52,648,630
6
8
null
2018-10-01 15:55:28.097 UTC
24
2022-06-08 12:34:54.893 UTC
2020-01-08 15:53:43.153 UTC
null
39,998
null
39,998
null
1
32
java|spring|spring-boot|jakarta-ee|properties
65,926
<p>After further research, <a href="https://stackoverflow.com/a/13248486/39998">reloading properties must be carefully considered</a>. In Spring, for example, we can reload the 'current' values of properties without much problem. But. Special care must be taken when resources were initialized at the context initialization time based on the values that were present in the application.properties file (e.g. Datasources, connection pools, queues, etc.). </p> <p><strong>NOTE</strong>: </p> <p>The abstract classes used for Spring and Java EE are not the best example of clean code. But it is easy to use and it does address this basic initial requirements:</p> <ul> <li>No usage of external libraries other than Java 8 Classes.</li> <li>Only one file to solve the problem (~160 lines for the Java EE version).</li> <li>Usage of standard Java Properties UTF-8 encoded file available in the File System.</li> <li>Support encrypted properties.</li> </ul> <p><strong>For Spring Boot</strong></p> <p>This code helps with hot-reloading application.properties file without the usage of a Spring Cloud Config server (which may be overkill for some use cases)</p> <p>This abstract class you may just copy &amp; paste (SO goodies :D ) It's a <a href="https://stackoverflow.com/a/40288822/39998">code derived from this SO answer</a></p> <pre><code>// imports from java/spring/lombok public abstract class ReloadableProperties { @Autowired protected StandardEnvironment environment; private long lastModTime = 0L; private Path configPath = null; private PropertySource&lt;?&gt; appConfigPropertySource = null; @PostConstruct private void stopIfProblemsCreatingContext() { System.out.println("reloading"); MutablePropertySources propertySources = environment.getPropertySources(); Optional&lt;PropertySource&lt;?&gt;&gt; appConfigPsOp = StreamSupport.stream(propertySources.spliterator(), false) .filter(ps -&gt; ps.getName().matches("^.*applicationConfig.*file:.*$")) .findFirst(); if (!appConfigPsOp.isPresent()) { // this will stop context initialization // (i.e. kill the spring boot program before it initializes) throw new RuntimeException("Unable to find property Source as file"); } appConfigPropertySource = appConfigPsOp.get(); String filename = appConfigPropertySource.getName(); filename = filename .replace("applicationConfig: [file:", "") .replaceAll("\\]$", ""); configPath = Paths.get(filename); } @Scheduled(fixedRate=2000) private void reload() throws IOException { System.out.println("reloading..."); long currentModTs = Files.getLastModifiedTime(configPath).toMillis(); if (currentModTs &gt; lastModTime) { lastModTime = currentModTs; Properties properties = new Properties(); @Cleanup InputStream inputStream = Files.newInputStream(configPath); properties.load(inputStream); environment.getPropertySources() .replace( appConfigPropertySource.getName(), new PropertiesPropertySource( appConfigPropertySource.getName(), properties ) ); System.out.println("Reloaded."); propertiesReloaded(); } } protected abstract void propertiesReloaded(); } </code></pre> <p>Then you make a bean class that allows retrieval of property values from applicatoin.properties that uses the abstract class</p> <pre><code>@Component public class AppProperties extends ReloadableProperties { public String dynamicProperty() { return environment.getProperty("dynamic.prop"); } public String anotherDynamicProperty() { return environment.getProperty("another.dynamic.prop"); } @Override protected void propertiesReloaded() { // do something after a change in property values was done } } </code></pre> <p>Make sure to add @EnableScheduling to your @SpringBootApplication </p> <pre><code>@SpringBootApplication @EnableScheduling public class MainApp { public static void main(String[] args) { SpringApplication.run(MainApp.class, args); } } </code></pre> <p>Now you can <strong>auto-wire</strong> the AppProperties Bean wherever you need it. Just make sure to <strong>always</strong> call the methods in it instead of saving it's value in a variable. And make sure to re-configure any resource or bean that was initialized with potentially different property values.</p> <p>For now, I have only tested this with an external-and-default-found <code>./config/application.properties</code> file.</p> <p><strong>For Java EE</strong> </p> <p>I made a common Java SE abstract class to do the job.</p> <p>You may copy &amp; paste this:</p> <pre><code>// imports from java.* and javax.crypto.* public abstract class ReloadableProperties { private volatile Properties properties = null; private volatile String propertiesPassword = null; private volatile long lastModTimeOfFile = 0L; private volatile long lastTimeChecked = 0L; private volatile Path propertyFileAddress; abstract protected void propertiesUpdated(); public class DynProp { private final String propertyName; public DynProp(String propertyName) { this.propertyName = propertyName; } public String val() { try { return ReloadableProperties.this.getString(propertyName); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } } protected void init(Path path) { this.propertyFileAddress = path; initOrReloadIfNeeded(); } private synchronized void initOrReloadIfNeeded() { boolean firstTime = lastModTimeOfFile == 0L; long currentTs = System.currentTimeMillis(); if ((lastTimeChecked + 3000) &gt; currentTs) return; try { File fa = propertyFileAddress.toFile(); long currModTime = fa.lastModified(); if (currModTime &gt; lastModTimeOfFile) { lastModTimeOfFile = currModTime; InputStreamReader isr = new InputStreamReader(new FileInputStream(fa), StandardCharsets.UTF_8); Properties prop = new Properties(); prop.load(isr); properties = prop; isr.close(); File passwordFiles = new File(fa.getAbsolutePath() + ".key"); if (passwordFiles.exists()) { byte[] bytes = Files.readAllBytes(passwordFiles.toPath()); propertiesPassword = new String(bytes,StandardCharsets.US_ASCII); propertiesPassword = propertiesPassword.trim(); propertiesPassword = propertiesPassword.replaceAll("(\\r|\\n)", ""); } } updateProperties(); if (!firstTime) propertiesUpdated(); } catch (Exception e) { e.printStackTrace(); } } private void updateProperties() { List&lt;DynProp&gt; dynProps = Arrays.asList(this.getClass().getDeclaredFields()) .stream() .filter(f -&gt; f.getType().isAssignableFrom(DynProp.class)) .map(f-&gt; fromField(f)) .collect(Collectors.toList()); for (DynProp dp :dynProps) { if (!properties.containsKey(dp.propertyName)) { System.out.println("propertyName: "+ dp.propertyName + " does not exist in property file"); } } for (Object key : properties.keySet()) { if (!dynProps.stream().anyMatch(dp-&gt;dp.propertyName.equals(key.toString()))) { System.out.println("property in file is not used in application: "+ key); } } } private DynProp fromField(Field f) { try { return (DynProp) f.get(this); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } protected String getString(String param) throws Exception { initOrReloadIfNeeded(); String value = properties.getProperty(param); if (value.startsWith("ENC(")) { String cipheredText = value .replace("ENC(", "") .replaceAll("\\)$", ""); value = decrypt(cipheredText, propertiesPassword); } return value; } public static String encrypt(String plainText, String key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException { SecureRandom secureRandom = new SecureRandom(); byte[] keyBytes = key.getBytes(StandardCharsets.US_ASCII); SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); KeySpec spec = new PBEKeySpec(key.toCharArray(), new byte[]{0,1,2,3,4,5,6,7}, 65536, 128); SecretKey tmp = factory.generateSecret(spec); SecretKey secretKey = new SecretKeySpec(tmp.getEncoded(), "AES"); byte[] iv = new byte[12]; secureRandom.nextBytes(iv); final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); GCMParameterSpec parameterSpec = new GCMParameterSpec(128, iv); //128 bit auth tag length cipher.init(Cipher.ENCRYPT_MODE, secretKey, parameterSpec); byte[] cipherText = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8)); ByteBuffer byteBuffer = ByteBuffer.allocate(4 + iv.length + cipherText.length); byteBuffer.putInt(iv.length); byteBuffer.put(iv); byteBuffer.put(cipherText); byte[] cipherMessage = byteBuffer.array(); String cyphertext = Base64.getEncoder().encodeToString(cipherMessage); return cyphertext; } public static String decrypt(String cypherText, String key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException { byte[] cipherMessage = Base64.getDecoder().decode(cypherText); ByteBuffer byteBuffer = ByteBuffer.wrap(cipherMessage); int ivLength = byteBuffer.getInt(); if(ivLength &lt; 12 || ivLength &gt;= 16) { // check input parameter throw new IllegalArgumentException("invalid iv length"); } byte[] iv = new byte[ivLength]; byteBuffer.get(iv); byte[] cipherText = new byte[byteBuffer.remaining()]; byteBuffer.get(cipherText); byte[] keyBytes = key.getBytes(StandardCharsets.US_ASCII); final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); KeySpec spec = new PBEKeySpec(key.toCharArray(), new byte[]{0,1,2,3,4,5,6,7}, 65536, 128); SecretKey tmp = factory.generateSecret(spec); SecretKey secretKey = new SecretKeySpec(tmp.getEncoded(), "AES"); cipher.init(Cipher.DECRYPT_MODE, secretKey, new GCMParameterSpec(128, iv)); byte[] plainText= cipher.doFinal(cipherText); String plain = new String(plainText, StandardCharsets.UTF_8); return plain; } } </code></pre> <p>Then you can use it this way:</p> <pre><code>public class AppProperties extends ReloadableProperties { public static final AppProperties INSTANCE; static { INSTANCE = new AppProperties(); INSTANCE.init(Paths.get("application.properties")); } @Override protected void propertiesUpdated() { // run code every time a property is updated } public final DynProp wsUrl = new DynProp("ws.url"); public final DynProp hiddenText = new DynProp("hidden.text"); } </code></pre> <p>In case you want to use encoded properties you may enclose it's value inside ENC() and a password for decryption will be searched for in the same path and name of the property file with an added .key extension. In this example it will look for the password in the application.properties.key file.</p> <p>application.properties -></p> <pre><code>ws.url=http://some webside hidden.text=ENC(AAAADCzaasd9g61MI4l5sbCXrFNaQfQrgkxygNmFa3UuB9Y+YzRuBGYj+A==) </code></pre> <p>aplication.properties.key -></p> <pre><code>password aca </code></pre> <p>For the encryption of property values for the Java EE solution I consulted Patrick Favre-Bulle excellent article on <a href="https://proandroiddev.com/security-best-practices-symmetric-encryption-with-aes-in-java-7616beaaade9" rel="noreferrer">Symmetric Encryption with AES in Java and Android</a>. Then checked the Cipher, block mode and padding in this SO question about <a href="https://stackoverflow.com/questions/31851612/java-aes-gcm-nopadding-what-is-cipher-getiv-giving-me">AES/GCM/NoPadding</a>. And finally I made the AES bits be derived from a password from @erickson excellent answer in SO about <a href="https://stackoverflow.com/a/992413/39998">AES Password Based Encryption</a>. Regarding encryption of value properties in Spring I think they are integrated with <a href="http://jasypt.org" rel="noreferrer">Java Simplified Encryption</a> </p> <p>Wether this qualify as a best practice or not may be out of scope. This answer shows how to have reloadable properties in Spring Boot and Java EE.</p>
30,758,894
Apache Server (xampp) doesn't run on Windows 10 (Port 80)
<p>I have installed the Windows 10 Insider Program. Everything works, except Apache. When I try to start it, it says that port 80 is blocked. Is there a way to unblock it or <strong>tell Apache to use another port instead?</strong></p> <p>I was using Windows 7 before. I had trouble with port 80 with skype, but i have disabled it.</p>
31,229,606
18
4
null
2015-06-10 14:12:26.497 UTC
33
2018-01-10 15:46:10.153 UTC
2015-06-10 20:52:12.607 UTC
null
3,393,058
null
3,393,058
null
1
86
apache|connection|webserver
142,087
<p>I had the same problem on windows 10, <strong>IIS/10.0 was using port 80</strong></p> <p>To solve that:</p> <ul> <li>find service "W3SVC" </li> <li>disable it, or set it to "manual"</li> </ul> <p>French name is: "<em>Service de publication World Wide Web</em>"</p> <p>English name is: "<em>World Wide Web Publishing Service</em>"</p> <p>german name is: "WWW-Publishingdienst" – thanks @fiffy</p> <p>Polish name is: "Usługa publikowania w sieci WWW" - thanks @KrzysDan</p> <p>Russian name is "Служба веб-публикаций" – thanks @Kreozot</p> <p>Italian name is "Servizio Pubblicazione sul Web" – thanks @Claudio-Venturini</p> <p>Español name is "Servicio de publicación World Wide Web" - thanks @Daniel-Santarriaga</p> <p>Portuguese (Brazil) name is "Serviço de publicação da World Wide Web" - thanks @thiago-born</p> <hr> <p>Alternatives :</p> <ul> <li>Another solution is to shutodwn the service via an admin console with command <code>sc stop W3SVC</code></li> <li>see community wiki from Tobias Hochgürtel <a href="https://stackoverflow.com/questions/30758894/apache-server-xampp-doesnt-run-on-windows-10-port-80/31229606#32259668">Apache Server (xampp) doesn&#39;t run on Windows 10 (Port 80)</a></li> </ul> <hr> <p>Edit 07 oct 2015: For more details, see Matthew Stumphy's answer <a href="https://stackoverflow.com/questions/30758894/apache-server-xampp-doesnt-run-on-windows-10-port-80/31229606?noredirect=1#answer-32016509">Apache Server (xampp) doesn&#39;t run on Windows 10 (Port 80)</a></p>
32,471,499
Why does the compiler prefer an int overload to a varargs char overload for a char?
<p>Code</p> <pre><code>public class TestOverload { public TestOverload(int i){System.out.println("Int");} public TestOverload(char... c){System.out.println("char");} public static void main(String[] args) { new TestOverload('a'); new TestOverload(65); } } </code></pre> <p>Output</p> <pre><code>Int Int </code></pre> <p>Is it expected behaviour? If so, then why? I am expecting: char, Int</p> <p>Note: I am using Java 8</p>
32,471,523
4
8
null
2015-09-09 05:25:26.147 UTC
9
2017-01-16 20:35:31.307 UTC
2015-09-10 10:36:15.923 UTC
null
2,692,339
null
453,767
null
1
63
java|overloading
3,923
<p>Methods with varargs (<code>...</code>) have the lowest priority when the compiler determines which overloaded method to choose. Therefore <code>TestOverload(int i)</code> is chosen over <code>TestOverload(char... c)</code> when you call <code>TestOverload</code> with a single <code>char</code> parameter <code>'a'</code>, since a <code>char</code> can be automatically promoted to an <code>int</code>.</p> <p><a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.2">JLS 15.12.2</a> :</p> <blockquote> <ol> <li><p>The first phase (§15.12.2.2) performs overload resolution <strong>without permitting</strong> boxing or unboxing conversion, or <strong>the use of variable arity method invocation</strong>. If no applicable method is found during this phase then processing continues to the second phase. This guarantees that any calls that were valid in the Java programming language before Java SE 5.0 are not considered ambiguous as the result of the introduction of variable arity methods, implicit boxing and/or unboxing. However, the declaration of a variable arity method (§8.4.1) can change the method chosen for a given method method invocation expression, because a variable arity method is treated as a fixed arity method in the first phase. For example, declaring m(Object...) in a class which already declares m(Object) causes m(Object) to no longer be chosen for some invocation expressions (such as m(null)), as m(Object[]) is more specific.</p></li> <li><p>The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing, but <strong>still precludes the use of variable arity method invocation</strong>. If no applicable method is found during this phase then processing continues to the third phase. This ensures that a method is never chosen through variable arity method invocation if it is applicable through fixed arity method invocation.</p></li> <li><p>The third phase (§15.12.2.4) <strong>allows overloading to be combined with variable arity methods</strong>, boxing, and unboxing.</p></li> </ol> </blockquote> <p>EDIT:</p> <p>It you wish to force the compiler to call the <code>TestOverload(char... c)</code> constructor, you can pass to the constructor call a <code>char[]</code> :</p> <pre><code>new TestOverload (new char[] {'a'}); </code></pre>
44,215,902
Check if Object already exists in Collection - Laravel
<p>I am looking to add objects to a new collection as I loop through a series of different results.</p> <p>The query:</p> <pre><code>$osRed = Item::where('category', 'Hardware') -&gt;where(function ($query) { $query-&gt;where('operating_system', 'xxx') -&gt;orWhere('operating_system', 'xxx') -&gt;orWhere('operating_system', 'xxx'); }) -&gt;orderBy('operating_system', 'ASC') -&gt;get(); </code></pre> <p>Then, loop through these results and add related objects to a new collection.</p> <pre><code>foreach ($osRed as $os) { foreach ($os-&gt;services as $service) { if (!($servicesImpacted-&gt;contains($service))) { $servicesImpacted-&gt;push($service); } } } </code></pre> <p>I then go on to another set of results and add the related services from those results to the collection.</p> <p>However, it is not picking up that the object is already in the collection and I end up with a large number of (what appear to be) duplicates. </p> <p>Ideally, I would like to match up on the name attribute of the $service object, but that doesn't seem to be supported by the contains method.</p> <pre><code>toString() must not throw an exception </code></pre>
44,215,930
2
2
null
2017-05-27 10:46:27.887 UTC
3
2017-12-29 08:29:25.873 UTC
null
null
null
null
1,533,549
null
1
38
php|laravel
76,600
<p>You can use <a href="https://laravel.com/docs/5.4/collections#method-contains" rel="noreferrer"><code>contains()</code></a> with key and value defined:</p> <pre><code>if (!$servicesImpacted-&gt;contains('name', $service-&gt;name)) </code></pre> <p>Or you could use <a href="https://laravel.com/docs/5.4/collections#method-where" rel="noreferrer"><code>where()</code></a> and <a href="https://laravel.com/docs/5.4/collections#method-count" rel="noreferrer"><code>count()</code></a> collection methods in this case, for example:</p> <pre><code>if ($servicesImpacted-&gt;where('name', $service-&gt;name)-&gt;count() === 0) </code></pre>
17,978,182
Common lisp: portability
<p><strong>question</strong></p> <p>If I make a 2d game in common lisp (uses: lispbuilder-sdl, quicklisp, cffi) using clozure cl on windows, will I be able to <em>easily</em> port it to other platforms (linux/iPhone(maybe)/android) later? Is lisp "suitable" for installable programs?</p> <p><strong>information</strong></p> <ol> <li>The game will use OpenGL for graphics. Most likely it'll use sdl for input/opengl initialization, and either sdl or openal for audio. Might end up using my own library instead of sdl later.</li> <li>Writing few C++ libraries for cffi (to wrap functionality in "portable" way) is not a problem.</li> </ol> <p><strong>reasoning</strong></p> <p>I'm really, really tired of C++. Want to try something (that is not python) with simpler syntax + more power. Have a game project in mind, want to know whether choosing lisp for a game means serious trouble if I suddenly decide to distribute/port the game later.</p> <p>--edit--</p> <p><strong>additional info</strong></p> <blockquote> <p>What do you mean by "suitable" and "installable programs"? </p> </blockquote> <p>I'm not sure how well CFFI/quicklisp will play if I try to turn finished program that can run onto my machine into installable package (windows installer on Windows, for example). quicklisp, for example, sets up paths/repositories within user's home dir (which might not be acceptable behavior) and tries to download packages automatically from external sources, which is not a good thing when you try to distribute program and make sure it works as intended. CFFI at some points "binds" foreign libraries to lisp functions, and it is unclear for me how well it will work, say, if I dump program image, embed it into exe and run said exe on another machine. According to common sense, that should work just fine as it is, but in the worst-case scenario it could result in me having to write complicate installer specific to lisp distribution.</p>
17,991,999
4
5
null
2013-07-31 18:32:46.11 UTC
10
2013-08-01 15:23:20.713 UTC
2013-07-31 22:09:50.79 UTC
null
271,376
null
271,376
null
1
22
opengl|common-lisp|portability
3,362
<p>** NOTE: Sorry if I state the obvious in this post, I'm not sure of you familiarity with Common Lisp** </p> <h2>Carrying on from sds:</h2> <p>There does seem to be a bit of life on getting clozure running on android but the performance available remains to be seen. It is very unlikely that we will get to see lisp games in the iphone store unless they compile to some other language where the compiler is not available at runtime (See <a href="http://programming.nu/">Nu</a> or for a proprietary option see <a href="https://wukix.com/mocl">mocl</a> which both have ways of addressing this issue)</p> <h2>Portability - Across Implementations</h2> <p>In libraries it is definitely worth while to get them working portably across as many implementations as possible, however for games I'd really just pick one implementation and hone your code on there. You will probably be distributing your game as a package for each platform as opposed to through quicklisp right? </p> <h2>Portability - Across Platforms</h2> <p>Do make sure to check out the progress of you preferred implementation on each platform, there can be subtle gotchas. For me I use SBCL and under Windows only 32bit is fully supported, whilst 64 is still under development.</p> <h2>Packaging</h2> <p>This has some good timing for you as some information on <a href="http://permalink.gmane.org/gmane.lisp.openmcl.devel/8774">packaging Clozure apps for Apple Mac Store was posted on openmcl-devel today</a> . I haven't had a good read yet but the thread may provide more info.</p> <p>Zach Beane has also made <a href="http://www.xach.com/lisp/buildapp/">buildapp for SBCL</a> </p> <p>The lispbuilder folks also seem to have some <a href="http://code.google.com/p/lispbuilder/wiki/StandAloneExecutables">info on making standalone executables</a>. </p> <h2>Tools</h2> <p><a href="https://github.com/3b/cl-opengl">cl-opengl</a> is a very good wrapper for opengl. It supports both old and modern opengl styles and so I find the areas which try to provide higher level abstractions a bit limiting (I personally steer clear of cl-opengl's gl-arrays). Do have a read of the source though as the is some great stuff there, especially when you start writing more cffi code. <em>{cl-opengl is still being developed and available through quicklisp - I have used it under linux and windows happily}</em></p> <p><a href="http://code.google.com/p/lispbuilder/">lispbuilder-sdl</a> is very cool but again you may find the urge to take control of some areas. For example the sdl:with-events macro is great, but takes control of your main loop and time-step handling. This may work perfectly for you but if not don't be afraid to dig around and write something better to replace those parts! </p> <p>Also lispbuilder provides a range of libraries so before using them check if there is a more recent equivalent in quicklisp. For example lispbuilder has lispbuilder-opengl. Don’t use this, stick with cl-opengl. Again lispbuilder has lispbuilder-regex while it is probably much better to use <a href="http://weitz.de/cl-ppcre/">CL-PPCRE</a>.</p> <p>I probably wouldn't recommend use it as it stands but I spent a little time a while back stripping out all of <a href="https://github.com/cbaggers/lispbuilder-mini">lispbuilder-sdl that didn’t pertain to modern opengl games</a> (so no sdl software surfaces etc). I DON’T think people should use this yet but it may give you some ideas! <em>{lispbuilder isn't under heavy development but is available through quicklisp - I have used it under linux and windows happily}</em></p> <p>Also whilst I am pimping code written by great people and then torn apart by me, see <a href="https://www.youtube.com/watch?v=6pMyhrDcMzw">this video on how to recompile parts of your game whilst it is running</a>. It is not my technique but does work very well.</p> <p>The above will require you to be using <a href="http://common-lisp.net/project/slime/">SLIME</a> or <a href="http://www.vim.org/scripts/script.php?script_id=2531">SLIMV</a> which means using either Vim or Emacs. SLIME is really worth your time so do have a look!</p> <p>All in all, good luck, common lisp is great fun to develop on and while you may find it takes a while to get an opengl work-flow you enjoy, if you have the time I have no doubt you will have a great time.</p> <p>Look forward to seeing the game!</p>