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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
358,891 | How do I find the module dependencies of my Perl script? | <p>I want another developer to run a Perl script I have written. The script uses many CPAN modules that have to be installed before the script can be run. Is it possible to make the script (or the <code>perl</code> binary) to dump a list of all the missing modules? Perl prints out the missing modules’ names when I attempt to run the script, but this is verbose and does not list all the missing modules at once. I’d like to do something like:</p>
<pre><code>$ cpan -i `said-script --list-deps`
</code></pre>
<p>Or even:</p>
<pre><code>$ list-deps said-script > required-modules # on my machine
$ cpan -i `cat required-modules` # on his machine
</code></pre>
<p>Is there a simple way to do it? This is not a show stopper, but I would like to make the other developer’s life easier. (The required modules are sprinkled across several files, so that it’s not easy for me to make the list by hand without missing anything. I know about <a href="http://search.cpan.org/~smueller/PAR-0.983/lib/PAR.pm" rel="noreferrer">PAR</a>, but it seems a bit too complicated for what I want.)</p>
<hr/>
<p><strong>Update:</strong> Thanks, Manni, that will do. I did not know about <code>%INC</code>, I only knew about <code>@INC</code>. I settled with something like this:</p>
<pre><code>print join("\n", map { s|/|::|g; s|\.pm$||; $_ } keys %INC);
</code></pre>
<p>Which prints out:</p>
<pre><code>Moose::Meta::TypeConstraint::Registry
Moose::Meta::Role::Application::ToClass
Class::C3
List::Util
Imager::Color
…
</code></pre>
<p>Looks like this will work.</p> | 358,959 | 5 | 0 | null | 2008-12-11 10:19:53.307 UTC | 16 | 2017-09-01 14:20:35.8 UTC | 2008-12-11 19:18:46.667 UTC | brian d foy | 2,766,176 | zoul | 17,279 | null | 1 | 31 | perl|dependencies|module|cpan | 26,609 | <p>You could dump <code>%INC</code> at the end of your script. It will contain all used and required modules. But of course, this will only be helpful if you don't require modules conditionally (require Foo if $bar).</p> |
286,958 | Any AOP support library for Python? | <p>I am trying to use some AOP in my Python programming, but I do not have any experience of the various libraries that exist. </p>
<p>So my question are:</p>
<blockquote>
<p>What AOP support exists for Python? And what are the advantages of the differents libraries between them?</p>
</blockquote>
<hr>
<h3>Edit</h3>
<p>I've found some, but I don't know how they compare:</p>
<ul>
<li><a href="http://www.aspyct.org" rel="noreferrer">Aspyct</a></li>
<li><a href="http://www.cs.tut.fi/~ask/aspects/aspects.html" rel="noreferrer">Lightweight AOP for Python</a></li>
</ul>
<h3>Edit 2</h3>
<p>In which context will I use these? </p>
<p>I have two applications, written in Python, which have typically methods which compute taxes and other money things. I'd like to be able to write a "skeleton" of a functionality, and customize it at runtime, for example changing the way local taxes are applied (by country, or state, or city, etc.) without having to overload the full stack.</p> | 5,220,447 | 6 | 1 | null | 2008-11-13 13:51:27.807 UTC | 14 | 2019-05-21 10:27:08.793 UTC | 2017-03-12 16:11:42.997 UTC | edomaur | 3,924,118 | edomaur | 14,262 | null | 1 | 31 | python|aop | 16,773 | <p>Edit: I no longer maintain pytilities and it has been unmaintained for years. You may want to consider one of the other answers instead or this <a href="https://en.wikipedia.org/wiki/Aspect-oriented_programming#cite_note-41" rel="nofollow noreferrer">list on Wikipedia</a>.</p>
<p>Another AOP library for python would be <a href="https://pypi.org/project/pytilities/" rel="nofollow noreferrer"><code>pytilities</code></a> (<a href="http://pytilities.sourceforge.net/doc/1.2.0/" rel="nofollow noreferrer">Documentation</a>; <a href="https://sourceforge.net/p/pytilities/code/HEAD/tree/" rel="nofollow noreferrer">svn repo</a>). It is currently the most powerful (as far as I know).</p>
<p>Its features are:</p>
<ul>
<li>make reusable Aspect classes</li>
<li>apply multiple aspects to an instance or class</li>
<li>unapply aspects to an instance/class</li>
<li>add new attributes to an instance by using an aspect</li>
<li>apply advice to all attributes of an instance/class</li>
<li>...</li>
</ul>
<p>It also has other goodies such as some special descriptors (see the documentation)</p> |
680,456 | Vim keep cursor location while scrolling | <p>Is there a way to keep the cusror location off-screen in Vim / gVim while scrolling? Similar to many Windows editors.<br>
I know about marks, and do use them. I also know the '.' mark (last edit location), But looking for other ideas.
I'm asking this because sometimes i want to keep the cursor at some location, scroll to another place using the mouse-wheel, and then just press an arow key or something to get me back to that location. </p> | 680,583 | 6 | 0 | null | 2009-03-25 06:41:17.88 UTC | 14 | 2020-10-08 05:39:54.15 UTC | null | null | null | Ayman | 77,222 | null | 1 | 51 | vim | 8,154 | <p>No. vim is a console application, so it doesn't really make sense to have the cursour off-screen (it's possible, but would just be confusing)</p>
<p>An alternative solution, to paraphrase posts from <a href="http://groups.google.com/group/comp.editors/browse_thread/thread/2ed904497fe930fa" rel="noreferrer">this thread from comp.editors</a>:</p>
<p><code>Ctrl+o</code> goes to the previous cursor location, <code>Ctrl+i</code> goes to the next (like undo/redo for motions)</p>
<p>Marks seem like the other solution..</p>
<blockquote>
<p>Also, use marks. Marks are named by letters. For instance typing ma remembers
the current location under mark a. To jump to the line containing mark a,
type 'a. To the exact location use `a. </p>
<p>Lower-case-letter marks are per-file. Upper-case-letter marks are global;
`A will switch to the file containing mark A, to the exact location. </p>
</blockquote>
<p>Basically <code>ma</code>, move around, then `a to jump back.</p>
<p>Another option which Paul suggested,</p>
<blockquote>
<p><code>gi</code> command switches Vim to Insert mode and places cursor in the same position as where Insert mode was stopped last time.</p>
</blockquote> |
156,243 | Object allocate and init in Objective C | <p>What is the difference between the following 2 ways to allocate and init an object?</p>
<pre><code>AController *tempAController = [[AController alloc] init];
self.aController = tempAController;
[tempAController release];
</code></pre>
<p>and</p>
<pre><code>self.aController= [[AController alloc] init];
</code></pre>
<p>Most of the apple example use the first method. Why would you allocate, init and object and then release immediately?</p> | 156,289 | 6 | 0 | null | 2008-10-01 04:31:43.607 UTC | 42 | 2011-01-14 18:07:04.467 UTC | 2010-04-07 19:10:25.783 UTC | Ned Batchelder | 1,987 | ronin | 1,987 | null | 1 | 56 | objective-c|cocoa|cocoa-touch|memory-management | 34,062 | <p>Every object has a reference count. When it goes to 0, the object is deallocated.</p>
<p>Assuming the property was declared as <code>@property (retain)</code>:</p>
<p>Your first example, line by line:</p>
<ol>
<li>The object is created by <code>alloc</code>, it has a reference count of 1.</li>
<li>The object is handed over to <code>self</code>'s <code>setAController:</code> method, which sends it a <code>retain</code> message (because the method doesn't know where the object is coming from), incrementing its reference count to 2.</li>
<li>The calling code no longer needs the object itself, so it calls <code>release</code>, decrementing the reference count to 1.</li>
</ol>
<p>Your second example basically does steps 1 and 2 but not 3, so at the end the object's reference count is 2.</p>
<p>The rule is that if you create an object, you are responsible for releasing it when you're done with it. In your example, the code is done with tempAController after it sets the property. It is the setter method's responsibility to call <code>retain</code> if it needs that object to stick around.</p>
<p>It's important to remember that <code>self.property = foo;</code> in Objective-C is really just shorthand for <code>[self setProperty:foo];</code> and that the <code>setProperty:</code> method is going to be retaining or copying objects as needed.</p>
<p>If the property was declared <code>@property (copy)</code>, then the object would have been copied instead of retained. In the first example, the original object would be released right away; in the second example, the original object's reference count would be 1 even though it should be 0. So you would still want to write your code the same way.</p>
<p>If the property was declared <code>@property (assign)</code>, then <code>self</code> isn't claiming ownership of the object, and somebody else needs to retain it. In this case, the first example would be incorrect. These sorts of properties are rare, usually only used for object delegates.</p> |
37,864,542 | Jenkins Pipeline NotSerializableException: groovy.json.internal.LazyMap | <p><strong>Solved</strong>: Thanks to <a href="https://stackoverflow.com/a/37897833/3318642">below answer</a> from S.Richmond. I needed to unset <strong>all</strong> stored maps of the <code>groovy.json.internal.LazyMap</code> type which meant nullifying the variables <code>envServers</code> and <code>object</code> after use.</p>
<p><strong>Additional</strong>: People searching for this error might be interested to use the Jenkins pipeline step <code>readJSON</code> instead - find more info <a href="https://jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#code-readjson-code-read-json-from-files-in-the-workspace" rel="noreferrer">here</a>.</p>
<hr>
<p>I am trying to use Jenkins Pipeline to take input from the user which is passed to the job as json string. Pipeline then parses this using the slurper and I pick out the important information. It will then use that information to run 1 job multiple times in parallel with differeing job parameters.</p>
<p>Up until I add the code below <code>"## Error when below here is added"</code> the script will run fine. Even the code below that point will run on its own. But when combined I get the below error.</p>
<p>I should note that the triggered job is called and does run succesfully but the below error occurs and fails the main job. Because of this the main job does not wait for the return of the triggered job. I <em>could</em> try/catch around the <code>build job:</code> however I want the main job to wait for the triggered job to finish.</p>
<p>Can anyone assist here? If you need anymore information let me know.</p>
<p>Cheers</p>
<pre><code>def slurpJSON() {
return new groovy.json.JsonSlurper().parseText(BUILD_CHOICES);
}
node {
stage 'Prepare';
echo 'Loading choices as build properties';
def object = slurpJSON();
def serverChoices = [];
def serverChoicesStr = '';
for (env in object) {
envName = env.name;
envServers = env.servers;
for (server in envServers) {
if (server.Select) {
serverChoicesStr += server.Server;
serverChoicesStr += ',';
}
}
}
serverChoicesStr = serverChoicesStr[0..-2];
println("Server choices: " + serverChoicesStr);
## Error when below here is added
stage 'Jobs'
build job: 'Dummy Start App', parameters: [[$class: 'StringParameterValue', name: 'SERVER_NAME', value: 'TestServer'], [$class: 'StringParameterValue', name: 'SERVER_DOMAIN', value: 'domain.uk'], [$class: 'StringParameterValue', name: 'APP', value: 'application1']]
}
</code></pre>
<p>Error:</p>
<pre><code>java.io.NotSerializableException: groovy.json.internal.LazyMap
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:860)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:569)
at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
at org.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
at org.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.LinkedHashMap.internalWriteEntries(Unknown Source)
at java.util.HashMap.writeObject(Unknown Source)
...
...
Caused by: an exception which occurred:
in field delegate
in field closures
in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@5288c
</code></pre> | 37,897,833 | 13 | 3 | null | 2016-06-16 16:21:27.497 UTC | 23 | 2022-08-12 07:55:10.933 UTC | 2017-11-01 08:05:36.297 UTC | null | 1,000,551 | null | 3,318,642 | null | 1 | 110 | json|jenkins|groovy|jenkins-pipeline | 97,443 | <p>I ran into this myself today and through some bruteforce I've figured out both how to resolve it and potentially why.</p>
<p>Probably best to start with the why:</p>
<p>Jenkins has a paradigm where all jobs can be interrupted, paused and resumable through server reboots. To achieve this the pipeline and its data must be fully serializable - IE it needs to be able to save the state of everything. Similarly, it needs to be able to serialize the state of global variables between nodes and sub-jobs in the build, which is what I think is happening for you and I and why it only occurs if you add that additional build step.</p>
<p>For whatever reason JSONObject's aren't serializable by default. I'm not a Java dev so I cannot say much more on the topic sadly. There are plenty of answers out there about how one may fix this properly though I do not know how applicable they are to Groovy and Jenkins. <a href="https://stackoverflow.com/a/25326211/420787">See this post</a> for a little more info.</p>
<p>How you fix it:</p>
<p>If you know how, you can possibly make the JSONObject serializable somehow. Otherwise you can resolve it by ensuring no global variables are of that type. </p>
<p>Try unsetting your <code>object</code> var or wrapping it in a method so its scope isn't node global.</p> |
37,929,055 | integrating gitlab with sonarqube | <p>I have GitLab CE (v8.5 at least) installed on my server. I would like to integrate it with sonarqube so that merge requests shows any issues in the comment section. Has anyone integrated these 2 systems successfully?</p>
<p>At the moment, only sonarqube plugin I found is the following but I'm not able to successfully integrate it with GitLab.</p>
<p><a href="https://gitlab.talanlabs.com/gabriel-allaigre/sonar-gitlab-plugin">https://gitlab.talanlabs.com/gabriel-allaigre/sonar-gitlab-plugin</a></p>
<p>I used a docker container for sonarqube (v5.5) and copied the plugin into extensions directory. Configured gitlab user token and gitlab uri in the plugin's setting page in sonarqube.</p>
<p>I'm using GitLab CI for continuous integration and I have the following build job for sonarqube (using gradle)</p>
<pre><code>sh gradlew sonarqube -Psonar.analysis.mode=preview -Psonar.issuesReport.console.enable=true \
-Psonar.gitlab.commit_sha=$CI_BUILD_REF -Psonar.gitlab.ref_name=$CI_BUILD_REF_NAME \
-Psonar.gitlab.project_id=$CI_PROJECT_ID
</code></pre>
<p>But, I'm not sure what to after this. Couple of questions:</p>
<ol>
<li><p>What happens when a merge request does not exist yet? In my git workflow, users will submit a merge request after they're done working on their branch. So, how will this plugin know which merge request to update?</p></li>
<li><p>Right now I have the sonarqube valiation task set to be running only on master branch. I think this will need to be changed to user branches too, right?</p></li>
</ol>
<p>I did try submitting a merge request, but I didn't see any comments being added. I think I'm missing some configuration or a process. Really appreciate if you can help point me to the right direction.</p> | 42,944,319 | 2 | 3 | null | 2016-06-20 18:07:47.82 UTC | 9 | 2017-03-22 07:00:02.543 UTC | 2016-06-21 10:44:30.1 UTC | null | 390,177 | null | 6,450,957 | null | 1 | 27 | plugins|sonarqube|integration|gitlab|gitlab-8 | 12,723 | <ul>
<li>You should use -Dsonar.gitlab... instead of -Psonar.gitlab... etc. (see <a href="https://groups.google.com/forum/#!topic/sonarqube/dx8UIkcz55c" rel="nofollow noreferrer">https://groups.google.com/forum/#!topic/sonarqube/dx8UIkcz55c</a> )</li>
<li>In the newest version of the plugin you can enable to add a comment when no issue is found. This helps with debugging.</li>
</ul>
<p>@1: The comments will be added to your commits and will then show up in the discussion section of a merge request</p>
<p>@2: We are running a full analysis on master and a preview on any branches.</p> |
47,492,459 | How do I draw a route, along an existing road, between two points? | <p>I want to show the driving route between two locations in my android app. I want to draw the route only on top of road segments.</p>
<p>There are several answers on stack overflow itself, and all of them were using the same method. Get the directions from start point to destination using google directions API, and draw a polyline across the points returned. Following are some of the answers which uses this method.</p>
<p><a href="https://stackoverflow.com/a/17007360/1015678">https://stackoverflow.com/a/17007360/1015678</a></p>
<p><a href="https://stackoverflow.com/a/40563930/1015678">https://stackoverflow.com/a/40563930/1015678</a></p>
<p>But, problem with above method is, when the roads are not straight, the dawn rote is not always on top of the roads, because directions API only returns points where you need to turn from one road to another (at junctions). It doesn't give point details in the bends of the same road segment. So, when I use above method in an area where the roads have so many bends, the route drawn almost always is not on top of road segments.</p>
<p>I found <a href="https://stackoverflow.com/a/27343990/1015678">this</a> answer, which does what I need to do, using the javascript API. In this solution, the drawn route nicely follows the roads, similar to the google maps android app. Does someone know whether this is achievable in an android app?</p>
<p>Google Maps android app can nicely draw a route from one point to another, keeping the route on the roads. Does anyone know how Google Maps is doing this? Is it using any other API which is not publicly exposed?</p> | 47,556,917 | 5 | 10 | null | 2017-11-26 02:26:46.047 UTC | 24 | 2022-09-07 13:07:01.717 UTC | 2018-12-05 19:14:01.777 UTC | null | 3,924,118 | null | 1,015,678 | null | 1 | 31 | android|google-maps|google-maps-android-api-2 | 86,248 | <p>Indeed, you can draw precise route in Google Maps Android API using results provided by Directions API web service. If you read the documentation for <a href="https://developers.google.com/maps/documentation/directions/intro#DirectionsResponses" rel="noreferrer">Directions API</a> you will see that response contains information about route legs and steps. Each step has a field <code>polyline</code> that is described in the documentation as</p>
<blockquote>
<p>polyline contains a single points object that holds an encoded polyline representation of the step. This polyline is an approximate (smoothed) path of the step.</p>
</blockquote>
<p>So, the main idea to solve your issue is to get response from Directions API, loop through route legs and steps, for each step get <a href="https://developers.google.com/maps/documentation/utilities/polylinealgorithm" rel="noreferrer">encoded polyline</a> and decode it to the list of coordinates. Once done you will have a list of all coordinates that compound the route, not only begin and end point of each step.</p>
<p>For simplicity I recommend using the Java client library for Google Maps Web services:</p>
<p><a href="https://github.com/googlemaps/google-maps-services-java" rel="noreferrer">https://github.com/googlemaps/google-maps-services-java</a></p>
<p>Using this library you can avoid implementing your own async tasks and decoding function for polylines. Read the documentation to figure out how to add the client library in your project. </p>
<p>In Gradle it should be something similar to </p>
<pre><code>compile 'com.google.maps:google-maps-services:(insert latest version)'
compile 'org.slf4j:slf4j-nop:1.7.25'
</code></pre>
<p>I have created a simple example to demonstrate how it works. Have a look at my comments in the code</p>
<pre><code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private String TAG = "so47492459";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng barcelona = new LatLng(41.385064,2.173403);
mMap.addMarker(new MarkerOptions().position(barcelona).title("Marker in Barcelona"));
LatLng madrid = new LatLng(40.416775,-3.70379);
mMap.addMarker(new MarkerOptions().position(madrid).title("Marker in Madrid"));
LatLng zaragoza = new LatLng(41.648823,-0.889085);
//Define list to get all latlng for the route
List<LatLng> path = new ArrayList();
//Execute Directions API request
GeoApiContext context = new GeoApiContext.Builder()
.apiKey("YOUR_API_KEY")
.build();
DirectionsApiRequest req = DirectionsApi.getDirections(context, "41.385064,2.173403", "40.416775,-3.70379");
try {
DirectionsResult res = req.await();
//Loop through legs and steps to get encoded polylines of each step
if (res.routes != null && res.routes.length > 0) {
DirectionsRoute route = res.routes[0];
if (route.legs !=null) {
for(int i=0; i<route.legs.length; i++) {
DirectionsLeg leg = route.legs[i];
if (leg.steps != null) {
for (int j=0; j<leg.steps.length;j++){
DirectionsStep step = leg.steps[j];
if (step.steps != null && step.steps.length >0) {
for (int k=0; k<step.steps.length;k++){
DirectionsStep step1 = step.steps[k];
EncodedPolyline points1 = step1.polyline;
if (points1 != null) {
//Decode polyline and add points to list of route coordinates
List<com.google.maps.model.LatLng> coords1 = points1.decodePath();
for (com.google.maps.model.LatLng coord1 : coords1) {
path.add(new LatLng(coord1.lat, coord1.lng));
}
}
}
} else {
EncodedPolyline points = step.polyline;
if (points != null) {
//Decode polyline and add points to list of route coordinates
List<com.google.maps.model.LatLng> coords = points.decodePath();
for (com.google.maps.model.LatLng coord : coords) {
path.add(new LatLng(coord.lat, coord.lng));
}
}
}
}
}
}
}
}
} catch(Exception ex) {
Log.e(TAG, ex.getLocalizedMessage());
}
//Draw the polyline
if (path.size() > 0) {
PolylineOptions opts = new PolylineOptions().addAll(path).color(Color.BLUE).width(5);
mMap.addPolyline(opts);
}
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(zaragoza, 6));
}
}
</code></pre>
<p>Please note that for web service you have to create a separate API key, the API key with Android app restriction won't work with web service.</p>
<p>The result of my example is shown in screenshot</p>
<p><a href="https://i.stack.imgur.com/V96Sg.png" rel="noreferrer"><img src="https://i.stack.imgur.com/V96Sg.png" alt="enter image description here"></a></p>
<p>You can also download a complete sample project from</p>
<p><a href="https://github.com/xomena-so/so47492459" rel="noreferrer">https://github.com/xomena-so/so47492459</a></p>
<p>Don't forget replace the API key with yours.</p>
<p>I hope this helps!</p> |
54,273,412 | "Failed to install the following Android SDK packages as some licences have not been accepted" error | <p>I am getting this error in jitpack, I've tried everything on the internet. Below is my error </p>
<pre><code>Failed to install the following Android SDK packages as some licences have not been accepted.
platforms;android-26 Android SDK Platform 26
build-tools;28.0.3 Android SDK Build-Tools 28.0.3
To build this project, accept the SDK license agreements and install the missing components using the Android Studio SDK Manager.
</code></pre>
<p>And when i run ./sdkmanager --licenses</p>
<pre><code> All SDK package licenses accepted.======] 100% Computing updates...
</code></pre>
<p>Using sudo with the above command gives </p>
<pre><code>Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
... 5 more
</code></pre>
<p>additional error log </p>
<pre><code>File /opt/android-sdk-linux/.android/repositories.cfg could not be loaded.
Checking the license for package Android SDK Build-Tools 28.0.3 in /opt/android-sdk-linux/licenses
Warning: License for package Android SDK Build-Tools 28.0.3 not accepted.
Checking the license for package Android SDK Platform 26 in /opt/android-sdk-linux/licenses
Warning: License for package Android SDK Platform 26 not accepted.
</code></pre>
<p>I don't know why it's checking for licenses there when my sdk location is other</p> | 55,641,042 | 31 | 5 | null | 2019-01-20 03:47:32.143 UTC | 69 | 2022-03-31 10:49:25.24 UTC | 2020-05-15 12:00:59.643 UTC | null | 208,273 | null | 6,228,832 | null | 1 | 407 | android|android-studio|android-sdk-tools | 447,946 | <p>You need to accept the licences before building.</p>
<p>According to <a href="https://developer.android.com/studio/command-line/sdkmanager.html" rel="noreferrer">Android SDK docs</a> you can use the following command depending on the sdkmanager location: Docs on <code>--licenses</code> option seems to be missing though.</p>
<pre><code>yes | sdkmanager --licenses
</code></pre>
<p>GNU/Linux Distributions:</p>
<pre><code>yes | ~/Android/Sdk/tools/bin/sdkmanager --licenses
</code></pre>
<p>macOS:</p>
<pre><code>export JAVA_HOME=/Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home
yes | ~/Library/Android/sdk/tools/bin/sdkmanager --licenses
</code></pre>
<p>Windows:</p>
<pre><code>%ANDROID_HOME%/tools/bin/sdkmanager --licenses
</code></pre>
<p>Flutter:</p>
<pre><code>> flutter doctor --android-licenses
</code></pre> |
54,596,743 | How do I call the `function` function? | <p>I am trying to call the function <code>`function`</code> to define a function in R code.</p>
<p>As we all know™️, <code>`function`</code>is a <code>.Primitive</code> that’s used <em>internally</em> by R to define functions when the user uses the conventional syntax, i.e.</p>
<pre><code>mean1 = function (x, ...) base::mean(x, ...)
</code></pre>
<p>But there’s nothing preventing me from calling that primitive directly. <em>Or so I thought</em>. I can call other primitives directly (and even redefine them; for instance, in a moment of madness <a href="https://gist.github.com/klmr/d10623a0b4c7e1e9a6523eebee4913d1" rel="noreferrer">I overrode R’s builtin <code>`for`</code></a>). So this <em>is</em> in principle possible.</p>
<p>Yet I cannot get it to work for <code>`function`</code>. Here’s what I tried:</p>
<pre><code># Works
mean2 = as.function(c(formals(mean), quote(mean(x, ...))))
# Works
mean3 = eval(call('function', formals(mean), quote(mean(x, ...))))
# Error: invalid formal argument list for "function"
mean4 = `function`(formals(mean), quote(mean(x, ...)))
</code></pre>
<p>The fact that <code>mean3</code> in particular works indicates to me that <code>mean4</code> <em>should</em> work. But it doesn’t. Why?</p>
<p>I checked the definition of the <code>`function`</code> primitive in the R source. <a href="https://github.com/wch/r-source/blob/780021752eb83a71e2198019acf069ba8741103b/src/main/eval.c#L1563-L1577" rel="noreferrer"><code>do_function</code> is defined in <code>eval.c</code></a>. And I see that it calls <a href="https://github.com/wch/r-source/blob/780021752eb83a71e2198019acf069ba8741103b/src/main/eval.c#L2101-L2111" rel="noreferrer"><code>CheckFormals</code></a>, which ensures that each argument is a symbol, and this fails. But why does it check this, and what does that mean?</p>
<p>And most importantly: Is there a way of calling the <code>`function`</code> primitive directly?</p>
<hr>
<p>Just to clarify: There are trivial workarounds (this question lists two, and there’s at least a third). But I’d like to understand how this (does not) works.</p> | 54,597,846 | 3 | 6 | null | 2019-02-08 16:39:41.01 UTC | 5 | 2022-01-14 14:02:08.89 UTC | null | null | null | null | 1,968 | null | 1 | 29 | r | 1,072 | <p>This is because <code>function</code> is a special primitive:</p>
<pre><code>typeof(`function`)
#> [1] "special"
</code></pre>
<p>The arguments are not evaluated, so you have actually passed <code>quote(formals(mean))</code> instead of the value of <code>formals(mean)</code>. I don't think there's a way of calling <code>function</code> directly without evaluation tricks, except with an empty formals list which is just <code>NULL</code>.</p> |
2,270,643 | What is a 'make target'? | <p>Why do I need to make a <code>make target</code> before being able to build my source code?</p>
<p>More specifically, what is <a href="http://publib.boulder.ibm.com/infocenter/rsdvhelp/v6r0m1/index.jsp?topic=/org.eclipse.cdt.doc.user/tasks/cdt_t_addmaketarget.htm" rel="noreferrer">make target</a> exactly?</p> | 2,270,701 | 5 | 0 | null | 2010-02-16 04:30:04.227 UTC | 5 | 2021-10-09 13:51:14.24 UTC | null | null | null | null | 113,124 | null | 1 | 27 | build-process|build|makefile | 40,064 | <p>Makefiles look like this:</p>
<pre><code>all: mybinary
mybinary: files.o it.o depends.o on.o
[tab]$(CC) $(CFLAGS) files.o it.o depends.o on.o -o mybinary
files.o: files.c files.h
[tab]$(CC) -c $(CPPFLAGS) $(CFLAGS) $< -o $@
...
</code></pre>
<p>This means, when you type <code>make all</code> (the shorthand is just to type <code>make</code>), it will make sure that the mybinary target or file is up to date. To do that, it needs to make sure that mybinary is newer than all of files.o it.o depends.o and on.o. If not, then it uses the shell commands specified on the next line to build mybinary. But before doing that, it first makes sure that files.o and so on are up to date. This means they have to be newer than files.c and files.h. If not, then it uses the shell commands specified on the next line to build files.o. Once all the *.o files are up to date, it can build mybinary. Once mybinary is built, the all target is satisfied.</p>
<p>Targets are usually just files. The format of a block is:</p>
<pre><code>target: list of dependency files
[tab]shell commands to build target if it's older than any of its dependencies
[tab]more shell commands
[tab]still more
</code></pre>
<p>Targets can also be specified using wildcards, for instance <code>%.c</code> means what in the shell you'd call <code>*.c</code>.</p>
<p>Some targets are "phony" targets meaning they don't correspond to any real file. The "all" target is of this sort. So too is the "clean" target (<code>make clean</code>). And so on. You don't really need or want to build a file called "all" or "clean". There are various ways to specify that a target is phony.</p>
<p>The first target to appear in the Makefile is the one that will be invoked if you simply type <code>make</code>. One convention is to name this target "all". So then <code>make</code> will be the same as <code>make all</code>.</p> |
1,704,401 | Is there a simple process-based parallel map for python? | <p>I'm looking for a simple process-based parallel map for python, that is, a function</p>
<pre><code>parmap(function,[data])
</code></pre>
<p>that would run function on each element of [data] on a different process (well, on a different core, but AFAIK, the only way to run stuff on different cores in python is to start multiple interpreters), and return a list of results.</p>
<p>Does something like this exist? I would like something <strong>simple</strong>, so a simple module would be nice. Of course, if no such thing exists, I will settle for a big library :-/</p> | 1,704,501 | 5 | 0 | null | 2009-11-09 22:33:42.073 UTC | 26 | 2021-02-25 20:52:39.897 UTC | null | null | null | null | 164,171 | null | 1 | 79 | python|parallel-processing|smp | 56,552 | <p>I seems like what you need is the <a href="http://docs.python.org/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.map" rel="noreferrer">map method in multiprocessing.Pool()</a>:</p>
<blockquote>
<p><strong>map(func, iterable[, chunksize])</strong></p>
<pre><code>A parallel equivalent of the map() built-in function (it supports only
one iterable argument though). It blocks till the result is ready.
This method chops the iterable into a number of chunks which it submits to the
process pool as separate tasks. The (approximate) size of these chunks can be
specified by setting chunksize to a positive integ
</code></pre>
</blockquote>
<p>For example, if you wanted to map this function:</p>
<pre><code>def f(x):
return x**2
</code></pre>
<p>to range(10), you could do it using the built-in map() function:</p>
<pre><code>map(f, range(10))
</code></pre>
<p>or using a multiprocessing.Pool() object's method map():</p>
<pre><code>import multiprocessing
pool = multiprocessing.Pool()
print pool.map(f, range(10))
</code></pre> |
1,642,447 | How to change the Content of a <textarea> with JavaScript | <p>How would I change the content of a <code><textarea></code> element with JavaScript?</p>
<p>I want to make it empty.</p> | 1,642,452 | 5 | 1 | null | 2009-10-29 09:09:00.217 UTC | 11 | 2020-12-04 05:24:58.993 UTC | 2020-12-04 05:22:06.683 UTC | null | 63,550 | null | 109,859 | null | 1 | 191 | javascript | 365,315 | <p>Like this:</p>
<pre><code>document.getElementById('myTextarea').value = '';
</code></pre>
<p>or like this in jQuery:</p>
<pre><code>$('#myTextarea').val('');
</code></pre>
<p>Where you have</p>
<pre><code><textarea id="myTextarea" name="something">This text gets removed</textarea>
</code></pre>
<p>For all the downvoters and non-believers:</p>
<ul>
<li><p><a href="http://msdn.microsoft.com/en-us/library/ms535122(VS.85).aspx" rel="noreferrer">Here's the MSDN reference</a></p>
<blockquote>
<p>value Property: Retrieves or sets the text in the entry field of the textArea element.</p>
</blockquote></li>
<li><p><a href="https://developer.mozilla.org/en-US/docs/DOM/HTMLTextAreaElement" rel="noreferrer">Here's the MDN reference</a></p>
<blockquote>
<p>value DOMString The raw value contained in the control.</p>
</blockquote></li>
</ul> |
2,314,750 | How to assign the output of a Bash command to a variable? | <p>I have a problem putting the content of <code>pwd</code> command into a shell variable that I'll use later. </p>
<p>Here is my shell code (the loop doesn't stop):</p>
<pre><code>#!/bin/bash
pwd= `pwd`
until [ $pwd = "/" ]
do
echo $pwd
ls && cd .. && ls
$pwd= `pwd`
done
</code></pre>
<p>Could you spot my mistake, please?</p> | 2,314,765 | 5 | 2 | null | 2010-02-22 22:25:31.21 UTC | 42 | 2019-07-05 13:01:43.267 UTC | 2015-07-03 17:13:39.787 UTC | null | 3,924,118 | null | 262,854 | null | 1 | 210 | bash|shell | 364,126 | <p>Try:</p>
<pre><code>pwd=`pwd`
</code></pre>
<p>or</p>
<pre><code>pwd=$(pwd)
</code></pre>
<blockquote>
<p>Notice no spaces after the equals sign.</p>
</blockquote>
<p>Also as Mr. Weiss points out; you don't assign to <code>$pwd</code>, you assign to <code>pwd</code>.</p> |
1,463,480 | How can I use PHP to dynamically publish an ical file to be read by Google Calendar? | <p>Any Google search on PHP ical just brings up phpicalendar and how to parse or read IN ical files. I just want to write a PHP file that pulls events from my database and writes them out in ical format.</p>
<p>My problem is I can't find anywhere that will answer two questions:</p>
<ol>
<li>What is the <em>exact</em> ical format, including headers, file format, footers, etc.? In other words, what does the file have to have, exactly, in order to be properly read in by Google Calendar, etc.?</li>
<li>If I build this file using a .php extension, how do I publish it as ical? Do I have to write to a new .ics file? Or will Google Calendar etc. read a .php file as ical so long as the contents are in the correct format? (Much like a style.css.php file will be read as a CSS file if the contents are actually CSS, etc.)</li>
</ol>
<p>Any help you all can give or point me to will be greatly appreciated!!!</p> | 1,464,355 | 7 | 0 | null | 2009-09-23 01:16:17.577 UTC | 85 | 2016-04-13 10:33:05.8 UTC | null | null | null | null | 171,021 | null | 1 | 114 | php|calendar|icalendar | 110,241 | <p>This should be very simple if Google Calendar does not require the <code>*.ics</code>-extension (which will require some URL rewriting in the server).</p>
<pre><code>$ical = "BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
BEGIN:VEVENT
UID:" . md5(uniqid(mt_rand(), true)) . "@yourhost.test
DTSTAMP:" . gmdate('Ymd').'T'. gmdate('His') . "Z
DTSTART:19970714T170000Z
DTEND:19970715T035959Z
SUMMARY:Bastille Day Party
END:VEVENT
END:VCALENDAR";
//set correct content-type-header
header('Content-type: text/calendar; charset=utf-8');
header('Content-Disposition: inline; filename=calendar.ics');
echo $ical;
exit;
</code></pre>
<p>That's essentially all you need to make a client think that you're serving a iCalendar file, even though there might be some issues regarding caching, text encoding and so on. But you can start experimenting with this simple code.</p> |
1,761,626 | Weighted random numbers | <p>I'm trying to implement a weighted random numbers. I'm currently just banging my head against the wall and cannot figure this out.</p>
<p>In my project (Hold'em hand-ranges, subjective all-in equity analysis), I'm using Boost's random -functions. So, let's say I want to pick a random number between 1 and 3 (so either 1, 2 or 3). Boost's mersenne twister generator works like a charm for this. However, I want the pick to be weighted for example like this:</p>
<pre><code>1 (weight: 90)
2 (weight: 56)
3 (weight: 4)</code></pre>
<p>Does Boost have some sort of functionality for this?</p> | 1,761,646 | 8 | 0 | null | 2009-11-19 07:56:32.687 UTC | 85 | 2022-05-06 18:56:38.78 UTC | 2017-02-24 21:05:46.743 UTC | null | 8,368 | null | 102,797 | null | 1 | 117 | c++|boost|random | 111,554 | <p>There is a straightforward algorithm for picking an item at random, where items have individual weights:</p>
<p>1) calculate the sum of all the weights</p>
<p>2) pick a random number that is 0 or greater and is less than the sum of the weights</p>
<p>3) go through the items one at a time, subtracting their weight from your random number, until you get the item where the random number is less than that item's weight</p>
<p>Pseudo-code illustrating this:</p>
<pre><code>int sum_of_weight = 0;
for(int i=0; i<num_choices; i++) {
sum_of_weight += choice_weight[i];
}
int rnd = random(sum_of_weight);
for(int i=0; i<num_choices; i++) {
if(rnd < choice_weight[i])
return i;
rnd -= choice_weight[i];
}
assert(!"should never get here");
</code></pre>
<p>This should be straightforward to adapt to your boost containers and such.</p>
<hr>
<p>If your weights are rarely changed but you often pick one at random, and as long as your container is storing pointers to the objects or is more than a few dozen items long (basically, you have to profile to know if this helps or hinders), then there is an optimisation:</p>
<p>By storing the cumulative weight sum in each item you can use a <a href="http://en.wikipedia.org/wiki/Binary_search_algorithm" rel="noreferrer">binary search</a> to pick the item corresponding to the pick weight.</p>
<hr>
<p>If you do not know the number of items in the list, then there's a very neat algorithm called <a href="http://xlinux.nist.gov/dads//HTML/reservoirSampling.html" rel="noreferrer">reservoir sampling</a> that can be adapted to be weighted.</p> |
1,938,294 | Select div using wildcard ID | <p>How to select a div using it's ID but with a widcard?</p>
<p>If the DIV's ID is <code>statusMessage_1098</code>, I would like to select it in some way like <code>document.getElementById('statusMessage_*')</code>.</p>
<p>This is because until the page is generated, I don't know the suffix of the ID and only one such ID will be present in a page. Is this possible?</p>
<p>Thanks for any help.</p> | 1,938,300 | 9 | 0 | null | 2009-12-21 05:01:14.527 UTC | 2 | 2020-04-22 17:34:18.083 UTC | 2018-07-15 01:59:29.653 UTC | null | 1,296,209 | null | 137,954 | null | 1 | 10 | javascript|jquery|dom|prototypejs | 45,298 | <p>Using jQuery you can do this</p>
<pre><code>$("div[id^='statusMessage_']")
</code></pre>
<p>See <strong><a href="http://docs.jquery.com/Selectors/attributeStartsWith#attributevalue" rel="noreferrer">attributeStartsWith</a></strong></p>
<p><strong><em>Edit - with class name selector</em></strong></p>
<p>If you can use a class name then you can use something like this</p>
<pre><code>$$('div.myDivClass');
</code></pre>
<p>gets all div elements with class 'myDivClass'</p> |
1,695,115 | How do I draw the lines of a family tree using HTML CSS? | <p>I'm trying to implement something similar to what <a href="http://www.ancestry.com" rel="noreferrer">http://www.ancestry.com</a> has, but I'm not sure how to draw the lines.</p>
<p>Here is a rough ascii sketch of what I want to do:</p>
<pre><code> +----GrDAD1
|
+----DAD----+
| +----GrMOM1
ME --+
| +----GrDAD2
+----MOM----+
|
+----GrMOM2
</code></pre>
<p>I think one way to do this is to create a table of cells, and create images of the lines,
connecting each of the children to their parents.
I'm guessing there's an easier way to do this though, but my knowledge of CSS is quite limited.
Does anyone have a suggestion on how I can implement this?</p> | 1,695,193 | 9 | 0 | null | 2009-11-08 02:10:27.81 UTC | 9 | 2014-07-14 17:56:36.997 UTC | 2011-11-06 02:48:45.48 UTC | null | 1,022,826 | null | 93,430 | null | 1 | 16 | javascript|html|css|family-tree | 34,803 | <p>Another option for a graphical interface would be the canvas element. You can find some info on it <a href="https://developer.mozilla.org/en/Canvas_tutorial" rel="noreferrer">here</a>, <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html" rel="noreferrer">here</a>, and some demos of what it can do <a href="http://www.canvasdemos.com/" rel="noreferrer">here</a>.</p>
<p>Personally, I would choose Canvas with an image map overlay or possibly Flash. Creating a graphical layout using only divs or tables could get out of hand very quickly and create huge and ugly code. Although that's a matter of opinion. :)</p>
<p>You could use canvas to render the lines, and then absolutely position divs with text for each node. Or you could render the whole thing in canvas (at which point you would need an image map overlay if you want the rendered tree to be interactive.)</p> |
1,490,803 | How to reduce Eclipse's memory usage? | <p>The memory usage of Eclipse 3.4 is through the roof to the point where it's becoming an issue. </p>
<p>I have a simple BlackBerry project loaded and the usage skyrockets to nearly 400 MB, sometimes higher. Is there something that can be done to bring it down?</p> | 1,491,157 | 10 | 3 | null | 2009-09-29 06:03:22.413 UTC | 14 | 2020-11-09 20:35:40.173 UTC | null | null | null | null | 9,382 | null | 1 | 88 | eclipse | 85,870 | <p>Eclipse 3.4 can consume a lot more memory than the previous versions, <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=233156" rel="noreferrer">courtesy the spellchecker plug-in</a>.</p>
<p>You can switch off the plug-in by going to Window -> Preferences -> General -> Editors -> Text Editors -> Spelling, and unchecking the box title 'Enable spell checking'.</p>
<p>Of course, the tips offered to use larger heap sizes and better garbage collectors would do you good as well.</p> |
2,041,000 | Loop through all the resources in a .resx file | <p>Is there a way to loop through all the resources in a <code>.resx</code> file in C#?</p> | 2,041,049 | 11 | 1 | null | 2010-01-11 09:53:56.16 UTC | 26 | 2022-07-25 18:58:15.553 UTC | 2016-09-30 00:28:50.4 UTC | null | 869,184 | null | 186,914 | null | 1 | 133 | c#|.net|embedded-resource | 111,920 | <p>You should always use the resource manager and not read files directly to ensure globalization is taken into account.</p>
<pre><code>using System.Collections;
using System.Globalization;
using System.Resources;
</code></pre>
<p>...</p>
<pre><code>/* Reference to your resources class -- may be named differently in your case */
ResourceManager MyResourceClass =
new ResourceManager(typeof(Resources));
ResourceSet resourceSet =
MyResourceClass.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
string resourceKey = entry.Key.ToString();
object resource = entry.Value;
}
</code></pre> |
8,377,268 | File compression before upload on the client-side | <p>Basically I'll be working with large XML files (approx. 20 - 50 MB). These files needs to be uploaded on a server.</p>
<p>I know it isn't possible to touch the files with javascript, nor to implement HTTP compression on the client-side.</p>
<p>My question is that if any solution exists (flash / action script) that compresses a file and has a javascript API?</p>
<p>The scenario is this: </p>
<ol>
<li>Trying to upload 50 MB XML file</li>
<li>Before upload a grab it with Javascript and send it to the compressor.</li>
<li>Upload the compressed file instead of the original one.</li>
</ol> | 8,385,557 | 6 | 2 | null | 2011-12-04 17:45:57.097 UTC | 9 | 2017-01-15 14:20:28.4 UTC | null | null | null | null | 201,605 | null | 1 | 15 | javascript|flash|apache-flex|upload|compression | 30,749 | <p>Flash's inbuilt implementation of ByteArray has a method (<code>ByteArray::deflate</code> to deflate the contents (of the bytearray) The deflate algorithm is the <a href="http://www.ietf.org/rfc/rfc1951.txt" rel="nofollow">DEFLATE Compressed Data Format Specification version 1.3</a>.</p>
<p>There;s also a <code>ByteArray::compress</code> method which compresses using the <a href="http://www.ietf.org/rfc/rfc1950.txt" rel="nofollow">zlib</a> algorithm</p>
<p>Hold on a bit, I'll write you some sample code to use this class and expose it to JavaScript.</p>
<p><strong>EDIT</strong></p>
<p>I've uploaded the file at <a href="http://www.filefactory.com/file/cf8a39c/n/demo5.zip" rel="nofollow">http://www.filefactory.com/file/cf8a39c/n/demo5.zip</a></p>
<p><strong>EDIT 2</strong> For those who couldn't download the files:</p>
<p>My ActionScript code in demo5.fla (compiled to demo5.swf)</p>
<pre><code>import flash.external.ExternalInterface;
import flash.net.FileReference;
import flash.events.Event;
import flash.utils.ByteArray;
if(ExternalInterface.available) {
//flash.system.Security.allowDomain("localhost");
ExternalInterface.addCallback("deflate", doDeflate);
ExternalInterface.addCallback("compress", doCompress);
}
var method:String="deflate";
var b:ByteArray;
function doCompress(_data:String):void {
method="compress";
exec(_data);
}
function doDeflate(_data:String):void {
method="deflate";
exec(_data);
}
function exec(_data:String):void {
b=new ByteArray();
b.writeUTFBytes(_data);
b.position=0;
if(method=="compress") {
b.compress();
} else if(method=="deflate") {
b.deflate();
}
executed();
}
function executed():void {
if(ExternalInterface.available) {
b.position=0;
var str:String=b.readUTFBytes(b.bytesAvailable);
ExternalInterface.call("onExec", str);
}
}
</code></pre>
<p>My HTML code to embed the swf:</p>
<pre><code><button onclick="doDeflate()">Deflate</button>
<button onclick="doCompress()">Compress</button>
<div id="flashContent">
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="1" height="1" id="demo5" align="middle">
<param name="movie" value="demo5.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="play" value="true" />
<param name="loop" value="true" />
<param name="wmode" value="window" />
<param name="scale" value="showall" />
<param name="menu" value="true" />
<param name="devicefont" value="false" />
<param name="salign" value="" />
<param name="allowScriptAccess" value="always" />
<embed src="demo5.swf" quality="high" bgcolor="#869ca7"
width="1" height="1" name="demo5" align="middle"
play="true" loop="false" quality="high" allowScriptAccess="always"
type="application/x-shockwave-flash"
pluginspage="http://www.macromedia.com/go/getflashplayer">
</embed>
</object>
</div>
</code></pre>
<p>and finally the javascript code:</p>
<pre><code>function doDeflate() {
var data="fdg fhnkl,hgltrebdkjlgyu ia43uwriu67ri8m nirugklhvjsd fgvu";
//DATA CONTAINS DATA TO BE DEFLATED
thisMovie("demo5").deflate(data);
}
function doCompress() {
var data="fdg fhnkl,hgltrebdkjlgyu ia43uwriu67ri8m nirugklhvjsd fgvu";
//DATA CONTAINS DATA TO BE DEFLATED
thisMovie("demo5").compress(data);
}
function onExec(data) {
//DATA CONTAINS THE DEFLATED DATA
alert(data);
}
function thisMovie(movieName) {
if (navigator.appName.indexOf("Microsoft") != -1) {
return window[movieName];
} else {
return document[movieName];
}
}
</code></pre> |
42,080,648 | Why/When you would not want to have Java 8 UseStringDeduplication enabled in JVM? | <p>Java 8 introduced String Deduplication that can be enabled by launching JVM with <code>-XX:+UseStringDeduplication</code> option allowing to save some memory by referencing similar <code>String</code> objects instead of keeping duplicates. Of course it's effectiveness varies from program to program depending on utilisation of <code>Strings</code> but I think it is safe to say that in general it can be considered beneficial for most applications (if not all) making me wonder about few things:</p>
<p>Why is it not enabled by default? Is it because of costs associated with dedeuplication or simply because G1GC is still considered new?</p>
<p>Are there (or could there be) any edge cases where you would not want to use deduplication?</p> | 42,080,794 | 2 | 2 | null | 2017-02-07 02:26:40.413 UTC | 8 | 2020-08-24 15:17:49.457 UTC | 2017-02-07 03:08:54.27 UTC | null | 1,810,406 | null | 1,810,406 | null | 1 | 36 | java|performance|optimization|java-8 | 15,865 | <p>Cases where String de-duplication <em>could be</em> harmful include:</p>
<ul>
<li>There are lots of strings but a very low probability of duplicates: the time overhead of looking for duplicates and the space overhead of the de-duping data structure would not be repaid.</li>
<li><p>There is a reasonable probability of duplicates, but most strings die in within a couple of GC cycles<sup>1</sup> anyway. The de-duplication is less beneficial if the de-duped strings were going to be GC'ed soon anyway.</p>
<p>(This is not about strings that don't survive the first GC cycle. It would make no sense for the GC to even <em>try</em> to de-dup strings that it knows to be garbage.)</p></li>
</ul>
<p>We can only speculate as to why the Java team didn't turn on de-duping by default, but they are in a much better position to make rational (i.e. evidence based) decisions on this that you and I. My understanding is that they have access to many large real-world applications for benchmarking / trying out the effects of optimizations. They may also have contacts in partner or customer organizations with similarly large code-bases and concerns about efficiency ... who they can ask for feedback on whether optimizations in an early access release work as expected.</p>
<p><sup>1 - This depends on the value of the <code>StringDeduplicationAgeThreshold</code>
JVM setting. This defaults to 3 meaning that (roughly) a string has to survive 3 minor collections or a major collection to be considered for de-duping. But anyhow, if a string is de-duped and then found to be unreachable shortly afterwards, the de-duping overheads will not be repaid for that string.</sup></p>
<hr>
<p>If you are asking when you should consider enabling de-duping, my advice would be to try it and see if it helps <em>on a per-application basis</em>. But you need to do some application-level benchmarking (which takes effort!) to be sure that the de-duping is beneficial ...</p>
<p>A careful read of <a href="http://openjdk.java.net/jeps/192" rel="noreferrer">JEP 192</a> would also help you understand the issues, and make a judgment on how they might apply for your Java application.</p> |
23,934,656 | How can I copy rich text contents to the clipboard with JavaScript? | <h2>Premise</h2>
<p>I need help copying rich text to the clipboard using JavaScript. I have searched around and haven't found anything to suit my specific needs.</p>
<h2>Code</h2>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function ctrlA1(corp) {
with(corp) {}
if (document.all) {
txt = corp.createTextRange()
txt.execCommand("Copy")
} else
setTimeout("window.status=''", 5000)
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="sc1">hello <br> <b> world </b> </div>
<button onclick="ctrlA1(document.getElementById('sc1') )"></button></code></pre>
</div>
</div>
</p>
<h2>Problem</h2>
<p>The aforementioned code isn't working and is resulting in an <code>object expected error</code>. Any help is appreciated!
I have seen a library out there called <code>zeroclipboard</code>, but would prefer to write my own function.</p>
<hr>
<h1>Edit:</h1>
<p>I now have this function to select text on the page. is it possible to write a formula to copy the selected range as is?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function containerSelect(id) {
containerUnselect();
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(id);
range.select();
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(id);
window.getSelection().addRange(range);
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><label onclick="containerSelect(this); select_all()">
<p>hello world</p>
<img src="imagepath.png">
</label></code></pre>
</div>
</div>
</p> | 24,066,243 | 6 | 2 | null | 2014-05-29 13:33:55.297 UTC | 15 | 2022-08-28 15:18:36.133 UTC | 2022-04-07 15:32:09.72 UTC | null | 1,264,804 | null | 1,972,914 | null | 1 | 55 | javascript|html|clipboard | 35,177 | <p>i searched for a week now and finally found my answer!!!
for those of you looking to copy rich text to the clipboard with javascript, then use the function at the link below, works like a charm.
no need of flash and other stuff suggested :)</p>
<p><a href="https://stackoverflow.com/questions/8743559/copying-an-image-to-clipboard-using-javascript-jquery">Copying an image to clipboard using JavaScript/jquery</a></p> |
18,226,747 | Stata: how to change a string variable to a date? | <p>I'm new to Stata, and I'm wondering how can I change a string variable which contains a date to a date format.</p>
<p>The data in the variable looks like this:</p>
<p>yyyy-mm-dd</p>
<p>Should I first remove the dashes so that Stata can recognize the format in order to later use <code>gen var = date()</code> ?</p>
<p>Thank you for your help.</p> | 18,229,128 | 2 | 2 | null | 2013-08-14 08:30:25.507 UTC | 3 | 2015-07-06 17:12:38.737 UTC | 2013-08-14 08:34:21.797 UTC | null | 2,492,977 | null | 2,313,307 | null | 1 | 10 | string|date|format|stata | 56,688 | <p>The Stata <code>date</code> function is smart about removing separator characters. See <a href="http://www.stata.com/help.cgi?datetime_translation">help datetime_translation</a> under the section "the date function"</p>
<p>If your dates are in <code>v1</code> and in the form <code>yyyy-mm-dd</code> you can specify the commands:</p>
<pre><code>generate v2 = date(v1, "YMD")
format %td v2
</code></pre>
<p>The <code>YMD</code> is called a <em>mask</em>, and it tells Stata the order in which the parts of the date are specified. The second line will assign the variable the Stata daily date format, which means that when you look at that variable in the data, it will be shown in human readable form. The date is stored, however, as the number of days since January 1, 1960.</p>
<p>The best way to experiment with the <code>date</code> function is to use the <code>display</code> command. The first line will display an integer representing the number of days since January 1, 1960. The second line will display the date in a human readable format.</p>
<pre><code>display date("2013-08-14", "YMD")
display %td date("2013-08-14", "YMD")
</code></pre> |
15,733,972 | jQuery parse/display json data from php json_encode | <p>Initial .ajax call in jquery:</p>
<pre><code>$.ajax({
type: 'post',
url: 'items_data.php',
data: "id="+id,
dataType: 'json',
success: function(data){
if(data){
make_item_rows(data);
}else{
alert("oops nothing happened :(");
}
}
});
</code></pre>
<p>Sends a simple string to a php file which looks like:</p>
<pre><code>header('Content-type: application/json');
require_once('db.php');
if( isset($_POST['id'])){
$id = $_POST['id'];
}else{
echo "Danger Will Robinson Danger!";
}
$items_data = $pdo_db->query ("SELECT blah blah blah with $id...");
$result_array = $items_data->fetchAll();
echo json_encode($result_array);
</code></pre>
<p>I am catching the $result_array just fine and passing it on to another function. I double checked that there is indeed proper values being returned as I can just echo result to my page and it displays something like the following:</p>
<pre><code>[{"item_id":"230","0":"230","other_id":"700"},{"item_id":"231","0":"231","other_id":"701"},{"item_id":"232","0":"232","other_id":"702"}]
</code></pre>
<p>I am having trouble figuring out how to iterate through the results so I can inject values into a table I have in my HTML. Here is what I have for my function:</p>
<pre><code>function make_item_rows(result_array){
var string_buffer = "";
$.each(jQuery.parseJSON(result_array), function(index, value){
string_buffer += value.item_id; //adding many more eventually
$(string_buffer).appendTo('#items_container');
string_buffer = ""; //reset buffer after writing
});
}
</code></pre>
<p>I also tried putting an alert in the $.each function to make sure it was firing 3 times, which it was. However no data comes out of my code. Have tried some other methods as well with no luck. </p>
<p>UPDATE: I changed my code to include the parseJSON, no dice. Got an unexpected token error in my jquery file (right when it attempts to use native json parser). Tried adding the json header to no avail, same error. jquery version 1.9.1. Code as it is now should be reflected above.</p> | 15,734,090 | 6 | 1 | null | 2013-03-31 20:09:21.45 UTC | 1 | 2018-12-08 10:52:19.157 UTC | 2014-02-16 13:05:05.107 UTC | null | 2,926,271 | null | 1,103,092 | null | 1 | 4 | php|jquery|ajax|json | 58,004 | <p>Set the <code>dataType:"JSON"</code> and callback in your ajax call. </p>
<p>For example: </p>
<pre><code>$.ajax({
url: "yourphp.php?id="+yourid,
dataType: "JSON",
success: function(json){
//here inside json variable you've the json returned by your PHP
for(var i=0;i<json.length;i++){
$('#items_container').append(json[i].item_id)
}
}
})
</code></pre>
<p>Please also consider in your PHP set the JSON content-type. <code>header('Content-type: application/json');</code></p> |
19,120,653 | Shared Database vs. Messaging Architecture | <p>I was down the pub with a friend of mine yesterday and we started discussing the architecture in use at the company he works at. The conversation basically surrounded the pros/cons of a shared database architecture against a distributed independent application architecture - we couldn't get to a consensus in which case I'd like to hear people's opinions on the pros/cons of both approaches.</p>
<p>Basically, the company that he works for has a large architecture with many different applications. Some applications have a single database that they share between them. For example, there is 1 application which provides a UI for users to alter reference data. This reference data is used by another application which also accesses the same data. I believe the code is actually written as shared libraries (i.e. both applications will use a common code set that is redeployed for each (one has it as a dependency)).</p>
<p>There are also other applications with a database that is also used by other applications by direct JDBC connection with data access code (not common between the two apps - duplicated!! erghh!).</p>
<p>My question is around the pros/cons of this architecture vs. an architecture where each application contains it's "master" data in silo. If an application x requires data from application y they use web services or some messaging technology to receive that data.</p>
<p>The messaging approach would introduce a problem whereby reference data 'codes' (or foreign keys) which are used within the db's of other applications currently now have to be fetched from another source. In the current architecture the 'decodes' for these can change at any time and be reflected in the external application immediately, rather than having to have a master/slave relationship where data is copied - or an alternative where application x has to query application y just to display the decode values.</p>
<p>I had read Enterprise Integration Patterns and whilst it does give some examples of the advantages of messaging - i'm not so convinced.</p>
<p>Thanks
Iain</p> | 19,229,234 | 3 | 2 | null | 2013-10-01 15:51:07.653 UTC | 13 | 2019-03-21 11:03:36.487 UTC | 2013-10-02 05:14:16.503 UTC | null | 842,788 | null | 2,294,382 | null | 1 | 22 | architecture|messaging|shared-data | 10,345 | <p>The advantages of <a href="http://www.enterpriseintegrationpatterns.com/patterns/messaging/Messaging.html" rel="nofollow noreferrer">message-based</a> integration over a <a href="http://www.enterpriseintegrationpatterns.com/patterns/messaging/SharedDataBaseIntegration.html" rel="nofollow noreferrer">shared database</a> are difficult to articulate, but will here be attempted: </p>
<p>There is the inevitable argument where the DBAs want to model all the relationships between the entities so that the data is <a href="https://en.wikipedia.org/wiki/Consistency_(database_systems)" rel="nofollow noreferrer">100% consistent</a> at all times. On the other hand, you have the developers warning the DBAs about <a href="https://en.wikipedia.org/wiki/Coupling_(computer_programming)" rel="nofollow noreferrer">tight-coupling</a> that emerges from <a href="https://en.wikipedia.org/wiki/Monolithic_application" rel="nofollow noreferrer">monolithic architecture</a> and how applications bound to master tables cannot be changed easily.</p>
<p>I think both of these arguments are kind of scratching the surface and building a system which is easy to change is challenging, regardless of how you do the integration. I want to put forward another kind of argument for SOA and message-based integration.</p>
<p>What it comes down to is this:</p>
<ol>
<li>Shared database integration is generally driven by a "big system" view of the world. </li>
<li>Message-based integration is generally driven by a "small system" view of the world.</li>
</ol>
<p>How many times have you come across large systems with hundreds of users which do many, many different jobs supporting multiple and diverse business functions? I come across them all the time. They are the staple of enterprise software at the moment it seems. </p>
<p>One thing all these systems seem to have in common is that they are very expensive to change. And one of the reasons for this is, as Joe R says in <a href="https://stackoverflow.com/a/19121071/569662">his answer</a>, tight coupling. </p>
<p>However, <em>coupling</em> is something of a loaded term and I think there are two very different types of coupling we need to consider. </p>
<p>The first can be thought of as <em>technological coupling</em> and this means vertical coupling inside the technology stack, usually n-tiered, between one tier and another tier. </p>
<p>So we have coupling between the database and data access layer of an application, coupling between the data access layer and business logic layer, etc. To regard such coupling as bad or wrong seems to be generally accepted, but thinking rationally should we not <em>expect</em>, or even welcome, a high degree of coupling between, say, the User DTO, the UserRepository class, and the User database table? </p>
<p>Let's consider what coupling actually means at the implementation level. Coupling happens when concepts which "belong" to one thing leak into another thing. This leakage is inevitable when you have multiple layers basically talking to each other about the same business entity. </p>
<p>The second kind of coupling, and the one I'd like to address, can be thought of as <em><a href="https://en.wikipedia.org/wiki/Capability_management_in_business" rel="nofollow noreferrer">business capability</a> coupling</em>, also known as horizontal coupling. This is where we have concepts belonging to one business capability leaking into another business capability. </p>
<p><strong>It is my assertion that</strong> this <em>horizontal coupling is encouraged by the use of databases as an integration platform</em>.</p>
<p>As an example, imagine a typical back-end system supporting an e-commerce website system. You would generally have inventory, ordering, pricing, and CRM as your core capabilities. </p>
<p>If we model this domain inside a single database, we are in effect coupling different capabilities together. Every foreign key constraint potentially increases the degree of coupling between these capabilities. In fact, <em>the system by this point can already be thought of as several different "services" integrated across a shared database</em>. </p>
<p>This is the "big system" picture of the world, which is supported and encouraged by linking different areas of your enterprise together using huge 500+ table databases. </p>
<p>Contrast this with the "small system" picture of the world, where in our example back-end web application inventory, ordering, pricing, and CRM are completely separate applications, with their own technology stacks, their own project teams, their own release schedules, and their own databases. </p>
<p>Each application, or <em>service</em>, will have its own understanding of what a given entity is, and that will fit the definition of that entity according to the business capability it is supporting. </p>
<p>An example of this is the "User". CRM are going to have a very different definition of User than ordering or fulfilment. Ordering only cares about the user in terms of what the user is buying. CRM cares about other stuff like customer buying patterns, and fulfilment cares about name, address, etc. This is not easily achieved with a single User table in a shared database.</p>
<p>This picture to me is preferable to the shared database route and the main reason is that the resulting system will better model the actual business processes it is supposed to be supporting. One of the main tenets of <a href="https://en.wikipedia.org/wiki/Domain-driven_design" rel="nofollow noreferrer">DDD</a> is that a system should resemble as much as possible the business who owns it. </p>
<p>In a typical business, these various capabilities are not implemented across the layers of big, enterprise-spanning teams, but instead by small vertical teams, often completely autonomous, who communicate among themselves and with other vertical teams often by sending requests, directives, or by letting other teams know that a certain process or task has been started/completed etc. </p>
<p>OK, but without the shared database, the website now relies on data from all of these different services for it's UI. It still needs to display this stuff together on the same screen. How can the website "presentation" layer assemble all this and render it to the UI? </p>
<p>More importantly, what if CRM wants to know when a customer orders something? What if ordering wants to know when the prices of products change, or when products are out of stock in the inventory? If these services are completely separate then how can they exchange data? </p>
<p>Addressing the UI question first, this can be done with <a href="https://www.google.co.uk/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=composite%20ui%20pattern" rel="nofollow noreferrer">composite UIs</a>. There are many techniques for this, but suffice to say it's a relatively well-known landscape and not really our focus here. </p>
<p>The second question of how do these services communicate is, well, they exchange messages. What kind of messages? <a href="http://www.eaipatterns.com/EventMessage.html" rel="nofollow noreferrer">Events</a>. Events are published by one system in order that they are consumed by any other system which is interested in that event. </p>
<p>In our e-commerce example, kinds of events could be:</p>
<ol>
<li>OrderPlaced</li>
<li>CustomerUpgradedToGold</li>
<li>ProductDiscounted</li>
<li>StockExhausted</li>
</ol>
<p>These events have business meaning. That means we can get an additional benefit with the small system approach which is that the integration medium itself has business meaning, and can be expressed in business language, which lends itself well to scrum and agile methodologies. </p>
<p>So, to finally answer the OP's question, I don't think that from a technological perspective there is much difference between Shared Database vs Messaging integration approaches. Both approaches require the same kind of abstractions and semantics. But I do think there is a huge difference in the driving forces behind them, and the outcomes of adopting more of a small systems mindset provide better business value overall. </p> |
35,282,548 | Visual Studio: The Operation could not be completed. The parameter is incorrect | <p>I have been working on a new solution all evening. Building without an issue, however all of a sudden I have started to get the following error when building: </p>
<blockquote>
<p>The Operation could not be completed. The parameter is incorrect.</p>
</blockquote>
<p>Now, I have searched many threads, but I am yet to find a decent solution. I should also mention. I have restarted, tried to repair my VS 2015 Express install with no luck. </p>
<p>This is happening on EVERY solution, not just my new one, even if I close everything, start a brand new project and try and build. </p>
<p>Any suggestions would be welcome!</p> | 42,070,115 | 15 | 6 | null | 2016-02-09 01:39:42.57 UTC | 1 | 2022-09-21 06:53:19.687 UTC | 2016-02-09 04:08:11.993 UTC | null | 2,263,683 | null | 4,783,157 | null | 1 | 56 | c#|visual-studio|build|visual-studio-2015 | 55,065 | <p>Dan (the original poster) mentioned in a comment above that running Visual Stuio as admin solved this for him.</p> |
35,226,245 | Angular2 Routerlink: add query parameters | <p>How can I add query parameters to <code>routerLink</code>?</p>
<pre><code>@RouteConfig {
{path: '/search', name: 'Search', component: SearchCmp}
}
</code></pre>
<p>Let' say I want to route to <code>/search?q=asdf</code>,</p>
<pre><code><a [routerLink]= " [ '/Search' , {q= 'asdf'}] ">Link 1</a>
</code></pre>
<p>this resolves to <code>/search</code> .</p>
<p>Is there a way to add query parameters without using:</p>
<pre><code>this.router.navigate( ['Search', { q: 'asdf'}]);
</code></pre>
<p>or</p>
<pre><code><a href="/search?a=asdf"> Link 2 </a>
</code></pre>
<p>?</p> | 35,254,254 | 2 | 8 | null | 2016-02-05 14:11:07.65 UTC | 10 | 2017-09-14 05:58:32.737 UTC | 2017-03-18 13:07:55.343 UTC | null | 1,033,581 | null | 5,826,789 | null | 1 | 67 | angular|angular2-routing | 78,918 | <p>If u need something as <code>/search?q=asdf</code> than you can simply use:</p>
<pre class="lang-ts prettyprint-override"><code>@RouteConfig {
{path: '/search', name: 'Search', component: SearchCmp}
}
//And to generate router Links use:
<a [routerLink]="['/Search']" [queryParams]="{q:'asdf'}"></a>
</code></pre>
<p>This will generate the href tag as <code><a href="/search"</code> but on clicking the anchor tag will lead you to url <code>/search?q=asdf</code>. [queryParams] will let you add the query params with "?", otherwise they will be appended by ";". You can get this parameter in your <code>SearchCmp</code> using:</p>
<pre class="lang-ts prettyprint-override"><code>constructor(private _routeParams: RouteParams) {
var queryParam = this._routeParams.get('q');
}
</code></pre> |
51,388,735 | The model item passed into the ViewDataDictionary is of type X[] but this ViewDataDictionary instance requires a model item of type X | <p>Error:</p>
<blockquote>
<p>InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'Test.Models.Ticket[]', but this ViewDataDictionary instance requires a model item of type 'Test.Models.Ticket'.</p>
</blockquote>
<p>Hello,<br>
After staring at an error for a few days and doing some research, I've determined that I don't know enough about MVC to solve this problem. I understand enough to know that my controller is trying to pass an array to the view, but that the view is not looking for an array(?). Below is the code:</p>
<p><strong>Controller:</strong></p>
<pre><code>//this is supposed to take the last five "tickets" created from a database
[Route("Ticket")]
public IActionResult Index(int page = 0)
{
var model = _db.Tickets.OrderByDescending(x => x.Time).Take(5).ToArray();
return View(model);
}
</code></pre>
<p><strong>View:</strong> (file is titled "Index.cshtml" under the "Ticket" folder within the "Views" folder)</p>
<pre><code>@model IEnumerable<Test.Models.Ticket>
@{
Layout = "_Layout";
}
<p>Below is supposed to display the latest 5 "tickets" from a database.</p>
<div class="ticket-create">
@foreach (var ticket in Model)
{
@Html.Partial("_Ticket", ticket)
}
</div>
</code></pre>
<p><strong>Partial View "_Ticket":</strong></p>
<pre><code>@model Test.Models.Ticket
<article class="ticket-create">
<h1>@Html.ActionLink(Model.Type, "Create", "Ticket", new { year = Model.Time.Year, month = Model.Time.Month, day = Model.Time.Day, time = Model.Time.TimeOfDay, key = Model.Key })</h1>
<div class="type">
Created on <span>@Model.Time</span> by <span>@Model.Name</span>
</div>
<div class="desc">
@Model.Desc
</div>
<div class="clearance">
@Model.Clearance
</div>
</article>
</code></pre>
<p><strong>Model "Ticket":</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Test.Models
{
public class Ticket
{
public long Id { get; set; }
private string _key;
public string Key
{
get
{
if(_key == null)
{
_key = Regex.Replace(Name.ToLower(), "[^a-z0-9]", "-");
}
return _key;
}
set { _key = value; }
}
[Required]
[DataType(DataType.Text)]
public string Type { get; set; }
[Required]
[DataType(DataType.Text)]
public string Name { get; set; }
[StringLength(300, MinimumLength = 5, ErrorMessage = "The description must be between 5 and 300 characters long.")]
[DataType(DataType.MultilineText)]
public string Desc { get; set; }
[DataType(DataType.DateTime)]
public DateTime Time { get; set; }
[Required]
[DataType(DataType.Text)]
public string Clearance { get; set; }
[DataType(DataType.Text)]
public string Author { get; set; }
}
}
</code></pre>
<p>_Layout.cshtml declares the following model: "@model Test.Models.Ticket"</p>
<p>I read through a wonderful post located <a href="https://stackoverflow.com/questions/40373595/the-model-item-passed-into-the-dictionary-is-of-type-but-this-dictionary-requ">here</a>, but while I think that helped me an awful lot in many aspects of my understanding of what's happening, I am still finding the error difficult to resolve.</p> | 51,389,027 | 1 | 6 | null | 2018-07-17 19:16:06.943 UTC | 3 | 2018-07-17 19:37:10.743 UTC | 2018-07-17 19:37:10.743 UTC | null | 2,141,621 | null | 10,094,426 | null | 1 | 14 | c#|asp.net-mvc | 48,902 | <p>The problem is that the Layout the View is using expects a model of <code>Ticket</code> and you are passing it a <code>Ticket[]</code> (notice that this is done implicitly when you use <code>return View(model)</code>). </p>
<p>Normally, since the Layout is used through multiple Views, the Layout does not declare a <code>@model</code>. Removing the <code>@model</code> from the Layout will solve your problem.</p> |
5,147,830 | How to center text inside a li element inside an unordered list | <p>This list is working great for me but the text within the <code><li></code> elements is not centering.</p>
<p>The <code><li></code>s must auto resize to their content.</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#nav-menu {
font-family: Verdana, Arial, Helvetica, sans-serif;
height: 30px;
background-image: url(../img/menu_bg.png);
background-repeat: repeat-x;
border-bottom: dotted thin #666666;
border-top: dotted thin #666666;
text-align: center;
width: 800px;
}
#nav-menu ul {
list-style: none;
padding: 0;
margin: auto 0;
}
#nav-menu li {
float: left;
border-right: dotted thin #666666;
list-style: none;
padding: 0.5em 2em 0.5em 0.75em;
}
#nav-menu li a {
line-height: 1.5em;
color: #333333;
text-decoration: none;
font-size: 12px;
font-weight: bold;
display: block;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="nav-menu">
<ul>
<li class="current_page_item"><a href="#" title="Home">Home</a>
<li class="current_page_item"><a href="#" title="Home">Home</a>
<li class="current_page_item"><a href="#" title="Home">Home</a>
<li class="current_page_item"><a href="#" title="Home">zxczczxczHome</a>
</ul>
</div></code></pre>
</div>
</div>
</p> | 5,147,900 | 2 | 2 | null | 2011-02-28 21:34:44.747 UTC | null | 2016-04-12 21:32:57.857 UTC | 2016-04-12 21:31:47.92 UTC | null | 2,756,409 | null | 638,400 | null | 1 | 6 | css|text|html-lists | 46,814 | <p>While you're assigning unequal <code>padding</code> values to the left and right of the <code>li</code> (<code>0.75em</code> and <code>2em</code> respectively) the text <em>can't be centred</em> since you're forcing it off-centre with the <code>padding</code>.</p>
<p>If you amend the padding to: <code>padding: 0.5em 1em;</code> (<code>0.5em</code> top and bottom, <code>1em</code> left and right) then it can be centred.</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>#nav-menu {
font-family: Verdana, Arial, Helvetica, sans-serif;
height: 30px;
background-image: url(../img/menu_bg.png);
background-repeat: repeat-x;
border-bottom: dotted thin #666666;
border-top: dotted thin #666666;
text-align: center;
width: 800px;
}
#nav-menu ul {
list-style: none;
padding: 0;
margin: auto 0;
}
#nav-menu li {
float: left;
border-right: dotted thin #666666;
list-style: none;
padding: 0.5em 1em;
}
#nav-menu li a {
line-height: 1.5em;
color: #333333;
text-decoration: none;
font-size: 12px;
font-weight: bold;
display: block;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="nav-menu">
<ul>
<li class="current_page_item"><a href="#" title="Home">Home</a></li>
<li class="current_page_item"><a href="#" title="Home">Home</a></li>
<li class="current_page_item"><a href="#" title="Home">Home</a></li>
<li class="current_page_item"><a href="#" title="Home">zxczczxczHome</a></li>
</ul>
</div></code></pre>
</div>
</div>
</p>
<p><a href="http://jsfiddle.net/davidThomas/gfTH2/1/" rel="nofollow noreferrer">JSFiddle demo</a> of the above.</p> |
256,370 | Fatal CLR Error 80004005 | <p>Today, everytime I try to open any <strong>.Net application</strong> I get:</p>
<pre><code>CLR error: 80004005
The program will now terminate.
</code></pre>
<p>Any suggestions?</p> | 256,373 | 7 | 0 | null | 2008-11-02 01:29:36.923 UTC | 2 | 2021-07-16 19:41:35.397 UTC | 2012-12-21 08:05:03.27 UTC | Blair Conrad | 621,188 | Nescio | 14,484 | null | 1 | 17 | clr | 60,627 | <p>I'd start with <a href="http://msdn.microsoft.com/en-us/netframework/aa569263.aspx" rel="noreferrer">downloading</a> and re-installing the .NET framework.</p> |
1,225,586 | Checking email with Python | <p>I am interested to trigger a certain action upon receiving an email from specific
address with specific subject. In order to be able to do so I need to implement
monitoring of my mailbox, checking every incoming mail (in particular, i use gmail).
what is the easiest way to do that?</p> | 1,231,136 | 7 | 0 | null | 2009-08-04 03:15:46.757 UTC | 40 | 2022-03-11 22:45:37.177 UTC | 2016-10-23 07:11:18.267 UTC | null | 832,230 | null | 111,833 | null | 1 | 61 | python|email | 102,721 | <p>Gmail provides the ability to connect over POP, which you can turn on in the gmail settings panel. Python can make connections over POP pretty easily:</p>
<pre><code>import poplib
from email import parser
pop_conn = poplib.POP3_SSL('pop.gmail.com')
pop_conn.user('username')
pop_conn.pass_('password')
#Get messages from server:
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
# Concat message pieces:
messages = ["\n".join(mssg[1]) for mssg in messages]
#Parse message intom an email object:
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
for message in messages:
print message['subject']
pop_conn.quit()
</code></pre>
<p>You would just need to run this script as a cron job. Not sure what platform you're on so YMMV as to how that's done.</p> |
454,762 | vector or map, which one to use? | <p>I've heard many people say that if the number of expected elements in the container is relatively small, it is better to use <code>std::vector</code> instead of <code>std::map</code> even if you were to use the container for lookups only and not iterating.</p>
<p>What is the real reason behind this?</p>
<p>Obviously the lookup performance of <code>std::map</code> cannot be worse than <code>std::vector</code> (although it may differ in nanoseconds/microseconds) so does it have something to do with memory usage?</p>
<p>Does <code>std::vector</code> fare any better/worse than <code>std::map</code> in fragmenting the virtual address space?</p>
<p>I am using the STL library that comes along with Visual Studio (i.e. Microsoft's implementation). Does that make any difference compared to other implementations?</p> | 454,782 | 7 | 0 | null | 2009-01-18 07:06:05.053 UTC | 36 | 2021-06-29 15:12:49.243 UTC | 2020-05-20 23:06:58.847 UTC | Naveen | 3,841,734 | Naveen | 39,742 | null | 1 | 81 | c++|performance|stl | 108,562 | <p>I presume you're comparing <code>map<A, B></code> with <code>vector<pair<A, B> ></code>.</p>
<p>Firstly, finding an item in a very small vector can easily be faster than the same thing in a map, because all the memory in a vector is always contiguous (and so plays more nicely with computers' caches and such things), and the number of comparisons needed to find something in a vector might be about the same as for a map. Finding an element in a map needs fewer operations in the limit of very large containers. </p>
<p>The point where maps become faster than vectors depends on the implementation, on your processor, what data is in the map, and subtle things like what memory is in the processor's cache. Typically, the point where map becomes faster would be about 5-30 elements.</p>
<p>An alternative is to use a hash container. They are often named <code>hash_map</code> or <code>unordered_map</code>. Classes named <code>hash_map</code> are not part of the official standard (and there are a few variants out there); <code>std::tr1::unordered_map</code> is. A hash map is often faster than a normal map for lookups, regardless of how many elements are in it, but whether it is actually faster depends on what the key is, how it is hashed, what values you have to deal with, and how the key is compared in std::map. It doesn't keep things in a specific order like std::map, but you've said that you don't care about that. I'd recommend hash maps particularly if the keys are integers or pointers, because these hash very quickly.</p> |
1,195,112 | How can I get the CPU temperature? | <p>I need to gather some system information for the application I'm developing. The memory available and the CPU load are easy to get using C#. Unfortunately, the CPU temperature it's not that easy. I have tried using WMI, but I couldn't get anything using</p>
<pre><code>Win32_TemperatureProbe
</code></pre>
<p>or</p>
<pre><code>MSAcpi_ThermalZoneTemperature
</code></pre>
<p>How can I do this? I'm wondering how monitoring programs, as SiSoftware Sandra, can get that information...</p>
<p>Here is the code of the class:</p>
<pre><code>public class SystemInformation
{
private System.Diagnostics.PerformanceCounter m_memoryCounter;
private System.Diagnostics.PerformanceCounter m_CPUCounter;
public SystemInformation()
{
m_memoryCounter = new System.Diagnostics.PerformanceCounter();
m_memoryCounter.CategoryName = "Memory";
m_memoryCounter.CounterName = "Available MBytes";
m_CPUCounter = new System.Diagnostics.PerformanceCounter();
m_CPUCounter.CategoryName = "Processor";
m_CPUCounter.CounterName = "% Processor Time";
m_CPUCounter.InstanceName = "_Total";
}
public float GetAvailableMemory()
{
return m_memoryCounter.NextValue();
}
public float GetCPULoad()
{
return m_CPUCounter.NextValue();
}
public float GetCPUTemperature()
{
//...
return 0;
}
}
</code></pre> | 1,195,150 | 8 | 1 | null | 2009-07-28 16:03:50.46 UTC | 38 | 2021-06-11 17:07:40.353 UTC | 2021-06-11 16:35:11.203 UTC | null | 63,550 | null | 110,466 | null | 1 | 67 | c#|.net|wmi | 146,075 | <p>I'm pretty sure it's manufacturer dependent, since they will be accessed through an I/O port. If you have a specific board you're trying to work with, try looking through the manuals and/or contacting the manufacturer.</p>
<p>If you want to do this for a lot of different boards, I'd recommend contacting someone at something like SiSoftware or be prepared to read a <em>lot</em> of motherboard manuals.</p>
<p>As another note, not all boards have temperature monitors.</p>
<p>You also might run into problems getting privileged access from the kernel.</p> |
1,457 | Modify Address Bar URL in AJAX App to Match Current State | <p>I'm writing an AJAX app, but as the user moves through the app, I'd like the URL in the address bar to update despite the lack of page reloads. Basically, I'd like for them to be able to bookmark at any point and thereby return to the current state. </p>
<p>How are people handling maintaining RESTfulness in AJAX apps? </p> | 1,468 | 8 | 4 | null | 2008-08-04 17:53:32.5 UTC | 82 | 2021-10-25 11:49:32.35 UTC | 2013-01-09 05:43:50.98 UTC | null | 1,471,203 | null | 331 | null | 1 | 167 | ajax|url|rest|address-bar | 74,143 | <p>The way to do this is to manipulate <code>location.hash</code> when AJAX updates result in a state change that you'd like to have a discrete URL. For example, if your page's url is:</p>
<blockquote>
<p><a href="http://example.com/" rel="nofollow noreferrer">http://example.com/</a></p>
</blockquote>
<p>If a client side function executed this code:</p>
<pre><code>// AJAX code to display the "foo" state goes here.
location.hash = 'foo';
</code></pre>
<p>Then, the URL displayed in the browser would be updated to:</p>
<blockquote>
<p><a href="http://example.com/#foo" rel="nofollow noreferrer">http://example.com/#foo</a></p>
</blockquote>
<p>This allows users to bookmark the "foo" state of the page, and use the browser history to navigate between states.</p>
<p>With this mechanism in place, you'll then need to parse out the hash portion of the URL on the client side using JavaScript to create and display the appropriate initial state, as fragment identifiers (the part after the #) are not sent to the server.</p>
<p><a href="http://benalman.com/projects/jquery-hashchange-plugin/" rel="nofollow noreferrer">Ben Alman's hashchange plugin</a> makes the latter a breeze if you're using jQuery.</p> |
1,027,663 | How do I make a tabbed view in HTML? | <p>When clicking on tab A, show content for tab A. Click on tab B, show content for tab B, and so on.</p>
<p>What's the most simple and compatible way of constructing a HTML snippet?</p>
<p>I don't mean to use any libraries here, so none of <a href="http://en.wikipedia.org/wiki/JQuery" rel="nofollow noreferrer">jQuery</a> or any other libraries.</p> | 1,029,252 | 9 | 0 | null | 2009-06-22 14:53:22.07 UTC | 3 | 2016-06-12 12:58:02.8 UTC | 2016-06-12 12:46:11.167 UTC | null | 63,550 | null | 104,015 | null | 1 | 17 | html|tabbed-view | 83,005 | <p>If you want to roll your own tab control, you could do something like this:</p>
<pre><code><html>
<head>
<script type="text/javascript">
function activateTab(pageId) {
var tabCtrl = document.getElementById('tabCtrl');
var pageToActivate = document.getElementById(pageId);
for (var i = 0; i < tabCtrl.childNodes.length; i++) {
var node = tabCtrl.childNodes[i];
if (node.nodeType == 1) { /* Element */
node.style.display = (node == pageToActivate) ? 'block' : 'none';
}
}
}
</script>
</head>
<body>
<ul>
<li>
<a href="javascript:activateTab('page1')">Tab 1</a>
</li>
<li>
<a href="javascript:activateTab('page2')">Tab 2</a>
</li>
...
</ul>
<div id="tabCtrl">
<div id="page1" style="display: block;">Page 1</div>
<div id="page2" style="display: none;">Page 2</div>
...
</div>
</body>
</html>
</code></pre> |
860,200 | DDD: Primary keys (Ids) and ORMs (for example, NHibernate) | <p>Why is it considered OK to have an Id field in the domain entities?
I have seen several solutions that provide base class with Id and Id-based GetHashCode/Equals.</p>
<p>My understanding of domain model is that it should contain only things related to the domain. While in rare cases (trackable orders) Ids are meaningful, most of the time they do not provide anything except a simple way to reference objects in DB/on UI.</p>
<p>I do not see a Equals/GetHashCode benefits either, since the Identity Map implementation should guarantee that reference equality <strong>is</strong> the id equality anyway.</p>
<p>Strangely, I can not easily find what other people think on this subject, so I am asking it here. What is the general opinion on using non-domain related Ids in the domain entities? And are there any problems with NHibernate if I do not add Ids to my domain entities?</p>
<p><strong>UPDATE:</strong></p>
<p>Thanks for the answers.</p>
<p>Several of them suggest that having Id is the only way for the ORM to do a DB update. I do not think this is the case. ORM already keeps track of all entities loaded from the DB, so it should be easily able to get an Id internally when it needs one.</p>
<p><strong>UPDATE 2:</strong></p>
<p>Answer to Justice and similar points:
<em>What if we have a web application and <strong>need</strong> a way to reference the entity between sessions? Like edit/resource/id?</em></p>
<p>Well, I see this as a specific need of the constrained UI/environment, not a domain model need. Having an application service or repository with GetIdentitity method (consistent with Load(identity) method) seems to be enough for this scenario.</p> | 860,686 | 9 | 3 | null | 2009-05-13 20:19:11.903 UTC | 10 | 2022-04-07 08:51:33.313 UTC | 2009-09-01 13:32:34.713 UTC | null | 39,068 | null | 39,068 | null | 1 | 18 | nhibernate|architecture|domain-driven-design | 3,477 | <p>I just can talk about NHibernate. There you need a field for the primary key, it's up to you if you take business data (not recommended) or a surrogate key with no business meaning.</p>
<p>Typical scenarios are:</p>
<ul>
<li>auto-incrementing value generated by the database</li>
<li>guid generated by NHibernate</li>
<li>guid generated by the business logic</li>
</ul>
<p><strong>There is a big advantage to have a unique id.</strong> When you pass your object around, for instance to the client and back to the server, you can't rely on memory identity. You could even have several instances in memory of the same business instance. The business instance is identified by the id.</p>
<p><strong>Id-based comparison</strong> is a matter of taste. Personally I like simple and reliable code, and id-based comparison <em>is</em> simple and reliable, while <em>deep-comparison</em> is always a bit risky, error-prone, unmaintainable. So you end up with operator == comparing the memory identity and Equals comparing the business (and database) identity.</p>
<p>NHibernate is the less intrusive way to map a class model to a relational database I know. In our large project we have primary keys and version properties (they are used for optimistic locking). You could argue that this is intrusive, because it is not used for the business logic.</p>
<p><strong>NH doesn't require to have these properties.</strong> (however it needs one of the properties as primary key.) But consider:</p>
<ul>
<li>It just works better, eg. pessimistic locking is only possible with a appropriate property,</li>
<li>faster: int id's perform better on many databases then other data types</li>
<li>and easier: taking properties with a meaning to the business are discouraged for several reasons.</li>
</ul>
<p>So why making your life harder than necessary?</p>
<hr>
<p><strong>Edit:</strong> Just read <a href="http://nhforge.org/doc/nh/en/index.html#mapping-declaration-id" rel="nofollow noreferrer">the documentation</a> and found that NHibernate does <strong>not</strong> need an id property in the persistent class! If you don't have an indentifier, <a href="http://nhforge.org/doc/nh/en/index.html#persistent-classes-poco-identifier" rel="nofollow noreferrer">you can't use some features</a>. It is recommended to have it, it just makes your life easier.</p> |
476,714 | Is there a good, online, interactive regex tutorial? | <p>Now, I know both SQL and regexes just fine, but a few times on this site, I came across someone working through the exercises on <a href="http://sqlzoo.net/" rel="noreferrer">SQLzoo.net</a>. As far as I could tell, this was a wonderful online resource where someone can pretty easily learn SQL by example, writing many toy queries against several toy databases. I will likely redirect people wanting to learn SQL to that site.</p>
<p>These SQLzoo people also run some other tutorials, including some on a few programming languages. However, the section on regular expressions is pretty small (<em>e.g.</em>, see <a href="http://progzoo.net/wiki/Strings_Tutorial%2C_Pattern_Matching" rel="noreferrer">Java</a>'s page), and I don't think you can actually <em>learn</em> regexes from it. I think a good, online tutorial <em>might</em> help with the onslaught of basic regex questions we have here. (Maybe after the answer, we could suggest that they take a look at the tutorial.)</p>
<p>So, <strong>is there a good, online, interactive regex tutorial</strong> along the lines of that SQL tutorial? I looked online briefly, but all I could find were non-interactive tutorials or simple pages (still useful, though!) that let you match a string against a pattern so that you could see what it matches/captures/etc.</p> | 476,824 | 9 | 3 | null | 2009-01-24 21:50:00.127 UTC | 38 | 2015-12-17 07:02:18.153 UTC | 2013-08-09 13:36:32.79 UTC | user1228 | null | A. Rex | 3,508 | null | 1 | 60 | regex | 25,171 | <p>The site written by @wchung, RegexOne seems to be a perfect answer to the original question. Check that out first ;)</p>
<p>The tool txt2re is, as commenters have rightly mentioned, very ugly. <a href="http://gskinner.com/RegExr/" rel="noreferrer">RegExr</a> (ht @runrunraygun) is a much prettier tool for editing regular expressions, although has completely different functionality and still no tutorial.</p>
<p>The main reason it might be useful for learning regexes is the ability to see the effect each edit is having on the matching.</p>
<p><strong>Original answer:</strong></p>
<p>I always thought <a href="http://www.txt2re.com/" rel="noreferrer">txt2re</a> was a very clever tool. You just type an example of some text you want to match, and then it lets you pick bits out to match against. I'd consider it to be a fairly useful tool for learning regular expressions.</p> |
125,597 | Boost dependency for a C++ open source project? | <p>Boost is meant to be <strong>the</strong> standard non-standard C++ library that every C++ user can use. Is it reasonable to assume it's available for an open source C++ project, or is it a large dependency too far?</p> | 125,811 | 10 | 0 | null | 2008-09-24 05:44:09.913 UTC | 8 | 2013-12-20 21:08:01.827 UTC | 2012-09-07 16:17:51.31 UTC | null | 1,561,378 | dajobe | 11,177 | null | 1 | 30 | c++|boost|standard-library | 7,440 | <p>Basically your question boils down to “is it reasonable to have [free library xyz] as a dependency for a C++ open source project.”</p>
<p>Now consider the following quote from Stroustrup and the answer is really a no-brainer:</p>
<blockquote>
<p>Without a good library, most interesting tasks are hard to do in
C++; but given a good library, almost any task can be made easy</p>
</blockquote>
<p>Assuming that this is correct (and in my experience, it is) then writing a reasonably-sized C++ project <em>without</em> dependencies is downright unreasonable.</p>
<p>Developing this argument further, the <em>one</em> C++ dependency (apart from system libraries) that can reasonably be expected on a (developer's) client system is the Boost libraries.
I <em>know</em> that they aren't but it's not an unreasonable presumption for a software to make.</p>
<p>If a software can't even rely on Boost, it can't rely on <em>any</em> library.</p> |
979,141 | How to programmatically cause a core dump in C/C++ | <p>I would like to force a core dump at a specific location in my C++ application.</p>
<p>I know I can do it by doing something like:</p>
<pre><code>int * crash = NULL;
*crash = 1;
</code></pre>
<p>But I would like to know if there is a cleaner way?</p>
<p>I am using Linux by the way.</p> | 979,161 | 10 | 5 | null | 2009-06-11 03:16:17.523 UTC | 46 | 2020-05-14 21:39:08.213 UTC | 2017-03-23 15:36:38.72 UTC | null | 1,033,581 | null | 42,303 | null | 1 | 99 | c++|c|linux|coredump|abort | 88,886 | <p>Raising of signal number 6 (<code>SIGABRT</code> in Linux) is one way to do it (though keep in mind that SIGABRT is not <em>required</em> to be 6 in all POSIX implementations so you may want to use the <code>SIGABRT</code> value itself if this is anything other than quick'n'dirty debug code).</p>
<pre><code>#include <signal.h>
: : :
raise (SIGABRT);
</code></pre>
<p>Calling <code>abort()</code> will also cause a core dump, and you can even do this <em>without</em> terminating your process by calling <code>fork()</code> followed by <code>abort()</code> in the child only - see <a href="https://stackoverflow.com/a/131539/60462">this answer</a> for details.</p> |
1,175,620 | In Java, what is a shallow copy? | <p>java.util.Calendar.clone() returns "...a new Calendar with the same properties" and returns "a shallow copy of this Calendar".</p>
<p>This does not appear to be a shallow copy as answered <a href="https://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy">here</a> on SO. That question is tagged <strong>language-agnostic,</strong> Java does not seem to follow the language agnostic definition. As I step through the code I notice that the structure and the elements are copied to this new object, more than the language agnostic structure only.</p>
<p>In Java, what is a shallow copy?</p>
<p>How does it differ from a Java deep copy (if that exists)?</p> | 1,175,667 | 11 | 1 | null | 2009-07-24 03:32:44.3 UTC | 33 | 2019-10-19 10:32:34.36 UTC | 2017-05-23 12:02:37.033 UTC | null | -1 | null | 53,498 | null | 1 | 62 | java|clone|shallow-copy | 110,553 | <p>A shallow copy just copies the values of the references in the class. A deep copy copies the values. given:</p>
<pre><code>class Foo {
private Bar myBar;
...
public Foo shallowCopy() {
Foo newFoo = new Foo();
newFoo.myBar = myBar;
return newFoo;
}
public Foo deepCopy() {
Foo newFoo = new Foo();
newFoo.myBar = myBar.clone(); //or new Bar(myBar) or myBar.deepCopy or ...
return newFoo;
}
}
Foo myFoo = new Foo();
Foo sFoo = myFoo.shallowCopy();
Foo dFoo = myFoo.deepCopy();
myFoo.myBar == sFoo.myBar => true
myFoo.myBar.equals(sFoo.myBar) => true
myFoo.myBar == dFoo.myBar => **false**
myFoo.myBar.equals(dFoo.myBar) => true
</code></pre>
<p>In this case the shallow copy has the same reference (<code>==</code>) and the deep copy only has an equivalent reference (<code>.equals()</code>). </p>
<p>If a change is made to the value of a shallowly copied reference, then the copy reflects that change because it shares the same reference. If a change is made to the value of a deeply copied reference, then the copy does not reflect that change because it does not share the same reference.</p>
<p>C-ism</p>
<pre><code>int a = 10; //init
int& b = a; //shallow - copies REFERENCE
int c = a; //deep - copies VALUE
++a;
</code></pre>
<p>Result:</p>
<pre><code>a is 11
*b is 11
c is 10
</code></pre> |
936,377 | Static method in a generic class? | <p>In Java, I'd like to have something as:</p>
<pre><code>class Clazz<T> {
static void doIt(T object) {
// ...
}
}
</code></pre>
<p>But I get</p>
<pre>Cannot make a static reference to the non-static type T</pre>
<p>I don't understand generics beyond the basic uses and thus can't make much sense of that. It doesn't help that I wasn't able to find much info on the internet about the subject.</p>
<p>Could someone clarify if such use is possible, by a similar manner? Also, why was my original attempt unsuccessful?</p> | 936,951 | 12 | 0 | null | 2009-06-01 19:35:34.233 UTC | 50 | 2021-12-16 23:15:36.357 UTC | 2020-04-03 18:30:59.397 UTC | null | 1,735,406 | null | 4,850 | null | 1 | 214 | java|generics|static-methods | 194,011 | <p>You can't use a class's generic type parameters in static methods or static fields. The class's type parameters are only in scope for instance methods and instance fields. For static fields and static methods, they are shared among all instances of the class, even instances of different type parameters, so obviously they cannot depend on a particular type parameter.</p>
<p>It doesn't seem like your problem should require using the class's type parameter. If you describe what you are trying to do in more detail, maybe we can help you find a better way to do it.</p> |
198,337 | Testing HTML/CSS/Javascript skills when hiring | <p>When hiring a front-end developer, what specific skills and practices should you test for? What is a good metric for evaluating their skill in HTML, CSS and Javascript?</p>
<p>Obviously, table-less semantic HTML and pure CSS layout are probably the key skills. But what about specific techniques? Should he/she be able to effortlessly mock up a multi-column layout? CSS sprites? Equal height (or faux) columns? Does HTML tag choice matter (ie, relying too heavily on <code><div></code>)? Should they be able to explain (in words) how floats work?</p>
<p>And what about javascript skills? How important is framework experience (jQuery, Prototype, etc). today?</p>
<p>Obviously, the details of the position and the sites they'll be working on are the best indication of what skills are needed. But I'm wondering what specific skills people might consider to be deal-breakers (or makers) when creating tests for candidates. </p> | 198,354 | 13 | 0 | null | 2008-10-13 17:26:31.6 UTC | 20 | 2014-10-29 06:23:20.463 UTC | 2014-10-29 06:23:20.463 UTC | null | 76,337 | Bryan M. | 4,636 | null | 1 | 27 | javascript|html|css|frontend | 19,493 | <p>When I interview people for a position of Client-Side developer I try to figure out:</p>
<pre>
1) Understanding DOM (what is that, how is it related to HTML etc)
2) Understanding XML/namespaces
3) Understanding JavaScript (object-oriented? what otherwise)
4) Knowing approaches to componentization (XBL, HTC) - plus
5) Understanding OO principles
6) JavaScript closures
7) Memory leaks in browsers
</pre>
<p>The only simple test case I give right away:</p>
<pre>
<script type="text/javascript">
var a = 1;
</script>
</pre>
<p>I suggest interviewee to explain in technical terms that line.</p>
<p>And I also check on overall awareness of the current state of the Web technologies, among other questions I suggest designing a web-browser where interviewee is suggested to pick technologies he would put into his brand-new creature, suggest ones that might be missing from the current client-side platform.</p> |
418,503 | Common Header / Footer with static HTML | <p>Is there a decent way with static HTML/XHTML to create common header/footer files to be displayed on each page of a site? I know you can obviously do this with PHP or server side directives, but is there any way of doing this with absolutely no dependencies on the server stitching everything together for you?</p>
<p>Edit: All very good answers and was what I expected. HTML is static, period. No real way to change that without something running server side or client side. I've found that Server Side Includes seem to be my best option as they are very simple and don't require scripting.</p> | 418,582 | 14 | 4 | null | 2009-01-06 22:50:14.9 UTC | 19 | 2021-01-31 19:25:40.763 UTC | 2009-01-08 14:30:46.953 UTC | Adam Haile | 194 | Adam Haile | 194 | null | 1 | 84 | html | 119,683 | <p>There are three ways to do what you want</p>
<h2>Server Script</h2>
<p>This includes something like php, asp, jsp.... But you said no to that</p>
<h2>Server Side Includes</h2>
<p>Your server is serving up the pages so why not take advantage of the built in <a href="http://en.wikipedia.org/wiki/Server_Side_Includes" rel="noreferrer">server side includes</a>? Each server has its own way to do this, take advantage of it.</p>
<h2>Client Side Include</h2>
<p>This solutions has you calling back to the server after page has already been loaded on the client.</p> |
1,043,433 | How to auto-remove trailing whitespace in Eclipse? | <p>The question has two parts, one of which I already have the answer for.</p>
<ol>
<li>How to auto-remove trailing whitespace <strong>from the entire file being edited</strong>? -> Answer: use the <a href="http://andrei.gmxhome.de/anyedit/" rel="noreferrer">AnyEdit plugin</a>, which can be set to do that on any save to the file.</li>
<li>How to auto-remove trailing whitespace <strong>only from the lines I changed</strong>? -> This I don't know and would appreciate any help.</li>
</ol> | 2,618,521 | 14 | 4 | null | 2009-06-25 11:34:04.03 UTC | 82 | 2019-11-07 12:57:39.083 UTC | 2019-11-07 12:57:39.083 UTC | null | 897,024 | null | 128,734 | null | 1 | 431 | eclipse|whitespace | 192,315 | <ol>
<li>Removing whitespace <em>from the entire file being edited</em>:</li>
</ol>
<p><kbd>Preferences</kbd> -> <kbd>Java</kbd> -> <kbd>Editors</kbd> -> <kbd>Save Actions</kbd> -> check <kbd>Perform the selected actions on save</kbd> -> check <kbd>Additional actions</kbd> -> click <kbd>Configure..</kbd> -> go to <kbd>Code organizing</kbd> tab -> check <kbd>Remove trailing whitespace</kbd> -> select <kbd>All lines</kbd>.</p>
<ol start="2">
<li>Removing whitespace <em>only from the lines I changed</em>:</li>
</ol>
<p><kbd>Preferences</kbd> -> <kbd>Java</kbd> -> <kbd>Editor</kbd> -> <kbd>Save Actions</kbd> -> check "<kbd>Perform the selected actions on save</kbd> -> check <kbd>Format source code</kbd> -> select <kbd>Format edited lines</kbd>.</p>
<p>Note it is not necessary to click <kbd>Configure the formatter settings on the Formatter page</kbd> - all the code styles automatically include removing trailing whitespace. At least I couldn't find a setting for this in Formatter configuration, and it worked out of the box for built-in Java Conventions, Eclipse, Eclipse 2.1 styles, as well as <a href="https://github.com/google/styleguide/blob/gh-pages/eclipse-java-google-style.xml" rel="noreferrer">GoogleStyle</a>.</p>
<p>When using this set-up, you obviously need to also <strong>turn off</strong> the solution to part 1 of the question.</p>
<pre><code>Eclipse version checked: 4.5.2, 4.11
</code></pre> |
150,505 | Capturing URL parameters in request.GET | <p>I am currently defining regular expressions in order to capture parameters in a URL, as described in the tutorial. How do I access parameters from the URL as part the <code>HttpRequest</code> object?</p>
<p>My <code>HttpRequest.GET</code> currently returns an empty <code>QueryDict</code> object.</p>
<p>I'd like to learn how to do this without a library, so I can get to know Django better.</p> | 150,518 | 16 | 0 | null | 2008-09-29 20:29:55.223 UTC | 184 | 2022-03-03 03:42:02.047 UTC | 2020-06-27 17:24:51.337 UTC | null | 63,550 | thaiyoshi | 1,227,001 | null | 1 | 586 | django|url|rest | 778,102 | <p>When a URL is like <code>domain/search/?q=haha</code>, you would use <code>request.GET.get('q', '')</code>.</p>
<p><code>q</code> is the parameter you want, and <code>''</code> is the default value if <code>q</code> isn't found.</p>
<p>However, if you are instead just configuring your <code>URLconf</code>**, then your captures from the <code>regex</code> are passed to the function as arguments (or named arguments).</p>
<p>Such as:</p>
<pre><code>(r'^user/(?P<username>\w{0,50})/$', views.profile_page,),
</code></pre>
<p>Then in your <code>views.py</code> you would have</p>
<pre><code>def profile_page(request, username):
# Rest of the method
</code></pre> |
44,905 | C# switch statement limitations - why? | <p>When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.</p>
<p>For example (and yes, I know, if you're doing this sort of thing it probably means your <a href="https://en.wikipedia.org/wiki/Object-oriented_programming" rel="noreferrer">object-oriented</a> (OO) architecture is iffy - this is just a contrived example!),</p>
<pre><code> Type t = typeof(int);
switch (t) {
case typeof(int):
Console.WriteLine("int!");
break;
case typeof(string):
Console.WriteLine("string!");
break;
default:
Console.WriteLine("unknown!");
break;
}
</code></pre>
<p>Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.</p>
<p>Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement <em>has</em> to succumb to static analysis only, and why the value being switched on has to be integral (that is, primitive). What is the justification?</p> | 44,921 | 17 | 3 | null | 2008-09-04 22:34:47.03 UTC | 35 | 2022-07-10 13:49:53.56 UTC | 2014-12-17 19:27:28.463 UTC | ecleel | -1 | kronoz | 3,394 | null | 1 | 149 | c#|switch-statement | 118,782 | <p>This is my original post, which sparked some debate... <strong>because it is wrong</strong>:</p>
<blockquote>
<p>The switch statement is not the same
thing as a big if-else statement.
Each case must be unique and evaluated
statically. The switch statement does
a constant time branch regardless of
how many cases you have. The if-else
statement evaluates each condition
until it finds one that is true.</p>
</blockquote>
<hr>
<p>In fact, the C# switch statement is <strong>not</strong> always a constant time branch.</p>
<p>In some cases the compiler will use a CIL switch statement which is indeed a constant time branch using a jump table. However, in sparse cases as pointed out by <a href="https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why#48259">Ivan Hamilton</a> the compiler may generate something else entirely.</p>
<p>This is actually quite easy to verify by writing various C# switch statements, some sparse, some dense, and looking at the resulting CIL with the ildasm.exe tool.</p> |
211,041 | Do you use Javadoc for every method you write? | <p>Should I be writing Doc Comments for all of my java methods? </p> | 211,060 | 19 | 1 | null | 2008-10-17 04:04:20.857 UTC | 15 | 2016-10-19 15:25:25.75 UTC | 2008-10-17 04:16:18.057 UTC | Alan | 17,205 | mawaldne | 24,717 | null | 1 | 52 | java|api|javadoc | 50,985 | <p>@Claudiu</p>
<blockquote>
<p>When I write code that others will use - Yes. Every method that somebody else can use (any public method) should have a javadoc at least stating its obvious purpose.</p>
</blockquote>
<p>@Daniel Spiewak</p>
<blockquote>
<p>I thoroughly document every public method in every API class. Classes which have public members but which are not intended for external consumption are prominently marked in the class javadoc. I also document every protected method in every API class, though to a lesser extent. This goes on the idea that any developer who is extending an API class will already have a fair concept of what's going on.</p>
<p>Finally, I will occasionally document private and package private methods for my own benefit. Any method or field that I think needs some explanation in its usage will receive documentation, regardless of its visibility.</p>
</blockquote>
<p>@Paul de Vrieze</p>
<blockquote>
<p>For things, like trivial getters and setters, share the comment between then and describe the purpose of the property, not of the getter/setter</p>
</blockquote>
<pre><code>/**
* Get the current value of the foo property.
* The foo property controls the initial guess used by the bla algorithm in
* {@link #bla}
* @return The initial guess used by {@link #bla}
*/
int getFoo() {
return foo;
}
</code></pre>
<p>And yes, this is more work.</p>
<p>@VonC</p>
<p>When you break a huge complex method (because of <a href="https://stackoverflow.com/questions/105852/conditional-logging-with-minimal-cyclomatic-complexity">high cyclomatic complexity</a> reason) into:</p>
<ul>
<li>one public method calling</li>
<li>several private methods which represent internal steps of the public one</li>
</ul>
<p>, it is very useful to javadoc the private methods as well, even though that documentation will not be visible in the javadoc API files.<br />
Still, it allows you to remember more easily the precise nature of the different steps of your complex algorithm.</p>
<p>And remember: <strong><a href="https://stackoverflow.com/questions/61604">limit values or boundary conditions</a></strong> should be part of your javadoc as well.</p>
<p>Plus, <em><strong>javadoc is way better than simple "//comment"</strong></em>:</p>
<ul>
<li>It is recognized by IDE and used to display a pop-up when you move your cursor on top of one of your - javadoc-ed - function. For instance, a <em>constant</em> - that is private static final variable -, should have a javadoc, especially when its value is not trivial. Case in point: <em><strong>regexp</strong></em> (its javadoc should includes the regexp in its non-escaped form, what is purpose is and a literal example matched by the regexp)</li>
<li>It can be parsed by external tools (like <a href="http://xdoclet.sourceforge.net/xdoclet/index.html" rel="noreferrer">xdoclet</a>)</li>
</ul>
<p>@Domci</p>
<blockquote>
<p>For me, if somebody will see it or not doesn't matter - it's not likely I'll know what some obscure piece of code I wrote does after a couple of months. [...]<br />
In short, comment logic, not syntax, and do it only once, on a proper place.</p>
</blockquote>
<p>@Miguel Ping</p>
<blockquote>
<p>In order to comment something, you have to understand it first. When you trying to comment a function, you are actually thinking of what the method/function/class does, and this makes you be more specific and clear in your javadoc, which in turn makes you write more clear and concise code, which is good.</p>
</blockquote> |
458,304 | How can I programmatically determine if my app is running in the iphone simulator? | <p>As the question states, I would mainly like to know whether or not my code is running in the simulator, but would also be interested in knowing the specific iphone version that is running or being simulated.</p>
<p>EDIT: I added the word 'programmatically' to the question name. The point of my question is to be able to dynamically include / exclude code depending on which version / simulator is running, so I'd really be looking for something like a pre-processor directive that can provide me this info.</p> | 458,388 | 21 | 2 | null | 2009-01-19 16:55:32.907 UTC | 72 | 2020-09-21 18:24:27.427 UTC | 2018-08-08 13:10:23.07 UTC | lostInTransit | 4,850,561 | Jeffrey Meyer | 2,323 | null | 1 | 287 | ios|objective-c|swift|xcode|ios-simulator | 127,078 | <p>Already asked, but with a very different title.</p>
<p><a href="https://stackoverflow.com/questions/146986/what-defines-are-setup-by-xcode-when-compiling-for-iphone">What #defines are set up by Xcode when compiling for iPhone</a></p>
<p>I'll repeat my answer from there:</p>
<p>It's in the SDK docs under "Compiling source code conditionally"</p>
<p>The relevant definition is TARGET_OS_SIMULATOR, which is defined in /usr/include/TargetConditionals.h within the iOS framework. On earlier versions of the toolchain, you had to write:</p>
<pre><code>#include "TargetConditionals.h"
</code></pre>
<p>but this is no longer necessary on the current (Xcode 6/iOS8) toolchain.</p>
<p>So, for example, if you want to check that you are running on device, you should do</p>
<pre><code>#if TARGET_OS_SIMULATOR
// Simulator-specific code
#else
// Device-specific code
#endif
</code></pre>
<p>depending on which is appropriate for your use-case.</p> |
885,009 | R cannot be resolved - Android error | <p>I just downloaded and installed the new Android SDK. I wanted to create a simple application to test drive it.</p>
<p>The wizard created this code:</p>
<pre><code>package eu.mauriziopz.gps;
import android.app.Activity;
import android.os.Bundle;
public class ggps extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
</code></pre>
<p>but <a href="http://en.wikipedia.org/wiki/Eclipse_%28software%29" rel="noreferrer">Eclipse</a> gives me the error</p>
<blockquote>
<p>R cannot be resolved</p>
</blockquote>
<p>on line</p>
<pre><code>setContentView(R.layout.main);
</code></pre>
<p>Why?</p>
<p>PS: I do have an XML file named <code>main.xml</code> under <code>res/layout/</code>.</p> | 886,494 | 108 | 5 | 2011-09-22 11:22:43.243 UTC | 2009-05-19 21:02:20.117 UTC | 195 | 2020-03-18 14:32:54.06 UTC | 2016-06-16 08:41:03.43 UTC | null | 2,252,113 | null | 61,996 | null | 1 | 1,124 | android|eclipse|compiler-errors|android-resources|android-sdk-tools | 902,918 | <p>What Will said was right</p>
<blockquote>
<p>R is an automatically generated class that holds the constants used to identify your >resources. If you don't have an R.java file (it would be gen/eu.mauriziopz.gps/R.java in >Eclipse with the 1.5 SDK) I would recommend closing and reopening your project or going to >Project > Build all (and selecting "Build Automatically" while there as recommended by >Josef). If that doesn't work than try making a new project, if the problem is recreated than >post here again and we'll go into more detail.</p>
</blockquote>
<p>but I've found out that there was another problem that was causing the first one. The tools in the SDK directory didn't have the permissions to be executed, so it was like the didn't exist for Eclipse, thus it didn't build the <code>R.java</code> file.</p>
<p>So modifying the permission and selecting "Build Automatically" solved the problem.</p> |
6,335,563 | Self-reference for cell, column and row in worksheet functions | <p>In a worksheet function in Excel, how do you self-reference the cell, column or row you're in?</p> | 13,188,362 | 9 | 1 | null | 2011-06-13 19:54:21.427 UTC | 9 | 2020-08-18 23:05:06.66 UTC | 2020-08-18 23:05:06.66 UTC | null | 13,295 | null | 13,295 | null | 1 | 25 | excel|worksheet-function|self-reference | 182,890 | <p>where F13 is the cell you need to reference:</p>
<pre><code>=CELL("Row",F13) yields 13; its row number
=CELL("Col",F13) yields 6; its column number;
=SUBSTITUTE(ADDRESS(1,COLUMN(F13)*1,4),"1","") yields F; its column letter
</code></pre> |
6,394,762 | How do I set up SSH access for an Amazon EC2 instance? | <p>I need SSH access to an Amazon EC2 instance running Ubuntu 10.4. All I have is the Amazon username and password. Any ideas?</p> | 6,407,649 | 13 | 1 | null | 2011-06-18 08:17:37.703 UTC | 39 | 2019-06-23 14:42:26.283 UTC | 2019-06-23 14:42:26.283 UTC | null | 964,243 | null | 671,639 | null | 1 | 90 | ubuntu|amazon-ec2|ubuntu-10.04 | 100,149 | <p>Basically, you need a private-key file to login into your EC2 via SSH. Follow these steps to create one:</p>
<ul>
<li>Go <a href="https://console.aws.amazon.com/ec2/home">https://console.aws.amazon.com/ec2/home</a> & sign in to your existing Amazon account.</li>
<li>Click on "Key Pairs" on LHS or <a href="https://console.aws.amazon.com/ec2/home?region=us-east-1#s=KeyPairs">https://console.aws.amazon.com/ec2/home?region=us-east-1#s=KeyPairs</a>.
<ul>
<li>You should see the list of KEYs generated by you (or during EC2 creation process).</li>
<li>Click on "Create Key Pair" if you don't see any or you lost your private-key.</li>
<li>Enter a unique name and hit enter.</li>
<li>A download panel will appear for you to save the private-key, save it.</li>
<li>Keep it somewhere with the file permission "0600"</li>
</ul></li>
<li>Click on "Instances" on LHS or <a href="https://console.aws.amazon.com/ec2/home?region=us-east-1#s=Instances">https://console.aws.amazon.com/ec2/home?region=us-east-1#s=Instances</a>
<ul>
<li>You should see the list of ec2-instances, if you don't see any, then please create one.</li>
<li>Click on the EC2 machine and note down the Public DNS address.</li>
</ul></li>
<li>Open your Terminal (in Linux) and type the following command
<ul>
<li><code>ssh -i /path/to/private-key root@<ec2-public-dns-address></code> - the root username has been avoided in the latest releases, based on your distribution select <code>ec2-user</code> or <code>ubuntu</code> as your username.</li>
<li>hit Enter</li>
<li>That's it.</li>
</ul></li>
</ul> |
38,477,720 | Remove index.php from url in CodeIgniter 3 | <p>I am doing a project in CodeIgniter 3. I need to remove <code>index.php</code> from url. For that help me to get <code>.htaccess</code> file for CodeIgniter 3 and also where to place this file.</p>
<p>This is my baseurl</p>
<pre><code>http://cableandmedia.com/demo/
</code></pre> | 38,477,932 | 7 | 2 | null | 2016-07-20 09:42:45.96 UTC | 10 | 2022-09-04 15:12:09.993 UTC | 2016-07-20 16:36:32.483 UTC | null | 594,235 | null | 6,294,033 | null | 1 | 8 | php|.htaccess|codeigniter|codeigniter-3 | 56,957 | <p>Update your htaccess file with the below code</p>
<pre><code>RewriteEngine On
RewriteBase /demo
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</code></pre>
<p>and in config file, please change base url with below code:-</p>
<pre><code>$root = "http://".$_SERVER['HTTP_HOST'];
$root .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
$config['base_url'] = $root;
</code></pre> |
15,900,387 | How to stop all runnable thread in java executor class? | <pre><code>final ExecutorService executor = Executors.newFixedThreadPool(1);
final Future<?> future = executor.submit(myRunnable);
executor.shutdown();
if(executor.awaitTermination(10, TimeUnit.SECONDS)) {
System.out.println("task completed");
}else{
System.out.println("Executor is shutdown now");
}
//MyRunnable method is defined as task which I want to execute in a different thread.
</code></pre>
<p>Here is <code>run</code> method of executor class:</p>
<pre><code>public void run() {
try {
Thread.sleep(20 * 1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
</code></pre>
<p>Here it is waiting for <code>20</code> second but when i run the code it throws an exception:</p>
<pre><code>java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
</code></pre>
<p>I am not able to close the concurrent thread ruining in <code>Java Executor class</code>. Here is my Code flow:</p>
<ul>
<li>Created a new Thread with Java executor class to run some task i.e written in <code>MyRunnable</code></li>
<li><code>executor</code> wait for 10 second to complete the tasks.</li>
<li>If the task has completed then runnable thread also got terminated.</li>
<li>If the task is not completed within 10 second then <code>executor</code> class should terminate the thread.</li>
</ul>
<p>Everything works fine except the termination of tasks in the last scenario. How should I do it? </p> | 15,900,500 | 2 | 1 | null | 2013-04-09 11:15:36.813 UTC | 6 | 2013-04-09 11:41:56.953 UTC | 2013-04-09 11:29:20.487 UTC | null | 834,239 | null | 834,239 | null | 1 | 17 | java|multithreading|executorservice | 65,447 | <p>The <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#shutdown%28%29" rel="noreferrer"><code>shutDown()</code></a> method simply prevents additional tasks from being scheduled. Instead, you could call <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#shutdownNow%28%29" rel="noreferrer"><code>shutDownNow()</code></a> and check for thread interruption in your <code>Runnable</code>.</p>
<pre><code>// in your Runnable...
if (Thread.interrupted()) {
// Executor has probably asked us to stop
}
</code></pre>
<p>An example, based on your code, might be:</p>
<pre><code>final ExecutorService executor = Executors.newFixedThreadPool(1);
executor.submit(new Runnable() {
public void run() {
try {
Thread.sleep(20 * 1000);
} catch (InterruptedException e) {
System.out.println("Interrupted, so exiting.");
}
}
});
if (executor.awaitTermination(10, TimeUnit.SECONDS)) {
System.out.println("task completed");
} else {
System.out.println("Forcing shutdown...");
executor.shutdownNow();
}
</code></pre> |
15,730,037 | Prevent output escaping in Twig function extension | <p>I have created a Twig extension:</p>
<pre><code>{{ image ("image.png", 200) }}
</code></pre>
<p>HI know I can just do</p>
<pre><code>{{ image ("image.png", 200)|raw }}
</code></pre>
<p>...but I would prefer to use PHP code so that everything (from this 'image' extension) is not escaped.</p>
<p>I can't see this possible.</p>
<p>I know I can prevent all output escaping in Twig, but I just want this one extension not to escape output, and everything else to do so.</p> | 15,730,279 | 4 | 0 | null | 2013-03-31 13:47:01.297 UTC | 4 | 2018-12-04 21:58:43.44 UTC | 2013-03-31 14:34:30.953 UTC | null | 569,101 | null | 2,143,356 | null | 1 | 29 | symfony|twig | 12,279 | <p>This can be done by adding <a href="http://twig.sensiolabs.org/doc/advanced.html#automatic-escaping">an option</a> at the extension registration.</p>
<pre class="lang-php prettyprint-override"><code>public function getFilters(){
return array(
// ...
'image' => new \Twig_Filter_Method($this, 'imageFilter',
array('is_safe' => array('html'))
),
// ...
);
}
</code></pre>
<p>This will provide unescaped input HTML and return unescaped HTML output. If you need to work with escaped HTML input, see the option <code>'pre_escaped' => 'html'</code>.</p> |
10,509,476 | How to clear console in Java - Eclipse SDK | <p>I've searched far and wide, but haven't found something that works...
There HAS to be a way!!! So, what I need is a code that clears the console in Eclipse (makes it blank). And NO, not printing 50 blank lines, CLEARING IT! </p>
<p>I found this: </p>
<pre><code>Import import java.io.Console;
public void ClearConsole() {
Console console = System.console();
if (console == null)
System.out.println("Couldn't get Console object !");
console.clear();
}
</code></pre>
<p>But it gives me an error: "<em>The method clear() is undefined for the type Console</em>"</p> | 10,510,969 | 2 | 4 | null | 2012-05-09 03:31:58.97 UTC | 5 | 2020-07-11 15:20:42.567 UTC | 2020-07-08 23:11:06.71 UTC | null | 8,422,953 | null | 1,378,968 | null | 1 | 23 | java | 90,665 | <p>In Eclipse tool you can clear the console panel by <em>right clicking</em> + <em>clear</em> but not in Java.</p>
<p>Console is a log tool, it cannot be cleared for administration security.</p> |
31,853,699 | MSHTML DLL on Windows 10 | <p>I have a C# solution that makes use of <a href="https://smithhtmleditor.codeplex.com/">Smith Html Editor</a> (I'm developing on the main project which uses this, so I don't know much about this library), which makes a reference to MSHTML. This worked fine until my upgrade to Windows 10 and it can't find MSHTML anymore. I can directly reference the DLL on the GAC folder, and it stops complaining and thus builds, but it's getting some runtime errors related to the editor not instantiating.</p>
<p>After a little research, it turns out that MSHTML is phased out of Windows 10 as it now uses EdgeHTML. Does anyone have any idea how I can go around this? </p>
<p>The solution still works for Windows 7.</p> | 38,871,078 | 8 | 4 | null | 2015-08-06 10:43:25.98 UTC | 9 | 2019-07-12 10:31:25.853 UTC | null | null | null | null | 1,685,167 | null | 1 | 33 | c#|wpf|windows-10|mshtml|microsoft-edge | 28,446 | <p>I just created a <a href="http://techninotes.blogspot.com/2016/08/fixing-cannot-find-wrapper-assembly-for.html">blog post</a> on this issue. The problem is that the Microsoft.mshtml.dll assembly in the Global Assembly Cache becomes unregistered from ActiveX during the upgrade process. To fix this issue, it is necessary to run "regasm" on the assembly:</p>
<ol>
<li>Open an instance of "Developer Command Prompt for VS2013" (or whatever version of Visual Studio you happen to be using). Run it as Administrator by right-clicking the icon and selecting, "Run as Administrator."</li>
<li>Navigate to "C:\Windows\assembly\GAC\Microsoft.mshtml\7.0.3300.0__b03f5f7f11d50a3a." It is possible your path will vary. To verify, go to "C:\Windows\assembly\GAC\Microsoft.mshtml" and type "dir."</li>
<li>Once you are in the correct path, type <code>regasm Microsoft.mshtml.dll</code></li>
</ol> |
10,382,929 | How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version | <p>I am trying to use <a href="http://en.wikipedia.org/wiki/Notepad%2B%2B" rel="noreferrer">Notepad++</a> as my all-in-one tool edit, run, compile, etc.</p>
<p>I have <a href="http://en.wikipedia.org/wiki/Java_Virtual_Machine#Execution_environment" rel="noreferrer">JRE</a> installed, and I have setup my path variable to the <code>.../bin</code> directory.</p>
<p>When I run my "Hello world" in Notepad++, I get this message:</p>
<pre class="lang-none prettyprint-override"><code>java.lang.UnsupportedClassVersionError: test_hello_world :
Unsupported major.minor version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(Unknown Source)
.........................................
</code></pre>
<p>I think the problem here is about versions; some versions of Java may be old or too new.</p>
<ol>
<li>How do I fix it?</li>
<li>Should I install the JDK, and setup my path variable to the JDK instead of JRE?</li>
<li>What is the difference between the <code>PATH</code> variable in JRE or JDK?</li>
</ol> | 11,432,195 | 50 | 10 | null | 2012-04-30 11:28:24.877 UTC | 408 | 2022-08-07 12:33:20.56 UTC | 2019-03-23 06:42:00.063 UTC | null | 2,361,308 | null | 898,042 | null | 1 | 1,686 | java|jvm|incompatibility|unsupported-class-version | 2,119,681 | <p>The version number shown describes the version of the JRE the class file is compatible with.</p>
<p>The reported major numbers are:</p>
<pre class="lang-none prettyprint-override"><code>Java SE 18 = 62,
Java SE 17 = 61,
Java SE 16 = 60,
Java SE 15 = 59,
Java SE 14 = 58,
Java SE 13 = 57,
Java SE 12 = 56,
Java SE 11 = 55,
Java SE 10 = 54,
Java SE 9 = 53,
Java SE 8 = 52,
Java SE 7 = 51,
Java SE 6.0 = 50,
Java SE 5.0 = 49,
JDK 1.4 = 48,
JDK 1.3 = 47,
JDK 1.2 = 46,
JDK 1.1 = 45
</code></pre>
<p>(Source: <a href="https://en.wikipedia.org/wiki/Java_class_file#General_layout" rel="nofollow noreferrer">Wikipedia</a>)</p>
<p>To fix the actual problem you should try to either run the Java code with a newer version of Java JRE or specify the target parameter to the Java compiler to instruct the compiler to create code compatible with earlier Java versions.</p>
<p>For example, in order to generate class files compatible with Java 1.4, use the following command line:</p>
<pre class="lang-none prettyprint-override"><code>javac -target 1.4 HelloWorld.java
</code></pre>
<p>With newer versions of the Java compiler you are likely to get a warning about the bootstrap class path not being set. More information about this error is available in a blog post <em><a href="https://blogs.oracle.com/darcy/entry/bootclasspath_older_source" rel="nofollow noreferrer">New javac warning for setting an older source without bootclasspath</a></em>.</p> |
37,768,819 | How do I edit the response of a form submission in Google Forms/Sheets? | <p>Recently, I've been conducting a survey. I began creating it in Excel Forms Online but switched to Google Forms after I realized several of its shortcomings. I hit a few snags but I thought I was all set to go.</p>
<p>Unfortunately, I began adding questions to the form and changing responses (misspellings, etc...) and this began causing a whole bunch of problems. It's enough that I have to go back and ask users for their responses to new questions if applicable. What's worse is I can't modify a submission at all. I can't edit the spreadsheet connected to the form because results are stored in the form. If I regenerate the spreadsheet, then the response submitted in the form replaces whatever was there before. So I can't edit the spreadsheet at all.</p>
<p>I've been looking into a way to try to manually edit a user's submitted response. I found a resource <a href="https://stackoverflow.com/questions/10710354/how-to-add-edit-response-link-to-google-forms-emails">here on Stack Overflow</a>, and <a href="https://productforums.google.com/forum/#!topic/docs/LSKKCR3VHC8" rel="noreferrer">here on Google Groups at the Products Forum</a>, but unfortunately, I tried all of the examples and none of them worked (yes, I put my form's URL in and everything and replaced the name with the spreadsheet name).</p>
<p>The error I continued receiving after I filled in my info was <code>TypeError: Cannot call method "getDataRange" of null. (line 8, file "Code")</code>. But the sheet is not empty and I know that.</p>
<p>Is there some other way to make this work, or a better way to potentially edit sheet responses?</p>
<p>The only way to do this right now is to <em>manually</em> go back and re-submit the form again <em>as that user</em>. It's kind of a pain because it's 10 minutes of checking boxes and copying and pasting. Plus, last night I accidentally skipped copying 1 character and now I'd have to do it all over again.</p>
<p>From what I've seen online, this can be done, but nothing I have tried works. The form is currently live and accepting responses right now. Any solution is acceptable as long as there would be a way to edit their responses, either with a script or some other tool, so I don't need to manually re-do everything myself.</p> | 42,211,883 | 1 | 6 | null | 2016-06-11 21:52:35.533 UTC | 7 | 2021-06-22 21:25:58.287 UTC | 2018-07-29 22:07:21.7 UTC | null | 6,110,631 | null | 6,110,631 | null | 1 | 16 | google-apps-script|google-sheets|google-forms|editing | 56,410 | <p>The <a href="https://stackoverflow.com/a/21818349/26510">code suggested here</a> works, as I just tried it myself on Feb 13, 2017.</p>
<h3>Here are the steps I followed to get this to work</h3>
<ul>
<li>First, load your form as if you were going to edit the form.</li>
<li>Look for the "form id" for your form in the url in the address bar. It should look something like this:</li>
</ul>
<blockquote>
<p><a href="https://docs.google.com/" rel="noreferrer">https://docs.google.com/</a>...
/forms/d/<strong>1ZIrWiRZQrUsz1y8OBoeB7AtCOM4Ax4FxAQm8xAR1OYo</strong>/edit</p>
</blockquote>
<ul>
<li>So the id in this example would've been "1ZIrWiRZQrUsz1y8OBoeB7AtCOM4Ax4FxAQm8xAR1OYo"</li>
<li>Now go to <a href="https://script.google.com" rel="noreferrer">https://script.google.com</a></li>
<li><p>Replace all the text that shows up in the <code>Code.js</code> section with the following, AFTER you've edited it and put your form id in place of YOUR_FORM_ID_HERE below. </p>
<pre><code>function dumpEditResponseUrlsForYourForm() {
// Change this next line to use the id of your form
var myFormId = "YOUR_FORM_ID_HERE";
var form = FormApp.openById(myFormId);
var formResponses = form.getResponses();
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
Logger.log(formResponse.getEditResponseUrl());
}
}
</code></pre></li>
<li>Click "View | Logs" in the Google Script web page. It'll pop up a window with links to your form responses.</li>
</ul> |
53,273,146 | Python pyodbc connect to Sql Server using SQL Server Authentication | <p>The window user details is different from the Sql Server user I log in. So I had tried to use pyodbc connect to the database using the username(Admin_JJack) and password. But the connection show fails for the Window User(Jack) and I don't know where goes wrong.</p>
<p>my connection string :</p>
<pre><code>connection = pyodbc.connect(
"Driver={"SQL Driver"};"
"Server= "ServerName";"
"Database="DatabaseName";"
"UID="UserName";"
"PWD="Password";"
"Trusted_Connection=yes"
)
</code></pre>
<blockquote>
<p>pyodbc.InterfaceError: ('28000', "[28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user 'Jack'. (18456) (SQLDriverConnect);</p>
</blockquote>
<p>How to connect to the database using sql server authentication ?</p> | 53,273,577 | 3 | 4 | null | 2018-11-13 02:58:57.657 UTC | 1 | 2021-12-01 03:33:45.873 UTC | 2018-11-13 03:18:31.38 UTC | null | 4,647,377 | null | 4,647,377 | null | 1 | 4 | python|sql-server|pyodbc|sql-server-authentication | 45,731 | <p>When you use "Trusted_Connection=yes" both the UID and PWD keys are ignored and the Windows account is used for authentication. </p>
<p>If you want to use the UID and PWD values for authentication instead of the Windows NTLM account you must use "Trusted_Connection=No" or remove this option from the connection string.</p>
<blockquote>
<p><strong>Trusted_Connection</strong></p>
<p>Specifies whether a user connects through a user account by using
either Kerberos [RFC4120] or another platform-specific authentication
as specified by the fIntSecurity field (for details, see [MS-TDS]
section 2.2.6.4).</p>
<p>The valid values are "Yes", "1", or empty string, which are
equivalent, or "No". If the value "No" is not specified, the value
"Yes" is used.</p>
<p>If the value is "No", the UID and PWD keys have to be used to
establish a connection with the data source.</p>
<p>If the DSN key and the UID key are not included in the connection
string or if the value of the UID key is an empty string, the value of
the Trusted_Connection key has to be "Yes". If the Trusted_Connection
key is not specified in the connection string, the value has to be
obtained from the contents of the settings in the DSN key. If the
Trusted_Connection key is not specified in DSN or if the given DSN
does not exist, the default value is "No".</p>
<p>If the value of the Trusted_Connection key is "Yes", both the UID and
PWD keys are ignored. Otherwise, the UID key has to be specified.</p>
<p>In Microsoft implementations, this user account is a Windows user
account and NTLM authentication [MSDN-NTLM] is used when the value of
the Trusted_Connection key is "Yes".</p>
</blockquote>
<p>source: <a href="https://msdn.microsoft.com/en-us/library/ee224059(v=sql.105).aspx#Appendix_A_2" rel="noreferrer">https://msdn.microsoft.com/</a></p> |
22,806,784 | Why is it impossible to implement a generic interface multiple times with different type parameters? | <p>I have an interface:</p>
<pre><code>public static interface Consumer<T> {
void consume(T t);
}
</code></pre>
<p>And I want to be able to have:</p>
<pre><code>public static class Foo implements Consumer<String>, Consumer<Integer> {
public void consume(String t) {..}
public void consume(Integer i) {..}
}
</code></pre>
<p>It doesn't work - the compiler doesn't let you implement the same interface twice.</p>
<p>The question is: <strong>Why?</strong></p>
<p>People have asked similar questions here, but the answer was always "type erasure", i.e. you cannot do it because the types are erased at runtime.</p>
<p>And they aren't - some types are retained at runtime. And they are retained in this particular case:</p>
<pre><code>public static void main(String[] args) throws Exception {
ParameterizedType type = (ParameterizedType) Foo.class.getGenericInterfaces()[0];
System.out.println(type.getActualTypeArguments()[0]);
}
</code></pre>
<p>This prints <code>class java.lang.String</code> (if I only keep <code>Consumer<String></code> in order to compile)</p>
<p>So, erasure, in its simplest explanation, is not the reason, or at least it needs elaboration - the type is there, and also, you don't care about the type resolution, because you already have two methods with distinct signature. Or at least it seems so.</p> | 22,807,212 | 2 | 3 | null | 2014-04-02 09:18:02.503 UTC | 12 | 2014-04-02 10:03:34.527 UTC | null | null | null | null | 203,907 | null | 1 | 30 | java|generics | 2,016 | <p>The answer is still "type erasure", but it's not that simple. The keywords are: <strong>raw types</strong></p>
<p>Imagine the following:</p>
<pre><code>Consumer c = new Foo();
c.consume(1);
</code></pre>
<p>What would that do? It appears that <code>consume(String s)</code> is not actually <code>consume(String s)</code> - it is still <code>consume(Object o)</code>, even though it is defined to take <code>String</code>.</p>
<p>So, the above code is ambiguous - the runtime can't know which of the two <code>consume(..)</code> methods to invoke.</p>
<p>A funny follow-up example is to remove <code>Consumer<Integer></code>, but keep the <code>consume(Integer i)</code> method. Then invoking the <code>c.consume(1)</code> on a raw <code>Consumer</code>. throws <code>ClassCastException</code> - unable to cast from Integer to String. The curious thing about this exception is that it happens on <em>line 1</em>.</p>
<p>The reason is the use of <a href="http://docs.oracle.com/javase/tutorial/java/generics/bridgeMethods.html#bridgeMethods" rel="noreferrer">bridge methods</a>. The compiler generates the bridge method:</p>
<pre><code>public void consume(Object o) {
consume((String) o);
}
</code></pre>
<p>The generated bytecode is:</p>
<pre><code>public void consume(java.lang.String);
public void consume(java.lang.Integer);
public void consume(java.lang.Object);
Code:
0: aload_0
1: aload_1
2: checkcast #39 // class java/lang/String
5: invokevirtual #41 // Method consume:(Ljava/lang/String;)V
</code></pre>
<p>So even if the methods you have defined keep their signatures, each of them has a corresponding bridge method that is actually invoked when working with the class (regardless whether it's raw or parameterized).</p> |
13,247,848 | Is this possible to clear the session whenever browser closed in asp.net? | <p>In my asp.net application, i want to clear the session whenever my browser closed or my tab (if my browser containing multiple tabs)closed.</p>
<p>Please guide me to get out of this issue...</p> | 13,247,947 | 7 | 0 | null | 2012-11-06 09:15:22.483 UTC | 3 | 2017-05-23 10:22:44.387 UTC | 2012-11-06 09:18:49.457 UTC | null | 64,976 | null | 452,680 | null | 1 | 7 | c#|asp.net|session | 48,998 | <p>Short version, No.
There's no solid way of a server detecting if the client has closed their browser. It's just the nature of web development's asynchronous pattern.</p>
<p>Long version, if it's really, really important to you;
Put a bit of javascript in the page that sends a regular post to your website in the background and set up a serverside agent or service that disposes of the sessions if it doesnt receive these regular "heartbeat" signals.</p>
<p>You can put a javascript postback onto the page's unload() event but dont rely on it, it doesnt always fire.</p> |
13,404,337 | How to get list of users from LDAP directory using PHP? | <pre><code>$ldaphost = "my_host_name";
$ds=ldap_connect($ldaphost) or die("Could not connect to $ldaphost");
ldap_set_option ($ds, LDAP_OPT_REFERRALS, 0);
ldap_set_option ($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
if ($ds)
{
$basedn = 'my_dc_string';
$samaccountname = 'my_user_name';
$filters = "(samaccountname={$samaccountname})";
$result = ldap_search($ds, $basedn, $filters);
}
</code></pre>
<p>How do I get the list of all users from LDAP using PHP? The above code fails on the ldap_search function giving this warning</p>
<p>"Warning: ldap_search(): Search: Operations error"</p>
<p>my username, ldaphost etc are correct. I am not sure about the filters though.</p> | 13,404,617 | 2 | 0 | null | 2012-11-15 19:02:48.153 UTC | 12 | 2017-06-14 21:12:12.963 UTC | null | null | null | user187809 | null | null | 1 | 11 | php|ldap | 58,005 | <pre><code>/**
* Get a list of users from Active Directory.
*/
$ldap_password = 'PASSWORD';
$ldap_username = 'USERNAME@DOMAIN';
$ldap_connection = ldap_connect(HOSTNAME);
if (FALSE === $ldap_connection){
// Uh-oh, something is wrong...
}
// We have to set this option for the version of Active Directory we are using.
ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3) or die('Unable to set LDAP protocol version');
ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0); // We need this for doing an LDAP search.
if (TRUE === ldap_bind($ldap_connection, $ldap_username, $ldap_password)){
$ldap_base_dn = 'DC=XXXX,DC=XXXX';
$search_filter = '(&(objectCategory=person)(samaccountname=*))';
$attributes = array();
$attributes[] = 'givenname';
$attributes[] = 'mail';
$attributes[] = 'samaccountname';
$attributes[] = 'sn';
$result = ldap_search($ldap_connection, $ldap_base_dn, $search_filter, $attributes);
if (FALSE !== $result){
$entries = ldap_get_entries($ldap_connection, $result);
for ($x=0; $x<$entries['count']; $x++){
if (!empty($entries[$x]['givenname'][0]) &&
!empty($entries[$x]['mail'][0]) &&
!empty($entries[$x]['samaccountname'][0]) &&
!empty($entries[$x]['sn'][0]) &&
'Shop' !== $entries[$x]['sn'][0] &&
'Account' !== $entries[$x]['sn'][0]){
$ad_users[strtoupper(trim($entries[$x]['samaccountname'][0]))] = array('email' => strtolower(trim($entries[$x]['mail'][0])),'first_name' => trim($entries[$x]['givenname'][0]),'last_name' => trim($entries[$x]['sn'][0]));
}
}
}
ldap_unbind($ldap_connection); // Clean up after ourselves.
}
$message .= "Retrieved ". count($ad_users) ." Active Directory users\n";
</code></pre> |
13,266,192 | Accessing iframe from chrome extension | <p>I'm developing a chrome extension and bumped into a big problem.</p>
<p>I'm using content scripts to inject my javascript code on a web site. The web site has an iframe.
I can change the source code of the iframe but don't seem to get any access to the iframe's contentWindow property. I need it to insert text at the current carret position.</p>
<p>So basically this code works perfectly in the context of the page:</p>
<pre><code>$("#iframe1").contentWindow.document.execCommand("InsertHTML", false, 'test text');
</code></pre>
<p>But when I try it to run in the context of my chrome extension I get this error:</p>
<pre><code>TypeError: Cannot read property 'document' of undefined
</code></pre>
<p>What's strange is that I can access the html of the iframe. So this code works perfectly from the chrome extension:</p>
<pre><code>$("#iframe1").contents().find('div').html('test')
</code></pre>
<p>I tried putting "all_frames": true in the manifest file but no luck :(</p> | 13,271,692 | 1 | 2 | null | 2012-11-07 08:55:35.773 UTC | 12 | 2013-03-02 13:15:57.56 UTC | null | null | null | null | 1,796,666 | null | 1 | 17 | javascript|iframe|google-chrome-extension | 22,993 | <p>To understand why your code does not work, I include <a href="https://stackoverflow.com/questions/11812786/window-open-returns-undefined-in-chrome-extension/11815581#11815581">a fragment of my previous answer</a>:</p>
<blockquote>
<p>Content scripts do not have any access to a page's global <code>window</code> object. For content scripts, the following applies:</p>
<ul>
<li>The <strong><code>window</code></strong> variable does not refer to the page's global object. Instead, it refers to a new context, a "layer" over the page. The page's DOM is fully accessible. <sup><a href="http://code.google.com/chrome/extensions/content_scripts.html#execution-environment" rel="noreferrer">#execution-environment</a></sup></li>
</ul>
<p>Given a document consisting of   <code><iframe id="frameName" src="http://domain/"></iframe></code>:</p>
<ul>
<li>Access to the contents of a frame is restricted by the <a href="https://developer.mozilla.org/En/Same_origin_policy_for_JavaScript" rel="noreferrer">Same origin policy</a> of the page; the permissions of your extension does not relax the policy.</li>
<li><code>frames[0]</code> and <code>frames['frameName']</code>, (normally referring to the the frame's containing global <code>window</code> object) is <strong><code>undefined</code></strong>.</li>
<li><code>var iframe = document.getElementById('frameName');</code>
<ul>
<li><strong><code>iframe.contentDocument</code></strong> returns a <strong><code>document</code></strong> object of the containing frame, because content scripts have access to the DOM of a page. This property is <strong><code>null</code></strong> when the Same origin policy applies.</li>
<li><strong><code>iframe.contentDocument.defaultView</code></strong> (refers to the <code>window</code> object associated with the document) is <strong>undefined</strong>.</li>
<li><strong><code>iframe.contentWindow</code></strong> is <strong>undefined</strong>.</li>
</ul></li>
</ul>
</blockquote>
<h3>Solution for same-origin frames</h3>
<p>In your case, either of the following will work:</p>
<pre><code>// jQuery:
$("#iframe1").contents()[0].execCommand( ... );
// VanillaJS
document.getElementById("iframe1").contentDocument.execCommand( ... );
// "Unlock" contentWindow property by injecting code in context of page
var s = document.createElement('script');
s.textContent = 'document.getElementById("iframe1").contentWindow.document.execCommand( ... );';
document.head.appendChild(s);
</code></pre>
<h2>Generic solution</h2>
<p>The generic solution is using <code>"all_frames": true</code> in the manifest file, and use something like this:</p>
<pre><code>if (window != top) {
parent.postMessage({fromExtension:true}, '*');
addEventListener('message', function(event) {
if (event.data && event.data.inserHTML) {
document.execCommand('insertHTML', false, event.data.insertHTML);
}
});
} else {
var test_html = 'test string';
// Explanation of injection at https://stackoverflow.com/a/9517879/938089 :
// Run code in the context of the page, so that the `contentWindow`
// property becomes accessible
var script = document.createElement('script');
script.textContent = '(' + function(s_html) {
addEventListener('message', function(event) {
if (event.data.fromExtension === true) {
var iframe = document.getElementById('iframe1');
if (iframe && (iframe.contentWindow === event.source)) {
// Window recognised, post message back
iframe.contentWindow.postMessage({insertHTML: s_html}, '*');
}
}
});
} + ')(' + JSON.stringify(test_html) + ');';
(document.head||document.documentElement).appendChild(script);
script.parentNode.removeChild(script);
}
</code></pre>
<p>This demo is for educational purposes only, <strong>do not use this demo in a real extension</strong>. Why? Because it uses <a href="https://developer.mozilla.org/en-US/docs/DOM/window.postMessage" rel="noreferrer"><code>postMessage</code></a> to pass messages around. These events can also be generated by the client, which causes a security leak (XSS: arbitrary HTML injection).</p>
<p>The alternative to <code>postMessage</code> is Chrome's message API. For a demo, see <a href="https://stackoverflow.com/questions/11325415/access-iframe-content-from-a-chromes-extension-content-script/11326942#11326942">this answer</a>. You won't be able to compare the <code>window</code> objects though. What you <em>can</em> do is to rely the <code>window.name</code> property. The <code>window.name</code> property is automatically set to the value of the iframe's <code>name</code> attribute (just once, when the iframe is loaded).</p> |
13,264,847 | Xcode with iOS - Creating a library in a way that is easy to run in debug mode, distribute, iterate | <p>This is for Xcode 4.5.x iOS armv7 armv7s and the sim and specifcially about Xcode project setup / project build setup:</p>
<p>I have a project "A" that is an app in the app store.
I have a project "B" that is a library that will be used in A as a dependency, but also distributed as a 3rd-party library to other companies to use in their apps. (other companies' 3rd party apps are represented in this case as "Y").</p>
<p>Here are the requirements:</p>
<ul>
<li>Must be able to run "A" in debug mode, and of course debug the nested "B" project concurrently, in the same build/session.</li>
<li>From "A" I can CMD+Click on a method signature from "B" and jump right into that src file, where I'm free to edit and then recompile, as if it were from the same project.</li>
<li>A dev "X" at some other company must be able to easily drag our library "B" into his project "Y", where "B" is a static library with only the required header files exposed. "Y" of course calls methods from a subset of "B"'s actual header files. Only the files from this subset should be included in distribution for Dev "X".</li>
<li>Dev "X" should not need to modify anything at all in his Xcode project, just drag the folder for "B" (which contains the static lib and subset of header files) into his project and click "Copy resources, create references, etc".</li>
<li>I need to be able to generate the static library build of "B" easily, based on the same files I have been editing this whole time as I iterate and debug this project "B" inside of its dependent project "A".</li>
<li>"B" has no resources aside from source code -- there are no image assets, xibs, or anything like that.</li>
<li>From "B", I click "Archive" and Poof! there's a static lib (must be fat binary, by that I mean it works on the <strong>simulator + armv7 + armv7s</strong>, please!!) with the essential header files ready to be distributed.</li>
<li>All of this must be <strong>app store approval</strong>-friendly</li>
<li>Also this must be reliable. It's no good if I have to keep coming back to make a lot of config changes every time I add one file.</li>
</ul>
<p><strong>UPDATE:</strong><br>
<strong>*</strong> <em>MOST IMPORTANT</em><strong>: This needs to be a repo I can check out that is a full end-to-end template of what am looking for, and I need to be able to open up Xcode 4.5.2+ and click play and see this thing build, pain-free.</strong></p>
<p><strong>500 points</strong> to anyone who can provide me a template project that demonstrates everything I have described above, "A", "B", and "Y" (with "B" static lib used as a dep). All i need is a set of skeleton projects ("A", "B" (nested inside "A"), and "Y") that shows how this can be done. Please don't hold back the answer until the bounty is posted. If it meets my requirements, I'll make sure you get my bounty points.</p>
<p>I'm somewhat worried that with the limitations of Xcode that this is not even possible in a way that is not a complete hassle. Please prove me wrong.</p>
<p>UPDATE: I decided I don't care about armv6 anymore. Goodbye, armv6.
<strike>Extra credit if you can get armv6 rolled into the dist output along with armv7, armv7s, i386/simulator.</strike></p>
<p>P.S. I promise that I will be reasonable awarding the points. I'm not looking to withhold them on a technicality. If you make my life dramatically less painful in this one area, I will gladly award you the points.</p> | 13,290,461 | 3 | 0 | null | 2012-11-07 07:13:30.843 UTC | 18 | 2012-12-15 06:16:46.733 UTC | 2012-12-15 06:16:46.733 UTC | null | 192,819 | null | 192,819 | null | 1 | 21 | ios|xcode4|xcode4.5|xcodebuild | 4,135 | <p>This will not be possible in Xcode alone. You will need some build Scripts (which you can call from within Xcode of course) because of the compilation target switch (simulator, device, etc.).</p>
<p>I think you will have to add additional distribution headers to a "Copy files" build step at least. But other modifications should not be necessary if you change something.</p>
<p>I did something like this for libturbojpeg, see <a href="https://github.com/dunkelstern/libturbojpeg-ios" rel="nofollow">https://github.com/dunkelstern/libturbojpeg-ios</a> for reference. It currently puts a fat library into "lib" if you call the "build.sh" file from the terminal, but omits distribution headers. In the case of libturbojpeg I needed 2 project files because each target compiles a different subset of assembler files into the library (better do not look at the assembler makefile stuff). To compile you will need a recent version of NASM as the version apple ships is ancient (get it with brew). I will post a template for such a library build project on the same account shortly. (Will edit or comment if done here with appropriate links)</p>
<p>Basically it works like this:</p>
<ol>
<li>Create a build script that calls <code>xcodebuild</code> for each needed platform target</li>
<li>The Xcode library project has to contain a script to drop the built libraries in a directory the build script can find</li>
<li>Additional headers have to be copied by a "Copy files" target action</li>
<li>The build script has to merge all library builds with <code>lipo</code></li>
<li>Add the build script as "Run Script" target to your build, but be aware you do not create an infinite loop (or just call it from terminal for creating a release build)</li>
<li>In your main project add the library subproject</li>
</ol>
<p>You can then distribute the output dir with the copied header files and the <code>lipo</code> merged universal library and use the library normally as subproject in your workspace as you would do normally (it builds and links only the needed libs then, not the universal lib but that should be no problem)</p>
<p>This does not in fact solve the problem of creating DSYM files for the library. But normally the debugging symbols should be in the library itself when building a debug build. It will strip the debugging symbols on release build and you will have no DSYM then.</p>
<p>Link to example project: <a href="https://github.com/dunkelstern/StaticLibraryTemplate" rel="nofollow">https://github.com/dunkelstern/StaticLibraryTemplate</a></p> |
13,747,809 | Android EditText Gmail like to field | <p>I'm working at an app, and I'm trying to make a gmail like "To" field, which has blocks inside which cannot be edited once added, but just removed entirely (like in the attached image). If it can have an image too, that would be perfect.
<img src="https://i.stack.imgur.com/fpJZJ.png" alt="gmail "To" field"></p> | 13,748,105 | 2 | 6 | null | 2012-12-06 16:14:00.533 UTC | 20 | 2013-10-22 22:51:45.523 UTC | null | null | null | null | 1,023,517 | null | 1 | 38 | android|gmail|android-edittext | 17,629 | <p>This technique -- referred to as "chips" -- is discussed by Roman Nurik in <a href="https://plus.google.com/113735310430199015092/posts/WUd7GrfZfiZ" rel="nofollow noreferrer">a Google+ post</a>. He, in turn, points to <a href="https://stackoverflow.com/questions/8090711/android-labels-or-bubbles-in-edittext/8128848#8128848">Macarse's answer here on StackOverflow</a>. They, in turn, point to <a href="https://android.googlesource.com/platform/packages/apps/Mms/+/refs/heads/master/src/com/android/mms/ui/" rel="nofollow noreferrer">the implementation of this UI</a> that you see in the stock messaging client.</p> |
13,715,179 | My Git bash forgets my aliases. What can I do? | <p>I am working with the latest Git bash for Windows, on my laptop running Windows 7.
When I define my aliases like:</p>
<pre><code>$ alias gitc='git commit -a'
</code></pre>
<p>Everything works well during the session, but I cannot recover them if I close and open the bash.
The command history is preserved, though.</p>
<p>What should I do? What I have missed?</p>
<p>Thanks!</p> | 13,715,213 | 8 | 3 | null | 2012-12-05 02:00:41.57 UTC | 16 | 2021-11-05 19:08:27.683 UTC | 2012-12-05 02:44:52.873 UTC | null | 1,877,609 | null | 1,877,609 | null | 1 | 49 | git|bash | 25,313 | <p>When you open the git bash type in the command <code>touch .bash_profile</code>.
Following this type <code>vim .bash_profile</code>.
You can then add your aliases to this file. Save the file and reopen the git bash and your aliases should work as expected.</p>
<p>This method allows you to create aliases for any bash command available in git bash however as others have answered it is also possible to create git specific aliases using git itself.</p> |
13,240,047 | Clear dropdown using jQuery Select2 | <p>I'm trying to programmatically clear a drop down using the fantastic <a href="http://ivaynberg.github.com/select2/">Select2</a> library. The drop down is dynamically filled with a remote ajax call using the Select2 <code>query</code> option.</p>
<p>HTML:</p>
<pre><code><input id="remote" type="hidden" data-placeholder="Choose Something" />
</code></pre>
<p>Javascript:</p>
<pre><code> var $remote = $('#remote');
$remote.select2({
allowClear: true,
minimumInputLength: 2,
query: function(options){
$.ajax({
dataType: 'json',
url: myURL + options.term,
error: function(jqXHR, textStatus, errorThrown){
smoke.alert(textStatus + ": server returned error on parsing arguments starting with " + options.term);
},
success: function(data, textStatus, jqXHR){
var results = [];
for(var i = 0; i < data.length; ++i){
results.push({id: data[i].id, text: data[i].name});
}
options.callback({results: results, more: false});
}
});
}
});
</code></pre>
<p>Unfortunately, the call to <code>$remove.select2('val', '')</code> throws the following exception:</p>
<pre><code> Uncaught Error: cannot call val() if initSelection() is not defined
</code></pre>
<p>I've tried setting the <code>attr</code>, setting the <code>val</code>, <code>text</code> and the Select2 specific <code>data</code> function. Can't seem to make the guy clear and work in a radio button like manner. Anyone got suggestions?</p> | 13,519,546 | 17 | 5 | null | 2012-11-05 20:43:02.717 UTC | 6 | 2021-05-24 10:53:59.677 UTC | 2016-03-24 18:09:30.383 UTC | null | 812,720 | null | 178,060 | null | 1 | 57 | javascript|jquery|jquery-select2 | 143,165 | <p>This works for me: </p>
<pre><code> $remote.select2('data', {id: null, text: null})
</code></pre>
<p>It also works with jQuery validate when you clear it that way. </p>
<p>--
edit 2013-04-09</p>
<p>At the time of writing this response, it was the only way. With recent patches, a proper and better way is now available. </p>
<pre><code>$remote.select2('data', null)
</code></pre> |
13,525,480 | Mongoose populate after save | <p>I cannot manually or automatically populate the creator field on a newly saved object ... the only way I can find is to re-query for the objects I already have which I would hate to do.</p>
<p>This is the setup:</p>
<pre><code>var userSchema = new mongoose.Schema({
name: String,
});
var User = db.model('User', userSchema);
var bookSchema = new mongoose.Schema({
_creator: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
description: String,
});
var Book = db.model('Book', bookSchema);
</code></pre>
<p>This is where I am pulling my hair</p>
<pre><code>var user = new User();
user.save(function(err) {
var book = new Book({
_creator: user,
});
book.save(function(err){
console.log(book._creator); // is just an object id
book._creator = user; // still only attaches the object id due to Mongoose magic
console.log(book._creator); // Again: is just an object id
// I really want book._creator to be a user without having to go back to the db ... any suggestions?
});
});
</code></pre>
<p>EDIT: latest mongoose fixed this issue and added populate functionality, see the new accepted answer.</p> | 17,505,622 | 16 | 0 | null | 2012-11-23 08:39:50.257 UTC | 30 | 2022-08-28 00:11:12.2 UTC | 2015-01-19 17:14:56.007 UTC | null | 742,390 | null | 742,390 | null | 1 | 115 | node.js|mongodb|mongoose|populate | 80,892 | <p>You should be able to use the Model's populate function to do this: <a href="http://mongoosejs.com/docs/api.html#model_Model.populate">http://mongoosejs.com/docs/api.html#model_Model.populate</a> In the save handler for book, instead of:</p>
<pre><code>book._creator = user;
</code></pre>
<p>you'd do something like:</p>
<pre><code>Book.populate(book, {path:"_creator"}, function(err, book) { ... });
</code></pre>
<p>Probably too late an answer to help you, but I was stuck on this recently, and it might be useful for others.</p> |
13,777,215 | What are Compass and Sass and how do they differ? | <p>I would like to start using Compass and Sass to speed up development. At the moment, I have installed Sass on a mac and instructed it to watch a Scss file for input, and a CSS file for generated output.</p>
<p>From many articles, Sass is used with Compass, I'm wondering why that is the case and just what does Compass add that Sass comes without? If you can give an example, the better.</p> | 13,777,311 | 2 | 0 | null | 2012-12-08 11:55:02.773 UTC | 27 | 2021-10-04 13:35:16.957 UTC | 2021-10-04 13:35:16.957 UTC | null | 2,756,409 | null | 249,956 | null | 1 | 170 | css|sass|compass-sass | 47,570 | <p>From <em>Sass and Compass in Action</em>, by Wynn Netherland, Nathan Weizenbaum, Chris Eppstein, and Brandon Mathis:</p>
<blockquote>
<h3>1.3 What is Compass?</h3>
<p>Compass helps Sass authors write smarter stylesheets and empowers a community
of designers and developers to create and share powerful frameworks. Put simply,
<strong>Compass is a Sass framework</strong>, designed to make the work of styling the web
smooth and efficient. Much like Rails as a web application framework for Ruby,
<strong>Compass is a collection of helpful tools and battle-tested best practices for Sass</strong>.</p>
</blockquote>
<p>(emphasis added)</p> |
16,463,938 | Why does this sed command to match number not work? | <p>My command is like this:</p>
<pre><code>echo "12 cats" | sed 's/[0-9]+/Number/g'
</code></pre>
<p>(I'm using the <code>sed</code> in vanilla Mac)</p>
<p>I expect the result to be:</p>
<pre><code>Number cats
</code></pre>
<p>However, the real result is:</p>
<pre><code>12 cats
</code></pre>
<p>Does anyone have ideas about this? Thanks!</p> | 16,464,110 | 4 | 1 | null | 2013-05-09 14:15:59.163 UTC | 1 | 2017-07-08 09:34:37.217 UTC | 2013-05-09 14:29:34.033 UTC | null | 1,272,683 | null | 1,272,683 | null | 1 | 20 | linux|bash|shell|sed | 40,908 | <p>Expanding the <code>+</code> modifier works for me:</p>
<pre><code>echo "12 cats" | sed 's/[0-9][0-9]*/Number/g'
</code></pre>
<p>Also, the <code>-E</code> switch would make the <code>+</code> modifier work, see choroba’s answer.</p> |
16,532,316 | How to get Meteor.user() to return on the server side? | <p>in a file called /server/main.js (in order to ensure it is loaded last).</p>
<pre><code>console.dir(Meteor.user());
</code></pre>
<p>Throws:</p>
<pre><code>Error: Meteor.userId can only be invoked in method calls. Use this.userId in publish functions.
</code></pre>
<p>So I try to use, in the same file:</p>
<pre><code>console.dir(this.userId);
</code></pre>
<p>returns: </p>
<pre><code>undefined
</code></pre>
<p>so, not giving up, I'm thinking "that's fine I'll just read from the cookies in the header":</p>
<pre><code>var connect = Npm.require('connect');
__meteor_bootstrap__.app.use(connect.query()).use(function(req, res, next) {
console.dir(req.headers);
next();
});
</code></pre>
<p>.... returns nothing in terms of cookies except for 'cookie: 'uvf=1''</p>
<p>I'm not sure what to conclude - this is senseless as I can otherwise use the Meteor.Account framework just fine, read/set user properties, etc. The server is clearly aware of the user, and the current user clearly logged in. </p>
<p>I'm at a complete loss, any explanation / hint / pointer would be greatly appreciated.</p> | 16,533,163 | 4 | 0 | null | 2013-05-13 22:39:36.727 UTC | 12 | 2017-05-20 21:34:28.713 UTC | 2013-05-14 00:28:34.213 UTC | null | 821,423 | null | 821,423 | null | 1 | 37 | meteor | 37,559 | <p>You have to use Meteor.user() in a place where a request is made from the client (such as a Meteor.methods or a Meteor.publish). </p>
<p>It can't be placed anywhere else because meteor wouldn't know at that point in the code the user is supposed to bound to. If there is a place a request of some form is made from the client it can do this:</p>
<p>In a Meteor.publish:</p>
<pre><code>Meteor.publish("collection", function() {
//returns undefined if not logged in so check if logged in first
if(this.userId) {
var user = Meteor.users.findOne(this.userId);
//var user is the same info as would be given in Meteor.user();
}
});
</code></pre>
<p>In a Meteor.methods:</p>
<pre><code>Meteor.methods({
"test":function() {
//should print the user details if logged in, undefined otherwise.
console.log(Meteor.user());
}
}
</code></pre>
<p>To use Meteor.user() on a server side route:</p>
<p>You need <a href="https://github.com/tmeasday/meteor-router" rel="noreferrer">Meteor router</a> installed as a package via <a href="https://github.com/oortcloud/meteorite" rel="noreferrer">meteorite</a> to allow you to have a server rendered page. (installed via <code>mrt install router</code>)</p>
<p>A server side route could then handle the web request:</p>
<pre><code> Meteor.Router.add('/awebpage', function(id) {
var userId = this.params.userid;
var logintoken = this.params.logintoken;
var isdirect = this.param.direct;
var user = Meteor.users.findOne({_id:userId,"services.resume.loginTokens.token":logintoken});
if(user) {
//the user is successfully logged in
return "You, "+user.profile.name+", are logged in!";
}
else
{
if(isdirect) {
return "<h3>Loading</h3><script>window.location.href="/awebpage?direct=true&userid="+localStorage.getItem("Meteor.userId") +"&logintoken="+localStorage.getItem("Meteor.loginToken")</script>";
}
else
{
return "Not logged in"
}
}
});
</code></pre>
<p>So now when you visit <code>/awebpage</code> it would check whether the user is logged in and do the thing you want when they are logged in. Initially there is a redirect to relay the data from localstorage back to the URI.</p> |
16,280,040 | CSS3 Flexbox: display: box vs. flexbox vs. flex | <p>Yesterday I got a website in the school which uses the CSS 3 flexbox statement. I never used that before. So I googled it a bit and found a lot of different styles of the flexbox statements. </p>
<p>Some guys write <code>display: box;</code>, some use <code>display: flexbox;</code>, and other <code>display: flex;</code>.</p>
<p>So what are the differences? Which I should use? </p> | 16,280,118 | 3 | 11 | null | 2013-04-29 13:35:40.08 UTC | 29 | 2019-07-06 02:20:57.41 UTC | 2019-07-06 02:20:57.41 UTC | user1722486 | 63,550 | user1722486 | null | null | 1 | 106 | css|flexbox | 88,941 | <p>These are different styles.<br>
<code>display: box;</code> is a version of 2009.<br>
<code>display: flexbox;</code> is a version of 2011.<br>
<code>display: flex;</code> is the actual version. </p>
<p><em>Quote of Paul Irish</em></p>
<blockquote>
<p>Warning: Flexbox has undergone some major revisions, so this article
is out of date. In summary, the <a href="http://www.w3.org/TR/2009/WD-css3-flexbox-20090723/">old standard (Flexbox 2009)</a>, which
this article is based on, was implemented in Chrome since v4, Firefox
since v2, and IE10 beta.</p>
<p>Since then, <a href="http://dev.w3.org/csswg/css-flexbox/">the new flexbox standard debuted</a> and started to debut in
Chrome 17. Stephan Hay has <a href="http://www.the-haystack.com/2012/01/04/learn-you-a-flexbox/">written a guide on the new flexbox
implementation</a>. Since then, the spec underwent naming changes which
started landing in Chrome 21. Chrome 22 has a stable implementation of
the latest spec.</p>
<p>At this point, implementing either <a href="http://html5please.com/#flexbox">has its risks</a>, so be aware.</p>
</blockquote>
<p><a href="http://www.html5rocks.com/en/tutorials/flexbox/quick/">Here</a> is the blog about the different flexbox statements.<br>
<a href="http://css-tricks.com/old-flexbox-and-new-flexbox/">This</a> is a blog entry by css-tricks about the different versions.</p>
<p>When i use flexbox, i always write it like that:</p>
<pre><code>display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
</code></pre>
<p>Edit:<br>
Still not everyone has a browser/device capable of viewing flexbox layouts. So for fallback solutions or alternatives there is <a href="http://kyusuf.com/post/almost-complete-guide-to-flexbox-without-flexbox">this article</a> by Kenan Yusuf on how to <em>use flexbox without using flexbox</em>.</p> |
12,922,909 | How to make text appear in columns in HTML | <p>Sorry, this is probably a thick question, but how to I get HTML to display similar to using the tab button in Word? I want to display like this:</p>
<pre><code>header text header text Header text
text in column text in column text in column
</code></pre>
<p>If i use the spacebar, it just ignores the spaces. Actually, I will be putting razor variables in the columns, but that's the general idea of what I'm trying to create. </p>
<p>No doubt there's a div tag or similar that represents the 'tab' function, or columnises the text - I just don't know it!</p> | 12,922,965 | 7 | 1 | null | 2012-10-16 20:30:07.347 UTC | null | 2019-09-25 09:55:40.97 UTC | 2015-04-27 11:27:10.997 UTC | null | 109,305 | null | 1,736,320 | null | 1 | 5 | html|razor|webmatrix | 42,535 | <p>You might just end up with a HTML table:</p>
<pre><code><table>
<tr>
<th>header text</th>
<th>header text</th>
<th>header text</th>
</tr>
<tr>
<td>text in column</td>
<td>text in column</td>
<td>text in column</td>
</tr>
</table>
</code></pre>
<p>And a litte styling of course, you could check out this tool: <a href="http://tablestyler.com" rel="nofollow">http://tablestyler.com</a> </p> |
15,126,050 | Running Python on Windows for Node.js dependencies | <p>I am getting into a Node.js codebase which requires that I download a few dependencies via NPM, namely jQuery.</p>
<p>In attempting to run <code>npm install jquery</code>, I keep getting this error:</p>
<pre><code>Your environment has been set up for using Node.js 0.8.21 (x64) and NPM
C:\Users\Matt Cashatt>npm install jquery
npm http GET https://registry.npmjs.org/jquery
npm http 304 https://registry.npmjs.org/jquery
npm http GET https://registry.npmjs.org/jsdom
npm http GET https://registry.npmjs.org/xmlhttprequest
npm http GET https://registry.npmjs.org/htmlparser/1.7.6
npm http GET https://registry.npmjs.org/location/0.0.1
npm http GET https://registry.npmjs.org/navigator
npm http GET https://registry.npmjs.org/contextify
npm http 304 https://registry.npmjs.org/htmlparser/1.7.6
npm http 304 https://registry.npmjs.org/xmlhttprequest
npm http 304 https://registry.npmjs.org/location/0.0.1
npm http 304 https://registry.npmjs.org/navigator
npm http 304 https://registry.npmjs.org/jsdom
npm http 304 https://registry.npmjs.org/contextify
npm http GET https://registry.npmjs.org/bindings
npm http GET https://registry.npmjs.org/cssom
npm http GET https://registry.npmjs.org/cssstyle
npm http GET https://registry.npmjs.org/request
npm http 304 https://registry.npmjs.org/bindings
> [email protected] install C:\Users\Matt Cashatt\node_modules\jquery\node_module
s\contextify
> node-gyp rebuild
C:\Users\Matt Cashatt\node_modules\jquery\node_modules\contextify>node "C:\Progr
am Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\b
in\node-gyp.js" rebuild
npm http 304 https://registry.npmjs.org/cssstyle
npm http 304 https://registry.npmjs.org/cssom
npm http 304 https://registry.npmjs.org/request
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "python", you can set the PYT
HON env variable.
gyp ERR! stack at failNoPython (C:\Program Files\nodejs\node_modules\npm\nod
e_modules\node-gyp\lib\configure.js:113:14)
gyp ERR! stack at C:\Program Files\nodejs\node_modules\npm\node_modules\node
-gyp\lib\configure.js:82:11
gyp ERR! stack at Object.oncomplete (fs.js:297:15)
gyp ERR! System Windows_NT 6.1.7601
gyp ERR! command "node" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modu
les\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\Matt Cashatt\node_modules\jquery\node_modules\contextify
gyp ERR! node -v v0.8.21
gyp ERR! node-gyp -v v0.8.4
gyp ERR! not ok
npm ERR! error rolling back Error: ENOTEMPTY, rmdir 'C:\Users\Matt Cashatt\node_
modules\jquery\node_modules\jsdom\node_modules\request\tests'
npm ERR! error rolling back [email protected] { [Error: ENOTEMPTY, rmdir 'C:\Users\M
att Cashatt\node_modules\jquery\node_modules\jsdom\node_modules\request\tests']
npm ERR! error rolling back errno: 53,
npm ERR! error rolling back code: 'ENOTEMPTY',
npm ERR! error rolling back path: 'C:\\Users\\Matt Cashatt\\node_modules\\jque
ry\\node_modules\\jsdom\\node_modules\\request\\tests' }
npm ERR! [email protected] install: `node-gyp rebuild`
npm ERR! `cmd "/c" "node-gyp rebuild"` failed with 1
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is most likely a problem with the contextify package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node-gyp rebuild
npm ERR! You can get their info via:
npm ERR! npm owner ls contextify
npm ERR! There is likely additional logging output above.
npm ERR! System Windows_NT 6.1.7601
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nod
ejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "jquery"
npm ERR! cwd C:\Users\Matt Cashatt
npm ERR! node -v v0.8.21
npm ERR! npm -v 1.2.11
npm ERR! code ELIFECYCLE
npm ERR! Error: ENOENT, lstat 'C:\Users\Matt Cashatt\node_modules\jquery\node_mo
dules\jsdom\node_modules\request\tests\test-pipes.js'
npm ERR! If you need help, you may report this log at:
npm ERR! <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR! <[email protected]>
npm ERR! System Windows_NT 6.1.7601
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nod
ejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "jquery"
npm ERR! cwd C:\Users\Matt Cashatt
npm ERR! node -v v0.8.21
npm ERR! npm -v 1.2.11
npm ERR! path C:\Users\Matt Cashatt\node_modules\jquery\node_modules\jsdom\node_
modules\request\tests\test-pipes.js
npm ERR! fstream_path C:\Users\Matt Cashatt\node_modules\jquery\node_modules\jsd
om\node_modules\request\tests\test-pipes.js
npm ERR! fstream_type File
npm ERR! fstream_class FileWriter
npm ERR! code ENOENT
npm ERR! errno 34
npm ERR! fstream_stack C:\Program Files\nodejs\node_modules\npm\node_modules\fst
ream\lib\writer.js:284:26
npm ERR! fstream_stack Object.oncomplete (fs.js:297:15)
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! C:\Users\Matt Cashatt\npm-debug.log
npm ERR! not ok code 0
C:\Users\Matt Cashatt>
</code></pre>
<p>It looks like the failure is due to a missing Python installation. Well, I have installed Python, set the variable, and rebooted and still the error.</p>
<p>Any clue as to what I am missing?</p> | 15,126,180 | 27 | 9 | null | 2013-02-28 01:48:44.793 UTC | 75 | 2022-05-20 18:22:55.94 UTC | 2013-02-28 02:47:37.58 UTC | null | 201,952 | null | 856,790 | null | 1 | 261 | python|windows|node.js|npm | 457,887 | <p>Your problem is that you <em>didn't</em> set the environment variable.</p>
<p>The error clearly says this:</p>
<pre><code>gyp ERR! stack Error: Can't find Python executable "python", you can set the PYTHON env variable.
</code></pre>
<p>And in your comment, you say you did this:</p>
<pre><code>set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib
</code></pre>
<p>That's nice, but that doesn't set the <code>PYTHON</code> variable, it sets the <code>PYTHONPATH</code> variable.</p>
<hr>
<p>Meanwhile, just using the <code>set</code> command only affects the current <code>cmd</code> session. If you reboot after that, as you say you did, you end up with a whole new <code>cmd</code> session that doesn't have that variable set in it.</p>
<p>There are a few ways to set environment variables permanently—the easiest is in the System Control Panel in XP, which is of course different in Vista, different again in 7, and different again in 8, but you can google for it.</p>
<p>Alternatively, just do the <code>set</code> right before the <code>npm</code> command, without rebooting in between.</p>
<hr>
<p>You can test whether you've done things right by doing the exact same thing the config script is trying to do: Before running <code>npm</code>, try running <code>%PYTHON%</code>. If you've done it right, you'll get a Python interpreter (which you can immediately quit). If you get an error, you haven't done it right.</p>
<hr>
<p>There are two problems with this:</p>
<pre><code>set PYTHON=%PYTHON%;D:\Python
</code></pre>
<p>First, you're setting <code>PYTHON</code> to <code>;D:\Python</code>. That extra semicolon is fine for a semicolon-separated list of paths, like <code>PATH</code> or <code>PYTHONPATH</code>, but not for a single value like <code>PYTHON</code>. And likewise, adding a new value to the existing value is what you want when you want to add another path to a list of paths, but not for a single value. So, you just want <code>set PYTHON=D:\Python</code>.</p>
<p>Second, <code>D:\Python</code> is not the path to your Python interpreter. It's something like <code>D:\Python\Python.exe</code>, or <code>D:\Python\bin\Python.exe</code>. Find the right path, make sure it works on its own (e.g., type <code>D:\Python\bin\Python.exe</code> and make sure you get a Python interpreter), then set the variable and use it.</p>
<hr>
<p>So:</p>
<pre><code>set PYTHON=D:\Python\bin\Python.exe
</code></pre>
<p>Or, if you want to make it permanent, do the equivalent in the Control Panel.</p> |
24,821,528 | Top-level control cannot be added to a control | <p>How to Load other Form inside panel in a primary form.</p>
<p>i was trying something like </p>
<pre><code>private void frmInitialEntryBooks_Load(object sender, EventArgs e)
{
frmSujbect objForm = new frmSujbect();
pnl.Controls.Add(objForm);
objForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
objForm.Dock = DockStyle.Fill;
objForm.Show();
}
</code></pre>
<p>but it throw exception <code>Top-level control cannot be added to a control</code> at line <code>pnl.Controls.Add(objForm);</code></p> | 24,821,740 | 3 | 5 | null | 2014-07-18 09:24:03.537 UTC | 3 | 2021-02-21 16:16:45.623 UTC | 2016-11-18 18:06:10.307 UTC | null | 832,052 | null | 2,545,270 | null | 1 | 24 | c#|winforms | 38,925 | <p>Use this:</p>
<pre><code>private void frmInitialEntryBooks_Load(object sender, EventArgs e)
{
frmSujbect objForm = new frmSujbect();
objForm.TopLevel = false;
pnl.Controls.Add(objForm);
objForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
objForm.Dock = DockStyle.Fill;
objForm.Show();
}
</code></pre>
<p>You are missing <code>objForm.TopLevel = false;</code></p> |
22,278,217 | mysqldump & gzip commands to properly create a compressed file of a MySQL database using crontab | <p>I am having problems with getting a <code>crontab</code> to work. I want to automate a MySQL database backup.</p>
<p>The setup:</p>
<ul>
<li>Debian GNU/Linux 7.3 (wheezy) </li>
<li>MySQL Server version: 5.5.33-0+wheezy1(Debian) </li>
<li>directories user, backup and backup2 have 755 permission</li>
<li>The user names for MySQL db and Debian account are the same</li>
</ul>
<p>From the shell this command works</p>
<pre><code>mysqldump -u user -p[user_password] [database_name] | gzip > dumpfilename.sql.gz
</code></pre>
<p>When I place this in a crontab using crontab -e </p>
<pre><code>* * /usr/bin/mysqldump -u user -pupasswd mydatabase | gzip> /home/user/backup/mydatabase-backup-`date +\%m\%d_\%Y`.sql.gz >/dev/null 2>&1
</code></pre>
<p>A file is created every minute in /home/user/backup directory, but has 0 bytes.</p>
<p>However when I redirect this output to a second directory, backup2, I note that the proper mysqldumpfile duly compressed is created in it. I am unable to figure what is the mistake that I am making that results in a 0 byte file in the first directory and the expected output in the second directory.</p>
<pre><code>* * /usr/bin/mysqldump -u user -pupasswd my-database | gzip> /home/user/backup/mydatabase-backup-`date +\%m\%d_\%Y`.sql.gz >/home/user/backup2/mydatabase-backup-`date +\%m\%d_\%Y`.sql.gz 2>&1
</code></pre>
<p>I would greatly appreciate an explanation.</p>
<p>Thanks</p> | 22,279,330 | 5 | 3 | null | 2014-03-09 03:58:02.68 UTC | 30 | 2021-04-21 19:45:20.65 UTC | 2016-03-24 14:54:16.953 UTC | null | 871,150 | null | 3,397,547 | null | 1 | 100 | crontab|mysqldump | 276,556 | <p>First the mysqldump command is executed and the output generated is redirected using the pipe. The pipe is sending the standard output into the gzip command as standard input. Following the filename.gz, is the output redirection operator (>) which is going to continue redirecting the data until the last filename, which is where the data will be saved.</p>
<p>For example, this command will dump the database and run it through gzip and the data will finally land in three.gz</p>
<pre><code>mysqldump -u user -pupasswd my-database | gzip > one.gz > two.gz > three.gz
$> ls -l
-rw-r--r-- 1 uname grp 0 Mar 9 00:37 one.gz
-rw-r--r-- 1 uname grp 1246 Mar 9 00:37 three.gz
-rw-r--r-- 1 uname grp 0 Mar 9 00:37 two.gz
</code></pre>
<p>My original answer is an example of redirecting the database dump to many compressed files (without double compressing). (Since I scanned the question and seriously missed - sorry about that)</p>
<p>This is an example of recompressing files:</p>
<pre><code>mysqldump -u user -pupasswd my-database | gzip -c > one.gz; gzip -c one.gz > two.gz; gzip -c two.gz > three.gz
$> ls -l
-rw-r--r-- 1 uname grp 1246 Mar 9 00:44 one.gz
-rw-r--r-- 1 uname grp 1306 Mar 9 00:44 three.gz
-rw-r--r-- 1 uname grp 1276 Mar 9 00:44 two.gz
</code></pre>
<p>This is a good resource explaining I/O redirection: <a href="http://www.codecoffee.com/tipsforlinux/articles2/042.html" rel="noreferrer">http://www.codecoffee.com/tipsforlinux/articles2/042.html</a></p> |
37,287,148 | iOS Safari/Chrome - Unwanted scrolling when focusing an input inside the modal | <p>Tested in Safari and Chrome - the same result, so I think it's iOS issue.</p>
<p>This happens only if there's an input inside the modal and I tap that input. In the same moment that input got focus and native iOS keyboard become visible. </p>
<p>Page below modal in the same moment is automatically scrolled to 50% of its height. This behaviour is totally unwanted and I have no clue how to prevent this default iOS "feature".</p>
<p>Demo:</p>
<p><a href="https://i.stack.imgur.com/MYeyB.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/MYeyB.gif" alt="enter image description here"></a></p> | 40,033,530 | 8 | 4 | null | 2016-05-17 22:20:16.73 UTC | 7 | 2022-02-25 22:58:43.69 UTC | 2016-10-15 18:42:12.997 UTC | null | 1,331,425 | null | 1,331,425 | null | 1 | 32 | javascript|html|ios|css|vertical-scrolling | 30,052 | <p>Just adding an answer here in case people stumble upon this question (<a href="https://stackoverflow.com/questions/39626302/ios-chrome-safari-unwanted-scrolling-when-focusing-an-input-inside-the-modal/40033422#40033422">rather than your other question, which has a great demo to illustrate this issue</a>)</p>
<p>We are facing a similar issue at work. As you mentioned, the offset is always ~50% of the height of the page, which happens regardless of where your initial offset is.</p>
<p>In the past, when I observed a similar "jumping" with earlier iOS versions (albeit, much less dramatic jumping), I have usually worked around this by applying <code>position: fixed</code> (or <code>relative</code>) to the <code>body</code> (<a href="https://stackoverflow.com/questions/3047337/does-overflowhidden-applied-to-body-work-on-iphone-safari">which allows <code>overflow: hidden</code> to properly work</a>).</p>
<p>However, this has the unintended consequence of jumping the user back to the top of the page, if they've scrolled down.</p>
<p>So, if you're open to addressing this issue with some <code>JavaScript</code>, here's a fix/hack I've thrown together:</p>
<pre><code>// Tapping into swal events
onOpen: function () {
var offset = document.body.scrollTop;
document.body.style.top = (offset * -1) + 'px';
document.body.classList.add('modal--opened');
},
onClose: function () {
var offset = parseInt(document.body.style.top, 10);
document.body.classList.remove('modal--opened');
document.body.scrollTop = (offset * -1);
}
</code></pre>
<p>And what the CSS looks like:</p>
<pre><code>.modal--opened {
position: fixed;
left: 0;
right: 0;
}
</code></pre>
<p>Here's a fork of your demo page (from your other question), to illustrate: <a href="https://jpattishall.github.io/sweetalert2/ios-bug.html" rel="nofollow noreferrer">https://jpattishall.github.io/sweetalert2/ios-bug.html</a></p>
<p>And for those who are looking for a more general fix, you could do something like the following when opening/closing a modal:</p>
<pre><code>function toggleModal() {
var offset;
if (document.body.classList.contains('modal--opened')) {
offset = parseInt(document.body.style.top, 10);
document.body.classList.remove('modal--opened');
document.body.scrollTop = (offset * -1);
} else {
offset = document.body.scrollTop;
document.body.style.top = (offset * -1) + 'px';
document.body.classList.add('modal--opened');
}
}
</code></pre>
<p>Edit: To avoid the "shifting/unshifting" on desktops, I would suggest feature detection/ua sniffing to apply this to only mobile safari.</p> |
55,491,242 | How to remove the Live Share button? | <p>I've installed Visual Studio 2019 and the first thing that annoys me is the large black, empty space on top of the screen after removing all my toolbars. </p>
<p>The 'Live Share' and 'Feedback' button don't show up as toolbars though.</p>
<p><a href="https://i.stack.imgur.com/af5gq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/af5gq.png" alt="enter image description here"></a></p>
<p>Is there a way to reclaim the whitespace by removing those two buttons?</p> | 55,508,041 | 5 | 8 | null | 2019-04-03 09:06:32.52 UTC | 8 | 2019-10-07 17:44:16.333 UTC | 2019-04-03 16:04:48.48 UTC | null | 1,797,425 | null | 21,679 | null | 1 | 47 | layout|visual-studio-2019|visual-studio-liveshare | 10,388 | <p>You can hide the Live Share and Feedback buttons area with Visual Commander: <a href="https://visualstudioextensions.vlasovstudio.com/2019/03/19/freeing-screen-space-in-visual-studio-2019/" rel="noreferrer">https://visualstudioextensions.vlasovstudio.com/2019/03/19/freeing-screen-space-in-visual-studio-2019/</a></p> |
26,506,364 | maven- not downloading new added dependency in pom.xml file | <p>I need new third party jar for reading csv in maven based project. So, I did entry in pom.xml for same as below.</p>
<pre><code><dependency>
<groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>2.0</version>
</dependency>
</code></pre>
<p>But when I run mvn install or mvn package command, It does not download newly added dependency and just build project and generate war.</p>
<p>I am trying to get the issue! Please share solution if anybody face this earlier!</p>
<p>Regards</p> | 26,506,927 | 8 | 3 | null | 2014-10-22 11:27:31.67 UTC | 3 | 2021-11-24 03:11:35.937 UTC | 2014-10-23 15:33:27.203 UTC | null | 2,087,640 | null | 966,709 | null | 1 | 11 | java|maven | 58,453 | <p>I resolved this issue by following steps:</p>
<p>1). Remove concerned jar from local /m2 folder.
2). Run <strong>mvn eclipse:eclipse</strong> command
3). And last run: <strong>mvn clean install</strong></p>
<p>Now I am looking for concerned jar in my project class path!</p> |
45,242,553 | How to speed up the Angular build process | <p>After making some changes in my TypeScript files, each build takes over 20 minutes.
I run this command: <code>ng build --output-path=..\..\static\angularjs</code>.</p>
<p>If I run it in Microsoft PowerShell, it needs 25 - 30 seconds. This is a lot of time.</p>
<p><strong>Enviroment</strong></p>
<ul>
<li>Windows 10</li>
<li>8 GB-Ram</li>
<li>PyCharm 64</li>
<li>MS PowerShell</li>
</ul>
<p>How can I speed this up?</p> | 45,245,580 | 12 | 4 | null | 2017-07-21 16:29:03.68 UTC | 24 | 2022-08-10 12:18:23.54 UTC | 2019-04-08 05:42:50.657 UTC | null | 11,015,427 | null | 3,760,481 | null | 1 | 101 | angular|angular-cli | 128,509 | <p>My app took 28secs to build, but I've reduced the time to 9secs. Usings this flag </p>
<pre><code>ng build --source-map=false
</code></pre>
<p>you can see the difference in time comparing the time:</p>
<pre><code>ng build --stats-json
ng build --stats-json --source-map=false
</code></pre>
<p>source map is intended only for debugging, Hope it helps</p> |
36,801,188 | Simple Regex: match everything until the last dot | <p>Just want to match every character up to but not including the last period</p>
<pre><code> dog.jpg -> dog
abc123.jpg.jpg -> abc123.jpg
</code></pre>
<p>I have tried</p>
<pre><code>(.+?)\.[^\.]+$
</code></pre> | 36,801,370 | 3 | 5 | null | 2016-04-22 18:41:53.613 UTC | 4 | 2016-04-22 18:57:08.667 UTC | 2016-04-22 18:51:03.083 UTC | null | 1,996,394 | null | 4,796,973 | null | 1 | 16 | regex | 53,562 | <p>Use lookahead to assert the last dot character:</p>
<pre><code>.*(?=\.)
</code></pre>
<p><a href="https://regex101.com/r/rI4pQ1/1" rel="noreferrer">Live demo.</a></p> |
18,275,295 | Remove a Single Object from a Javascript Object | <p>How do I remove one item based on both the courseID and endDate from the following javascript object?</p>
<pre><code> window.MyCheckedCourses = [
{ courseID: '123', endDate: '6/7/2010' },
{ courseID: '123', endDate: '3/9/2003' },
{ courseID: '456', endDate: '3/9/2003' }
];
</code></pre> | 18,275,420 | 2 | 5 | null | 2013-08-16 14:08:24.293 UTC | 2 | 2013-08-16 15:56:25.863 UTC | 2013-08-16 14:12:39.203 UTC | null | 616,443 | null | 1,542,058 | null | 1 | 52 | javascript | 1,533 | <p>Iteration is a must. You have to use <code>.splice()</code> to remove corresponding item and <code>break</code> the for loop. </p>
<pre><code>var i, id = '123', date = '6/7/2010';
for(var i = 0, il = MyCheckedCourses.length;i<il;i++) {
if(MyCheckedCourses[i].courseID == id && MyCheckedCourses[i].endDate == date) {
MyCheckedCourses.splice(i, 1);
break;
}
}
</code></pre>
<p>You can make a function and use it with parameters like this;</p>
<pre><code>function remove(id, date) {
for(var i = 0, il = MyCheckedCourses.length;i<il;i++) {
if(MyCheckedCourses[i].courseID == id && MyCheckedCourses[i].endDate == date) {
MyCheckedCourses.splice(i, 1);
break;
}
}
}
// Example usage:
remove('123', '6/7/2010');
</code></pre>
<p><strong>Edit after Ian's <a href="https://stackoverflow.com/questions/18275295/remove-a-single-object-from-a-javascript-object/18275420#comment26806518_18275420">comment</a>:</strong></p>
<p>I assume that your collection have unique items. If not you have to iterate through all items and you have to do it backwards because if you remove an element from array it's index will change and iteration will not work correctly. So this function is a much more safer version;</p>
<pre><code>function remove(id, date) {
for(var i = MyCheckedCourses.length - 1;i >= 0;i--) {
if(MyCheckedCourses[i].courseID == id && MyCheckedCourses[i].endDate == date) {
MyCheckedCourses.splice(i, 1);
}
}
}
// Example usage:
remove('123', '6/7/2010');
</code></pre> |
5,295,971 | Sorting a List with OrderBy | <p>Why won't the code below sort my list?</p>
<pre><code>List<string> lst = new List<string>() { "bac", "abc", "cab" };
lst.OrderBy(p => p.Substring(0));
</code></pre> | 5,295,980 | 3 | 0 | null | 2011-03-14 07:47:04.263 UTC | 3 | 2013-11-03 21:06:45.683 UTC | 2013-11-03 21:06:45.683 UTC | null | 5,640 | null | 658,398 | null | 1 | 17 | c#|linq | 61,589 | <p>since OrderBy returns IOrderedEnumerable you should do:</p>
<pre><code>lst = lst.OrderBy(p => p.Substring(0)).ToList();
</code></pre>
<p>you can also do the following:</p>
<pre><code>lst.Sort();
</code></pre> |
5,370,539 | What is the meaning of lines starting with a hash sign and number like '# 1 "a.c"' in the gcc preprocessor output? | <p>I print out the output of C preprocessor by using</p>
<pre><code>gcc -E a.c
</code></pre>
<p>The output contains many lines like</p>
<pre><code># 1 "a.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "a.c"
# 1 "c:\\mingw\\bin\\../lib/gcc/mingw32/4.5.0/../../../../include/stdio.h" 1 3
# 19 "c:\\mingw\\bin\\../lib/gcc/mingw32/4.5.0/../../../../include/stdio.h" 3
# 1 "c:\\mingw\\bin\\../lib/gcc/mingw32/4.5.0/../../../../include/_mingw.h" 1 3
# 31 "c:\\mingw\\bin\\../lib/gcc/mingw32/4.5.0/../../../../include/_mingw.h" 3
# 32 "c:\\mingw\\bin\\../lib/gcc/mingw32/4.5.0/../../../../include/_mingw.h" 3
# 20 "c:\\mingw\\bin\\../lib/gcc/mingw32/4.5.0/../../../../include/stdio.h" 2 3
</code></pre>
<p>I've never seen this kind of syntax in C. Can someone explain what this is doing?</p> | 5,370,592 | 3 | 1 | null | 2011-03-20 18:34:35.98 UTC | 19 | 2020-10-27 14:18:05.107 UTC | 2020-10-27 14:18:05.107 UTC | null | 3,889,449 | null | 607,722 | null | 1 | 68 | c|gcc|c-preprocessor | 41,697 | <p>These lines are hints for debugging (where the code following the line actually came from)</p>
<pre><code># line-number "source-file" [flags]
</code></pre>
<p>Meaning of flags (space separated):</p>
<ul>
<li>1 - Start of a new file</li>
<li>2 - Returning to previous file</li>
<li>3 - Following text comes from a system header file (#include <> vs #include "")</li>
<li>4 - Following text should be treated as being wrapped in an implicit extern "C" block.</li>
</ul> |
9,485,962 | Does Python have anything Like Capybara/Cucumber? | <p>Ruby has this great abstraction layer on top of Selenium called Capybara, which you can use do functional/acceptance/integration testing. It also has another library called Cucumber which takes this a step further and lets you actually write tests in English.</p>
<p>Both libraries are built on top of Selenium, and can be used to test against any major browser, but because of their abstraction layers it's super easy to write tests using them (well, as easy as functional testing gets at least).</p>
<p>My question is: does Python have anything like that? I have found Pythonistas doing functional testing with various tools but ...</p>
<p>A) Splinter: doesn't use Selenium (and doesn't have an IE driver)</p>
<p><strong>-EDIT-</strong>
It appears Spliter now does use Selenium (see answers below).</p>
<p>B) Alfajor: hasn't been updated in over a year; looks dead</p>
<p>C) Selenium (raw): a lot of people seem to be using Selenium directly, but it seems like an abstraction layer could make it a lot easier to use</p>
<p>So, does anyone know of anything Capybara-like, or better yet Cucumber-like, for Python (it doesn't have to actually use Selenium, but it needs to support all major browsers)?</p>
<p><strong>* EDIT *</strong></p>
<p>For those that aren't familiar with Capybara, it basically just adds an API so that instead of the normal Selenium API you can do something like this:</p>
<pre><code>When /I sign in/ do
within("#session") do
fill_in 'Login', :with => '[email protected]'
fill_in 'Password', :with => 'password'
end
click_link 'Sign in'
end
</code></pre>
<p>It's used by Cucumber, which let's you further abstract (almost to English):</p>
<pre><code>Scenario Outline: Add two numbers
Given I have entered <input_1> into the calculator
And I have entered <input_2> into the calculator
When I press <button>
Then the result should be <output> on the screen
Examples:
| input_1 | input_2 | button | output |
| 20 | 30 | add | 50 |
</code></pre>
<p>I would LOVE a Python Cucumber equivalent, but even just a Capybara equivalent would be helpful.</p> | 9,514,754 | 7 | 3 | null | 2012-02-28 16:40:19.58 UTC | 26 | 2016-12-29 01:23:04.177 UTC | 2015-04-16 03:55:53.393 UTC | null | 617,450 | null | 5,921 | null | 1 | 46 | python|functional-testing|acceptance-testing | 35,792 | <p>You can test Python code using Cucumber - see the <a href="https://github.com/cucumber/cucumber/wiki/Python">Cucumber wiki</a> on github for more information.</p>
<p>If you want a pure Python solution, check out <a href="http://lettuce.it">Lettuce</a>. I've never used it, but there is a fairly useful looking blog entry about it and splinter <a href="http://cilliano.com/blog/2011/02/07/django-bdd-with-lettuce-and-splinter/">here</a>.</p> |
9,524,025 | Why inner class can override private final method? | <p>I wondered if it makes sense to declare a private method as final as well, and I thought it doesn't make sense. But I imagined there's an exclusive situation and wrote the code to figure it out:</p>
<pre><code>public class Boom {
private void touchMe() {
System.out.println("super::I am not overridable!");
}
private class Inner extends Boom {
private void touchMe() {
super.touchMe();
System.out.println("sub::You suck! I overrided you!");
}
}
public static void main(String... args) {
Boom boom = new Boom();
Boom.Inner inner = boom.new Inner();
inner.touchMe();
}
}
</code></pre>
<p>It compiled and worked. "I should make touchMe() final" I thought and did it: </p>
<pre><code>public class Boom {
private final void touchMe() {
System.out.println("super::I am not overridable!");
}
private class Inner extends Boom {
private void touchMe() {
super.touchMe();
System.out.println("sub::You suck! I overrided you!");
}
}
public static void main(String... args) {
Boom boom = new Boom();
Boom.Inner inner = boom.new Inner();
inner.touchMe();
}
}
</code></pre>
<p>and it also works and tells me</p>
<pre><code>chicout@chicout-linlap:~$ java Boom
super::I am not overridable!
sub::You suck! I overrided you!
</code></pre>
<p>why?</p> | 9,524,058 | 5 | 5 | null | 2012-03-01 21:02:01.3 UTC | 12 | 2013-11-21 06:18:26.323 UTC | 2013-11-21 06:18:26.323 UTC | null | 2,922,515 | null | 1,112,240 | null | 1 | 66 | java|overriding|inner-classes|final | 4,140 | <p>Private methods can not be overridden (private methods are not inherited!) In fact, it makes no difference if you declare a private method final or not.</p>
<p>The two methods you have declared, <code>Boom.touchMe</code> and <code>Boom.Inner.touchMe</code> are two <strong>completely separate methods</strong> which just happen to share the same identifier. The fact that <code>super.touchMe</code> refers to a different method than <code>touchMe</code>, is just because <code>Boom.Inner.touchMe</code> <em>shadows</em> <code>Boom.touchMe</code> (and not because it overrides it).</p>
<p>This can be demonstrated in a number of ways:</p>
<ul>
<li><p>As you discovered yourself, if you change the methods to be public, the compiler will complain because you <em>are</em> suddenly trying to override a final method.</p></li>
<li><p>If you keep the methods private and add the <code>@Override</code> annotation, the compiler will complain.</p></li>
<li><p>As alpian points out, if you cast the <code>Boom.Inner</code> object to a <code>Boom</code> object (<code>((Boom) inner).touchMe()</code>) the <code>Boom.touchMe</code> is called (if it indeed was overridden, the cast wouldn't matter).</p></li>
</ul>
<p><strong>Related question:</strong></p>
<ul>
<li><a href="https://stackoverflow.com/questions/1984464/make-private-methods-final">Make private methods final?</a></li>
</ul> |
20,307,874 | What is the equivalent of the has_many 'conditions' option in Rails 4? | <p>Can someone tell me what is the equivalent way to do the following line in Rails 4?</p>
<pre><code>has_many :friends, :through => :friendships, :conditions => "status = 'accepted'", :order => :first_name
</code></pre>
<p>I tried the following:</p>
<pre><code>has_many :friends, -> { where status: 'accepted' }, :through => :friendships , :order => :first_name
</code></pre>
<p>But I get the following error:</p>
<pre><code>Invalid mix of scope block and deprecated finder options on ActiveRecord association: User.has_many :friends
</code></pre> | 20,307,896 | 5 | 2 | null | 2013-12-01 01:55:59.847 UTC | 17 | 2020-06-08 11:14:07.143 UTC | 2017-02-25 09:52:54.323 UTC | null | 276,959 | null | 2,392,106 | null | 1 | 77 | ruby-on-rails-4 | 72,130 | <p>Needs to be the second arg: </p>
<pre><code>class Customer < ActiveRecord::Base
has_many :orders, -> { where processed: true }
end
</code></pre>
<p><a href="http://edgeguides.rubyonrails.org/association_basics.html#scopes-for-has-many">http://edgeguides.rubyonrails.org/association_basics.html#scopes-for-has-many</a></p>
<p><strong>RESPONSE TO UPDATE:</strong></p>
<p>Put the order inside the block:</p>
<pre><code>has_many :friends, -> { where(friendship: {status: 'accepted'}).order('first_name DESC') }, :through => :friendships
</code></pre> |
27,426,340 | StoryBoard Assistant Editor stopped showing associated file | <p>Xcode storyboard assistant editor stopped showing related files.
"Automatic" is selected and "Class" is filled in Identity Inspector.</p>
<p>It was working before, but know it has stopped.
"Auto" or "CounterPart" modes are still woking for other files except StoryBoard.</p>
<p>A few days ago, I tried to update from Xcode 5 to 6, but later on gave up.
Would that have something to do with it?</p> | 27,861,783 | 21 | 5 | null | 2014-12-11 15:25:39.023 UTC | 13 | 2022-07-28 05:23:45.14 UTC | 2015-09-09 12:59:05.893 UTC | null | 5,236,226 | null | 2,583,906 | null | 1 | 54 | ios|objective-c|xcode|xcode-storyboard | 40,442 | <p>Found the solution (at least worked for me), it's the same bug that causes you not to be able to create new outlets. You must delete the [DerivedData] folder:</p>
<ol>
<li>Close the project you are working on with.</li>
<li>Delete the<code>【DerivedData】</code>folder of you project. (This folder may inside your project's folder, or inside
~/Library/Developer/XCode/DerivedData/(your project)/ ) or somewhere
else that were setup by you.</li>
<li>Restart Xcode.</li>
</ol>
<p>see <a href="https://stackoverflow.com/a/16182672/400112">here</a>. </p> |
59,582,008 | Preserving indentation with Tesseract OCR 4.x | <p>I'm struggling with Tesseract OCR.
I have a blood examination image, it has a table with indentation. Although tesseract recognizes the characters very well, its structure isn't preserved in the final output. For example, look the lines below "Emocromo con formula" (Eng. Translation: blood count with formula) that are indented. I want to preserve that indentation.</p>
<p>I read the other related discussions and I found the option <code>preserve_interword_spaces=1</code>. The result became slightly better but as you can see, it isn't perfect. </p>
<p>Any suggestions?</p>
<p><strong>Update</strong>:</p>
<p>I tried Tesseract v5.0 and the result is the same.</p>
<p><strong>Code:</strong></p>
<p>Tesseract version is 4.0.0.20190314 </p>
<pre><code>from PIL import Image
import pytesseract
# Preserve interword spaces is set to 1, oem = 1 is LSTM,
# PSM = 1 is Automatic page segmentation with OSD - Orientation and script detection
custom_config = r'-c preserve_interword_spaces=1 --oem 1 --psm 1 -l eng+ita'
# default_config = r'-c -l eng+ita'
extracted_text = pytesseract.image_to_string(Image.open('referto-1.jpg'), config=custom_config)
print(extracted_text)
# saving to a txt file
with open("referto.txt", "w") as text_file:
text_file.write(extracted_text)
</code></pre>
<p><strong>Result with comparison:</strong></p>
<p><a href="https://i.stack.imgur.com/gSvYj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gSvYj.jpg" alt="Result"></a></p>
<p><strong>GITHUB:</strong></p>
<p>I have created a <a href="https://github.com/AlessandroCorradini/Blood-Examination-Text-Extraction-from-Image" rel="nofollow noreferrer">GitHub</a> repository if you want to try it yourself.</p>
<p>Thanks for your help and your time</p> | 59,666,326 | 1 | 6 | null | 2020-01-03 16:27:49.497 UTC | 10 | 2020-01-19 11:46:08.917 UTC | 2020-01-06 14:10:34.18 UTC | null | 4,023,306 | null | 4,023,306 | null | 1 | 2 | python|computer-vision|ocr|tesseract|python-tesseract | 3,268 | <p><code>image_to_data()</code> function provides much more information. For each word it will return it's bounding rectangle. You can use that. </p>
<p><code>Tesseract</code> segments the image automatically to blocks. Then you can sort block by their vertical position and for each block you can find mean character width (that depends on the block's recognized font). Then for each word in the block check if it is close to the previous one, if not add spaces accordingly. I'm using <code>pandas</code> to ease on calculations, but it's usage is not necessary. Don't forget that the result should be displayed using monospaced font.</p>
<pre><code>import pytesseract
from pytesseract import Output
from PIL import Image
import pandas as pd
custom_config = r'-c preserve_interword_spaces=1 --oem 1 --psm 1 -l eng+ita'
d = pytesseract.image_to_data(Image.open(r'referto-2.jpg'), config=custom_config, output_type=Output.DICT)
df = pd.DataFrame(d)
# clean up blanks
df1 = df[(df.conf!='-1')&(df.text!=' ')&(df.text!='')]
# sort blocks vertically
sorted_blocks = df1.groupby('block_num').first().sort_values('top').index.tolist()
for block in sorted_blocks:
curr = df1[df1['block_num']==block]
sel = curr[curr.text.str.len()>3]
char_w = (sel.width/sel.text.str.len()).mean()
prev_par, prev_line, prev_left = 0, 0, 0
text = ''
for ix, ln in curr.iterrows():
# add new line when necessary
if prev_par != ln['par_num']:
text += '\n'
prev_par = ln['par_num']
prev_line = ln['line_num']
prev_left = 0
elif prev_line != ln['line_num']:
text += '\n'
prev_line = ln['line_num']
prev_left = 0
added = 0 # num of spaces that should be added
if ln['left']/char_w > prev_left + 1:
added = int((ln['left'])/char_w) - prev_left
text += ' ' * added
text += ln['text'] + ' '
prev_left += len(ln['text']) + added + 1
text += '\n'
print(text)
</code></pre>
<p>This code will produce following output:</p>
<pre><code> ssseeess+ SERVIZIO SANITARIO REGIONALE Pagina 2 di3
seoeeeees EMILIA-RROMAGNA
©2888 800
©9868 6 006 : pe ‘ ‘ "
«ee @@e@ecee Azienda Unita Sanitaria Locale di Modena
Seat se ces Amends Ospedaliero-Universitaria Policlinico di Modena
Dipartimento interaziendale ad attivita integrata di Medicina di Laboratorio e Anatomia Patologica
Direttore dr. T.Trenti
Ospedale Civile S.Agostino-Estense
S.C. Medicina di Laboratorio
S.S. Patologia Clinica - Corelab
Sistema di Gestione per la Qualita certificato UNI EN ISO 9001:2015
Responsabile dr.ssa M.Varani
Richiesta (CDA): 49/073914 Data di accettazione: 18/12/2018
Data di check-in: 18/12/2018 10:27:06
Referto del 18/12/2018 16:39:53
Provenienza: D4-cp sassuolo
Sig.
Data di Nascita:
Domicilio:
ANALISI RISULTATO __UNITA'DI MISURA VALORI DI RIFERIMENTO
Glucosio 95 mg/dl (70 - 110 )
Creatinina 1.03 mg/dl ( 0.50 - 1.40 )
eGFR Filtrato glomerulare stimato >60 ml/min Cut-off per rischio di I.R.
7 <60. Il calcolo é€ riferito
Equazione CKD-EPI ad una superfice corporea
Standard (1,73 mq)x In Caso
di etnia afroamericana
moltiplicare per il fattore
1,159.
Colesterolo 212 * mg/dl < 200 v.desiderabile
Trigliceridi 106 mg/dl < 180 v.desiderabile
Bilirubina totale 0.60 mg/dl ( 0.16 - 1.10 )
Bilirubina diretta 0.10 mg/dl ( 0.01 - 0.3 )
GOT - AST 17 U/L (1-37)
GPT - ALT ay U/L (1- 40 )
Gamma-GT 15 U/L (1-55)
Sodio 142 mEq/L ( 136 - 146 )
Potassio 4.3 mEq/L (3.5 - 5.3)
Vitamina B12 342 pg/ml ( 200 - 960 )
TSH 5.47 * ulU/ml (0.35 - 4.94 )
FT4 9.7 pg/ml (7 = 15)
Urine chimico fisico morfologico
u-Colore giallo paglierino
u-Peso specifico 1.012 ( 1.010 - 1.027 )
u-pH 5.5 (5.5 - 6.5)
u-Glucosio assente mg/dl assente
u-Proteine assente mg/dl (0 -10 )
u-Emoglobina assente mg/dl assente
u-Corpi chetonici assente mg/dl assente
u-Bilirubina assente mg/dl assente
u-Urobilinogeno 0.20 mg/dl (0- 1.0 )
sedimento non significativo
Il Laureato:
Dott. CRISTINA ROTA
Per ogni informazione o chiarimento sugli aspetti medici, puo rivolgersi al suo medico curante
Referto firmato elettronicamente secondo le norme vigenti: Legge 15 marzo 1997, n. 59; D.P.R. 10 novembre 1997, n.513;
D.P.C.M. 8 febbraio 1999; D.P.R 28 dicembre 2000, n.445; D.L. 23 gennaio 2002, n.10.
Certificato rilasciato da: Infocamere S.C.p.A. (http://www.card.infocamere. it)
i! Laureato: Dr. CRISTINA ROTA
1! documento informatico originale 6 conservato presso Parer - Polo Archivistico della Regione Emilia-Romagna
</code></pre> |
15,326,777 | Uncaught URIError: URI malformed - jquery UI tabs on Windows | <p>I'm using jquery UI tabs in a local Windows development environment. I'm testing with their <a href="http://jqueryui.com/tabs/#default">demo code</a></p>
<pre><code><div id="tabs">
<ul>
<li><a href="#tabs-1">Nunc tincidunt</a></li>
<li><a href="#tabs-2">Proin dolor</a></li>
<li><a href="#tabs-3">Aenean lacinia</a></li>
</ul>
<div id="tabs-1">
<p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. </p>
</div>
<div id="tabs-2">
<p>Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie</p>
</div>
<div id="tabs-3">
<p>Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede ve</p>
</div>
</div>
</code></pre>
<p>The problem is that I'm getting a "Uncaught URIError: URI malformed" on this function:</p>
<pre><code>function isLocal( anchor ) {
return anchor.hash.length > 1 &&
decodeURIComponent( anchor.href.replace( rhash, "" ) ) ===
Uncaught URIError: URI malformed
decodeURIComponent( location.href.replace( rhash, "" ) );
}
</code></pre>
<p>I suspect this is due to the URI on windows environment that looks like this:</p>
<pre><code>file:///C:/Work/my%20project/yadda%20ac%E7%F5es%20yadda/submenu.html#tabs-1
</code></pre>
<p>How can I have it working on local Windows, since my clients will want to see it working there before going live? I've tested and I know this is being caused by the encoding of the special characters on the uri (like on the word "acções"). <strong>Is there a way to have it working even with special characters</strong>?</p>
<p>I know I can fix this simply by removing these characters and renaming the file/folder, but I'd like to have a solution that is more client proof in case they decide to rename the folders again (and everything just goes CABOOM on their faces).</p> | 21,078,971 | 6 | 5 | null | 2013-03-10 19:52:04.633 UTC | 1 | 2018-09-06 11:11:11.393 UTC | 2013-10-30 23:35:47.247 UTC | null | 684,229 | null | 1,941,635 | null | 1 | 18 | javascript|jquery|html|jquery-ui|uri | 41,152 | <p>This is a bug in jquery - <a href="http://bugs.jqueryui.com/ticket/9518" rel="nofollow noreferrer">http://bugs.jqueryui.com/ticket/9518</a> - present for non-UTF8 URLs. I had the same problem and solved it. As I couldn't change the encoding of my page to UTF-8, I finally patched my jqueryui and used Rainer Plumer's solution as a workaround, but I had to use it twice because I have some URI parameters which contain encoded URIs. So my solution was </p>
<pre><code>decodeURIComponent( unescape( unescape(s)) )
</code></pre>
<p>More generally, there should probably be repeat-until loop, unescaping until you keep getting the same result. This workaround is not a clean solution for sure. The clean solution is asked here: </p>
<p><a href="https://stackoverflow.com/q/19702662/684229">Submit form with get method in non UTF-8 encoding</a></p>
<p>PS: the entire patch of jquery UI:</p>
<pre><code>function isLocal( anchor ) {
return anchor.hash.length > 1 &&
decodeURIComponent( unescape( unescape( anchor.href.replace( rhash, "" ) ) ) ) ===
decodeURIComponent( unescape( unescape( location.href.replace( rhash, "" ) ) ) );
}
</code></pre> |
14,928,382 | How can I get a folder from remote machine to local machine? | <p>I am trying <code>scp -r usernameipaddress:/path /pathwhereIwanttocopy</code>, but I am getting it as connection refused. </p>
<p>How can I get it? How can I get connected?</p> | 14,928,420 | 3 | 3 | null | 2013-02-18 01:54:30.98 UTC | 12 | 2016-09-08 18:26:01.053 UTC | 2016-09-08 18:26:01.053 UTC | null | 1,850,130 | null | 1,850,130 | null | 1 | 23 | linux|scp | 63,441 | <p>The -r flag should work. In your example you seem to be forgetting the name of the folder you want to copy. Try:</p>
<pre><code>scp -r nameOfFolderToCopy username@ipaddress:/path/to/copy/
</code></pre>
<p>to copy a folder from your local computer to a remote one. Or</p>
<pre><code>scp -r username@ipaddress:/path/of/folder/to/copy /target/local/directory
</code></pre>
<p>to copy a folder from a remote machine to your local one.</p> |
15,033,020 | Windows Azure Storage Certificate Expired | <p>The certificate for our Azure blob storage expired today. This is not a certificate provided by us but provided by Microsoft as show in the picture below. How does one go about fixing this? I have tried searching for a solution but found nothing. Our app cannot connect to the storage as the certificate has expired and we are getting an error indicating: Could not establish trust relationship for the SSL/TLS secure channel</p>
<p><img src="https://i.stack.imgur.com/K8F15.png" alt="enter image description here"></p> | 15,033,389 | 4 | 5 | null | 2013-02-22 20:54:38.107 UTC | 5 | 2013-02-25 11:57:36.723 UTC | null | null | null | null | 489,213 | null | 1 | 45 | azure|blob|blobstorage | 9,285 | <p>As a temporary measure I was able to log into the azure portal and change the protocol part of the connection string from https to http.</p> |
15,216,897 | How does redis claim O(1) time for key lookup? | <p>I have a question - lookup of a key value pair in an index - let's say on cassandra or postgres - is typically at around O(logn) </p>
<p>source: <a href="https://github.com/tinkerpop/blueprints/wiki/Graph-Indices" rel="noreferrer">https://github.com/tinkerpop/blueprints/wiki/Graph-Indices</a>. </p>
<p>In the redis documentation it states that runtime complexity is O(1). </p>
<p>Source: <a href="http://redis.io/commands/get" rel="noreferrer">http://redis.io/commands/get</a>
<a href="http://redis.io/commands/hget" rel="noreferrer">http://redis.io/commands/hget</a></p>
<p>And getting the value of multiple keys is only linear O(m) where m is the number of keys retrieved
<a href="http://redis.io/commands/hmget" rel="noreferrer">http://redis.io/commands/hmget</a></p>
<p>How is it possible?</p> | 15,218,599 | 1 | 1 | null | 2013-03-05 06:03:48.18 UTC | 16 | 2018-03-30 23:46:33.673 UTC | 2018-03-30 23:46:33.673 UTC | null | 1,255,825 | null | 1,255,825 | null | 1 | 46 | redis|time-complexity | 12,559 | <p>Redis is an in-memory store. It can therefore use data structures which are adapted to memory storage (allowing for fast random access).</p>
<p>To implement dictionaries (used for the main dictionary, but also for hash and set objects, and in conjunction with a skip list for zset objects), Redis use <a href="http://en.wikipedia.org/wiki/Hash_table" rel="noreferrer">separate chaining hash tables</a>, whose access complexity is O(1+n/k) where n is the number of items and k the number of buckets.</p>
<p>Redis makes sure the number of buckets grows with the number of items so that in practice n/k is kept low. This rehashing activity is done incrementally in background. When the number of items is significant, the complexity is close to O(1) (amortized).</p>
<p>Other stores (Cassandra for instance) are designed to store data on disk while minimizing the number of random I/Os for performance reasons. A hash table is not a good data structure for this, because it does not enforce the locality of the data (it does not benefit from buffer caching very well). So disk based stores usually use B-tree variants (most RDBMS) or log-structured merge (LSM) trees variants (Cassandra), which have O(log n) complexity.</p>
<p>So yes, Redis offers O(1) for many operations, but there is a constraint: all data should fit in memory. There is no magic here.</p> |
48,160,728 | ResourceWarning unclosed socket in Python 3 Unit Test | <p>I'm modifying some code to be compatible between <code>Python 2</code> and <code>Python 3</code>, but have observed a warning in unit test output.</p>
<pre><code>/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/case.py:601:
ResourceWarning: unclosed socket.socket fd=4,
family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=6,
laddr=('1.1.2.3', 65087), raddr=('5.8.13.21', 8080)
</code></pre>
<p>A little research determined this was also happening from popular libraries like <a href="https://github.com/requests/requests/issues/3912" rel="noreferrer">requests</a> and <a href="https://github.com/boto/boto3/issues/454" rel="noreferrer">boto3</a>.</p>
<p>I could ignore the warning or <a href="https://stackoverflow.com/questions/14938716/socket-resourcewarning-using-urllib-in-python-3">filter it</a> completely. If was my service, I could set the <code>connection: close</code> header in my response (<a href="https://stackoverflow.com/questions/14938716/socket-resourcewarning-using-urllib-in-python-3">link</a>).</p>
<p>Here's an example that exhibits the warning in <code>Python 3.6.1</code>:</p>
<p><strong>app.py</strong></p>
<pre><code>import requests
class Service(object):
def __init__(self):
self.session = requests.Session()
def get_info(self):
uri = 'http://api.stackexchange.com/2.2/info?site=stackoverflow'
response = self.session.get(uri)
if response.status_code == 200:
return response.json()
else:
response.raise_for_status()
def __del__(self):
self.session.close()
if __name__ == '__main__':
service = Service()
print(service.get_info())
</code></pre>
<p><strong>test.py</strong></p>
<pre><code>import unittest
class TestService(unittest.TestCase):
def test_growing(self):
import app
service = app.Service()
res = service.get_info()
self.assertTrue(res['items'][0]['new_active_users'] > 1)
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>Is there a better / correct way to manage the session so that it gets explicitly closed and not rely on <code>__del__()</code> to result in this sort of warning.</p>
<p>Thanks for any help.</p> | 54,612,520 | 2 | 3 | null | 2018-01-09 02:38:55.77 UTC | 11 | 2021-05-24 18:49:55.23 UTC | 2018-07-23 19:22:41.797 UTC | null | 9,110,128 | null | 2,233,231 | null | 1 | 66 | python|python-3.x|sockets|python-unittest | 49,236 | <p>Having the teardown logic in <code>__del__</code> can make your program incorrect or harder to reason about, because there is no guarantee on when that method will get called, potentially leading to the warning you got. There are a couple of ways to address this:</p>
<h1>1) Expose a method to close the session, and call it in the test <code>tearDown</code></h1>
<p><code>unittest</code>'s <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.tearDown" rel="noreferrer"><code>tearDown</code></a> method allows you to define some code that will be run after each test. Using this hook to close the session will work even if the test fails or has an exception, which is nice.</p>
<p><strong>app.py</strong></p>
<pre><code>import requests
class Service(object):
def __init__(self):
self.session = requests.Session()
def get_info(self):
uri = 'http://api.stackexchange.com/2.2/info?site=stackoverflow'
response = self.session.get(uri)
if response.status_code == 200:
return response.json()
else:
response.raise_for_status()
def close(self):
self.session.close()
if __name__ == '__main__':
service = Service()
print(service.get_info())
service.close()
</code></pre>
<p><strong>test.py</strong></p>
<pre><code>import unittest
import app
class TestService(unittest.TestCase):
def setUp(self):
self.service = app.Service()
super().setUp()
def tearDown(self):
self.service.close()
def test_growing(self):
res = self.service.get_info()
self.assertTrue(res['items'][0]['new_active_users'] > 1)
if __name__ == '__main__':
unittest.main()
</code></pre>
<h1>2) Use a context manager</h1>
<p>A <a href="https://docs.python.org/3/library/stdtypes.html#typecontextmanager" rel="noreferrer">context manager</a> is also a very useful way to explicitly define the scope of something. In the previous example, you have to make sure <code>.close()</code> is called correctly at every call site, otherwise your resources will leak. With a context manager, this is handled automatically even if there is an exception within the scope of the context manager.</p>
<p>Building on top of solution 1), you can define extra magic methods (<code>__enter__</code> and <code>__exit__</code>) so that your class works with the <code>with</code> statement.</p>
<p><em>Note: The nice thing here is that this code also supports the usage in solution 1), with explicit <code>.close()</code>, which can be useful if a context manager was inconvenient for some reason.</em></p>
<p><strong>app.py</strong></p>
<pre><code>import requests
class Service(object):
def __init__(self):
self.session = requests.Session()
def __enter__(self):
return self
def get_info(self):
uri = 'http://api.stackexchange.com/2.2/info?site=stackoverflow'
response = self.session.get(uri)
if response.status_code == 200:
return response.json()
else:
response.raise_for_status()
def close(self):
self.session.close()
def __exit__(self, exc_type, exc_value, traceback):
self.close()
if __name__ == '__main__':
with Service() as service:
print(service.get_info())
</code></pre>
<p><strong>test.py</strong></p>
<pre><code>import unittest
import app
class TestService(unittest.TestCase):
def test_growing(self):
with app.Service() as service:
res = service.get_info()
self.assertTrue(res['items'][0]['new_active_users'] > 1)
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>Depending on what you need, you can use either, or a combination of <code>setUp</code>/<code>tearDown</code> and context manager, and get rid of that warning, plus having more explicit resource management in your code!</p> |
9,549,780 | What does this symbol mean in JavaScript? | <h2>What is this?</h2>
<p>This is a collection of questions that come up every now and then about syntax in JavaScript. This is also a Community Wiki, <strong>so everyone is invited to participate in maintaining this list.</strong></p>
<h2>Why is this?</h2>
<p>Stack Overflow does not allow searching for particular characters. As a consequence, many questions about operators and other syntax tokens are not found easily when searching for them. This also makes closing duplicates more difficult. The list below is to help with this issue.</p>
<p>The main idea is to have links to existing questions on Stack Overflow, so it's easier for us to reference them, not to copy over content from the ECMAScript Spec.</p>
<p>Additionally, this is a blatant copy of the <a href="https://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php">PHP</a> symbol reference. We needed a JS one.</p>
<hr />
<p><strong>Please help. Edit and add links to other operators/syntax references, or if you can't find good questions/answers on a particular piece of syntax, add an answer to this question and link it</strong></p> | 9,550,412 | 1 | 7 | 2012-03-03 21:02:17.887 UTC | 2012-03-03 20:52:17.957 UTC | 221 | 2022-06-07 16:24:14.093 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 719,312 | null | 1 | 86 | javascript | 322,745 | <p>See the documentation on MDN about <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators" rel="noreferrer">expressions and operators</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements" rel="noreferrer">statements</a>.</p>
<h2>Basic keywords and general expressions</h2>
<h3><code>this</code> keyword:</h3>
<ul>
<li><a href="https://stackoverflow.com/q/3127429/1529630">How does the "this" keyword work?</a></li>
</ul>
<h3><code>var x = function()</code> vs. <code>function x()</code> — Function declaration syntax</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname">var functionName = function() {} vs function functionName() {}</a></li>
</ul>
<h3><code>(function(){</code>…<code>})()</code> — IIFE (Immediately Invoked Function Expression)</h3>
<ul>
<li><a href="https://stackoverflow.com/q/592396/1048572">What is the purpose?</a>, <a href="https://stackoverflow.com/q/8228281/1048572">How is it called?</a></li>
<li><a href="https://stackoverflow.com/q/1634268/1048572">Why does <code>(function(){…})();</code> work but <code>function(){…}();</code> doesn't?</a></li>
<li><a href="https://stackoverflow.com/q/3384504/1048572"><code>(function(){…})();</code> vs <code>(function(){…}());</code></a></li>
<li><a href="https://stackoverflow.com/q/5827290/1048572">shorter alternatives</a>:
<ul>
<li><code>!function(){…}();</code> - <a href="https://stackoverflow.com/q/3755606/1048572">What does the exclamation mark do before the function?</a></li>
<li><code>+function(){…}();</code> - <a href="https://stackoverflow.com/q/13341698/1048572">JavaScript plus sign in front of function expression</a></li>
<li><a href="https://stackoverflow.com/q/8305915/1048572">!function(){ }() vs (function(){ })()</a>, <a href="https://stackoverflow.com/q/24067605/1048572"><code>!</code> vs leading semicolon</a></li>
</ul>
</li>
<li><a href="https://stackoverflow.com/q/2716069/1048572"><code>(function(window, undefined){…}(window));</code></a></li>
</ul>
<h3><code>someFunction()()</code> — Functions which return other functions</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/18234491/two-sets-of-parentheses-after-function-call">Two sets of parentheses after function call</a></li>
</ul>
<h3><code>=></code> — Equal sign, greater than: arrow function expression syntax</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/24900875/whats-the-meaning-of-in-javascript">What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?</a></li>
</ul>
<h3><code>|></code> — Pipe, greater than: Pipeline operator</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/55143363/what-does-the-operator-do-in-javascript">What does the "|>" operator do in JavaScript?</a></li>
</ul>
<h3><code>function*</code>, <code>yield</code>, <code>yield*</code> — Star after <code>function</code> or <code>yield</code>: generator functions</h3>
<ul>
<li><a href="https://stackoverflow.com/q/9620586/1529630">What is "function*" in JavaScript?</a></li>
<li><a href="https://stackoverflow.com/q/2282140/1529630">What's the yield keyword in JavaScript?</a></li>
<li><a href="https://stackoverflow.com/q/17491779/1529630">Delegated yield (yield star, yield *) in generator functions</a></li>
</ul>
<h3><code>[]</code>, <code>Array()</code> — Square brackets: array notation</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/931872/whats-the-difference-between-array-and-while-declaring-a-javascript-ar">What’s the difference between "Array()" and "[]" while declaring a JavaScript array?</a></li>
<li><a href="https://stackoverflow.com/questions/1094723/what-is-array-literal-notation-in-javascript-and-when-should-you-use-it">What is array literal notation in javascript and when should you use it?</a></li>
</ul>
<p>If the square brackets appear on the left side of an assignment (<code>[a] = ...</code>), or inside a function's parameters, it's a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment" rel="noreferrer">destructuring assignment</a>.</p>
<h3><code>{key: value}</code> — Curly brackets: object literal syntax (not to be confused with blocks)</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/9699064/what-do-curly-braces-in-javascript-mean">What do curly braces in JavaScript mean?</a></li>
<li><a href="https://stackoverflow.com/questions/34414766/javascript-or-json-what-exactly-is-a-b-c">Javascript object literal: what exactly is {a, b, c}?</a></li>
<li><a href="https://stackoverflow.com/questions/34831262/what-do-square-brackets-around-a-property-name-in-an-object-literal-mean">What do square brackets around a property name in an object literal mean?</a></li>
<li><a href="https://stackoverflow.com/questions/32404617/how-does-this-object-method-definition-work-without-the-function-keyword">How does this object method definition work without the "function" keyword?</a> (ES2015 Method definitions)</li>
</ul>
<p>If the curly brackets appear on the left side of an assignment (<code>{ a } = ...</code>) or inside a function's parameters, it's a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment" rel="noreferrer">destructuring assignment</a>.</p>
<h3><code>`</code>…<code>${</code>…<code>}</code>…<code>`</code> — Backticks, dollar sign with curly brackets: template literals</h3>
<ul>
<li><a href="https://stackoverflow.com/q/36107981/1048572">What does this <code>`…${…}…`</code> code from the node docs mean?</a></li>
<li><a href="https://stackoverflow.com/questions/27678052/usage-of-the-backtick-character-in-javascript">Usage of the backtick character (`) in JavaScript?
</a></li>
<li><a href="https://stackoverflow.com/questions/53507972/what-is-the-purpose-of-template-literals-backticks-following-a-variable-defini">What is the purpose of template literals (backticks) following a function in ES6?</a></li>
</ul>
<h3><code>/</code>…<code>/</code> — Slashes: regular expression literals</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/16345748/meaning-of-javascript-text-between-two-slashes">Meaning of javascript text between two slashes</a></li>
</ul>
<h3><code>$</code> — Dollar sign in regex replace patterns: <code>$$</code>, <code>$&</code>, <code>$`</code>, <code>$'</code>, <code>$<i>n</i></code></h3>
<ul>
<li><a href="https://stackoverflow.com/questions/38866071/javascript-replace-method-dollar-signs">JavaScript replace() method dollar signs</a></li>
</ul>
<h3><code>()</code> — Parentheses: grouping operator</h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Grouping" rel="noreferrer">MDN: Grouping operator</a></li>
</ul>
<hr />
<h2>Property-related expressions</h2>
<h3><code>obj.prop</code>, <code>obj[prop]</code>, <code>obj["prop"]</code> — Square brackets or dot: property accessors</h3>
<ul>
<li><a href="https://stackoverflow.com/q/4968406">JavaScript property access: dot notation vs. brackets?</a></li>
</ul>
<h3><code>?.</code>, <code>?.[]</code>, <code>?.()</code> — Question mark, dot: optional chaining operator</h3>
<ul>
<li><a href="https://stackoverflow.com/q/63722601">Question mark after parameter</a></li>
<li><a href="https://stackoverflow.com/questions/32139078/null-safe-property-access-and-conditional-assignment-in-es6-2015">Null-safe property access (and conditional assignment) in ES6/2015</a></li>
<li><a href="https://stackoverflow.com/questions/26183944/optional-chaining-in-javascript">Optional Chaining in JavaScript</a></li>
<li><a href="https://stackoverflow.com/questions/6613952/is-there-a-null-coalescing-elvis-operator-or-safe-navigation-operator-in-javas">Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?</a></li>
<li><a href="https://stackoverflow.com/questions/476436/is-there-a-null-coalescing-operator-in-javascript">Is there a "null coalescing" operator in JavaScript?</a></li>
</ul>
<h3><code>::</code> — Double colon: bind operator</h3>
<ul>
<li><a href="https://stackoverflow.com/q/31220078/1529630">JavaScript double colon (bind operator)</a></li>
</ul>
<h3><code>new</code> operator</h3>
<ul>
<li><a href="https://stackoverflow.com/q/1646698/1529630">What is the 'new' keyword in JavaScript?</a></li>
<li><a href="https://stackoverflow.com/q/32450516/1529630">What is "new.target"?</a></li>
</ul>
<h3><code>...iter</code> — Three dots: spread syntax; rest parameters</h3>
<ul>
<li><code>(...rest) => {}</code> — <a href="https://stackoverflow.com/q/42184674">What is the meaning of “…args” (three dots) in a function definition?</a></li>
<li><code>fn(...args)</code> — <a href="https://stackoverflow.com/q/42118201">What is the meaning of “foo(…arg)” (three dots in a function call)?</a></li>
<li><code>[...iter]</code> — <a href="https://stackoverflow.com/q/33890525">javascript es6 array feature […data, 0] “spread operator”</a></li>
<li><code>{...props}</code> — <a href="https://stackoverflow.com/q/48464211">Javascript Property with three dots (…)</a>, <a href="https://stackoverflow.com/q/47689680">What does the '…rest' stand for in this object destructuring?</a></li>
</ul>
<hr />
<h2>Increment and decrement</h2>
<h3><code>++</code>, <code>--</code> — Double plus or minus: pre- / post-increment / -decrement operators</h3>
<ul>
<li><a href="https://stackoverflow.com/q/3469885/1048572"><code>++someVariable</code> vs <code>someVariable++</code> in Javascript</a></li>
</ul>
<hr />
<h2>Unary and binary (arithmetic, logical, bitwise) operators</h2>
<h3><code>delete</code> operator</h3>
<ul>
<li><a href="https://stackoverflow.com/q/8945276/1529630">What is the purpose of the delete operator in Javascript?</a></li>
</ul>
<h3><code>void</code> operator</h3>
<ul>
<li><a href="https://stackoverflow.com/q/7452341/1048572">What does `void 0` mean?</a></li>
</ul>
<h3><code>+</code>, <code>-</code> — Plus and minus: addition or concatenation, and subtraction operators; unary sign operators</h3>
<ul>
<li><a href="https://stackoverflow.com/q/15129137/1048572">What does = +_ mean in JavaScript</a>, <a href="https://stackoverflow.com/q/14470973/1048572">Single plus operator in javascript</a></li>
<li><a href="https://stackoverflow.com/q/5450076/1048572">What's the significant use of unary plus and minus operators?</a></li>
<li><a href="https://stackoverflow.com/questions/7124884/why-is-1-2-3-4-1-23-4-in-javascript">Why is [1,2] + [3,4] = "1,23,4" in JavaScript?</a></li>
<li><a href="https://stackoverflow.com/questions/24383788/1048572">Why does JavaScript handle the plus and minus operators between strings and numbers differently?</a></li>
</ul>
<h3><code>|</code>, <code>&</code>, <code>^</code>, <code>~</code> — Single pipe, ampersand, circumflex, tilde: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_logical_operators" rel="noreferrer">bitwise OR, AND, XOR, & NOT operators</a></h3>
<ul>
<li><a href="https://stackoverflow.com/questions/4535328/what-do-these-operators-do">What do these JavaScript bitwise operators do?</a></li>
<li><a href="https://stackoverflow.com/q/6260475/1048572">How to: The ~ operator?</a></li>
<li><a href="https://stackoverflow.com/q/3374811/1048572">Is there a & logical operator in Javascript</a></li>
<li><a href="https://stackoverflow.com/q/6194950/1048572">What does the "|" (single pipe) do in JavaScript?</a></li>
<li><a href="https://stackoverflow.com/q/12854644/1048572">What does the operator |= do in JavaScript?</a></li>
<li><a href="https://stackoverflow.com/q/3618340/1048572">What does the ^ (caret) symbol do in JavaScript?</a></li>
<li><a href="https://stackoverflow.com/questions/7487977/using-bitwise-or-0-to-floor-a-number">Using bitwise OR 0 to floor a number</a>, <a href="https://stackoverflow.com/questions/9049677/how-does-x0-floor-the-number-in-javascript">How does x|0 floor the number in JavaScript?</a></li>
<li><a href="https://stackoverflow.com/q/31377474/1048572">Why does <code>~1</code> equal <code>-2</code>?</a></li>
<li><a href="https://stackoverflow.com/q/4055633/1048572">What does ~~ ("double tilde") do in Javascript?</a></li>
<li><a href="https://stackoverflow.com/q/9316612/1048572">How does !!~ (not not tilde/bang bang tilde) alter the result of a 'contains/included' Array method call?</a> (also <a href="https://stackoverflow.com/q/12299665/1048572">here</a> and <a href="https://stackoverflow.com/q/10582286/1048572">here</a>)</li>
</ul>
<h3><code>%</code> — Percent sign: remainder operator</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/8900652/what-does-do-in-javascript">What does % do in JavaScript?</a></li>
</ul>
<h3><code>&&</code>, <code>||</code>, <code>!</code> — Double ampersand, double pipe, exclamation point: logical operators</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/4535647/logical-operators-in-javascript-how-do-you-use-them">Logical operators in JavaScript — how do you use them?</a></li>
<li><a href="https://stackoverflow.com/questions/9579262/logical-operator-in-javascript-0-stands-for-boolean-false">Logical operator || in javascript, 0 stands for Boolean false?</a></li>
<li><a href="https://stackoverflow.com/questions/6439579/what-does-var-foo-foo-mean-in-javascript">What does "var FOO = FOO || {}" (assign a variable or an empty object to that variable) mean in Javascript?</a>, <a href="https://stackoverflow.com/q/2100758/1048572">JavaScript OR (||) variable assignment explanation</a>, <a href="https://stackoverflow.com/q/2802055/1048572">What does the construct x = x || y mean?</a></li>
<li><a href="https://stackoverflow.com/q/3163407/1048572">Javascript AND operator within assignment</a></li>
<li><a href="https://stackoverflow.com/q/6970346/1048572">What is "x && foo()"?</a> (also <a href="https://stackoverflow.com/q/12664230/1048572">here</a> and <a href="https://stackoverflow.com/q/6829736/1048572">here</a>)</li>
<li><a href="https://stackoverflow.com/questions/784929/what-is-the-not-not-operator-in-javascript">What is the !! (not not) operator in JavaScript?</a></li>
<li><a href="https://stackoverflow.com/questions/8012003/what-is-an-exclamation-point-in-javascript">What is an exclamation point in JavaScript?</a></li>
</ul>
<h3><code>??</code> — Double question mark: nullish-coalescing operator</h3>
<ul>
<li><a href="https://stackoverflow.com/q/65022531/4642212">How is the nullish coalescing operator (??) different from the logical OR operator (||) in ECMAScript?</a></li>
<li><a href="https://stackoverflow.com/questions/6613952/is-there-a-null-coalescing-elvis-operator-or-safe-navigation-operator-in-javas">Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?</a></li>
<li><a href="https://stackoverflow.com/questions/476436/is-there-a-null-coalescing-operator-in-javascript">Is there a "null coalescing" operator in JavaScript?</a></li>
</ul>
<h3><code>**</code> — Double star: power operator (exponentiation)</h3>
<ul>
<li><code>x ** 2</code> is equivalent to <code>Math.pow(x, 2)</code></li>
<li><a href="https://stackoverflow.com/questions/33284569/is-the-double-asterisk-a-valid-javascript-operator">Is the double asterisk ** a valid JavaScript operator?</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation" rel="noreferrer">MDN documentation</a></li>
</ul>
<hr />
<h2>Equality operators</h2>
<h3><code>==</code>, <code>===</code> — Equal signs: equality operators</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use">Which equals operator (== vs ===) should be used in JavaScript comparisons?</a></li>
<li><a href="https://stackoverflow.com/questions/27523765/how-does-js-type-coercion-work">How does JS type coercion work?</a></li>
<li><a href="https://stackoverflow.com/questions/664886/in-javascript-int-value-int-value-evaluates-to-true-why-is-it-so">In Javascript, <int-value> == "<int-value>" evaluates to true. Why is it so?</a></li>
<li><a href="https://stackoverflow.com/questions/38662231">[] == ![] evaluates to true</a></li>
<li><a href="https://stackoverflow.com/questions/19277458/why-does-undefined-equals-false-return-false/19277873">Why does "undefined equals false" return false?</a></li>
<li><a href="https://stackoverflow.com/questions/8695341/why-does-new-booleanfalse-equals-false-in-javascript">Why does !new Boolean(false) equals false in JavaScript?</a></li>
<li><a href="https://stackoverflow.com/questions/25190495/javascript-0-0-explain-this-example">Javascript 0 == '0'. Explain this example</a></li>
<li><a href="https://stackoverflow.com/questions/38814212/why-false-false-is-false">Why false == "false" is false?</a></li>
</ul>
<h3><code>!=</code>, <code>!==</code> — Exclamation point and equal signs: inequality operators</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/1889260/javascript-operator">!= vs. !==</a></li>
<li><a href="https://stackoverflow.com/questions/1889260/javascript-operator">What is the difference between != and !== operators in JavaScript?</a></li>
</ul>
<hr />
<h2>Bit shift operators</h2>
<h3><code><<</code>, <code>>></code>, <code>>>></code> — Two or three angle brackets: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_shift_operators" rel="noreferrer">bit shift operators</a></h3>
<ul>
<li><a href="https://stackoverflow.com/questions/4535328/what-do-these-operators-do">What do these JavaScript bitwise operators do?</a></li>
<li><a href="https://stackoverflow.com/q/5528119">Double more-than symbol in JavaScript</a></li>
<li><a href="https://stackoverflow.com/q/1822350/1048572">What is the JavaScript >>> operator and how do you use it?</a></li>
</ul>
<hr />
<h2>Conditional operator</h2>
<h3>…<code>?</code>…<code>:</code>… — Question mark and colon: conditional (ternary) operator</h3>
<ul>
<li><a href="https://stackoverflow.com/q/1771786/1048572">Question mark and colon in JavaScript</a></li>
<li><a href="https://stackoverflow.com/q/1788917/1048572">Operator precedence with Javascript Ternary operator</a></li>
<li><a href="https://stackoverflow.com/q/6259982/1106925">How do you use the ? : (conditional) operator in JavaScript?</a></li>
</ul>
<hr />
<h2><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#Assignment_operators" rel="noreferrer">Assignment operators</a></h2>
<h3><code>=</code> — Equal sign: assignment operator</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/11871616/in-javascript-vs/">What is the difference between the `=` and `==` operators and what is `===`? (Single, double, and triple equals)</a></li>
</ul>
<p>This symbol is also used for <em>default parameters</em> or <em>default values</em> in a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment" rel="noreferrer">destructuring assignment</a>:</p>
<ul>
<li><a href="https://stackoverflow.com/q/35526463">what does (state = {}) => state means</a></li>
<li><a href="https://stackoverflow.com/q/65523228">What does ({"key": "value"} = {}) syntax mean inside a JavaScript function</a></li>
</ul>
<h3><code>%=</code> — Percent equals: remainder assignment</h3>
<ul>
<li><a href="https://stackoverflow.com/q/62771733">Having Confusion with Modulo operator</a></li>
</ul>
<h3><code>+=</code> — Plus equals: addition assignment operator</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/6826260/how-does-plus-equal-work">How does += (plus equal) work?</a></li>
</ul>
<h3><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND_assignment" rel="noreferrer"><code>&&=</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR_assignment" rel="noreferrer"><code>||=</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_nullish_assignment" rel="noreferrer"><code>??=</code></a> — Double ampersand, pipe, or question mark, followed by equal sign: logical assignments</h3>
<ul>
<li><a href="https://stackoverflow.com/q/64617548">What purpose do &&=, ||= and ??= serve?</a></li>
<li><a href="https://stackoverflow.com/a/62824506">Replace a value if null or undefined in JavaScript</a></li>
<li><a href="https://stackoverflow.com/a/62824667">Set a variable if undefined</a></li>
<li><a href="https://stackoverflow.com/a/58635332">Ruby’s <code>||=</code> (or equals) in JavaScript?</a></li>
<li><a href="https://github.com/tc39/proposal-logical-assignment" rel="noreferrer">Original proposal</a></li>
<li><a href="https://tc39.es/ecma262/#sec-assignment-operators" rel="noreferrer">Specification</a></li>
</ul>
<h3><code><<=</code>, <code>>>=</code>, <code>>>>=</code>, <code>&=</code>, <code>^=</code>, <code>|=</code> — Double less than, double greater than, triple greater than, ampersand, caret, or pipe followed by equal sign: bitwise assignments</h3>
<ul>
<li><a href="https://stackoverflow.com/q/4535328">What do these JavaScript bitwise operators do?</a></li>
</ul>
<h3>Destructuring</h3>
<ul>
<li>of function parameters: <a href="https://stackoverflow.com/q/10804982/1048572">Where can I get info on the object parameter syntax for JavaScript functions?</a></li>
<li>of arrays: <a href="https://stackoverflow.com/q/3986348/1048572">Multiple assignment in javascript? What does [a,b,c] = [1, 2, 3]; mean?</a></li>
<li>of objects/imports: <a href="https://stackoverflow.com/q/26999820/1048572">Javascript object bracket notation ({ Navigation } =) on left side of assign</a></li>
</ul>
<hr />
<h2>Comma operator</h2>
<h3><code>,</code> — Comma operator (not to be confused with the comma used in variable declarations)</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/3561043/javascript-syntax-what-comma-means">What does a comma do in JavaScript expressions?</a></li>
<li><a href="https://stackoverflow.com/questions/5580596/javascript-comma-operator">Comma operator returns first value instead of second in argument list?</a></li>
<li><a href="https://stackoverflow.com/questions/9579546/comma-operator-where-it-can-really-be-useful">When is the comma operator useful?</a></li>
</ul>
<hr />
<h2>Control flow</h2>
<h3><code>{</code>…<code>}</code> — Curly brackets: blocks (not to be confused with object literal syntax)</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/18130025/javascript-curly-braces-with-no-function-or-json">JavaScript curly braces with no function or json</a></li>
</ul>
<h2>Declarations</h2>
<h3><code>var</code>, <code>let</code>, <code>const</code> — Declaring variables</h3>
<ul>
<li><a href="https://stackoverflow.com/q/762011/1529630">What's the difference between using "let" and "var"?</a></li>
<li><a href="https://stackoverflow.com/q/130396/1529630">Are there constants in JavaScript?</a></li>
<li><a href="https://stackoverflow.com/q/33198849/1529630">What is the temporal dead zone?</a></li>
<li><code>var a, b;</code> — Comma used in variable declarations (not to be confused with the comma operator): <a href="https://stackoverflow.com/q/3781406/4642212">JavaScript variable definition: Commas vs. Semicolons</a></li>
</ul>
<hr />
<h2>Label</h2>
<h3><code>label:</code> — Colon: labels</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/39655737">What does the JavaScript syntax foo: mean?</a></li>
<li><a href="https://stackoverflow.com/questions/418799">What does ':' (colon) do in JavaScript?</a></li>
</ul>
<hr />
<h2>Other</h2>
<h3><code>123n</code> — <code>n</code> after integer: BigInt</h3>
<ul>
<li><a href="https://stackoverflow.com/q/59977095">What does character 'n' after numeric literal mean in JavaScript?</a></li>
</ul>
<h3><code>#</code> — Hash (number sign): Private methods or private fields</h3>
<ul>
<li><a href="https://stackoverflow.com/q/64968964/4642212">What does the <code>#</code> symbol do in JavaScript?</a></li>
</ul>
<h2><code>_</code> — Underscore: separator in numeric literals</h2>
<ul>
<li><a href="https://stackoverflow.com/q/58965960">Javascript numeric separators?</a></li>
<li><a href="https://stackoverflow.com/q/20350106">Is there a Javascript equivalent to the Ruby syntax using underscores (e.g. 10_000 = 10000) to make larger integers human readable?</a></li>
</ul> |
4,917,326 | How to iterate over the files of a certain directory, in Java? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/3154488/best-way-to-iterate-through-a-directory-in-java">Best way to iterate through a directory in java?</a> </p>
</blockquote>
<p>I want to process each file in a certain directory using Java. </p>
<p>What is the easiest (and most common) way of doing this?</p> | 4,917,347 | 4 | 2 | null | 2011-02-07 00:53:08.677 UTC | 20 | 2016-09-27 10:40:18.947 UTC | 2017-05-23 12:18:15.39 UTC | null | -1 | null | 492,886 | null | 1 | 122 | java|file|directory | 248,315 | <p>If you have the directory name in <code>myDirectoryPath</code>,</p>
<pre><code>import java.io.File;
...
File dir = new File(myDirectoryPath);
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
// Do something with child
}
} else {
// Handle the case where dir is not really a directory.
// Checking dir.isDirectory() above would not be sufficient
// to avoid race conditions with another process that deletes
// directories.
}
</code></pre> |
5,123,489 | How to overlay a play button over a YouTube thumbnail image | <p>In a project I'm working on, we're pulling over a bunch of YouTube videos that our media team has published into a database so we can present them as related content. </p>
<p>Something we'd like to be able to do is overlay a play button on top of the generated YouTube thumbnails so it's more obvious that the thumbnail represents a video that can be played. </p>
<p>I'm looking for the best way to accomplish this - I've done some searching and either no one is interested in doing this, it's really obvious how to do it or I'm just struggling to come up with the right search terms. </p>
<p>The ways I've come up with so far are: </p>
<ol>
<li>Use a container div that has a play background image and lower the opacity of the thumbnail to display the play button over the thumbnail. I'm not a huge fan of this because of the extra div and it doesn't seem to work in IE.</li>
<li>Batch process the thumbnails in photoshop - altering them so they have a play button. This would be somewhat unfortunate because we're pulling down videos every night - so sometime there would be some videos without play buttons.</li>
<li>Modify the import process to dynamically generate new thumbnails with the play button. This would fix both of the above issues, but would be more difficult to do.</li>
</ol>
<p>I was hoping to be able to just add a class to the image and use javascript and/or CSS to overlay the image. </p>
<p>If anyone has some advice on this, I'd really appreciate it.</p>
<p>Current html (posted by OP in comments):</p>
<pre><code><li>
<a
class="youtube"
title="{ video id here }"
href="youtube.com/watch?v={video id here}">
<img
src="i3.ytimg.com/vi{ video id here }/default.jpg"
alt="{ video title here }" />
</a><br />
<a
class="youtube"
title="{vide id here }"
href="youtube.com/watch?v={ video id here }">
{ video title here }
</a>
</li>
</code></pre> | 5,123,612 | 5 | 4 | null | 2011-02-25 22:38:48.507 UTC | 10 | 2022-07-25 12:56:40.457 UTC | 2012-09-27 11:58:30.337 UTC | null | 316,041 | null | 133,273 | null | 1 | 29 | jquery|css|youtube|photoshop | 97,736 | <pre><code><div class="video">
<img src="thumbnail..." />
<a href="#">link to video</a>
</div>
</code></pre>
<p>css</p>
<pre><code>.video { position: relative; }
.video a {
position: absolute;
display: block;
background: url(url_to_play_button_image.png);
height: 40px;
width: 40px;
top: 20px;
left: 20px;
}
</code></pre>
<p>I would do something like that. In any case, I don't think it's a good idea to post process the images to add the play button. What if you need to change the button design for instance?</p>
<hr>
<p>If you want to center the button, a nice way to do it is to set top and left to 50%, and then adding negative margins equal to half of the size of the button:</p>
<pre><code>.video a {
position: absolute;
display: block;
background: url(url_to_play_button_image.png);
height: 40px;
width: 40px;
top: 50%;
left: 50%;
margin: -20px 0 0 -20px;
}
</code></pre> |
5,437,158 | Remove a trailing slash from a string(changed from url type) in JAVA | <p>I want to remove the trailing slash from a string in Java. </p>
<p>I want to check if the string ends with a url, and if it does, i want to remove it.</p>
<p>Here is what I have:</p>
<pre><code>String s = "http://almaden.ibm.com/";
s= s.replaceAll("/","");
</code></pre>
<p>and this:</p>
<pre><code>String s = "http://almaden.ibm.com/";
length = s.length();
--length;
Char buff = s.charAt((length);
if(buff == '/')
{
LOGGER.info("ends with trailing slash");
/*how to remove?*/
}
else LOGGER.info("Doesnt end with trailing slash");
</code></pre>
<p>But neither work.</p> | 57,960,233 | 10 | 0 | null | 2011-03-25 19:24:27.79 UTC | 2 | 2019-09-16 15:38:21.213 UTC | 2013-04-11 22:51:17.64 UTC | null | 445,131 | null | 450,117 | null | 1 | 49 | java|url|slash|trailing | 70,678 | <p>You can achieve this with <a href="https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#removeEnd-java.lang.String-java.lang.String-" rel="noreferrer">Apache Commons StringUtils</a> as follows:</p>
<pre><code>String s = "http://almaden.ibm.com/";
StringUtils.removeEnd(s, "/")
</code></pre> |
5,446,316 | Code-first vs Model/Database-first | <p><strong>What are the pros & cons of using Entity Framework 4.1 Code-first over Model/Database-first with EDMX diagram?</strong></p>
<p>I'm trying to fully understand all the approaches to building data access layer using EF 4.1. I'm using Repository pattern and <code>IoC</code>.</p>
<p>I know I can use code-first approach: define my entities and context by hand and use <code>ModelBuilder</code> to fine-tune the schema.</p>
<p>I can also create an <code>EDMX</code> diagram and choose a code generation step that uses T4 templates to generate the same <code>POCO</code> classes. </p>
<p>In both cases I end up with <code>POCO</code> object which are <code>ORM</code> agnostic and context that derives from <code>DbContext</code>.</p>
<p>Database-first seems to be most appealing since I can design database in Enterprise Manager, quickly synch the model and fine-tune it using the designer. </p>
<p>So what is the difference between those two approaches? Is it just about the preference VS2010 vs Enterprise Manager?</p> | 5,446,587 | 10 | 5 | null | 2011-03-27 00:17:41.667 UTC | 311 | 2019-06-20 20:25:44.517 UTC | 2015-06-29 15:26:47.81 UTC | null | 7,720 | null | 449,906 | null | 1 | 650 | entity-framework|ef-code-first|entity-framework-4.1|poco|ef-database-first | 344,028 | <p>I think the differences are:</p>
<p><strong>Code first</strong></p>
<ul>
<li>Very popular because hardcore programmers don't like any kind of designers and defining mapping in EDMX xml is too complex.</li>
<li>Full control over the code (no autogenerated code which is hard to modify).</li>
<li>General expectation is that you do not bother with DB. DB is just a storage with no logic. EF will handle creation and you don't want to know how it does the job.</li>
<li>Manual changes to database will be most probably lost because your code defines the database.</li>
</ul>
<p><strong>Database first</strong></p>
<ul>
<li>Very popular if you have DB designed by DBAs, developed separately or if you have existing DB. </li>
<li>You will let EF create entities for you and after modification of mapping you will generate POCO entities.</li>
<li>If you want additional features in POCO entities you must either T4 modify template or use partial classes.</li>
<li>Manual changes to the database are possible because the database defines your domain model. You can always update model from database (this feature works quite well).</li>
<li>I often use this together VS Database projects (only Premium and Ultimate version).</li>
</ul>
<p><strong>Model first</strong></p>
<ul>
<li>IMHO popular if you are designer fan (= you don't like writing code or SQL).</li>
<li>You will "draw" your model and let workflow generate your database script and T4 template generate your POCO entities. You will lose part of the control on both your entities and database but for small easy projects you will be very productive.</li>
<li>If you want additional features in POCO entities you must either T4 modify template or use partial classes.</li>
<li>Manual changes to database will be most probably lost because your model defines the database. This works better if you have Database generation power pack installed. It will allow you updating database schema (instead of recreating) or updating database projects in VS.</li>
</ul>
<p>I expect that in case of EF 4.1 there are several other features related to Code First vs. Model/Database first. Fluent API used in Code first doesn't offer all features of EDMX. I expect that features like stored procedures mapping, query views, defining views etc. works when using Model/Database first and <code>DbContext</code> (I haven't tried it yet) but they don't in Code first.</p> |
12,164,977 | Write data to a file in Python | <p>How can I save data to a file (that I will plot later on) effectively?</p>
<p>I have got this from my research:</p>
<pre><code>#Open new data file
f = open("data2.txt", "w")
f.write( str(yEst) ) # str() converts to string
f.close()
</code></pre>
<p>Here is a bit of my code so far:</p>
<pre><code>for i in drange2(0, 2*math.pi + 0.0634665182543392 , 0.0634665182543392):
for x in range(1,N+1):
yEst = yEst + a * cos(x* i)
#print yEst
f.write( str(yEst) ) # str() converts to string
yEst=0
f.close()
</code></pre>
<p>Now, when I go and open my file "<code>data2.txt</code>" I can not read the data because it is not 'organized'. How can I go to the next line using the <code>f.write( str(yEst) )</code> so that I have a column that contains my 'yEst' data into the file "data2.txt?
Thank you in advance for your consideration :)</p>
<p>PS: yEst looks like (in the data2.txt file): <code>48.901347147148.605785828748.114506165947.429486 ..</code> and I want it as a column: --></p>
<pre><code>48.9013471471 (new line)
48.6057858287 (new line)
48.1145061659 (new line)
47.4294863684
etc ..
</code></pre> | 12,165,512 | 3 | 9 | null | 2012-08-28 18:05:32.89 UTC | 6 | 2015-08-24 15:04:07.403 UTC | 2015-08-24 15:04:07.403 UTC | null | 832,136 | null | 1,631,109 | null | 1 | 9 | python | 101,342 | <p>Do you mean to say you'd like each point of data on its own line, like this?</p>
<pre><code>48.9013471471
48.6057858287
48.1145061659
47.4294863684
</code></pre>
<p>If so, then you might like to try something like this:</p>
<pre><code>for i in drange2(0, 2*math.pi + 0.0634665182543392 , 0.0634665182543392):
for x in range(1,N+1):
yEst = yEst + a * cos(x* i)
f.write( str(yEst) + "\n" )
f.close()
</code></pre>
<p>Firstly, to write each data point to the line, it needs to be 'inside' the loop - that's why I've added extra space to the line before I call <code>f.write</code>. </p>
<p>The second thing I added is <code>+ "\n"</code> - this will add the new line character to the end of the line. You can change it to whatever you'd like! A couple of examples:</p>
<p><code>f.write( str(yEst) + " " )</code> will add one space after each data point:</p>
<pre><code>48.9013471471 48.6057858287 48.1145061659 47.4294863684
</code></pre>
<p><code>f.write( str(yEst) + "|" )</code> will add one pipe character after each data point:</p>
<pre><code>48.9013471471|48.6057858287|48.1145061659|47.4294863684|
</code></pre>
<hr>
<p>If, on the other hand, you'd rather just save the data as an array, try the below:</p>
<pre><code>yEst = 0 # or some initial value
yEstArray = []
for i in drange2(0, 2*math.pi + 0.0634665182543392 , 0.0634665182543392):
for x in range(1,N+1):
yEst = yEst + a * cos(x* i)
yEstArray.append(yEst)
</code></pre>
<p>Then, you can iterate over the array like so:</p>
<pre><code>for yEst in yEstArray:
do something with yEst
</code></pre>
<p>or</p>
<pre><code>for yEst, index in enumerate(yEstArray):
do something with yEst and its index
</code></pre> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.