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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7,228,715 | Git: failed to push some refs although I have done git pull | <p>I started to get 'failed to push some refs' error when I changed some files and tried to do push. Most instructions tell to do git pull first. I have done it and git says everything is up to date. Any idea how to solve the error? I also started getting 'no version information available' message, I don't know does that have anything to do with the error.</p>
<pre><code>git push origin master
git: /usr/local/lib/libz.so.1: no version information available (required by git)
Enter passphrase for key '/root/.ssh/id_rsa':
To git@[mydomain].beanstalkapp.com:/repo-git.git
! [rejected] master -> master (non-fast forward)
error: failed to push some refs to 'git@[mydomain].beanstalkapp.com:/repo-git.git'
</code></pre> | 7,228,868 | 7 | 1 | null | 2011-08-29 10:08:03.38 UTC | 4 | 2017-10-28 16:51:22.013 UTC | null | null | null | null | 692,695 | null | 1 | 23 | git | 68,134 | <p>The error is that somebody else has pushed in the <code>master</code> branch and you would overwrite their change if <code>git</code> allowed you to push (this is what <code>non-fast forward</code> error means). So you need to merge your local <code>master</code> branch with the remote <code>master</code> branch.</p>
<p>This can happen if you did the <code>git pull</code> while the local branch was not the <code>master</code> branch. If you only want to push the branch you are working on and not the <code>master</code> branch, you need to tell it to <code>git</code> using the complete form of <code>git-push</code>:</p>
<pre><code>$ git push remote local-branch:remote-branch
</code></pre> |
14,022,791 | What is Control.Applicative.Lift useful for? | <p>I wrote about <a href="http://hackage.haskell.org/package/transformers" rel="noreferrer"><code>transformers</code></a> in a recent blog post, and someone asked "what do people use <a href="http://hackage.haskell.org/packages/archive/transformers/0.3.0.0/doc/html/Control-Applicative-Lift.html" rel="noreferrer">Control.Applicative.Lift</a> for?" I wasn't able to answer this, so I echo the question to StackOverflow - what <em>is</em> <a href="http://hackage.haskell.org/packages/archive/transformers/0.3.0.0/doc/html/Control-Applicative-Lift.html" rel="noreferrer"><code>Control.Applicative.Lift</code></a> used for?</p>
<p>I see one example use of it in the package, but I don't seem to be entirely able to parse what it does. Does anyone know any other examples in the wild?</p> | 14,022,871 | 1 | 0 | null | 2012-12-24 14:53:39.767 UTC | 10 | 2014-02-09 18:36:32.657 UTC | 2012-12-24 15:03:54.61 UTC | null | 83,805 | null | 74,497 | null | 1 | 21 | haskell|monads|monad-transformers|applicative | 1,101 | <p><a href="http://hackage.haskell.org/packages/archive/transformers/latest/doc/html/src/Control-Applicative-Lift.html#Lift">Lift</a> is a relatively new contribution:</p>
<pre><code>data Lift f a = Pure a | Other (f a)
</code></pre>
<p>That is, given a functor <code>f</code> , you can get a new functor by composing <code>f</code> with a pure value.</p>
<p>The package itself gives an example:</p>
<pre><code>-- | An applicative functor that collects a monoid (e.g. lists) of errors.
-- A sequence of computations fails if any of its components do, but
-- unlike monads made with 'ErrorT' from "Control.Monad.Trans.Error",
-- these computations continue after an error, collecting all the errors.
type Errors e = Lift (Constant e)
-- | Report an error.
failure :: Monoid e => e -> Errors e a
failure e = Other (Constant e)
</code></pre>
<p>I don't know of any in-the-wild uses of this, however.</p> |
13,822,348 | Are there any javascript libraries that can render terminal output in a browser? | <p>I've got a text file that contains terminal output which includes all kinds of character codes such as moving the cursor around, etc. How can I render this properly in a browser?</p> | 13,823,317 | 4 | 3 | null | 2012-12-11 14:54:59.06 UTC | 14 | 2018-06-14 08:21:01.317 UTC | null | null | null | null | 770,126 | null | 1 | 26 | javascript|linux | 8,785 | <p>There are sevral options that I've found based on terminal emulation using Javascript:</p>
<ul>
<li><a href="http://terminal.jcubic.pl/" rel="noreferrer">jQuery Terminal plugin</a></li>
<li><a href="https://github.com/liftoff/GateOne" rel="noreferrer">GateOne</a></li>
<li><a href="http://cb.vu/" rel="noreferrer">http://cb.vu/</a></li>
<li><a href="http://code.google.com/p/shellinabox/" rel="noreferrer">shellinabox</a></li>
</ul>
<p>The first option seems to be the closest solution to what you need.</p> |
14,184,956 | Async Google Maps API v3 undefined is not a function | <p>I'm writing an app that loads Google Maps asynchronously with a hand-built framework.<br>
When I load maps it will not load all of it for some reason and I'll end up with a <code>Uncaught TypeError: undefined is not a function</code>. I checked chrome inspector and found out that <code>google.maps</code> is a valid object, but it has none of its own properties. I manually call the "initialize function" well after the document has loaded. What am I doing wrong?!</p> | 14,185,834 | 1 | 2 | null | 2013-01-06 17:52:30.333 UTC | 15 | 2015-02-13 22:59:37.907 UTC | null | null | null | null | 558,721 | null | 1 | 30 | javascript|google-maps-api-3|asynchronous | 79,095 | <p>You can't load the maps-API asynchronous with the well-known URL( <a href="http://maps.googleapis.com/maps/api/js?v=3&sensor=false">http://maps.googleapis.com/maps/api/js?v=3&sensor=false</a> )</p>
<p>When you take a look at the script-file, you'll see, that this is not the API that gets loaded, it's a loader that loads the API. The loader makes use of <code>document.write()</code> , what will lead you to unexpected results when called after the document has been loaded.</p>
<p>Furthermore the onload-event of the document doesn't wait for asynchronous loaded objects, it may come too quick.</p>
<p>You also cannot use the load-event of the script to invoke the initialize-function, because when it fires, the loader is loaded, not the maps-API.</p>
<p><strong>What to do:</strong><br>
append a callback-parameter to the script-URL(with the name of the initialize-function as value) </p>
<p><code><a href="http://maps.googleapis.com/maps/api/js?v=3&sensor=false&callback=initialize">http://maps.googleapis.com/maps/api/js?v=3&sensor=false&<b>callback=initialize</b></a></code></p>
<p>Now you get a different loader which:</p>
<ol>
<li>doesn't use <code>document.write()</code></li>
<li>calls the callback-function(initialize) when the maps-API has been loaded</li>
</ol>
<p>Demo: <a href="http://jsfiddle.net/doktormolle/7cu2F/"><strong>http://jsfiddle.net/doktormolle/7cu2F/</strong></a></p>
<hr>
<p><strong>Related to the comment</strong>: <em>seems the callback has to be a function attached to window directly. not cool google :)</em></p>
<p>There is another option, <a href="https://developers.google.com/loader/">the google-API-loader</a> which supports the usage of function-references (instead of function-names).</p>
<p>Sample, which loads the maps-API asynchronously, but only when there is an element with the ID <code>map-canvas</code> in the document, and then creates a map:</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> window.addEventListener('load',function(){
if(document.getElementById('map-canvas')){
google.load("maps", "3",{
callback:function(){
new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(0,0),
zoom: 3
});
}
});
}
},false);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code> body,html,#map-canvas{
height:100%;
margin:0;
padding:0;
width:100%;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.google.com/jsapi?.js"></script>
<div id="map-canvas"></div></code></pre>
</div>
</div>
</p> |
14,230,145 | How can I convert a zero-terminated byte array to string? | <p>I need to read <code>[100]byte</code> to transfer a bunch of <code>string</code> data.</p>
<p>Because not all of the <code>string</code>s are precisely 100 characters long, the remaining part of the <code>byte array</code> is padded with <code>0</code>s.</p>
<p>If I convert <code>[100]byte</code> to <code>string</code> by: <code>string(byteArray[:])</code>, the tailing <code>0</code>s are displayed as <code>^@^@</code>s.</p>
<p>In C, the <code>string</code> will terminate upon <code>0</code>, so what's the best way to convert this <code>byte array</code> to <code>string</code> in Go?</p> | 14,230,206 | 11 | 2 | null | 2013-01-09 07:19:48.017 UTC | 109 | 2021-06-28 11:04:32.287 UTC | 2020-08-25 12:03:43.75 UTC | null | 63,550 | null | 639,165 | null | 1 | 544 | go | 504,619 | <p>Methods that read data into byte slices return the number of bytes read. You should save that number and then use it to create your string. If <code>n</code> is the number of bytes read, your code would look like this:</p>
<pre><code>s := string(byteArray[:n])
</code></pre>
<p>To convert the full string, this can be used:</p>
<pre><code>s := string(byteArray[:len(byteArray)])
</code></pre>
<p>This is equivalent to:</p>
<pre><code>s := string(byteArray[:])
</code></pre>
<p>If for some reason you don't know <code>n</code>, you could use the <code>bytes</code> package to find it, assuming your input doesn't have a null character embedded in it.</p>
<pre><code>n := bytes.Index(byteArray[:], []byte{0})
</code></pre>
<p>Or as icza pointed out, you can use the code below:</p>
<pre><code>n := bytes.IndexByte(byteArray[:], 0)
</code></pre> |
14,352,648 | How to Lock/Unlock screen programmatically? | <p>I am doing an application which Locks the screen on shake. Now it is locking and from there it going to a broadcast receiver from there if the screen is off its entering into a service which has to turn the screen on.</p>
<p>Below is the broadcast receiver:</p>
<pre><code> public class ScreenReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("Entered Broadcaste Reciever");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// DO WHATEVER YOU NEED TO DO HERE
System.out.println("SCREEN_OFF"+wasScreenOn);
wasScreenOn = false;
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", wasScreenOn);
context.startService(i);
System.out.println("jrkejhr keh");
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// AND DO WHATEVER YOU NEED TO DO HERE
wasScreenOn = true;
System.out.println("SCREEN_ON"+wasScreenOn);
}
}
</code></pre>
<p>And its entering to a service where i had written the intent action to go home is...</p>
<pre><code> ShakeListener mShaker;
int amountOfTime = 0;
Context context1;
@Override
public void onCreate() {
super.onCreate();
// REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC
System.out.println("Enterd Service");
final Vibrator vibe = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
public void onShake() {
vibe.vibrate(100);
Intent goHome = new Intent();
goHome.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
goHome.setAction("android.intent.action.MAIN");
goHome.addCategory("android.intent.category.HOME");
startActivity(goHome);
}
});
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
</code></pre>
<p>It is entering into the service. But home screen is not displaying. When the service is invoked the the screen is locked.</p> | 14,352,807 | 3 | 1 | null | 2013-01-16 06:39:34.78 UTC | 31 | 2021-12-20 15:30:52.347 UTC | 2015-01-23 12:48:18.15 UTC | null | 1,371,853 | null | 1,954,684 | null | 1 | 40 | android | 112,947 | <p><strong>Edit:</strong></p>
<p>As some folks needs help in Unlocking device after locking programmatically,
I came through post <a href="https://stackoverflow.com/questions/12723185/android-screen-lock-unlock-programatically/12723269#12723269"><strong>Android screen lock/ unlock programatically</strong></a>, please have look, may help you. </p>
<p><strong>Original Answer was:</strong></p>
<p>You need to get Admin permission and you can lock phone screen</p>
<p>please check below simple tutorial to achive this one</p>
<p><a href="http://rdcworld-android.blogspot.in/2012/03/lock-phone-screen-programmtically.html" rel="noreferrer"><strong>Lock Phone Screen Programmtically</strong></a> </p>
<p>also here is the code example..</p>
<p><strong>LockScreenActivity.java</strong></p>
<pre><code>public class LockScreenActivity extends Activity implements OnClickListener {
private Button lock;
private Button disable;
private Button enable;
static final int RESULT_ENABLE = 1;
DevicePolicyManager deviceManger;
ActivityManager activityManager;
ComponentName compName;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
deviceManger = (DevicePolicyManager)getSystemService(
Context.DEVICE_POLICY_SERVICE);
activityManager = (ActivityManager)getSystemService(
Context.ACTIVITY_SERVICE);
compName = new ComponentName(this, MyAdmin.class);
setContentView(R.layout.main);
lock =(Button)findViewById(R.id.lock);
lock.setOnClickListener(this);
disable = (Button)findViewById(R.id.btnDisable);
enable =(Button)findViewById(R.id.btnEnable);
disable.setOnClickListener(this);
enable.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v == lock){
boolean active = deviceManger.isAdminActive(compName);
if (active) {
deviceManger.lockNow();
}
}
if(v == enable){
Intent intent = new Intent(DevicePolicyManager
.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
compName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
"Additional text explaining why this needs to be added.");
startActivityForResult(intent, RESULT_ENABLE);
}
if(v == disable){
deviceManger.removeActiveAdmin(compName);
updateButtonStates();
}
}
private void updateButtonStates() {
boolean active = deviceManger.isAdminActive(compName);
if (active) {
enable.setEnabled(false);
disable.setEnabled(true);
} else {
enable.setEnabled(true);
disable.setEnabled(false);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RESULT_ENABLE:
if (resultCode == Activity.RESULT_OK) {
Log.i("DeviceAdminSample", "Admin enabled!");
} else {
Log.i("DeviceAdminSample", "Admin enable FAILED!");
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
</code></pre>
<p>MyAdmin.java</p>
<pre><code>public class MyAdmin extends DeviceAdminReceiver{
static SharedPreferences getSamplePreferences(Context context) {
return context.getSharedPreferences(
DeviceAdminReceiver.class.getName(), 0);
}
static String PREF_PASSWORD_QUALITY = "password_quality";
static String PREF_PASSWORD_LENGTH = "password_length";
static String PREF_MAX_FAILED_PW = "max_failed_pw";
void showToast(Context context, CharSequence msg) {
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
@Override
public void onEnabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: enabled");
}
@Override
public CharSequence onDisableRequested(Context context, Intent intent) {
return "This is an optional message to warn the user about disabling.";
}
@Override
public void onDisabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: disabled");
}
@Override
public void onPasswordChanged(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw changed");
}
@Override
public void onPasswordFailed(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw failed");
}
@Override
public void onPasswordSucceeded(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw succeeded");
}
}
</code></pre> |
14,022,374 | The differences between GeneratedValue strategies | <p>In the <a href="http://docs.doctrine-project.org/en/latest/reference/annotations-reference.html#annref-generatedvalue">Doctrine docs</a> they mention that there exists a few different strategies for the <code>@GeneratedValue</code> annotation:</p>
<ul>
<li><code>AUTO</code></li>
<li><code>SEQUENCE</code></li>
<li><code>TABLE</code></li>
<li><code>IDENTITY</code></li>
<li><code>UUID</code></li>
<li><code>CUSTOM</code></li>
<li><code>NONE</code></li>
</ul>
<p>Would someone please explain the differences between all thees strategies?</p> | 14,029,064 | 3 | 0 | null | 2012-12-24 14:05:10.007 UTC | 14 | 2020-04-30 04:32:16.573 UTC | 2014-05-28 14:36:40.28 UTC | null | 570,796 | null | 570,796 | null | 1 | 69 | doctrine-orm | 67,407 | <p>Check the <a href="https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/basic-mapping.html#identifiers-primary-keys" rel="noreferrer">latest doctrine documentation</a></p>
<p>Here is a summary :
the list of possible generation strategies:</p>
<p><strong>AUTO (default)</strong>: Tells Doctrine to pick the strategy that is preferred by the used database platform. The preferred strategies are <code>IDENTITY</code> for MySQL, SQLite and MsSQL and <code>SEQUENCE</code> for Oracle and PostgreSQL. This strategy provides full portability.</p>
<p><strong>SEQUENCE:</strong> Tells Doctrine to use a database sequence for <code>ID</code> generation. This strategy does currently not provide full portability. Sequences are supported by Oracle and PostgreSql and SQL Anywhere.</p>
<p><strong>IDENTITY:</strong> Tells Doctrine to use special identity columns in the database that generate a value on insertion of a row. This strategy does currently not provide full portability and is supported by the following platforms:</p>
<ul>
<li>MySQL/SQLite/SQL Anywhere => <code>AUTO_INCREMENT</code></li>
<li>MSSQL => <code>IDENTITY</code></li>
<li>PostgreSQL => <code>SERIAL</code></li>
</ul>
<p><strong>TABLE:</strong> Tells Doctrine to use a separate table for <code>ID</code> generation. This strategy provides full portability. <em>This strategy is not yet implemented!</em></p>
<p><strong>NONE:</strong> Tells Doctrine that the identifiers are assigned, and thus generated, by your code. The assignment must take place before a new entity is passed to EntityManager#persist. <code>NONE</code> is the same as leaving off the <code>@GeneratedValue</code> entirely.</p>
<h3>SINCE VERSION 2.3 :</h3>
<p><strong>UUID:</strong> Tells Doctrine to use the built-in Universally Unique Identifier generator. This strategy provides full portability.</p> |
14,352,608 | What's the right way to enable the node debugger with mocha's --debug-brk switch? | <p>I have some debugger statements in my module under test and want to run mocha with <code>--debug-brk</code> set and hit my breakpoint so that I can inspect the state of my module. Unfortunately, whenever I run mocha with this option, I end up with a blank cursor on the next line. I can enter text, but there's nothing that appears to be processing my commands (it certainly doesn't look like the node debugger):</p>
<pre><code>$ mocha --debug-brk tests.js -R spec
debugger listening on port 5858
[BLANK CURSOR]
</code></pre>
<p>Am I doing something wrong with how I'm launching mocha?</p> | 23,384,336 | 5 | 1 | null | 2013-01-16 06:36:16.59 UTC | 25 | 2022-04-21 07:35:59.98 UTC | 2021-02-27 10:52:27.287 UTC | null | 4,370,109 | null | 958,104 | null | 1 | 81 | javascript|node.js|mocha.js|dom-events | 51,240 | <p>To answer the original question, even though I also suggest you look into <code>node-inspector</code>: you can use the CLI debugger built into node through mocha with the <code>debug</code> option, instead of the <code>--debug</code> or <code>--debug-brk</code> <em>flags</em>. (Notice the lack of dashes.)</p>
<p>In your example, instead, it would be:</p>
<pre>$ mocha <strong>debug</strong> tests.js -R spec
debugger listening on port 5858
connecting... ok
break in node_modules/mocha/bin/_mocha:7
5 */
6
7 var program = require('commander')
8 , sprintf = require('util').format
9 , path = require('path')
debug> [CURSOR]</pre>
<p>Again, <code>debug</code> as above in bold, with no dashes. (=</p>
<p>Relevant: <a href="https://github.com/visionmedia/mocha/issues/247">https://github.com/visionmedia/mocha/issues/247</a></p> |
9,473,235 | reading an XML file in a C++ program | <p>I'm trying to read an XML file in my C++ program. The XML file looks something like this:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<myprogram>
<configuration>
<window>
<height> 300 </height>
<width> 500 </width>
</window>
</configuration>
</myprogram>
</code></pre>
<p>Right now I can look at the XML file and try to read it like this:</p>
<pre><code>ifstream in("mydata.xml");
//ignore the <?xml line
in.ignore(200, '\n');
//i know that the first value i want is the window height so i can ignore <myprogram> <configuration> and <window>
//ignore <myprogram>
in.ignore(200, '\n');
//ignore <configuration>
in.ignore(200, '\n');
//ignore <window>
in.ignore(200, '\n');
string s; int height;
//okay, now i have my height
in >> s >> height;
</code></pre>
<p>In general this seems like a bad idea and it really limits how the XML file can be modified. The above solution is very manual and if anything in the XML changes it seems that the entire method of reading it would have to be changed.</p>
<p>Is there a better way to do this?</p> | 9,473,269 | 5 | 1 | null | 2012-02-27 22:18:05.68 UTC | 9 | 2012-02-27 22:53:05.373 UTC | null | null | null | null | 974,967 | null | 1 | 16 | c++|xml | 115,070 | <p>You could use some library that will do it for you. If you are working on Windows platform, you could use <a href="http://msdn.microsoft.com/en-us/library/ms765540(v=vs.85).aspx" rel="nofollow noreferrer">MSXML</a> which is part of the system already.</p>
<p>Check this question: <a href="https://stackoverflow.com/q/5415788/1168156">Read Write XML File In C++</a></p>
<p>Other popular libraries: <strong><a href="/questions/tagged/xerces" class="post-tag" title="show questions tagged 'xerces'" rel="tag">xerces</a></strong>, <strong><a href="/questions/tagged/tinyxml" class="post-tag" title="show questions tagged 'tinyxml'" rel="tag">tinyxml</a></strong>, <strong><a href="/questions/tagged/rapidxml" class="post-tag" title="show questions tagged 'rapidxml'" rel="tag">rapidxml</a></strong></p> |
9,187,209 | haml by default | <p>Is there a way to configure rails to use haml by default, i.e. when a scaffold is generated the according <code>scaffold_name/index.html.haml</code> is generated instead of <code>scaffold_name/index.html.erb</code>. </p>
<p>Similar to how you are able to add <code>config.sass.preferred_syntax = :sass</code> to <code>config/application.rb</code> and have <code>scaffold_name.sass</code> generated by default.</p>
<p>Tried adding the following to <code>config/application.rb</code></p>
<pre><code>config.generators do |g|
g.template_engine :haml
end
</code></pre>
<p>but ened up with the following</p>
<pre><code>$ rails generate scaffold foo name:string
invoke active_record
create db/migrate/20120208152550_create_foos.rb
create app/models/foo.rb
invoke test_unit
create test/unit/foo_test.rb
create test/fixtures/foos.yml
route resources :foos
invoke scaffold_controller
create app/controllers/foos_controller.rb
error haml [not found]
invoke test_unit
create test/functional/foos_controller_test.rb
invoke helper
create app/helpers/foos_helper.rb
invoke test_unit
create test/unit/helpers/foos_helper_test.rb
invoke assets
invoke coffee
create app/assets/javascripts/foos.js.coffee
invoke sass
create app/assets/stylesheets/foos.css.sass
invoke sass
identical app/assets/stylesheets/scaffolds.css.sass
$ rails destroy scaffold foo
invoke active_record
remove db/migrate/20120208152550_create_foos.rb
remove app/models/foo.rb
invoke test_unit
remove test/unit/foo_test.rb
remove test/fixtures/foos.yml
route resources :foos
invoke scaffold_controller
remove app/controllers/foos_controller.rb
error haml [not found]
invoke test_unit
remove test/functional/foos_controller_test.rb
invoke helper
remove app/helpers/foos_helper.rb
invoke test_unit
remove test/unit/helpers/foos_helper_test.rb
invoke assets
invoke coffee
remove app/assets/javascripts/foos.js.coffee
invoke sass
remove app/assets/stylesheets/foos.css.sass
invoke sass
</code></pre>
<p>I created a nice little bundle command to replace all erb with haml files following <a href="http://screencasts.org/episodes/using-haml-with-rails-3">this</a> screencast but I'm still interested in making it default when the scaffold is created! How do I make it so haml files (not erb!) are generated by default?</p> | 9,204,950 | 6 | 1 | null | 2012-02-08 02:52:05.487 UTC | 8 | 2016-06-08 04:08:04.3 UTC | 2012-02-08 15:31:08.993 UTC | null | 1,134,742 | null | 1,134,742 | null | 1 | 47 | ruby-on-rails|haml|ruby-on-rails-3.2 | 21,583 | <p>I use <code>gem 'haml-rails', '= 0.3.4'</code> in my gemfile. it automatically generates <code>*.html.haml</code> without any configuration.</p> |
19,572,463 | How to remove a pattern from a string using Regex | <p>I want to find paths from a string and remove them
e.g. <code>string1 = "'c:\a\b\c'!MyUDF(param1, param2,..) + 'c:\a\b\c'!MyUDF(param3, param4,..)..."</code>, I'd like a regex to find the pattern <code>'[some path]'!MyUDF</code>, and remove '[path]'.
Thanks </p>
<p>Edit
e.g. input string1 ="'c:\a\b\c'!MyUDF(param1, param2,..) + 'c:\a\b\c'!MyUDF(param3, param4,..)";
expected output "MyUDF(param1, param2,...) + MyUDF(param3, param4,...)"
where MyUDF is a function name, so it consists of only letters</p> | 19,572,533 | 3 | 2 | null | 2013-10-24 17:20:27.293 UTC | null | 2013-10-24 19:44:53.153 UTC | 2013-10-24 19:44:53.153 UTC | null | 442,506 | null | 442,506 | null | 1 | 12 | c#|regex|replace | 41,436 | <pre><code>input=Regex.Replace(input,"'[^']+'(?=!MyUDF)","");
</code></pre>
<hr>
<p>In case if the path is followed by ! and some other word you can use</p>
<pre><code>input=Regex.Replace(input,@"'[^']+'(?=!\w+)","");
</code></pre> |
34,376,023 | Why are Redux's state functions called reducers? | <p>This is <a href="https://redux.js.org/basics/reducers#handling-actions" rel="noreferrer">a part the official Redux documentation</a>:</p>
<blockquote>
<p>It’s called a reducer because it’s the type of function you would pass
to <code>Array.prototype.reduce(reducer, ?initialValue)</code></p>
</blockquote>
<p>It doesn't make much sense to me. Could somebody explain to me why they are actually called reducers? The fact that they return a default value (or they have a default argument value) doesn't make them reducers IMHO.</p> | 34,376,154 | 11 | 3 | null | 2015-12-19 22:26:50.757 UTC | 18 | 2021-07-30 20:16:25.203 UTC | 2018-08-24 01:50:28.967 UTC | null | 9,238,547 | null | 3,040,875 | null | 1 | 92 | javascript|redux | 21,377 | <blockquote>
<p>The fact that they return a default value (or they have a default
argument value) doesn't make them reducers IMHO.</p>
</blockquote>
<p>Reducers do not <em>just</em> return default values. They always return the accumulation of the state (based on all previous and current actions).</p>
<p>Therefore, they act as a <em>reducer</em> of state. Each time a redux reducer is called, the state is passed in with the action <code>(state, action)</code>. This state is then <em>reduced</em> (or accumulated) based on the action, and then the next state is returned. This is one cycle of the classic <code>fold</code> or <code>reduce</code> function.</p>
<p>As @azium summed up with <code>state -> action -> state</code>.</p> |
34,287,668 | Is Haskell a strongly typed programming language? | <p>Is Haskell strongly typed? I.e. is it possible to change the type of a variable after you assigned one? I can't seem to find the answer on the internet.</p> | 34,288,753 | 4 | 5 | null | 2015-12-15 11:09:41.447 UTC | 14 | 2020-06-09 10:06:27.003 UTC | 2015-12-19 23:50:16.4 UTC | null | 247,623 | null | 2,846,781 | null | 1 | 29 | haskell|type-systems | 9,239 | <p><strong>Static</strong> — types are known at compile time. Java and Haskell have static typing. Also C/C++, C#, Go, Scala, Rust, Kotlin, Pascal to list a few more.</p>
<p>A statically typed language might or might not have type inference. Java almost completely lacks type inference (but it's very slowly changing just a little bit); Haskell has full type inference (except with certain very advanced extensions). </p>
<p>(Type inference is when you only have to declare a minimal amount of types by hand, e.g. <code>var isFoo = true</code> and <code>var person = new Person()</code>, instead of <code>bool isFoo = ...</code> and <code>Person person = ...</code>.)</p>
<p><strong>Dynamic</strong> — Python, JavaScript, Ruby, PHP, Clojure (and Lisps in general), Prolog, Erlang, Groovy etc. Can also be called "unityped"; dynamic typing can be "emulated" in a static setting, but the reverse is not true except by using external static analysis tools. Some languages make it possible to mix dynamic and static (see <a href="https://en.wikipedia.org/wiki/Gradual_typing" rel="noreferrer">gradual typing</a>, e.g. <a href="https://typedclojure.org/" rel="noreferrer">https://typedclojure.org/</a>).</p>
<p>Some languages enable static typing for one or more modules, applied at import time, for example: <a href="http://mypy-lang.org" rel="noreferrer">Python+Mypy</a>, <a href="http://typedclojure.org" rel="noreferrer">Typed Clojure</a>, <a href="https://flow.org" rel="noreferrer">JavaScript+Flow</a>, <a href="https://hacklang.org" rel="noreferrer">PHP+Hack</a> to name a few.</p>
<p><strong>Strong</strong> — values that are intended to be treated as <code>Cat</code> always are; trying to treat them like a <code>Dog</code> will cause a loud <code>meeewww</code>... I mean error.</p>
<p><strong>Weak</strong> — this effectively boils down to 2 similar but distinct things: type coercion (e.g. <code>"5"+3</code> equals <code>8</code> in PHP — or does it!) and memory reinterpretation (e.g. <code>(int) someCharValue</code> or <code>(bool) somePtr</code> in C, and C++ as well, but C++ wants you to explicitly say <code>reinterpret_cast</code>). So there's really <em>coercion-weak</em> and <em>reinterpretation-weak</em>, and different languages are weak in one or both of these ways.</p>
<p>Interestingly, note that coercion is implicit by nature and memory reinterpretation is explicit (except in Assembly) — so weak typing consists of an implicit <em>and</em> an explicit behavior. Maybe that's even more of a reason to refer to 2 distinct subcategories under weak typing.</p>
<hr>
<p>There are languages with all 4 possible combinations, and variations/gradations thereof. </p>
<p><strong>Haskell is static+strong</strong>; of course it has <code>unsafeCoerce</code> so it can be static+a bit reinterpret-weak at times, but <code>unsafeCoerce</code> is very much frowned upon except in extreme situations where you are sure about something being the case but just can't seem to persuade the compiler without going all the way back and retelling the entire story in a different way. </p>
<p><strong>C is static+weak</strong> because all memory can freely be reinterpreted as something it originally was not meant to contain, hence weak. But all of those reinterpretations are kept track of by the type checker, so still fully static too. But C does not do implicit coercions, so it's only <em>reinterpret-weak</em>.</p>
<p><strong>Python is dynamic+almost entirely strong</strong> — there are no types known on any given line of code prior to reaching that line during execution, however values that live at runtime do have types associated with them and it's impossible to reinterpret memory. Implicit coercions are also kept to a meaningful minimum, so one might say Python is 99.9% strong and 0.01% <em>coercion-weak</em>. </p>
<p><strong>PHP and JavaScript are dynamic+mostly weak</strong> — dynamic, in that nothing has type until you execute and introspect its contents, and also weak in that coercions happen all the time and with things you'd never really expect to be coerced, unless you are only calling methods and functions and not using built-in operations. These coercions are a source of a lot of humor on the internet. There are no memory reinterpretations so PHP and JS are <em>coercion-weak</em>.</p>
<hr>
<p>Furthermore, some people like to think that static typing is about variables having type, and strong typing is about values having type — this is a very useful way to go about understanding the full picture, but it's <em>not quite true</em>: some dynamically typed languages also allow variables/parameters to be annotated with types/constraints that are enforced at runtime. </p>
<p>In static typing, it's expressions that have a type; the fact of variables having type is only a consequence of variables being used as a means to glue bigger expressions together from smaller ones, so it's not variables per se that have types. </p>
<p>Similarly, in dynamic typing, it's not the variables that lack statically known type — it's all expressions! Variables lacking type is merely a consequence of the expressions they store lacking type. </p>
<hr>
<p><strong>One final illustration</strong></p>
<p>In dynamic typing, all the cats, dogs and even elephants (in fact entire zoos!) are packaged up in identically sized boxes. </p>
<p>In static typing these boxes look different and have stickers on them saying what's inside. </p>
<p>Some people like it because they can just use a single box form factor and don't have to put any labels on the boxes — it's only the arrangement of boxes with regards to each other that implicitly (and hopefully) provides type sanity.</p>
<p>Some people also like it because it allows them to do all sorts of tricks with tigers temporarily being transported in boxes that smell like lions, and bears put in the same array of interconnected boxes as wolves or deer.</p>
<p>In such label-free setting of transport boxes, all the possible logicistics scenarios need to be played or simulated in order to detect misalignment in the implicit arrangement, like in a stage performance. No reliable guarantees can be given based on reasoning only, generally speaking. (ad-hoc test cases that need for the entire system to be started up for any partial conclusions to be obtained of its soundness)</p>
<p>With labels and explicit rules on how to deal with boxes of various labels, automated/mechanized logical reasoning can be used to draw up conclusions on what the logistics system won't do or will do for sure (static verification, formal proof, or at least pseudo-proof like QuickCheck), Some aspects of the logistics still need to be verified with trial runs, such as whether the logistics team even got the client right. (integration testing, acceptance testing, end user sanity checks). </p>
<hr>
<p>Moreover, in weak typing dogs can be sliced up and reassembled as frankenstein cats. Whether they like it or not, and whether the result is ugly or not. (weak typing)</p>
<p>But if you add labels to the boxes, it still matters that Frankenstein cats be put in cat boxes. (static+weak typing)</p>
<hr>
<p>In strong typing, while you can put a cat in the box of a dog, but you can only keep pretending it's a dog until you try to humiliate it by feeding it something only dogs would eat — if that happens, it will scream out loud, but until that time, if you're in dynamic typing, it will silently accept its place (in a static world it would refuse to be put in a dog's box before you can say "kitty"). </p> |
52,355,132 | Spring @Autowired on a class new instance | <p>I'm not so familiar with Spring and I have the following situation:</p>
<p>A repository class:</p>
<pre><code>@Repository
public class MyRepository {
// ...
}
</code></pre>
<p>A class that uses the repository class:</p>
<pre><code>public class MyClass extends AbstractClass {
@Autowired
private MyRepository myRepository;
//...
}
</code></pre>
<p>I know that if I annotate my <code>MyClass</code> with <code>@Component</code> and use it with an <code>@Autowired</code>, then the <code>@Autowired</code> <code>MyRepository</code> is resolved just fine.
Problem is I am in a situation that I need to create new instances of <code>MyClass</code> with reflection. So <code>MyRepository</code> is never resolved and is null all the time.</p>
<p><strong>Is there a way to use <code>@Autowired</code> in this situation?</strong></p>
<p>Explaining better my situation:
I have some implementations of <code>AbstractClass</code>.
In a setup phase of my application I create a <code>HashMap</code> of these implementations. Basically:</p>
<pre><code>{"MyClass", MyClass.class}
//...
</code></pre>
<p>Then I have a generic <code>Controller</code> that maps to the url <code>/{class}?options=...</code>
Using the <code>{class}</code> <code>@PathVariable</code>, the <code>HashMap</code> above and reflection I am able to create a instance of a class based on the given <code>options</code> (this part is important). Do you guys think there's a better way of doing this?</p>
<p>Thanks in advance</p> | 52,355,649 | 6 | 4 | null | 2018-09-16 14:34:16.877 UTC | 3 | 2019-02-02 07:54:44.137 UTC | 2018-09-17 21:08:39.137 UTC | null | 2,044,302 | null | 1,808,082 | null | 1 | 17 | java|spring|dependency-injection|autowired | 46,836 | <p>Spring itself offers some functionality for doing auto-wiring in your objects
which you created by <code>new</code> or <code>newInstance()</code> or whatever.</p>
<p>To use it you need an <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/config/AutowireCapableBeanFactory.html" rel="noreferrer"><code>AutowireCapableBeanFactory</code></a>
which you get by Spring's normal dependency injection with <code>@Autowired</code>.</p>
<pre><code>@Autowired
private AutowireCapableBeanFactory autowireCapableBeanFactory;
</code></pre>
<p>Then you use its <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/config/AutowireCapableBeanFactory.html#autowireBean-java.lang.Object-" rel="noreferrer"><code>autowireBean(Object)</code></a> method
to inject the <code>@Autowired</code> properties into your bean.</p>
<pre><code>Object myBean = map.get(className).newInstance();
autowireCapableBeanFactory.autowireBean(myBean);
</code></pre>
<hr>
<p>Design note:</p>
<p>Think well if you really need the approach above.
The javadoc of <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/config/AutowireCapableBeanFactory.html" rel="noreferrer"><code>AutowireCapableBeanFactory</code></a> advises against using this interface for most use-cases:</p>
<blockquote>
<p>This subinterface of BeanFactory is not meant to be used in normal application code: stick to <code>BeanFactory</code> or <code>ListableBeanFactory</code> for typical use cases.</p>
<p>Integration code for other frameworks can leverage this interface to wire and populate existing bean instances that Spring does not control the lifecycle of. This is particularly useful for WebWork Actions and Tapestry Page objects, for example.</p>
</blockquote> |
567,219 | looking for good geospatial library | <p>What's a good library for geospatial functions? I mean things like</p>
<ul>
<li>distance between two points on the globe</li>
<li>coordinates of a circle of a given radius from a particular point</li>
<li>etc.</li>
</ul>
<p>Bonus if there's an interface to the various ways different databases
represent geolocations.</p>
<p>I'm a geo-noob (in case this question didn't make it obvious), so pointers to other geolocation/geospatial resources are welcome.</p>
<p>C++ and Python preferred, but all pointers welcome.</p> | 567,476 | 5 | 0 | null | 2009-02-19 21:21:45.033 UTC | 9 | 2022-06-24 18:02:23.027 UTC | 2009-02-22 22:20:09.913 UTC | null | 25,732 | Mark Harrison | 116 | null | 1 | 4 | gis|geospatial | 4,351 | <p>I've enjoyed using <a href="http://pypi.python.org/pypi/geopy" rel="noreferrer">geopy</a>. It's a simple library that finds great-circle distance in a number of projections. Geopy also provides a single interface to multiple geocoders like Google Maps and Microsoft Earth to give you coordinates for a street address.</p>
<p>You might be interested in the <a href="http://pypi.python.org/pypi?:action=browse&show=all&c=391" rel="noreferrer">Topic :: Scientific/Engineering :: GIS</a> section in PyPi.</p> |
497,317 | How can I view all grants for an SQL Database? | <p>I am using SQL Server 2005, I want to find out what all the grants are on a specific database for all tables. It would also help to find out all tables where the delete grant has been given for a specific user.</p>
<p>Note: this may be similar to <a href="https://stackoverflow.com/questions/212681/how-do-i-generate-a-table-of-permissions-granted-to-database-tables-for-a-databas">this question</a>, but I could not get the selected answer's solution working (if someone could provide a better example of how to use that, it would help as well)</p> | 499,216 | 5 | 0 | null | 2009-01-30 21:28:01.807 UTC | 6 | 2020-01-07 02:26:34.037 UTC | 2017-05-23 12:08:45.18 UTC | null | -1 | Joel Briggs | 43,472 | null | 1 | 25 | sql|sql-server-2005|permissions | 76,371 | <p>The given solution does not cover where the permission is granted against the schema or the database itself, which do grant permissions against the tables as well. This will give you those situations, too. You can use a WHERE clause against permission_name to restrict to just DELETE.</p>
<pre><code>SELECT
class_desc
, CASE WHEN class = 0 THEN DB_NAME()
WHEN class = 1 THEN OBJECT_NAME(major_id)
WHEN class = 3 THEN SCHEMA_NAME(major_id) END [Securable]
, USER_NAME(grantee_principal_id) [User]
, permission_name
, state_desc
FROM sys.database_permissions
</code></pre>
<p>Also, db_datawriter would need to be checked for membership because it gives implicit INSERT, UPDATE, and DELETE rights, meaning you won't see it show up in the permission DMVs or their derivatives.</p> |
1,207,269 | Sending a notification from a service in Android | <p>I have a service running, and would like to send a notification. Too bad, the notification object requires a <code>Context</code>, like an <code>Activity</code>, and not a <code>Service</code>.</p>
<p>Do you know any way to by pass that ? I tried to create an <code>Activity</code> for each notification but it seems ugly, and I can't find a way to launch an <code>Activity</code> without any <code>View</code>.</p> | 1,208,537 | 5 | 5 | null | 2009-07-30 15:12:30.58 UTC | 36 | 2018-03-08 18:56:12.913 UTC | 2018-03-08 18:56:12.913 UTC | null | 1,363,438 | null | 9,951 | null | 1 | 109 | android|service|notifications | 155,485 | <p>Both <code>Activity</code> and <code>Service</code> actually <code>extend</code> <a href="http://developer.android.com/reference/android/content/Context.html" rel="noreferrer"><code>Context</code></a> so you can simply use <code>this</code> as your <code>Context</code> within your <code>Service</code>.</p>
<pre><code>NotificationManager notificationManager =
(NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
Notification notification = new Notification(/* your notification */);
PendingIntent pendingIntent = /* your intent */;
notification.setLatestEventInfo(this, /* your content */, pendingIntent);
notificationManager.notify(/* id */, notification);
</code></pre> |
173,851 | What is the canonical way to determine commandline vs. http execution of a PHP script? | <p>I have a PHP script that needs to determine if it's been executed via the command-line or via HTTP, primarily for output-formatting purposes. What's the canonical way of doing this? I had thought it was to inspect <code>SERVER['argc']</code>, but it turns out this is populated, even when using the 'Apache 2.0 Handler' server API.</p> | 173,887 | 5 | 0 | null | 2008-10-06 10:51:04.267 UTC | 31 | 2016-09-16 06:18:29.663 UTC | 2008-12-05 11:28:34.59 UTC | RoBorg | 24,181 | Bobby Jack | 5,058 | null | 1 | 163 | php|http|command-line|command-line-interface | 43,940 | <p>Use the <a href="http://php.net/php_sapi_name" rel="noreferrer"><code>php_sapi_name()</code></a> function.</p>
<pre class="lang-php prettyprint-override"><code>if (php_sapi_name() == "cli") {
// In cli-mode
} else {
// Not in cli-mode
}
</code></pre>
<p>Here are some relevant notes from the docs:</p>
<blockquote>
<p><strong>php_sapi_name</strong> — Returns the type of interface between web server and PHP</p>
<p>Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, cli-server, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.</p>
</blockquote>
<p>In PHP >= 4.2.0, there is also a predefined constant, <code>PHP_SAPI</code>, that has the same value as <code>php_sapi_name()</code>.</p> |
751,415 | ASP.NET postback with jQuery? | <p>I have a ASP.NET button but recently, I replaced it with a standard HTML button ... What I need to do is a postback to an ASP.NET page and ensure a method is called.</p>
<p>The previous button was an ASP.NET button, so I had this event:</p>
<pre><code>Protected Sub btnCancelar_Click(ByVal sender As Object, ByVal e As System.EventArgs)
UtilTMP.DisposeObjects()
Server.Transfer("~\Forms\test.aspx", True)
End
</code></pre>
<p>But I was using a button with a JavaScript ALERT and I recently changed to a jQuery UI Modal dialog but it doesn't wait for me to answer the question.. the postback happenes immediatly ... so I decided to change to a standard HTML button ... but I need to postback to the ASP.NET page and call a method like.</p>
<p>If I just postback it won't call the cleanup</p>
<pre><code>Protected Sub Cleanup()
UtilTMP.DisposeObjects()
Server.Transfer("~\Forms\test.aspx", True)
End
</code></pre> | 753,013 | 6 | 1 | null | 2009-04-15 12:06:52.87 UTC | 9 | 2017-07-05 11:36:39.18 UTC | 2013-10-28 15:01:01.257 UTC | null | 2,619,912 | null | 85,040 | null | 1 | 16 | asp.net|jquery|user-interface|postback|modal-dialog | 88,689 | <p>While you can do Postbacks with JQuery, it might be better to call a web method (web service that is in your page). The call could also be faster because you are not posting the entire page ViewState.</p> |
484,742 | Notepad++ and code completion | <p>Is there any way to improve code completion in notepad++? </p>
<p>Currently it supports some kind of "static" code completion and it requires to make a list of instructions and they parameters in xml file or it works on a list of words in open document. I`m looking for something that can read *.h files and make that list automatically and also use variables and functions from current file.</p> | 484,767 | 6 | 0 | null | 2009-01-27 19:02:50.313 UTC | 7 | 2018-12-07 09:14:33.393 UTC | null | null | null | null | 58,877 | null | 1 | 36 | autocomplete|notepad++ | 72,952 | <p>You have some code completion sections to look at <a href="http://cybernetnews.com/2008/06/16/notepad-50-can-auto-complete-code/" rel="noreferrer">here</a>. But i would mainly suggest you change to an IDE for the programming language because Notepad++ doesn't have any of the benefits you find in a Real IDE. ( Maybe because it's a text-editor and not an IDE ).</p> |
289,362 | How to make a field NULL using MySQL GUI Tools? | <p>I'm using the MySQL Query Browser (part of the <a href="http://dev.mysql.com/downloads/gui-tools/" rel="noreferrer">MySQL GUI Tools</a>) and need to change a field to NULL, but I can't figure out how to do it - if I delete the value it tries to update it to <code>''</code>. Typing "NULL" makes it try to update to <code>'NULL'</code> (a string).</p>
<p>I know I could just write a query to do it, but that defeats the entire purpose of the tool, no?</p> | 289,377 | 6 | 0 | null | 2008-11-14 06:25:04.587 UTC | 2 | 2020-07-21 19:58:14.097 UTC | 2017-10-20 11:24:20.18 UTC | null | 1,000,551 | nickf | 9,021 | null | 1 | 65 | mysql|mysql-workbench|mysql-gui-tools | 38,615 | <p>In MySQL Query Browser, right click on the cell and select 'Clear field content' while the focus is in another cell.</p>
<p>In MySQL Workbench, right click on the cell and select 'Set Field to NULL'.</p> |
1,055,959 | Print the address or pointer for value in C | <p>I want to do something that seems fairly simple. I get results but the problem is, I have no way to know if the results are correct.</p>
<p>I'm working in C and I have two pointers; I want to print the contents of the pointer. I don't want to dereference the pointer to get the value pointed at, I just want the address that the pointer has stored. </p>
<p>I wrote the following code and what I need to know is if it is right and if not, how can I correct it.</p>
<pre><code>/* item one is a parameter and it comes in as: const void* item1 */
const Emp* emp1 = (const Emp*) item1;
printf("\n comp1-> emp1 = %p; item1 = %p \n", emp1, item1 );
</code></pre>
<p>While I'm posting this (and the reason it is important that it is correct) is that I eventually need to do this for a pointer-to-a-pointer. That is:</p>
<pre><code>const Emp** emp1 = (const Emp**) item1;
</code></pre> | 1,055,971 | 6 | 2 | null | 2009-06-28 22:48:49.87 UTC | 18 | 2021-01-17 22:10:33.43 UTC | 2018-10-14 10:21:07.447 UTC | null | 608,639 | null | 18,196 | null | 1 | 81 | c|pointers|memory-address | 242,139 | <p>What you have is correct. Of course, you'll see that emp1 and item1 have the same pointer value.</p> |
42,134,874 | Are there equivalents to slice::chunks/windows for iterators to loop over pairs, triplets etc? | <p>It can be useful to iterate over multiple variables at once, overlapping (<a href="https://doc.rust-lang.org/std/primitive.slice.html#method.windows" rel="noreferrer"><code>slice::windows</code></a>), or not (<a href="https://doc.rust-lang.org/std/primitive.slice.html#method.chunks" rel="noreferrer"><code>slice::chunks</code></a>).</p>
<p>This only works for slices; is it possible to do this for iterators, using tuples for convenience?</p>
<p>Something like the following could be written:</p>
<pre><code>for (prev, next) in some_iter.windows(2) {
...
}
</code></pre>
<p>If not, could it be implemented as a trait on existing iterators?</p> | 69,477,239 | 3 | 3 | null | 2017-02-09 10:59:26.263 UTC | 4 | 2021-11-08 14:01:35.33 UTC | 2021-01-30 14:49:29.533 UTC | null | 2,181,238 | null | 432,509 | null | 1 | 44 | iterator|rust | 24,383 | <p>Since Rust 1.51 this is possible with <strong>const generics</strong> where the iterator yields constant size arrays <strong><code>[T; N]</code></strong> for any <code>N</code>.</p>
<p>I built the little <a href="https://docs.rs/itermore" rel="noreferrer"><code>itermore</code></a> crate which does this. It provides <a href="https://docs.rs/itermore/*/itermore/trait.IterMore.html#method.chunks" rel="noreferrer"><code>.chunks()</code></a> and <a href="https://docs.rs/itermore/*/itermore/trait.IterMore.html#method.windows" rel="noreferrer"><code>.windows()</code></a> methods for any iterator.</p>
<pre class="lang-rust prettyprint-override"><code>for [a, b, c] in some_iter.chunks() {
...
}
</code></pre>
<pre class="lang-rust prettyprint-override"><code>for [prev, next] in some_iter.windows() {
...
}
</code></pre>
<p>Using the example given in the <code>Itertools</code> answer:</p>
<pre><code>use itermore::IterMore;
fn main() {
let some_iter = vec![1, 2, 3, 4, 5, 6].into_iter();
for [prev, next] in some_iter.chunks() {
println!("{}--{}", prev, next);
}
}
</code></pre>
<p>This outputs</p>
<pre><code>1--2
3--4
5--6
</code></pre>
<p>Most times the array size can be inferred but you can also specific it explicitly. Additionally, any reasonable size <code>N</code> can be used, there is no limit like in the <code>Itertools</code> case.</p>
<pre class="lang-rust prettyprint-override"><code>use itermore::IterMore;
fn main() {
let mut iter = vec![1, 2, 3, 4, 5, 6].into_iter().windows::<5>();
println!("{:?}", iter.next());
println!("{:?}", iter.next());
println!("{:?}", iter.next());
}
</code></pre>
<p>This outputs</p>
<pre><code>Some([1, 2, 3, 4, 5])
Some([2, 3, 4, 5, 6])
None
</code></pre>
<p>Note: <code>.windows()</code> uses clone to yield elements multiple times so its best used for references and cheap to copy types.</p> |
32,527,861 | Python unit test that uses an external data file | <p>I have a Python project that I'm working on in Eclipse and I have the following file structure:</p>
<pre><code>/Project
/projectname
module1.py
module2.py
# etc.
/test
testModule1.py
# etc.
testdata.csv
</code></pre>
<p>In one of my tests I create an instance of one of my classes giving <code>'testdata.csv'</code> as a parameter. This object does <code>open('testdata.csv')</code> and reads the contents. </p>
<p>If I run just this single test file with <code>unittest</code> everything works and the file is found and read properly. However if I try to run all my unit tests (i.e. run by right clicking the <code>test</code> directory rather than the individual test file), I get an error that file could not be found.</p>
<p>Is there any way to get around this (other than providing an absolute path, which I'd prefer not to do)?</p> | 32,528,173 | 5 | 5 | null | 2015-09-11 16:17:03.983 UTC | 5 | 2021-11-08 10:19:12.75 UTC | 2015-09-11 16:37:30.67 UTC | null | 3,001,761 | null | 3,849,445 | null | 1 | 45 | python|unit-testing | 30,715 | <p>Usually what I do is define</p>
<p><code>THIS_DIR = os.path.dirname(os.path.abspath(__file__))</code></p>
<p>at the top of each test module. Then it doesn't matter what working directory you're in - the file path is always the same relative to the where the test module sits.</p>
<p>Then I use something like this is in my test (or test setup):</p>
<pre><code>my_data_path = os.path.join(THIS_DIR, os.pardir, 'data_folder/data.csv')
</code></pre>
<p>Or in your case, since the data source is in the test directory:</p>
<pre><code>my_data_path = os.path.join(THIS_DIR, 'testdata.csv')
</code></pre>
<p><strong>Edit: for modern python</strong></p>
<pre><code>from pathlib import Path
THIS_DIR = Path(__file__).parent
my_data_path = THIS_DIR.parent / 'data_folder/data.csv'
# or if it's in the same directory
my_data_path = THIS_DIR / 'testdata.csv'
</code></pre> |
17,821,269 | Adding SSH Key to authorized_keys: permission denied(publickey) | <ul>
<li>I have an <code>id_rsa</code> and <code>id_rsa.pub</code> on my computer also tied into my BitBucket account. </li>
<li>As I understand I can use this public key anywhere I please <em>(as long as my private matches).</em></li>
</ul>
<p><strong>The Problem</strong>: I cannot figure out how to get any server to accept the public key, do you see what I've done wrong?</p>
<pre><code> $ cat id_rsa.pub >> authorized_keys
$ service ssh restart (I suppose this isn't needed)
$ git pull origin master
$ Permission denied(publickey)
</code></pre>
<p>What am I doing wrong? I've been stuck for days. </p> | 17,821,315 | 3 | 1 | null | 2013-07-23 21:17:42.777 UTC | 3 | 2017-09-19 18:44:48.53 UTC | 2013-07-24 08:14:33.583 UTC | null | 981,959 | null | 216,909 | null | 1 | 9 | linux|git|bitbucket|ssh-keys | 39,503 | <p>You need to copy the content of id_rsa.pub to the bitbucket avcount its in the settings page </p>
<p>For more info <a href="https://confluence.atlassian.com/display/BITBUCKET/How+to+install+a+public+key+on+your+Bitbucket+account" rel="nofollow">https://confluence.atlassian.com/display/BITBUCKET/How+to+install+a+public+key+on+your+Bitbucket+account</a></p> |
23,165,913 | Bundler and wrong binstubs? | <p>I run <code>rails s</code> or <code>bundle exec rails s</code> and I get this warning:</p>
<pre><code>Bundler is using a binstub that was created for a different gem.
This is deprecated, in future versions you may need to `bundle binstub rails` to work around a system/bundle conflict.
</code></pre>
<p>What does this mean? From looking around the bundler site, my understanding of binstubs is that you can set executables to them, so instead of running <code>bundle exec blabla</code> you can just do <code>bin/blabla</code>. So this error is saying my <code>bundler</code> isn't set to the right binstub?</p>
<p>When I run the <code>bundle binstub rails</code> I get this output</p>
<pre><code>rails has no executables, but you may want one from a gem it depends on.
railties has: rails
bundler has: bundle, bundler
</code></pre>
<p>I do not understand what my system is trying to tell me, and it's not breaking anything, but I have a hunch this could turn into a bigger issue if I don't fix it</p>
<pre><code>ruby 2.0.0p247
</code></pre>
<p>which ruby</p>
<pre><code>/Users/evan/.rvm/rubies/ruby-2.0.0-p247/bin/ruby
</code></pre>
<p>which bundler</p>
<pre><code>/Users/evan/.rvm/gems/ruby-2.0.0-p247/bin/bundler
</code></pre>
<p>Rails 4.0.2</p>
<p>Edit:</p>
<p>So, if I run the commands in the nag message:</p>
<pre><code> bundle config --delete bin # Turn off Bundler's stub generator
rake rails:update:bin # Use the new Rails 4 executables
</code></pre>
<p>I end up getting <code>uninitialized constant Bundler</code> errors with <code>bundle exec</code> commands and the only way I've found to fix that is to rerun <code>bundle install --binstubs</code> which brings back the nag message at the start of this post.</p> | 23,658,355 | 5 | 3 | null | 2014-04-19 04:40:02.2 UTC | 6 | 2020-05-12 13:58:52.903 UTC | 2014-04-28 12:10:19.07 UTC | null | 2,936,314 | null | 2,936,314 | null | 1 | 32 | ruby|bundler | 14,164 | <p>What worked for me was</p>
<p><code>rm -rf bin/*</code></p>
<p>Then open a new terminal session and</p>
<p><code>bundle exec rake app:update:bin</code></p> |
2,239,959 | "Faceted Project Problem (Java Version Mismatch)" error message | <p>Eclipse's "problems" tab is displaying this error:</p>
<blockquote>
<p>Description: Java compiler level does not match the version of the installed Java project facet.<br>
Resource: groupping<br>
Path: [blank]<br>
Location: Unknown<br>
Type: Faceted Project Problem (Java Version Mismatch)</p>
</blockquote>
<p>My <code>pom.xml</code> has this setting:</p>
<pre><code><plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</code></pre>
<p>Where else could the settings be mismatched?</p> | 2,239,973 | 5 | 0 | null | 2010-02-10 20:04:41.07 UTC | 22 | 2018-09-15 21:29:01.143 UTC | 2018-09-15 21:29:01.143 UTC | null | 141,774 | null | 39,677 | null | 1 | 72 | java|eclipse|maven-2|m2eclipse | 164,097 | <p>Did you check your <code>Project Properties -> Project Facets</code> panel? (From <a href="http://www.eclipsezone.com/eclipse/forums/t80428.html" rel="noreferrer">that post</a>)</p>
<blockquote>
<p>A WTP project is composed of multiple units of functionality (known as
facets). </p>
<p>The Java facet version needs to always match the java compiler compliance
level.<br>
The best way to change java level is to use the Project Facets
properties panel as that will update both places at the same time. </p>
</blockquote>
<p><img src="https://i.stack.imgur.com/mQsdL.jpg" alt="WTP"></p>
<blockquote>
<p>The "<code>Project->Preferences->Project Facets</code>" stores its configuration in this file, "<code>org.eclipse.wst.common.project.facet.core.xml</code>", under the "<code>.settings</code>" directory. </p>
<p>The content might look like this</p>
</blockquote>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<runtime name="WebSphere Application Server v6.1"/>
<fixed facet="jst.java"/>
<fixed facet="jst.web"/>
<installed facet="jst.java" version="5.0"/>
<installed facet="jst.web" version="2.4"/>
<installed facet="jsf.ibm" version="7.0"/>
<installed facet="jsf.base" version="7.0"/>
<installed facet="web.jstl" version="1.1"/>
</faceted-project>
</code></pre>
<p>Check also your <a href="https://stackoverflow.com/a/3050240/6309">Java compliance level</a>:</p>
<p><img src="https://i.stack.imgur.com/FsoIj.png" alt="Java compliance level"></p> |
1,883,467 | Is there a simple alternative to Readline? | <p>On a project I'm working on, I'm trying to make it accept user commands and provide history with the up arrow. I'm aiming to keep this project free of dependencies, and I don't want to have to require people to also install the readline development files just to compile my project. Does anyone know of a simple drop-in replacement for GNU Readline that provides only simple functionality?</p> | 1,883,508 | 6 | 0 | null | 2009-12-10 19:44:48.237 UTC | 9 | 2016-05-11 23:04:45.813 UTC | null | null | null | null | 6,967 | null | 1 | 13 | c|readline | 15,386 | <p>Most systems have readline installed, so I don't see that as being too much of an issue.</p>
<p>Secondly, I don't think there's any drop-in replacement for the GNU Readline library. You're going to have to stick with it. :(</p>
<p>Edit 5/11/2016: This answer is outdated, and any edit I'd make would be borrowing almost completely from the other, more correct answers. Summary: see <a href="https://github.com/antirez/linenoise" rel="nofollow noreferrer">linenoise</a> and <a href="http://thrysoee.dk/editline/" rel="nofollow noreferrer">editline</a> for modern readline alternatives.</p> |
1,407,715 | How to quickly zero out an array? | <p>I am currently doing it in a for loop, and I know in C there is the ZeroMemory API, however that doesn't seem to be available in C#. Nor does the somewhat equivalent Array.fill from Java exist either. I am just wondering if there is an easier/faster way?</p> | 1,407,729 | 7 | 3 | null | 2009-09-10 21:05:17.237 UTC | 8 | 2022-03-28 06:53:42.17 UTC | null | null | null | null | 92,692 | null | 1 | 65 | c#|arrays|memory | 90,038 | <p>Try <a href="http://msdn.microsoft.com/en-us/library/system.array.clear.aspx" rel="noreferrer">Array.Clear()</a>:</p>
<blockquote>
<p>Sets a range of elements in the Array
to zero, to <code>false</code>, or to
<code>null</code>
(Nothing in Visual Basic), depending
on the element type.</p>
</blockquote> |
1,564,372 | What causes a SIGSEGV | <p>I need to know the root cause of the segmentation fault (SIGSEGV), and how to handle it.</p> | 1,564,395 | 7 | 0 | null | 2009-10-14 05:20:14.98 UTC | 21 | 2021-03-07 00:13:42.647 UTC | 2019-04-02 11:58:37.757 UTC | null | 545,127 | null | 172,543 | null | 1 | 96 | segmentation-fault | 197,429 | <p><a href="http://en.wikipedia.org/wiki/SIGSEGV" rel="noreferrer">Wikipedia</a> has the answer, along with a number of other sources.</p>
<p>A segfault basically means you did something bad with pointers. This is probably a segfault:</p>
<pre><code>char *c = NULL;
...
*c; // dereferencing a NULL pointer
</code></pre>
<p>Or this:</p>
<pre><code>char *c = "Hello";
...
c[10] = 'z'; // out of bounds, or in this case, writing into read-only memory
</code></pre>
<p>Or maybe this:</p>
<pre><code>char *c = new char[10];
...
delete [] c;
...
c[2] = 'z'; // accessing freed memory
</code></pre>
<p>Same basic principle in each case - you're doing something with memory that isn't yours.</p> |
1,947,263 | Using an HTML button to call a JavaScript function | <p>I am trying to use an HTML button to call a JavaScript function.</p>
<p>Here's the code:</p>
<pre><code><input type="button" value="Capacity Chart" onclick="CapacityChart();">
</code></pre>
<p>It doesn't seem to work correctly though. Is there a better way to do this?</p>
<p>Here is the link:<a href="http://projectpath.ideapeoplesite.com/bendel/toolscalculators.html" rel="noreferrer">http://projectpath.ideapeoplesite.com/bendel/toolscalculators.html</a> click on the capacity tab in the bottom left section. The button should generate an alert if the values are not changed and should produce a chart if you enter values.</p> | 1,947,531 | 8 | 4 | null | 2009-12-22 15:56:56.197 UTC | 82 | 2019-12-24 14:21:36.21 UTC | 2017-07-23 11:44:34.107 UTC | null | 438,581 | null | 152,205 | null | 1 | 272 | javascript|html | 1,099,353 | <p>There are a few ways to handle events with HTML/DOM. There's no real right or wrong way but different ways are useful in different situations. </p>
<p>1: There's defining it in the HTML:</p>
<pre><code><input id="clickMe" type="button" value="clickme" onclick="doFunction();" />
</code></pre>
<p>2: There's adding it to the DOM property for the event in Javascript:</p>
<pre><code>//- Using a function pointer:
document.getElementById("clickMe").onclick = doFunction;
//- Using an anonymous function:
document.getElementById("clickMe").onclick = function () { alert('hello!'); };
</code></pre>
<p>3: And there's attaching a function to the event handler using Javascript:</p>
<pre><code>var el = document.getElementById("clickMe");
if (el.addEventListener)
el.addEventListener("click", doFunction, false);
else if (el.attachEvent)
el.attachEvent('onclick', doFunction);
</code></pre>
<p>Both the second and third methods allow for inline/anonymous functions and both must be declared after the element has been parsed from the document. The first method isn't valid XHTML because the onclick attribute isn't in the XHTML specification.</p>
<p>The 1st and 2nd methods are mutually exclusive, meaning using one (the 2nd) will override the other (the 1st). The 3rd method will allow you to attach as many functions as you like to the same event handler, even if the 1st or 2nd method has been used too.</p>
<p>Most likely, the problem lies somewhere in your <code>CapacityChart()</code> function. After visiting your link and running your script, the CapacityChart() function runs and the two popups are opened (one is closed as per the script). Where you have the following line:</p>
<pre><code>CapacityWindow.document.write(s);
</code></pre>
<p>Try the following instead:</p>
<pre><code>CapacityWindow.document.open("text/html");
CapacityWindow.document.write(s);
CapacityWindow.document.close();
</code></pre>
<p><strong>EDIT</strong><br>
When I saw your code I thought you were writing it specifically for IE. As others have mentioned you will need to replace references to <code>document.all</code> with <code>document.getElementById</code>. However, you will still have the task of fixing the script after this so I would recommend getting it working in at least IE first as any mistakes you make changing the code to work cross browser could cause even more confusion. Once it's working in IE it will be easier to tell if it's working in other browsers whilst you're updating the code.</p> |
1,353,384 | "l-value required" error | <p>When do we get "l-value required" error...while compiling C++ program???(i am using VC++ )</p> | 1,353,397 | 11 | 2 | null | 2009-08-30 07:53:12.287 UTC | 4 | 2019-12-11 20:00:27.433 UTC | 2009-08-30 08:06:03.273 UTC | null | 120,444 | null | 164,641 | null | 1 | 3 | c++|lvalue|rvalue | 72,357 | <p>An "lvalue" is a value that can be the target of an assignment. The "l" stands for "left", as in the left hand side of the equals sign. An rvalue is the right hand value and produces a value, and cannot be assigned to directly. If you are getting "lvalue required" you have an expression that produces an rvalue when an lvalue is required.</p>
<p>For example, a constant is an rvalue but not an lvalue. So:</p>
<pre><code>1 = 2; // Not well formed, assigning to an rvalue
int i; (i + 1) = 2; // Not well formed, assigning to an rvalue.
</code></pre>
<p>doesn't work, but:</p>
<pre><code>int i;
i = 2;
</code></pre>
<p>Does. Note that you can return an lvalue from a function; for example, you can return a reference to an object that provides a operator=().</p>
<p>As pointed out by Pavel Minaev in comments, this is not a formal definition of lvalues and rvalues in the language, but attempts to give a description to someone confused about an error about using an rvalue where an lvalue is required. C++ is a language with many details; if you want to get formal you should consult a formal reference.</p> |
2,198,377 | How can I clear previous output in Terminal in Mac OS X? | <p>I know the <code>clear</code> command that 'clears' the current screen, but it does this just by printing lots of newlines - the cleared contents just get scrolled up.</p>
<p>Is there a way to completely wipe all previous output from the terminal so that I can't reach it even by scrolling up?</p> | 2,198,403 | 14 | 4 | null | 2010-02-04 09:00:45.917 UTC | 169 | 2020-08-28 13:02:02.223 UTC | 2020-08-28 11:57:20.83 UTC | null | 63,550 | null | 246,776 | null | 1 | 648 | macos|shell|buffer | 323,487 | <h3>To clear the terminal manually:</h3>
<p><kbd>⌘</kbd>+<kbd>K</kbd></p>
<p><kbd>Command</kbd>+<kbd>K</kbd> for newer keyboards</p>
<h3>To clear the terminal from within a shell script;</h3>
<pre><code>/usr/bin/osascript -e 'tell application "System Events" to tell process "Terminal" to keystroke "k" using command down'
</code></pre> |
1,551,235 | compareTo() vs. equals() | <p>When testing for equality of <code>String</code>'s in Java I have always used <code>equals()</code> because to me this seems to be the most natural method for it. After all, its name already says what it is intended to do. However, a colleague of mine recently told me had been taught to use <code>compareTo() == 0</code> instead of <code>equals()</code>. This feels unnatural (as <code>compareTo()</code> is meant to provide an ordering and not compare for equality) and even somewhat dangerous (because <code>compareTo() == 0</code> does not necessarily imply equality in all cases, even though I know it does for <code>String</code>'s) to me.</p>
<p>He did not know why he was taught to use <code>compareTo()</code> instead of <code>equals()</code> for <code>String</code>'s, and I could also not find any reason why. Is this really a matter of personal taste, or is there any real reason for either method?</p> | 1,551,335 | 21 | 2 | null | 2009-10-11 17:35:16.603 UTC | 41 | 2020-04-16 10:15:11.047 UTC | 2019-10-27 07:18:50.59 UTC | null | 1,671,066 | null | 3,587 | null | 1 | 129 | java|string|equals|compareto | 207,300 | <p>A difference is that <code>"foo".equals((String)null)</code> returns false while <code>"foo".compareTo((String)null) == 0</code> throws a NullPointerException. So they are not always interchangeable even for Strings.</p> |
1,643,431 | How to get random value out of an array? | <p>I have an array called <code>$ran = array(1,2,3,4);</code></p>
<p>I need to get a random value out of this array and store it in a variable, how can I do this?</p> | 1,643,465 | 21 | 0 | null | 2009-10-29 12:39:47.383 UTC | 18 | 2022-09-23 19:21:08.883 UTC | 2020-09-08 11:38:08.763 UTC | null | 584,192 | null | 131,637 | null | 1 | 150 | php|arrays|random | 197,320 | <p>You can also do just:</p>
<pre><code>$k = array_rand($array);
$v = $array[$k];
</code></pre>
<p>This is the way to do it when you have an associative array.</p> |
1,547,252 | How do I concatenate two arrays in C#? | <pre><code>int[] x = new int [] { 1, 2, 3};
int[] y = new int [] { 4, 5 };
int[] z = // your answer here...
Debug.Assert(z.SequenceEqual(new int[] { 1, 2, 3, 4, 5 }));
</code></pre>
<hr>
<p>Right now I use </p>
<pre><code>int[] z = x.Concat(y).ToArray();
</code></pre>
<p>Is there an easier or more efficient method?</p> | 1,547,276 | 24 | 4 | null | 2009-10-10 06:58:25.64 UTC | 30 | 2022-01-25 22:17:12.027 UTC | 2020-05-07 11:22:17.983 UTC | null | 850,848 | null | 5,883 | null | 1 | 337 | c#|arrays|.net|linq | 429,933 | <pre><code>var z = new int[x.Length + y.Length];
x.CopyTo(z, 0);
y.CopyTo(z, x.Length);
</code></pre> |
1,877,475 | Repeat a string in JavaScript a number of times | <p>In Perl I can repeat a character multiple times using the syntax:</p>
<pre><code>$a = "a" x 10; // results in "aaaaaaaaaa"
</code></pre>
<p>Is there a simple way to accomplish this in Javascript? I can obviously use a function, but I was wondering if there was any built in approach, or some other clever technique.</p> | 1,877,479 | 25 | 0 | null | 2009-12-09 22:48:37.227 UTC | 121 | 2022-04-09 11:11:07.953 UTC | 2021-01-22 03:03:25.597 UTC | null | 319,266 | null | 131,640 | null | 1 | 789 | javascript|string|character|repeat | 348,483 | <p>These days, the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat" rel="noreferrer"><code>repeat</code> string method</a> is implemented <em>almost</em> everywhere. (It is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat#Browser_compatibility" rel="noreferrer">not in Internet Explorer</a>.) So unless you need to support older browsers, you can simply write:</p>
<pre><code>"a".repeat(10)
</code></pre>
<p>Before <code>repeat</code>, we used this hack:</p>
<pre><code>Array(11).join("a") // create string with 10 a's: "aaaaaaaaaa"
</code></pre>
<p>(Note that an array of length 11 gets you only 10 "a"s, since <code>Array.join</code> puts the argument <em>between</em> the array elements.)</p>
<p>Simon also points out that according to <a href="https://jsben.ch/PqOXU" rel="noreferrer">this benchmark</a>, it appears that it's faster in Safari and Chrome (but not Firefox) to repeat a character multiple times by simply appending using a for loop (although a bit less concise).</p> |
2,201,917 | How can I open a URL in Android's web browser from my application? | <p>How to open an URL from code in the built-in web browser rather than within my application?</p>
<p>I tried this:</p>
<pre><code>try {
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(download_link));
startActivity(myIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No application can handle this request."
+ " Please install a webbrowser", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
</code></pre>
<p>but I got an Exception:</p>
<pre><code>No activity found to handle Intent{action=android.intent.action.VIEW data =www.google.com
</code></pre> | 2,201,999 | 41 | 4 | null | 2010-02-04 17:51:45.483 UTC | 239 | 2022-09-14 09:59:56.57 UTC | 2022-09-14 09:59:56.57 UTC | null | 5,152,146 | null | 164,460 | null | 1 | 1,556 | android|url|android-intent|android-browser | 1,097,670 | <p>Try this:</p>
<pre><code>Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
</code></pre>
<p>That works fine for me.</p>
<p>As for the missing "http://" I'd just do something like this:</p>
<pre><code>if (!url.startsWith("http://") && !url.startsWith("https://"))
url = "http://" + url;
</code></pre>
<p>I would also probably pre-populate your EditText that the user is typing a URL in with "http://".</p> |
8,808,052 | C# Getting proxy settings from Internet Explorer | <p>i have a problem in certain company in germany. They use proxy in their network and my program cant communicate with server.</p>
<p>IE works with this settings:</p>
<p><img src="https://i.stack.imgur.com/Vk4nu.gif" alt="Their settings"></p>
<p>It means:
Automatically detect settings</p>
<p>This is the code:</p>
<pre><code>public static bool CompleteValidation(string regKey)
{
string uri = "***";
int c = 1;
if (Counter < 5) c = 6 - Counter;
string response = "";
try
{
System.Net.ServicePointManager.Expect100Continue = false;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.AllowWriteStreamBuffering = true;
request.Method = "POST";
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.Headers.Add(HttpRequestHeader.AcceptLanguage, "pl,en-us;q=0.7,en;q=0.3");
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
request.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-2,utf-8;q=0.7,*;q=0.7");
request.KeepAlive = true;
//proxy settings
string exepath = Path.GetDirectoryName(Application.ExecutablePath);
string proxySettings = exepath + @"\proxy.ini";
WebProxy wp = new WebProxy();
if (File.Exists(proxySettings)) {
request.Proxy = WebRequest.DefaultWebProxy;
IniFile ini = new IniFile(proxySettings);
string user = ini.IniReadValue("Proxy", "User");
string pass = ini.IniReadValue("Proxy", "Password");
string domain = ini.IniReadValue("Proxy", "Domain");
string ip = ini.IniReadValue("Proxy", "IP");
string port_s = ini.IniReadValue("Proxy", "Port");
int port = 0;
if (!string.IsNullOrEmpty(ip))
{
if (!string.IsNullOrEmpty(port_s))
{
try
{
port = Convert.ToInt32(port_s);
}
catch (Exception e)
{
ErrorLog.AddToLog("Problem with conversion of port:");
ErrorLog.AddToLog(e.Message);
ErrorLog.ShowLogWindow();
}
wp = new WebProxy(ip, port);
} else {
wp = new WebProxy(ip);
}
}
if (string.IsNullOrEmpty(domain))
wp.Credentials = new NetworkCredential(user, pass);
else
wp.Credentials = new NetworkCredential(user, pass, domain);
request.Proxy = wp;
}
string post = "***";
request.ContentLength = post.Length;
request.ContentType = "application/x-www-form-urlencoded";
StreamWriter writer = null;
try
{
writer = new StreamWriter(request.GetRequestStream()); // Here is the WebException thrown
writer.Write(post);
writer.Close();
}
catch (Exception e)
{
ErrorLog.AddToLog("Problem with request sending:");
ErrorLog.AddToLog(e.Message);
ErrorLog.ShowLogWindow();
}
HttpWebResponse Response = null;
try
{
Response = (HttpWebResponse)request.GetResponse();
}
catch (Exception e)
{
ErrorLog.AddToLog("Problem with response:");
ErrorLog.AddToLog(e.Message);
ErrorLog.ShowLogWindow();
}
//Request.Proxy = WebProxy.GetDefaultProxy();
//Request.Proxy.Credentials = CredentialCache.DefaultCredentials;
string sResponseHeader = Response.ContentEncoding; // get response header
if (!string.IsNullOrEmpty(sResponseHeader))
{
if (sResponseHeader.ToLower().Contains("gzip"))
{
byte[] b = DecompressGzip(Response.GetResponseStream());
response = System.Text.Encoding.GetEncoding(Response.ContentEncoding).GetString(b);
}
else if (sResponseHeader.ToLower().Contains("deflate"))
{
byte[] b = DecompressDeflate(Response.GetResponseStream());
response = System.Text.Encoding.GetEncoding(Response.ContentEncoding).GetString(b);
}
}
// uncompressed, standard response
else
{
StreamReader ResponseReader = new StreamReader(Response.GetResponseStream());
response = ResponseReader.ReadToEnd();
ResponseReader.Close();
}
}
catch (Exception e)
{
ErrorLog.AddToLog("Problem with comunication:");
ErrorLog.AddToLog(e.Message);
ErrorLog.ShowLogWindow();
}
if (response == "***")
{
SaveKeyFiles();
WriteRegKey(regKey);
RenewCounter();
return true;
}
else
{
return false;
}
}
</code></pre>
<p>My program logs it as:</p>
<pre><code>[09:13:18] Searching for hardware ID
[09:13:56] Problem with response:
[09:13:56] The remote server returned an error: (407) Proxy Authentication Required.
[09:15:04] problem with comunication:
[09:15:04] Object reference not set to an object instance.
</code></pre>
<p>If they write user and pass into proxy.ini file, program works. But the problem is they cant do that. And somehow IE works without it. Is there any way to get those settings from IE or system?</p> | 8,808,308 | 2 | 2 | null | 2012-01-10 17:57:41.643 UTC | 7 | 2015-11-14 13:00:34.053 UTC | null | null | null | null | 325,606 | null | 1 | 12 | c#|proxy|internet-explorer-7|webrequest | 40,046 | <p>Use <a href="http://msdn.microsoft.com/en-us/library/system.net.webrequest.getsystemwebproxy.aspx" rel="noreferrer">GetSystemWebProxy</a> to return what the system default proxy is.</p>
<pre><code> WebRequest.DefaultProxy = WebRequest.GetSystemWebProxy();
</code></pre>
<p>But every <a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx" rel="noreferrer">HttpWebRequest</a> should automatically be filled out with this information by default. For example, the following snippet in a standalone console application should print the correct information on a system with a PAC file configured.</p>
<pre><code> HttpWebRequest myWebRequest=(HttpWebRequest)WebRequest.Create("http://www.microsoft.com");
// Obtain the 'Proxy' of the Default browser.
IWebProxy proxy = myWebRequest.Proxy;
// Print the Proxy Url to the console.
if (proxy != null)
{
Console.WriteLine("Proxy: {0}", proxy.GetProxy(myWebRequest.RequestUri));
}
else
{
Console.WriteLine("Proxy is null; no proxy will be used");
}
</code></pre> |
8,752,541 | Jquery Delay After Click | <p>I'm creating a web app...</p>
<p>i got a kind of game, my idea is when the user completes each level appears a dialog box with some information, it is fine.</p>
<p>Now my issue is i want to show this message 5 seconds after the user clicks on the finish button.</p>
<p>thats my code:</p>
<pre><code>$('#option-main-menu').click(function(){
target.append('\
<div id="confirm">\
<h1>Are You Sure Want to Exist?</h1>\
<a href="#" id="dialog-confirm">Yes</a><a href="#" id="dialog-cancel">No</a>\
</div>\
');
});
</code></pre>
<p>also i tryed with <code>append().Delay(10000)</code> but does not work.</p>
<p>Thanks in advance.</p> | 8,752,555 | 7 | 2 | null | 2012-01-06 02:03:57.9 UTC | 6 | 2017-01-26 17:39:43.787 UTC | null | null | null | null | 1,040,643 | null | 1 | 15 | javascript|jquery|html | 69,471 | <p>Use <code>setTimeout()</code> with a delay of 5000 ms.</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$("button").click(
function() {
console.log("clicked...waiting...");
setTimeout(
function() {
alert("Called after delay.");
},
5000);
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button type="button">Click Me</button></code></pre>
</div>
</div>
</p>
<p>Just out of curiosity, why would you want to wait 5 seconds before prompting the user in response to an action? That's a long time; long enough for them to have clicked on a bunch of other things (if nothing else).</p> |
17,987,647 | Moment.js transform to date object | <p>Using Moment.js I can't transform a correct moment object to a date object with timezones. I can't get the correct date.</p>
<p><strong>Example:</strong></p>
<pre><code>var oldDate = new Date(),
momentObj = moment(oldDate).tz("MST7MDT"),
newDate = momentObj.toDate();
console.log("start date " + oldDate)
console.log("Format from moment with offset " + momentObj.format())
console.log("Format from moment without offset " + momentObj.utc().format())
console.log("(Date object) Time with offset " + newDate)
console.log("(Date object) Time without offset "+ moment.utc(newDate).toDate())
</code></pre> | 26,744,045 | 11 | 4 | null | 2013-08-01 07:25:25.843 UTC | 78 | 2021-10-27 08:17:15.417 UTC | 2016-09-10 02:02:20.82 UTC | null | 1,304,273 | null | 2,466,277 | null | 1 | 869 | javascript|momentjs | 924,067 | <p>Use this to transform a moment object into a date object:</p>
<p>From <a href="http://momentjs.com/docs/#/displaying/as-javascript-date/">http://momentjs.com/docs/#/displaying/as-javascript-date/</a></p>
<pre><code>moment().toDate();
</code></pre>
<p>Yields:</p>
<pre><code>Tue Nov 04 2014 14:04:01 GMT-0600 (CST)
</code></pre> |
6,916,129 | How to get two windows with different plots | <p>When we have a window with plots, is there a way to tell R to display a new plot in a new window?</p> | 6,916,147 | 3 | 0 | null | 2011-08-02 17:37:18.917 UTC | 5 | 2017-12-06 20:45:14.933 UTC | 2017-12-06 20:43:29.553 UTC | null | 63,550 | null | 747,311 | null | 1 | 34 | r|window|plot | 49,342 | <p>Create a new one:</p>
<pre><code>plot(1:10)
x11() # This has aliases on different OSes
plot(10:1)
</code></pre> |
6,791,944 | How exactly does document.cookie work? | <p>If I get Chrome to show me <code>document.cookie</code> by going into the console and typing <code>document.cookie;</code> it'll give me, say:</p>
<p><code>"name=John; gender=male";</code></p>
<p>But then if I type in, say, <code>document.cookie = 5;</code> all it does is add <code>5;</code> to the start of the string, so I get:</p>
<p><code>"5; name=John; gender=male";</code></p>
<p>If I try <code>document.cookie = null;</code> then it doesn't even do anything.</p>
<p>How can this be? It's a variable, isn't it? So why isn't the assignment operator working the way it should? Is it actually just a bit of syntactic sugar rather than a real variable? And if so, what precisely is the sugar covering up?</p> | 6,791,998 | 3 | 2 | null | 2011-07-22 15:02:52.813 UTC | 8 | 2019-06-05 06:46:01.853 UTC | 2013-10-14 19:32:16.113 UTC | null | 425,313 | null | 815,612 | null | 1 | 36 | javascript|debugging|google-chrome|javascript-debugger | 25,474 | <p><code>document.cookie</code> has <em>very</em> special behavior. As you've seen, assigning to it <em>adds</em> (or updates) a cookie (or multiple cookies), rather than <em>replacing</em> all of the cookies. It's very unusual.</p>
<p>Read all about it on <a href="https://developer.mozilla.org/en/Document.cookie" rel="noreferrer">MDN</a>.</p> |
35,937,118 | Build JSON response in Web API controller | <p>In a WebAPI project, i have a controller that checks a status of a product, based on a value the user enters.</p>
<p>Lets say they enter "123" and the response should be "status": 1, AND a list of products. If they enter "321" the "status" is 0, AND a list of products.</p>
<p>My question is, how do i build such a string correct in a WebAPI controller.</p>
<pre><code>[Route("{value:int}")]
public string GetProducts(int value)
{
var json = "";
var products = db.Products;
if (products.Any())
{
foreach (var s in products)
{
ProductApi product = new ProductApi();
product.Name = s.Name;
json += JsonConvert.SerializeObject(supplier);
}
}
var status = db.Status;
if (status.Any())
{
json += "{status:1}";
}
else
{
json += "{status:0}";
}
return json;
}
public class ProductApi
{
public string Name { get; set; }
}
</code></pre>
<p>Also, is this output/response considered valid?</p>
<pre><code>[
{
"id":1,
"name":"product name"
},
{
"id":2,
"name":"product name 2"
},
{
"id":3,
"name":"product name 3"
}
]
{
"status": 0
}
</code></pre> | 35,937,650 | 2 | 4 | null | 2016-03-11 09:59:51.1 UTC | 2 | 2017-05-22 15:57:52.013 UTC | 2016-03-11 11:27:20.673 UTC | null | 1,307,262 | null | 671,809 | null | 1 | 17 | c#|json|asp.net-web-api|asp.net-web-api2 | 99,400 | <p>So here are the changes for your post:</p>
<p>First, you should make your api return Json by default when you pass a <code>text/html</code> request (is this you are looking for?), adding this line to your <code>WebApiConfig</code> class:</p>
<pre><code>config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
</code></pre>
<p>Second, I changed the code to return a real object, impersonating your response:</p>
<pre><code>public class ProductApiCollection
{
public ProductApi[] Products { get; set; }
public byte Status { get; set; }
}
public class ProductApi
{
public string Name { get; set; }
}
</code></pre>
<p>Method body:</p>
<pre><code>public ProductApiCollection Get()
{
var result = new ProductApiCollection();
var dbProducts = db.Products;
var apiModels = dbProducts.Select(x => new ProductApi { Name = x.Name } ).ToArray();
result.Products = apiModels;
var status = db.Status.Any() ? 1 : 0;
result.Status = status;
return result;
}
</code></pre>
<p>This will results in the following example json:</p>
<pre><code>{
"Products": [
{
"Name": "Pork"
},
{
"Name": "Beef"
},
{
"Name": "Chicken"
},
{
"Name": "Salad"
}
],
"Status": 1
}
</code></pre>
<p>I strongly advise you not to do manual formatting for such things, and rely on built-in and 3rd party libraries. Otherwise, you will be reinventing the things already available, tested and ready to work.</p> |
40,256,338 | Calculating Average True Range (ATR) on OHLC data with Python | <p>The ATR is the average of the True Range for a given period. True Range is (High-Low) meaning I have computed this with the following:</p>
<pre><code>df['High'].subtract(df['Low']).rolling(distance).mean()
</code></pre>
<p>However if a short period (or 'distance' in the example above) is required the ATR can be very jumpy, i.e. with large sporadic gaps appearing between some numbers. </p>
<p>The real ATR equation recognises this and smooths it out by doing the following: </p>
<pre><code>Current ATR = [(Prior ATR x 13) + Current TR] / 14
</code></pre>
<p>However I am unsure how to do this in the same manner as I did above, i.e. a column wide operation.</p>
<p>Sample data including the TR and ATR(10) from my original method:</p>
<pre><code>Date Time Open High Low Close TR ATR
30/09/16 14:45:00+00:00 1.1216 1.1221 1.1208 1.1209 0.0013 0.0013
30/09/16 15:00:00+00:00 1.1209 1.1211 1.1203 1.1205 0.0008 0.0013
30/09/16 15:15:00+00:00 1.1205 1.1216 1.1204 1.1216 0.0012 0.0013
30/09/16 15:30:00+00:00 1.1217 1.1222 1.1213 1.1216 0.0008 0.0013
30/09/16 15:45:00+00:00 1.1216 1.1240 1.1216 1.1240 0.0025 0.0015
30/09/16 16:00:00+00:00 1.1239 1.1246 1.1228 1.1242 0.0019 0.0015
30/09/16 16:15:00+00:00 1.1242 1.1251 1.1235 1.1240 0.0016 0.0016
30/09/16 16:30:00+00:00 1.1240 1.1240 1.1234 1.1236 0.0007 0.0014
30/09/16 16:45:00+00:00 1.1237 1.1245 1.1235 1.1238 0.0009 0.0012
30/09/16 17:00:00+00:00 1.1238 1.1239 1.1231 1.1233 0.0008 0.0012
30/09/16 17:15:00+00:00 1.1233 1.1245 1.1232 1.1240 0.0013 0.0012
30/09/16 17:30:00+00:00 1.1240 1.1242 1.1228 1.1230 0.0013 0.0013
30/09/16 17:45:00+00:00 1.1230 1.1230 1.1221 1.1227 0.0009 0.0013
30/09/16 18:00:00+00:00 1.1227 1.1232 1.1227 1.1232 0.0005 0.0012
30/09/16 18:15:00+00:00 1.1232 1.1232 1.1227 1.1227 0.0005 0.0010
30/09/16 18:30:00+00:00 1.1227 1.1231 1.1225 1.1231 0.0006 0.0009
30/09/16 18:45:00+00:00 1.1231 1.1237 1.1230 1.1232 0.0007 0.0008
30/09/16 19:00:00+00:00 1.1232 1.1233 1.1229 1.1231 0.0004 0.0008
30/09/16 19:15:00+00:00 1.1231 1.1234 1.1230 1.1230 0.0004 0.0007
30/09/16 19:30:00+00:00 1.1231 1.1234 1.1230 1.1234 0.0004 0.0007
30/09/16 19:45:00+00:00 1.1233 1.1240 1.1230 1.1239 0.0010 0.0007
30/09/16 20:00:00+00:00 1.1239 1.1242 1.1237 1.1238 0.0005 0.0006
30/09/16 20:15:00+00:00 1.1238 1.1240 1.1235 1.1237 0.0005 0.0006
30/09/16 20:30:00+00:00 1.1237 1.1238 1.1235 1.1235 0.0003 0.0005
30/09/16 20:45:00+00:00 1.1235 1.1236 1.1233 1.1233 0.0003 0.0005
30/09/16 21:00:00+00:00 1.1233 1.1238 1.1233 1.1237 0.0006 0.0005
30/09/16 21:15:00+00:00 1.1237 1.1244 1.1237 1.1242 0.0008 0.0005
30/09/16 21:30:00+00:00 1.1242 1.1243 1.1239 1.1239 0.0004 0.0005
30/09/16 21:45:00+00:00 1.1239 1.1244 1.1236 1.1241 0.0008 0.0006
</code></pre> | 56,498,957 | 4 | 3 | null | 2016-10-26 07:37:12.42 UTC | 9 | 2022-04-12 13:41:27.13 UTC | 2016-10-26 09:25:13.41 UTC | null | 1,214,212 | null | 1,214,212 | null | 1 | 11 | python|pandas|dataframe | 22,501 | <p>For anyone else looking on how to do this, here is my answer.</p>
<pre><code>def wwma(values, n):
"""
J. Welles Wilder's EMA
"""
return values.ewm(alpha=1/n, adjust=False).mean()
def atr(df, n=14):
data = df.copy()
high = data[HIGH]
low = data[LOW]
close = data[CLOSE]
data['tr0'] = abs(high - low)
data['tr1'] = abs(high - close.shift())
data['tr2'] = abs(low - close.shift())
tr = data[['tr0', 'tr1', 'tr2']].max(axis=1)
atr = wwma(tr, n)
return atr
</code></pre> |
40,238,144 | Safe navigation operator (?.) or (!.) and null property paths | <p>In Angular 2 templates safe operator <code>?.</code> works, but not in <code>component.ts</code> using TypeScript 2.0. Also, safe navigation operator (<code>!.</code>) doesn't work.</p>
<p>For example:</p>
<p>This TypeScript</p>
<pre><code>if (a!.b!.c) { }
</code></pre>
<p>compiles to this JavaScript</p>
<pre><code>if (a.b.c) { }
</code></pre>
<p>But when I run it, I get the follow error:</p>
<blockquote>
<p>Cannot read property 'b' of undefined</p>
</blockquote>
<p>Is there any alternative to the following?</p>
<pre><code>if (a && a.b && a.b.c) { }
</code></pre> | 58,762,171 | 7 | 4 | null | 2016-10-25 10:57:42.93 UTC | 30 | 2021-10-01 11:16:23.187 UTC | 2020-10-29 20:15:37.717 UTC | null | 3,345,644 | null | 6,081,464 | null | 1 | 189 | typescript | 214,455 | <p>Since TypeScript 3.7 was released you can use optional chaining now.</p>
<p><strong>Property example:</strong></p>
<pre><code>let x = foo?.bar.baz();
</code></pre>
<p>This is equvalent to:</p>
<pre><code>let x = (foo === null || foo === undefined)
? undefined
: foo.bar.baz();
</code></pre>
<p>Moreover you can call:</p>
<p><strong>Optional Call</strong></p>
<pre><code>function(otherFn: (par: string) => void) {
otherFn?.("some value");
}
</code></pre>
<p><code>otherFn</code> will be called only if <code>otherFn</code> won't be equal to <code>null</code> or <code>undefined</code></p>
<p><strong>Usage optional chaining in IF statement</strong></p>
<p>This:</p>
<pre><code>if (someObj && someObj.someProperty) {
// ...
}
</code></pre>
<p>can be replaced now with this</p>
<pre><code>if (someObj?.someProperty) {
// ...
}
</code></pre>
<p>Ref: <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html" rel="noreferrer">https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html</a></p> |
228,648 | How do you list the currently available objects in the current scope in ruby? | <p>I'm new to ruby and I'm playing around with the IRB.</p>
<p>I found that I can list methods of an object using the ".methods" method, and that self.methods sort of give me what I want (similar to Python's dir(<strong>builtins</strong>)?), but how can I find the methods of a library/module I've loaded via include and require?</p>
<pre><code>irb(main):036:0* self.methods
=> ["irb_pop_binding", "inspect", "taguri", "irb_chws", "clone", "irb_pushws", "public_methods", "taguri=", "irb_pwws",
"public", "display", "irb_require", "irb_exit", "instance_variable_defined?", "irb_cb", "equal?", "freeze", "irb_context
", "irb_pop_workspace", "irb_cwb", "irb_jobs", "irb_bindings", "methods", "irb_current_working_workspace", "respond_to?"
, "irb_popb", "irb_cws", "fg", "pushws", "conf", "dup", "cwws", "instance_variables", "source", "cb", "kill", "help", "_
_id__", "method", "eql?", "irb_pwb", "id", "bindings", "send", "singleton_methods", "popb", "irb_kill", "chws", "taint",
"irb_push_binding", "instance_variable_get", "frozen?", "irb_source", "pwws", "private", "instance_of?", "__send__", "i
rb_workspaces", "to_a", "irb_quit", "to_yaml_style", "irb_popws", "irb_change_workspace", "jobs", "type", "install_alias
_method", "irb_push_workspace", "require_gem", "object_id", "instance_eval", "protected_methods", "irb_print_working_wor
kspace", "irb_load", "require", "==", "cws", "===", "irb_pushb", "instance_variable_set", "irb_current_working_binding",
"extend", "kind_of?", "context", "gem", "to_yaml_properties", "quit", "popws", "irb", "to_s", "to_yaml", "irb_fg", "cla
ss", "hash", "private_methods", "=~", "tainted?", "include", "irb_cwws", "irb_change_binding", "irb_help", "untaint", "n
il?", "pushb", "exit", "irb_print_working_binding", "is_a?", "workspaces"]
irb(main):037:0>
</code></pre>
<p>I'm used to python, where I use the dir() function to accomplish the same thing:</p>
<pre><code>>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>>
</code></pre> | 228,911 | 7 | 0 | null | 2008-10-23 05:38:15.673 UTC | 20 | 2017-08-21 12:17:58.763 UTC | 2017-08-21 12:17:58.763 UTC | monkut | 7,825,115 | monkut | 24,718 | null | 1 | 39 | ruby|introspection|irb | 35,384 | <p><a href="http://www.ruby-doc.org/core-1.8.7/classes/ObjectSpace.html#M000928" rel="noreferrer">ObjectSpace.each_object</a> could be what you are looking for.</p>
<p>To get a list of included modules you could use <a href="http://www.ruby-doc.org/core/classes/Module.html#M001697" rel="noreferrer">Module.included_modules</a>.</p>
<p>You can also check if an object responds to a method on a case-by-case basis using <a href="http://ruby-doc.org/core/classes/Object.html#M000333" rel="noreferrer">object.respond_to?</a>.</p> |
1,183,001 | How can I tail a zipped file without reading its entire contents? | <p>I want to emulate the functionality of gzcat | tail -n.</p>
<p>This would be helpful for times when there are huge files (of a few GB's or so). Can I tail the last few lines of such a file w/o reading it from the beginning? I doubt that this won't be possible since I'd guess for gzip, the encoding would depend on all the previous text.</p>
<p>But still I'd like to hear if anyone has tried doing something similar - maybe investigating over a compression algorithm that could provide such a feature.</p> | 1,183,012 | 7 | 2 | null | 2009-07-25 20:39:59.647 UTC | 5 | 2019-09-23 12:29:33.367 UTC | 2009-07-26 05:33:18.81 UTC | null | 68,507 | null | 82,413 | null | 1 | 40 | algorithm|compression | 39,409 | <p>No, you can't. The <a href="http://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch" rel="noreferrer">zipping algorithm</a> works on streams and adapts its internal codings to what the stream contains to achieve its high compression ratio.</p>
<p>Without knowing what the contents of the stream are before a certain point, it's impossible to know how to go about de-compressing from that point on.</p>
<p>Any algorithm which allows you to de-compress arbitrary parts of it will require multiple passes over the data to compress it.</p> |
78,799 | Is there a benefit to defining a class inside another class in Python? | <p>What I'm talking about here are nested classes. Essentially, I have two classes that I'm modeling. A DownloadManager class and a DownloadThread class. The obvious OOP concept here is composition. However, composition doesn't necessarily mean nesting, right?</p>
<p>I have code that looks something like this:</p>
<pre><code>class DownloadThread:
def foo(self):
pass
class DownloadManager():
def __init__(self):
dwld_threads = []
def create_new_thread():
dwld_threads.append(DownloadThread())
</code></pre>
<p>But now I'm wondering if there's a situation where nesting would be better. Something like:</p>
<pre><code>class DownloadManager():
class DownloadThread:
def foo(self):
pass
def __init__(self):
dwld_threads = []
def create_new_thread():
dwld_threads.append(DownloadManager.DownloadThread())
</code></pre> | 78,858 | 7 | 0 | 2008-09-17 01:02:31.157 UTC | 2008-09-17 01:02:31.157 UTC | 25 | 2021-08-17 14:26:53.15 UTC | 2015-01-11 21:41:42.717 UTC | null | 4,400,284 | fuentesjr | 10,708 | null | 1 | 131 | python|oop | 95,286 | <p>You might want to do this when the "inner" class is a one-off, which will never be used outside the <em>definition</em> of the outer class. For example to use a metaclass, it's sometimes handy to do</p>
<pre><code>class Foo(object):
class __metaclass__(type):
....
</code></pre>
<p>instead of defining a metaclass separately, if you're only using it once.</p>
<p>The only other time I've used nested classes like that, I used the outer class only as a namespace to group a bunch of closely related classes together:</p>
<pre><code>class Group(object):
class cls1(object):
...
class cls2(object):
...
</code></pre>
<p>Then from another module, you can import Group and refer to these as Group.cls1, Group.cls2 etc. However one might argue that you can accomplish exactly the same (perhaps in a less confusing way) by using a module.</p> |
1,008,785 | C#: Cleanest way to divide a string array into N instances N items long | <p>I know how to do this in an ugly way, but am wondering if there is a more elegant and succinct method. </p>
<p>I have a string array of e-mail addresses. Assume the string array is of arbitrary length -- it could have a few items or it could have a great many items. I want to build another string consisting of say, 50 email addresses from the string array, until the end of the array, and invoke a send operation after each 50, using the string of 50 addresses in the Send() method. </p>
<p>The question more generally is what's the cleanest/clearest way to do this kind of thing. I have a solution that's a legacy of my VBScript learnings, but I'm betting there's a better way in C#. </p> | 1,008,974 | 8 | 2 | null | 2009-06-17 18:28:45.37 UTC | 14 | 2017-11-26 10:22:40.433 UTC | null | null | null | Socrates | null | null | 1 | 19 | c#|arrays|string|loops | 10,797 | <p>You want elegant and succinct, I'll give you elegant and succinct:</p>
<pre><code>var fifties = from index in Enumerable.Range(0, addresses.Length)
group addresses[index] by index/50;
foreach(var fifty in fifties)
Send(string.Join(";", fifty.ToArray());
</code></pre>
<p>Why mess around with all that awful looping code when you don't have to? You want to group things by fifties, <em>then group them by fifties.</em>
That's what the group operator is for!</p>
<p>UPDATE: commenter MoreCoffee asks how this works. Let's suppose we wanted to group by threes, because that's easier to type.</p>
<pre><code>var threes = from index in Enumerable.Range(0, addresses.Length)
group addresses[index] by index/3;
</code></pre>
<p>Let's suppose that there are nine addresses, indexed zero through eight</p>
<p>What does this query mean? </p>
<p>The <code>Enumerable.Range</code> is a range of nine numbers starting at zero, so <code>0, 1, 2, 3, 4, 5, 6, 7, 8</code>.</p>
<p>Range variable <code>index</code> takes on each of these values in turn.</p>
<p>We then go over each corresponding <code>addresses[index]</code> and assign it to a group.</p>
<p>What group do we assign it to? To group <code>index/3</code>. Integer arithmetic rounds towards zero in C#, so indexes 0, 1 and 2 become 0 when divided by 3. Indexes 3, 4, 5 become 1 when divided by 3. Indexes 6, 7, 8 become 2.</p>
<p>So we assign <code>addresses[0]</code>, <code>addresses[1]</code> and <code>addresses[2]</code> to group 0, <code>addresses[3]</code>, <code>addresses[4]</code> and <code>addresses[5]</code> to group 1, and so on.</p>
<p>The result of the query is a sequence of three groups, and each group is a sequence of three items.</p>
<p>Does that make sense?</p>
<p>Remember also that the result of the <em>query expression</em> is a <em>query which represents this operation</em>. It does not <em>perform</em> the operation until the <code>foreach</code> loop executes.</p> |
55,901 | Web service - current time zone for a city? | <p>Is there a web service of some sort (or any other way) to pull a current time zone settings for a (US) city. For the parts of the country that don't follow the Daylight Saving Time and basically jump timezones when everyone else is switching summer/winter time... I don't fancy creating own database of the places that don't follow DST. Is there a way to pull this data on demand? </p>
<p>I need this for the database server (not for client workstations) - there entities stored in the database that have City, State as properties. I need know current timezone for these entities at any moment of time.</p> | 55,910 | 8 | 0 | null | 2008-09-11 06:30:04.667 UTC | 34 | 2021-11-12 09:58:34.727 UTC | 2013-09-09 13:12:09.633 UTC | sergeb | 1,400,768 | sergeb | 4,808 | null | 1 | 54 | web-services|timezone | 92,839 | <p>earthtools.org provides a free web service to get the time zone from a city here:</p>
<p><a href="http://www.earthtools.org/webservices.htm#timezone" rel="noreferrer">http://www.earthtools.org/webservices.htm#timezone</a></p>
<p>You just pass in the long/lat values like this: (This is for New York)</p>
<p><a href="http://www.earthtools.org/timezone-1.1/40.71417/-74.00639" rel="noreferrer">http://www.earthtools.org/timezone-1.1/40.71417/-74.00639</a></p>
<hr>
<p><strong>EDIT:</strong></p>
<p>It seems like earthtools has been shut down. A good alternative (That did not exist in 2008 when this question was answered) is the Google Time Zone API. To use it you must first <a href="https://console.developers.google.com/flows/enableapi?apiid=timezone_backend&keyType=SERVER_SIDE" rel="noreferrer">activate the Time Zone API</a> on your account. It is free if you stay below these limits:</p>
<ul>
<li>2500 requests per 24 hour period.</li>
<li>5 requests per second.</li>
</ul>
<p><a href="https://developers.google.com/maps/documentation/timezone/intro" rel="noreferrer">The documentation</a> is available on Google Developers.</p> |
1,284,959 | How to avoid circular unit reference? | <p>Imagine the following two classes of a chess game:</p>
<pre><code>TChessBoard = class
private
FBoard : array [1..8, 1..8] of TChessPiece;
...
end;
TChessPiece = class abstract
public
procedure GetMoveTargets (BoardPos : TPoint; Board : TChessBoard; MoveTargetList : TList <TPoint>);
...
end;
</code></pre>
<p>I want the two classes to be defined in two separate units <em>ChessBoard.pas</em> and <em>ChessPiece.pas</em>.</p>
<p>How can I avoid the circular unit reference that I run into here (each unit is needed in the other unit's interface section)?</p> | 1,290,791 | 9 | 0 | null | 2009-08-16 18:17:58.997 UTC | 9 | 2016-02-24 12:26:39.227 UTC | null | null | null | null | 62,391 | null | 1 | 16 | delphi|project-organization|circular-reference | 14,107 | <p>Change the unit that defines TChessPiece to look like the following:</p>
<pre><code>TYPE
tBaseChessBoard = class;
TChessPiece = class
procedure GetMoveTargets (BoardPos : TPoint; Board : TBaseChessBoard; ...
...
end;
</code></pre>
<p>then modify the unit that defines TChessBoard to look like the following:</p>
<pre><code>USES
unit_containing_tBaseChessboard;
TYPE
TChessBoard = class(tBaseChessBoard)
private
FBoard : array [1..8, 1..8] of TChessPiece;
...
end;
</code></pre>
<p>This allows you to pass concrete instances to the chess piece without having to worry about a circular reference. Since the board uses the Tchesspieces in its private, it really doesn't have to exist prior to the Tchesspiece declaration, just as place holder. Any state variables which the tChessPiece must know about of course should be placed in the tBaseChessBoard, where they will be available to both.</p> |
21,583 | Unit-Testing Databases | <p>This past summer I was developing a basic ASP.NET/SQL Server CRUD app, and unit testing was one of the requirements. I ran into some trouble when I tried to test against the database. To my understanding, unit tests should be:</p>
<ul>
<li>stateless</li>
<li>independent from each other</li>
<li>repeatable with the same results i.e. no persisting changes</li>
</ul>
<p>These requirements seem to be at odds with each other when developing for a database. For example, I can't test Insert() without making sure the rows to be inserted aren't there yet, thus I need to call the Delete() first. But, what if they aren't already there? Then I would need to call the Exists() function first.</p>
<p>My eventual solution involved very large setup functions (yuck!) and an empty test case which would run first and indicate that the setup ran without problems. This is sacrificing on the independence of the tests while maintaining their statelessness.</p>
<p>Another solution I found is to wrap the function calls in a transaction which can be easily rolled back, like <a href="http://weblogs.asp.net/rosherove/archive/2004/10/05/238201.aspx" rel="noreferrer">Roy Osherove's XtUnit</a>. This work, but it involves another library, another dependency, and it seems a little too heavy of a solution for the problem at hand.</p>
<p>So, what has the SO community done when confronted with this situation?</p>
<hr>
<p>tgmdbm said:</p>
<blockquote>
<p>You typically use your favourite
automated unit testing framework to
perform integration tests, which is
why some people get confused, but they
don't follow the same rules. You are
allowed to involve the concrete
implementation of many of your classes
(because they've been unit tested).
You are testing <strong>how your concrete
classes interact with each other and
with the database</strong>.</p>
</blockquote>
<p>So if I read this correctly, there is really no way to <em>effectively</em> unit-test a Data Access Layer. Or, would a "unit test" of a Data Access Layer involve testing, say, the SQL/commands generated by the classes, independent of actual interaction with the database?</p> | 21,603 | 9 | 0 | null | 2008-08-22 01:35:33.773 UTC | 16 | 2014-04-25 15:24:00.51 UTC | 2013-06-17 11:44:44.4 UTC | Chris Fournier | 16,587 | pbh101 | 1,266 | null | 1 | 32 | database|unit-testing|transactions|xtunit | 8,341 | <p>There's no real way to unit test a database other than asserting that the tables exist, contain the expected columns, and have the appropriate constraints. But that's usually not really worth doing.</p>
<p>You don't typically <strong>unit</strong> test the database. You usually involve the database in <strong>integration</strong> tests.</p>
<p>You typically use your favourite automated unit testing framework to perform integration tests, which is why some people get confused, but they don't follow the same rules. You are allowed to involve the concrete implementation of many of your classes (because they've been unit tested). You are testing how your concrete classes interact with each other and with the database.</p> |
331,976 | How do I serialize a C# anonymous type to a JSON string? | <p>I'm attempting to use the following code to serialize an anonymous type to JSON:</p>
<pre><code>var serializer = new DataContractJsonSerializer(thing.GetType());
var ms = new MemoryStream();
serializer.WriteObject(ms, thing);
var json = Encoding.Default.GetString(ms.ToArray());
</code></pre>
<p>However, I get the following exception when this is executed:</p>
<blockquote>
<p>Type
'<>f__AnonymousType1`3[System.Int32,System.Int32,System.Object[]]'
cannot be serialized. Consider marking
it with the DataContractAttribute
attribute, and marking all of its
members you want serialized with the
DataMemberAttribute attribute. See
the Microsoft .NET Framework
documentation for other supported
types.</p>
</blockquote>
<p>I can't apply attributes to an anonymous type (as far as I know). Is there another way to do this serialization or am I missing something? </p> | 331,983 | 9 | 0 | null | 2008-12-01 19:48:33.447 UTC | 39 | 2022-01-06 14:57:30.443 UTC | 2018-12-13 12:36:37.99 UTC | null | 297,823 | JC Grubbs | 4,541 | null | 1 | 178 | c#|json|anonymous-types|datacontractjsonserializer|json-serialization | 137,502 | <p>Try the JavaScriptSerializer instead of the DataContractJsonSerializer</p>
<pre><code>JavaScriptSerializer serializer = new JavaScriptSerializer();
var output = serializer.Serialize(your_anon_object);
</code></pre> |
1,063,125 | How can I parse CSV files on the Linux command line? | <p>How can I parse CSV files on the Linux command line?</p>
<p>To do things like:</p>
<pre><code>csvparse -c 2,5,6 filename
</code></pre>
<p>to extract fields from columns 2, 5 and 6 from all rows.</p>
<p>It should be able to handle the csv file format: <a href="https://www.rfc-editor.org/rfc/rfc4180" rel="nofollow noreferrer">https://www.rfc-editor.org/rfc/rfc4180</a> which means <strong>quoting fields and escaping inner quotes as appropriate</strong>, so for an example row with 3 fields:</p>
<pre><code>field1,"field, number ""2"", has inner quotes and a comma",field3
</code></pre>
<p>so that if I request field 2 for the row above I get:</p>
<pre><code>field, number "2", has inner quotes and a comma
</code></pre>
<p>I appreciate that there are numerous solutions, Perl, Awk (etc.) to this problem but I would like a native bash command line tool that does not require me to invoke some other scripting environment or write any additional code(!).</p> | 1,064,037 | 12 | 8 | null | 2009-06-30 11:16:02.817 UTC | 21 | 2018-09-11 16:50:10.83 UTC | 2021-10-07 05:46:31.917 UTC | null | -1 | null | 60,956 | null | 1 | 39 | linux|unix|csv | 61,643 | <p>My FOSS CSV stream editor <a href="https://bitbucket.org/neilb/csvfix/src" rel="nofollow noreferrer">CSVfix</a> does exactly what you want. There is a binary installer for Windows, and a compilable version (via a makefile) for UNIX/Linux.</p> |
93,900 | Can't add server to a moved workspace | <p>I have this workspace downloaded off the web and I try running it on a tomcat server from a fresh installation of Eclipse Ganymede. This particular project came with its own workspace. </p>
<p>When I select Tomcat v6.0 I get a message </p>
<blockquote>
<p>Cannot create a server using the selected type</p>
</blockquote>
<p>Older tomcat versions are available, though. </p>
<p>I guess I have to recreate some configuration setting. The question is which one? This seems to be some odd error as creating a new dynamic web project lets me configure tomcat for both of them</p> | 702,024 | 17 | 2 | 2008-09-18 16:00:54.017 UTC | 2008-09-18 16:00:54.017 UTC | 9 | 2016-12-22 07:52:10.937 UTC | 2009-08-20 13:14:21.28 UTC | null | 10,523 | null | 10,523 | null | 1 | 44 | eclipse|tomcat|jakarta-ee|workspace | 49,732 | <p>I had a similar problem, but my solution is a little simpler. The problem was causesd by renaming the original folder that was referenced by the server definition.</p>
<p>Go to Window/Preferences/Server/Runtime Environments, remove the broken reference. Then, click 'Add' to create a new reference, select the appropriate tomcat version, click next and you'll see the incorrect path reference. Fix it. Move on.</p> |
140,061 | When to use dynamic vs. static libraries | <p>When creating a class library in C++, you can choose between dynamic (<code>.dll</code>, <code>.so</code>) and static (<code>.lib</code>, <code>.a</code>) libraries. What is the difference between them and when is it appropriate to use which?</p> | 140,100 | 19 | 1 | null | 2008-09-26 15:02:01.607 UTC | 259 | 2022-04-15 07:00:57.64 UTC | 2018-12-21 15:46:06.677 UTC | null | 545,127 | Morten Christiansen | 4,055 | null | 1 | 488 | c++|dll|shared-libraries|static-linking|dynamic-linking | 276,933 | <p>Static libraries increase the size of the code in your binary. They're always loaded and whatever version of the code you compiled with is the version of the code that will run.</p>
<p>Dynamic libraries are stored and versioned separately. It's possible for a version of the dynamic library to be loaded that wasn't the original one that shipped with your code <strong>if</strong> the update is considered binary compatible with the original version.</p>
<p>Additionally dynamic libraries aren't necessarily loaded -- they're usually loaded when first called -- and can be shared among components that use the same library (multiple data loads, one code load).</p>
<p>Dynamic libraries were considered to be the better approach most of the time, but originally they had a major flaw (google DLL hell), which has all but been eliminated by more recent Windows OSes (Windows XP in particular).</p> |
498,970 | Trim string in JavaScript | <p>How do I remove all whitespace from the start and end of the string?</p> | 498,995 | 20 | 10 | null | 2009-01-31 15:12:23.267 UTC | 241 | 2022-06-13 01:47:20.377 UTC | 2022-06-13 01:47:20.377 UTC | Paul Tomblin | 365,102 | null | 20,951 | null | 1 | 1,354 | javascript|string|trim | 884,580 | <p>All browsers since IE9+ have <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim" rel="noreferrer"><code>trim()</code></a> method for strings:</p>
<pre><code>" \n test \n ".trim(); // returns "test" here
</code></pre>
<p>For those browsers who does not support <code>trim()</code>, you can use this polyfill from <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim" rel="noreferrer">MDN</a>:</p>
<pre><code>if (!String.prototype.trim) {
(function() {
// Make sure we trim BOM and NBSP
var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
String.prototype.trim = function() {
return this.replace(rtrim, '');
};
})();
}
</code></pre>
<hr />
<p>That said, if using <code>jQuery</code>, <code>$.trim(str)</code> is also available and handles undefined/null.</p>
<hr />
<p>See this:</p>
<pre><code>String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};
String.prototype.ltrim=function(){return this.replace(/^\s+/,'');};
String.prototype.rtrim=function(){return this.replace(/\s+$/,'');};
String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');};
</code></pre> |
303,200 | How do I remove/delete a folder that is not empty? | <p>I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: <code>os.remove("/folder_name")</code>. </p>
<p>What is the most effective way of removing/deleting a folder/directory that is not empty?</p> | 303,225 | 22 | 2 | null | 2008-11-19 20:15:38.557 UTC | 134 | 2022-07-14 14:55:07.18 UTC | 2019-09-23 09:35:37.027 UTC | S.Lott | 7,851,470 | Amara | 37,804 | null | 1 | 1,040 | python|file | 884,071 | <pre><code>import shutil
shutil.rmtree('/folder_name')
</code></pre>
<p><a href="http://docs.python.org/library/shutil.html#shutil.rmtree" rel="noreferrer">Standard Library Reference: shutil.rmtree</a>.</p>
<p>By design, <code>rmtree</code> fails on folder trees containing read-only files. If you want the folder to be deleted regardless of whether it contains read-only files, then use</p>
<pre><code>shutil.rmtree('/folder_name', ignore_errors=True)
</code></pre> |
993,358 | Creating a range of dates in Python | <p>I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this?</p>
<pre><code>import datetime
a = datetime.datetime.today()
numdays = 100
dateList = []
for x in range (0, numdays):
dateList.append(a - datetime.timedelta(days = x))
print dateList
</code></pre> | 993,367 | 23 | 0 | null | 2009-06-14 18:03:59.737 UTC | 123 | 2022-05-03 14:48:55.9 UTC | null | null | null | null | 122,792 | null | 1 | 537 | python|datetime|date | 752,210 | <p>Marginally better...</p>
<pre><code>base = datetime.datetime.today()
date_list = [base - datetime.timedelta(days=x) for x in range(numdays)]
</code></pre> |
110,928 | Is there a valid reason for enforcing a maximum width of 80 characters in a code file, this day and age? | <p>Seriously. On a 22" monitor, it only covers maybe a quarter of the screen. I need some ammo to axe down this rule.</p>
<hr>
<p>I'm not saying that there shouldn't be a limit; I'm just saying, 80 characters is very small.</p> | 111,009 | 32 | 5 | 2009-01-26 16:45:43.523 UTC | 2008-09-21 12:43:03.973 UTC | 56 | 2021-08-25 19:36:06.677 UTC | 2017-07-13 17:29:25.933 UTC | Roger Pate | 3,980,929 | TraumaPony | 18,658 | null | 1 | 176 | text-editor|coding-style|policy | 53,206 | <p>I think the practice of keeping code to 80 (or 79) columns was originally created to support people editing code on 80-column dumb terminals or on 80-column printouts. Those requirement have mostly gone away now, but there are still valid reasons to keep the 80 column rule:</p>
<ul>
<li>To avoid wrapping when copying code into email, web pages, and books.</li>
<li>To view multiple source windows side-by-side or using a side-by-side diff viewer.</li>
<li>To improve readability. Narrow code can be read quickly without having to scan your eyes from side to side.</li>
</ul>
<p>I think the last point is the most important. Though displays have grown in size and resolution in the last few years, <strong>eyes haven't</strong>.</p> |
156,767 | What's the difference between an argument and a parameter? | <p>When verbally talking about methods, I'm never sure whether to use the word <em>argument</em> or <em>parameter</em> or something else. Either way the other people know what I mean, but what's correct, and what's the history of the terms?</p>
<p>I'm a C# programmer, but I also wonder whether people use different terms in different languages.</p>
<p>For the record I'm self-taught without a background in Computer Science. (Please don't tell me to read <a href="http://www.amazon.co.uk/Code-Complete-Practical-Handbook-Construction/dp/0735619670/" rel="noreferrer">Code Complete</a> because I'm asking this for the benefit of other people who don't already have a copy of <a href="http://www.stevemcconnell.com/" rel="noreferrer">Steve McConnell</a>'s marvellous book.)</p>
<h3>Summary</h3>
<p>The general consensus seems to be that it's OK to use these terms interchangeably in a team environment. Except perhaps when you're defining the precise terminology; then you can also use "<em>formal</em> argument/parameter" and "<em>actual</em> argument/parameter" to disambiguate.</p> | 156,787 | 37 | 7 | 2008-10-01 09:25:49.453 UTC | 2008-10-01 08:57:20.13 UTC | 362 | 2022-06-29 10:01:03.597 UTC | 2016-05-16 13:34:34.337 UTC | rohancragg | 3,919,155 | rohancragg | 5,351 | null | 1 | 935 | parameters|language-agnostic|arguments|terminology | 361,907 | <p>A parameter is a variable in a method definition. When a method is called, the arguments are the data you pass into the method's parameters.</p>
<pre><code>public void MyMethod(string myParam) { }
...
string myArg1 = "this is my argument";
myClass.MyMethod(myArg1);
</code></pre> |
1,016,896 | How to get screen dimensions as pixels in Android | <p>I created some custom elements, and I want to programmatically place them to the upper right corner (<code>n</code> pixels from the top edge and <code>m</code> pixels from the right edge). Therefore I need to get the screen width and screen height and then set position:</p>
<pre><code>int px = screenWidth - m;
int py = screenHeight - n;
</code></pre>
<p>How do I get <code>screenWidth</code> and <code>screenHeight</code> in the main Activity?</p> | 1,016,941 | 46 | 5 | null | 2009-06-19 08:25:57.347 UTC | 504 | 2022-03-15 08:52:51.367 UTC | 2019-11-12 08:43:09.337 UTC | null | 6,717,610 | null | 22,996 | null | 1 | 1,943 | android|layout|screen|pixel|dimensions | 1,208,208 | <p>If you want the display dimensions in pixels you can use <a href="http://developer.android.com/reference/android/view/Display.html#getSize%28android.graphics.Point%29" rel="noreferrer"><code>getSize</code></a>:</p>
<pre><code>Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
</code></pre>
<p>If you're not in an <code>Activity</code> you can get the default <code>Display</code> via <code>WINDOW_SERVICE</code>:</p>
<pre><code>WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
</code></pre>
<p>If you are in a fragment and want to acomplish this just use Activity.WindowManager (in Xamarin.Android) or getActivity().getWindowManager() (in java).</p>
<p>Before <code>getSize</code> was introduced (in API level 13), you could use the <code>getWidth</code> and <code>getHeight</code> methods that are now deprecated:</p>
<pre><code>Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth(); // deprecated
int height = display.getHeight(); // deprecated
</code></pre>
<p>For the use case, you're describing, however, a margin/padding in the layout seems more appropriate.</p>
<p>Another way is: <a href="http://developer.android.com/reference/android/util/DisplayMetrics.html" rel="noreferrer">DisplayMetrics</a></p>
<blockquote>
<p>A structure describing general information about a display, such as its size, density, and font scaling. To access the DisplayMetrics members, initialize an object like this:</p>
</blockquote>
<pre><code>DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
</code></pre>
<p>We can use <code>widthPixels</code> to get information for:</p>
<blockquote>
<p>"The absolute width of the display in pixels."</p>
</blockquote>
<p><strong>Example:</strong></p>
<pre><code>Log.d("ApplicationTagName", "Display width in px is " + metrics.widthPixels);
</code></pre>
<p><strong>API level 30 update</strong></p>
<pre><code>final WindowMetrics metrics = windowManager.getCurrentWindowMetrics();
// Gets all excluding insets
final WindowInsets windowInsets = metrics.getWindowInsets();
Insets insets = windowInsets.getInsetsIgnoringVisibility(WindowInsets.Type.navigationBars()
| WindowInsets.Type.displayCutout());
int insetsWidth = insets.right + insets.left;
int insetsHeight = insets.top + insets.bottom;
// Legacy size that Display#getSize reports
final Rect bounds = metrics.getBounds();
final Size legacySize = new Size(bounds.width() - insetsWidth,
bounds.height() - insetsHeight);
</code></pre> |
6,516,902 | How to get response using cURL in PHP | <p>I want to have a standalone PHP class where I want to have a function which calls an API through cURL and gets the response. Can someone help me in this? </p>
<p>Thanks. </p> | 6,518,125 | 5 | 2 | null | 2011-06-29 07:05:08.07 UTC | 21 | 2021-08-08 14:41:58.153 UTC | 2012-02-02 11:25:53.81 UTC | null | 225,037 | null | 820,358 | null | 1 | 81 | php|curl | 329,883 | <p>Just use the below piece of code to get the response from restful web service url, I use social mention url.</p>
<pre><code>$response = get_web_page("http://socialmention.com/search?q=iphone+apps&f=json&t=microblogs&lang=fr");
$resArr = array();
$resArr = json_decode($response);
echo "<pre>"; print_r($resArr); echo "</pre>";
function get_web_page($url) {
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_USERAGENT => "test", // name of client
CURLOPT_AUTOREFERER => true, // set referrer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // time-out on connect
CURLOPT_TIMEOUT => 120, // time-out on response
);
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
</code></pre> |
6,647,736 | How to delete parent element using jQuery | <p>I have some list item tags in my jsp. Each list item has some elements inside, including a link ("a" tag) called delete. All that I want is to delete the entire list item when I click the link.</p>
<p>Here is the structure of my code:</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>$("a").click(function(event) {
event.preventDefault();
$(this).parent('.li').remove();
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="191" class="li">
<div class="text">Some text</div>
<h4><a href="URL">Text</a></h4>
<div class="details">
<img src="URL_image.jpg">
<span class="author">Some info</span>
<div class="info"> Text
<div class="msg-modification" display="inline" align="right">
<a name="delete" id="191" href="#">Delete</a>
</div>
</div>
</div>
</li></code></pre>
</div>
</div>
</p>
<p>But this doesn't work. I'm new at jQuery, so I tried some things, like for example:</p>
<pre><code>$(this).remove();
</code></pre>
<p>This works, it deletes the link when clicked.</p>
<pre><code>$("#221").remove();
</code></pre>
<p>This works, it deletes the indicated list item, but it's not "dynamic".</p>
<p>Can someone give me a tip?</p> | 6,647,788 | 7 | 0 | null | 2011-07-11 08:48:05.547 UTC | 23 | 2020-09-22 12:05:39.463 UTC | 2017-12-08 12:12:43.513 UTC | null | 685,273 | null | 685,273 | null | 1 | 78 | javascript|jquery|parent | 198,448 | <p>Simply use the <a href="http://api.jquery.com/closest/"><code>.closest()</code></a> method: <code>$(this).closest('.li').remove();</code><br>
It starts with the current element and then climbs up the chain looking for a matching element and stops as soon as it found one.</p>
<p><a href="http://api.jquery.com/parent/"><code>.parent()</code></a> only accesses the <em>direct</em> parent of the element, i.e. <code>div.msg-modification</code> which does not match <code>.li</code>. So it never reaches the element you are looking for.</p>
<p>Another solution besides <a href="http://api.jquery.com/closest/"><code>.closest()</code></a> (which checks the current element and then climbs up the chain) would be using <a href="http://api.jquery.com/parents/"><code>.parents()</code></a> - however, this would have the caveat that it does not stop as soon as it finds a matching element (and it doesn't check the current element but <em>only</em> parent elements). In your case it doesn't really matter but for what you are trying to do <code>.closest()</code> is the most appropriate method.</p>
<hr>
<h3>Another important thing:</h3>
<p><strong>NEVER</strong> use the same ID for more than one element. It's not allowed and causes very hard-to-debug problems. Remove the <code>id="191"</code> from the link and, if you need to access the ID in the click handler, use <code>$(this).closest('.li').attr('id')</code>. Actually it would be even cleaner if you used <code>data-id="123"</code> and then <code>.data('id')</code> instead of <code>.attr('id')</code> to access it (so your element ID does not need to resemble whatever ID the (database?) row has)</p> |
6,509,159 | How do I search for names with apostrophe in SQL Server? | <pre><code>SELECT *
FROM Header
WHERE (userID LIKE [%'%])
</code></pre> | 6,509,215 | 9 | 0 | null | 2011-06-28 15:42:02.763 UTC | 3 | 2020-05-12 16:11:16.78 UTC | 2011-06-28 15:47:48.27 UTC | null | 570,191 | null | 696,976 | null | 1 | 34 | sql|sql-server|apostrophe | 122,356 | <p>Double them to escape;</p>
<pre><code>SELECT *
FROM Header
WHERE userID LIKE '%''%'
</code></pre> |
6,916,805 | Why does a base64 encoded string have an = sign at the end | <p>I know what <code>base64</code> encoding is and how to calculate <code>base64</code> encoding in C#, however I have seen several times that when I convert a string into base64, there is an <code>=</code> at the end.</p>
<p>A few questions came up:</p>
<ol>
<li>Does a <code>base64</code> string always end with <code>=</code>?</li>
<li>Why does an <code>=</code> get appended at the end?</li>
</ol> | 36,571,117 | 10 | 2 | null | 2011-08-02 18:31:09.523 UTC | 82 | 2022-08-29 16:48:11.197 UTC | 2014-11-05 20:45:49.257 UTC | null | 1,087,335 | null | 449,897 | null | 1 | 432 | encoding|base64 | 248,138 | <p><strong>Q Does a base64 string always end with <code>=</code>?</strong></p>
<p>A: No. (the word <code>usb</code> is base64 encoded into <code>dXNi</code>)</p>
<p><strong>Q Why does an <code>=</code> get appended at the end?</strong></p>
<p>A: As a short answer:<br />
The last character (<code>=</code> sign) is added only as a complement (padding) in the final process of encoding a message with a <em>special</em> number of characters.</p>
<p>You will not have an <code>=</code> sign if your string has a multiple of 3 characters, because <code>Base64</code> encoding takes each <strong>three</strong> bytes (a character=1 byte) and represents them as <strong>four</strong> printable characters in the ASCII standard.</p>
<p><strong>Example</strong>:</p>
<p><strong>(a)</strong> If you want to encode</p>
<p><strong>ABCDEFG</strong> <=> [<code>ABC</code>] [<code>DEF</code>] [<code>G</code>]</p>
<p><code>Base64</code> deals with the first block (producing 4 characters) and the second (as they are complete). But for the third, it will add a double <strong><code>==</code></strong> in the output in order to complete the 4 needed characters. Thus, the result will be <strong>QUJD</strong> <strong>REVG</strong> <strong>Rw==</strong> (without spaces).</p>
<p>[<code>ABC</code>] => <code>QUJD</code></p>
<p>[<code>DEF</code>] => <code>REVG</code></p>
<p>[<code>G</code>] => <code>Rw==</code></p>
<p><strong>(b)</strong> If you want to encode <strong>ABCDEFGH</strong> <=> [<code>ABC</code>] [<code>DEF</code>] [<code>GH</code>]</p>
<p>similarly, it will add one <code>=</code> at the end of the output to get 4 characters.</p>
<p>The result will be <strong>QUJD</strong> <strong>REVG</strong> <strong>R0g=</strong> (without spaces).</p>
<p>[<code>ABC</code>] => <code>QUJD</code></p>
<p>[<code>DEF</code>] => <code>REVG</code></p>
<p>[<code>GH</code>] => <code>R0g=</code></p> |
6,446,007 | C# "No suitable method found to override." -- but there is one | <p>I'm having trouble overriding the method of a parent class in C#. The parent class is setup like so:</p>
<pre><code>public class Base {
public Base(Game1 game)
{
this.game = game;
}
public virtual void Draw()
{
}
}
</code></pre>
<p>...And the child class:</p>
<pre><code>public class Ext : Base {
public Ext(Game1 game) : base(game)
{
}
public override void Draw(SpriteBatch batch)
{
}
}
</code></pre>
<p>I know I've successfully overridden a parent method in the past, and right now I'm probably overlooking something incredibly simple... what is it?</p>
<p><strong>EDIT:</strong> That was actually a typo: in the actual script, Ext does derive from Base. The problem still persists. Thanks for the quick answers, though. :)</p> | 6,446,179 | 12 | 2 | null | 2011-06-22 20:17:23.987 UTC | 3 | 2018-02-13 05:56:51.743 UTC | 2011-06-22 20:47:46.003 UTC | null | 507,164 | null | 507,164 | null | 1 | 39 | c# | 172,217 | <p>Your code as given (after the edit) compiles fine, so something else is wrong that isn't in what you posted. </p>
<p>Some things to check, is everything public? That includes both the class and the method. </p>
<p>Overload with different parameters?</p>
<p>Are you sure that <code>Base</code> is the class you think it is? I.e. is there another class by the same name that it's actually referencing?</p>
<p>Edit:</p>
<p>To answer the question in your comment, you can't override a method with different parameters, nor is there a need to. You can create a new method (with the new parameter) without the <code>override</code> keyword and it will work just fine. </p>
<p>If your intention is to prohibit calling of the base method without the parameter you can mark the method as <code>protected</code> instead of <code>public</code>. That way it can only be called from classes that inherit from <code>Base</code></p> |
6,525,538 | Convert UTC date time to local date time | <p>From the server I get a datetime variable in this format: <code>6/29/2011 4:52:48 PM</code> and it is in UTC time. I want to convert it to the current user’s browser time zone using JavaScript.</p>
<p>How this can be done using JavaScript or jQuery?</p> | 6,525,602 | 37 | 4 | null | 2011-06-29 18:35:04.58 UTC | 131 | 2022-08-10 10:07:48.047 UTC | 2021-02-03 22:52:47.7 UTC | null | 251,034 | null | 20,126 | null | 1 | 482 | javascript|jquery|datetime|timezone|utc | 1,001,151 | <p>Append 'UTC' to the string before converting it to a date in javascript:</p>
<pre><code>var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"
</code></pre> |
45,691,032 | Mongod Service start exits with code 100 | <p><strong>Problem</strong></p>
<p>My mongo service does not start anymore:</p>
<pre><code>root@machine ~ # service mongod start
root@machine ~ # service mongod status
● mongod.service - High-performance, schema-free document-oriented database
Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Tue 2017-08-15 12:03:51 CEST; 2s ago
Docs: https://docs.mongodb.org/manual
Process: 26942 ExecStart=/usr/bin/mongod --config /etc/mongod.conf (code=exited, status=100)
Main PID: 26942 (code=exited, status=100)
Aug 15 12:03:50 machine systemd[1]: Started High-performance, schema-free document-oriented database.
Aug 15 12:03:51 machine systemd[1]: mongod.service: Main process exited, code=exited, status=100/n/a
Aug 15 12:03:51 machine systemd[1]: mongod.service: Unit entered failed state.
Aug 15 12:03:51 machine systemd[1]: mongod.service: Failed with result 'exit-code'.
</code></pre>
<p>Where exit code 100 is blurry defined as:</p>
<blockquote>
<p>Returned by mongod when the process throws an uncaught exception.</p>
</blockquote>
<p><strong>What I did</strong></p>
<p>First, I have installed my mongodb (3.4.7) on Ubuntu 16.04.2 LTS via <a href="https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/" rel="noreferrer">the official guide</a>.</p>
<p>Starting and stopping the service worked fine. So I continued to enable authentication (again via <a href="https://docs.mongodb.com/manual/tutorial/enable-authentication/" rel="noreferrer">the official guide</a>).</p>
<p>Then I added the service to be able <a href="https://askubuntu.com/questions/61503/how-to-start-mongodb-server-on-system-start">to run on server startup</a>.</p>
<pre><code>root@machine ~ # systemctl enable mongod.service
</code></pre>
<p><strong>mongod.conf</strong></p>
<p>I also edited my config file, which is passed a yaml linter:</p>
<pre class="lang-yaml prettyprint-override"><code># Where and how to store data.
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
# engine: mmapv1
# mmapv1:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
# network interfaces
net:
port: 27017
bindIp: 127.0.0.1
#processManagement:
security:
authorization: enabled
</code></pre>
<p>The ownership of the file is</p>
<pre><code>root@machine ~ # ls -la /etc/ | grep mongo
-rw-r--r-- 1 root root 599 Aug 15 11:42 mongod.conf
</code></pre>
<p><strong>DbPath</strong></p>
<p>I know there are issues with the dbpath so this is what <code>/var/lib/mongodb</code> has in terms of ownership:</p>
<pre><code>root@ machine ~ # ls -la /var/lib/ | grep mongo
drwxr-xr-x 4 mongodb mongodb 4096 Aug 15 11:54 mongodb
</code></pre>
<p><strong>Service List</strong></p>
<p>When listing all services via <code>service --status-all</code> there is no entry for any mongo related service.</p>
<p>Somebody has a clue what could cause the issue?</p>
<hr>
<p><strong>UPDATE</strong></p>
<p>As suggested I ran the following command (with a slight modification):</p>
<pre><code>root@machine ~ /usr/bin/mongod --verbose --config /etc/mongod.conf &
[1] 28495
</code></pre>
<p>When I get it right, this is a direct execute of the binary. This allows me now to at least login into mongo shell:</p>
<pre><code>root@machine ~ # mongo
MongoDB shell version v3.4.7
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.7
>
</code></pre>
<p>However, the service status is still remaining failed with exit code 100.</p>
<hr>
<p><strong>UPDATE UPDATE</strong></p>
<p>When typing <code>root@machine ~ # /usr/bin/mongod --verbose</code></p>
<p>I receive the following error:</p>
<pre><code>2017-08-15T13:45:40.973+0200 I CONTROL [initandlisten] MongoDB starting : pid=28642 port=27017 dbpath=/data/db 64-bit host=machine
2017-08-15T13:45:40.973+0200 I CONTROL [initandlisten] db version v3.4.7
2017-08-15T13:45:40.973+0200 I CONTROL [initandlisten] git version: cf38c1b8a0a8dca4a11737581beafef4fe120bcd
2017-08-15T13:45:40.973+0200 I CONTROL [initandlisten] OpenSSL version: OpenSSL 1.0.2g 1 Mar 2016
2017-08-15T13:45:40.973+0200 I CONTROL [initandlisten] allocator: tcmalloc
2017-08-15T13:45:40.973+0200 I CONTROL [initandlisten] modules: none
2017-08-15T13:45:40.973+0200 I CONTROL [initandlisten] build environment:
2017-08-15T13:45:40.973+0200 I CONTROL [initandlisten] distmod: ubuntu1604
2017-08-15T13:45:40.973+0200 I CONTROL [initandlisten] distarch: x86_64
2017-08-15T13:45:40.973+0200 I CONTROL [initandlisten] target_arch: x86_64
2017-08-15T13:45:40.973+0200 I CONTROL [initandlisten] options: { systemLog: { verbosity: 1 } }
2017-08-15T13:45:40.973+0200 D - [initandlisten] User Assertion: 29:Data directory /data/db not found. src/mongo/db/service_context_d.cpp 98
2017-08-15T13:45:40.973+0200 I STORAGE [initandlisten] exception in initAndListen: 29 Data directory /data/db not found., terminating
2017-08-15T13:45:40.973+0200 I NETWORK [initandlisten] shutdown: going to close listening sockets...
2017-08-15T13:45:40.973+0200 I NETWORK [initandlisten] shutdown: going to flush diaglog...
2017-08-15T13:45:40.973+0200 I CONTROL [initandlisten] now exiting
2017-08-15T13:45:40.973+0200 I CONTROL [initandlisten] shutting down with code:100
</code></pre> | 47,605,686 | 7 | 5 | null | 2017-08-15 10:26:38.39 UTC | 11 | 2022-07-11 05:48:00.42 UTC | 2017-08-15 11:48:14.27 UTC | null | 3,098,783 | null | 3,098,783 | null | 1 | 34 | mongodb|service|ubuntu-16.04 | 59,010 | <p>You may still have some problems with the permissions in your data directory. Especially if you have run mongod from the terminal to start with.</p>
<p>I find that the data files are created under root not the mongodb user when you run from the terminal. To fix ..</p>
<pre class="lang-sh prettyprint-override"><code>sudo chown -R mongodb:mongodb /var/lib/mongodb/*
</code></pre> |
41,675,813 | The username you provided is not allowed to use the text-based Tomcat Manager (error 403) when deploying on remote Tomcat8 using Jenkins | <p>I am trying to deploy a WAR on the remote Tomcat (Remote Machine) using Jenkins deploy to container Plugin.
I have done the following configuration in tomcat-users.xml</p>
<pre><code><user username="deployer" password="deployer" roles="manager-gui,manager-script,admin" />
</code></pre>
<p>I have setup the proper username password and port in Jenkins deployer container plugin. The setup is working fine for the local Tomcat.
But for remote Tomcat I keep getting the following error:</p>
<pre><code>Caused by: org.codehaus.cargo.container.tomcat.internal.TomcatManagerException: The username you provided is not allowed to use the text-based Tomcat Manager (error 403) at org.codehaus.cargo.container.tomcat.internal.TomcatManager.invoke(TomcatManager.java:555)
at org.codehaus.cargo.container.tomcat.internal.TomcatManager.list(TomcatManager.java:686)
at org.codehaus.cargo.container.tomcat.internal.TomcatManager.getStatus(TomcatManager.java:699)
at org.codehaus.cargo.container.tomcat.internal.AbstractTomcatManagerDeployer.redeploy(AbstractTomcatManagerDeployer.java:174)
... 16 more
Caused by: java.io.IOException: Server returned HTTP response code: 403 for URL: http://1.203.190.5:8080/manager/text/list
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at org.codehaus.cargo.container.tomcat.internal.TomcatManager.invoke(TomcatManager.java:544) ... 19 more
</code></pre> | 41,691,151 | 8 | 2 | null | 2017-01-16 11:52:08.33 UTC | 5 | 2022-09-20 14:34:57.21 UTC | 2021-12-10 09:09:04.443 UTC | null | 208,273 | null | 2,168,281 | null | 1 | 29 | maven|tomcat|jenkins|web-deployment | 27,501 | <p>This seems to be a Jenkins bug but I got around the problem by setting up following configuration in Tomcat:</p>
<p>Edit the file /webapps/manager/META-INF/context.xml:</p>
<p>Previous:</p>
<pre><code><Context antiResourceLocking="false" privileged="true">
<Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
</Context>
</code></pre>
<p>Change this file to comment the Value:</p>
<pre><code><Context antiResourceLocking="false" privileged="true">
<!--
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
-->
</Context>
</code></pre>
<p>This resolved the issue.</p> |
15,576,548 | How to pass parameters in GET requests with jQuery | <p>How should I be passing query string values in a jQuery Ajax request? I currently do them as follows but I'm sure there is a cleaner way that does not require me to encode manually.</p>
<pre><code>$.ajax({
url: "ajax.aspx?ajaxid=4&UserID=" + UserID + "&EmailAddress=" + encodeURIComponent(EmailAddress),
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
</code></pre>
<p>I’ve seen examples where query string parameters are passed as an array but these examples I've seen don't use the <code>$.ajax()</code> model, instead they go straight to <code>$.get()</code>. For example:</p>
<pre><code>$.get("ajax.aspx", { UserID: UserID , EmailAddress: EmailAddress } );
</code></pre>
<p>I prefer to use the $.ajax() format as it's what I’m used to (no particularly good reason - just a personal preference).</p>
<p><strong>Edit 09/04/2013:</strong></p>
<p>After my question was closed (as "Too Localised") i found a related (identical) question - with 3 upvotes no-less (My bad for not finding it in the first place):</p>
<p><a href="https://stackoverflow.com/questions/3066070/using-jquery-to-make-a-post-how-to-properly-supply-data-parameter">Using jquery to make a POST, how to properly supply 'data' parameter?</a></p>
<p>This answered my question perfectly, I found that doing it this way is much easier to read & I don't need to manually use <code>encodeURIComponent()</code> in the URL or the DATA values (which is what i found unclear in bipen's answer). This is because the <code>data</code> value is encoded automatically via <a href="http://api.jquery.com/jQuery.param/" rel="noreferrer"><code>$.param()</code></a>). Just in case this can be of use to anyone else, this is the example I went with:</p>
<pre><code>$.ajax({
url: "ajax.aspx?ajaxid=4",
data: {
"VarA": VarA,
"VarB": VarB,
"VarC": VarC
},
cache: false,
type: "POST",
success: function(response) {
},
error: function(xhr) {
}
});
</code></pre> | 15,576,581 | 8 | 2 | null | 2013-03-22 17:33:26.9 UTC | 50 | 2018-12-06 15:59:31.573 UTC | 2017-05-23 12:26:27.26 UTC | null | -1 | null | 856,066 | null | 1 | 312 | javascript|jquery|ajax|get | 736,084 | <p>Use data option of ajax. You can send data object to server by <code>data</code> option in ajax and the <code>type</code> which defines how you are sending it (either <code>POST</code> or <code>GET</code>). The default type is <code>GET</code> method</p>
<p>Try this</p>
<pre><code>$.ajax({
url: "ajax.aspx",
type: "get", //send it through get method
data: {
ajaxid: 4,
UserID: UserID,
EmailAddress: EmailAddress
},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
</code></pre>
<p>And you can get the data by (if you are using PHP)</p>
<pre><code> $_GET['ajaxid'] //gives 4
$_GET['UserID'] //gives you the sent userid
</code></pre>
<p>In aspx, I believe it is (might be wrong)</p>
<pre><code> Request.QueryString["ajaxid"].ToString();
</code></pre> |
36,117,583 | Pythonic way to avoid "if x: return x" statements | <p>I have a method that calls 4 other methods in sequence to check for specific conditions, and returns immediately (not checking the following ones) whenever one returns something Truthy.</p>
<pre><code>def check_all_conditions():
x = check_size()
if x:
return x
x = check_color()
if x:
return x
x = check_tone()
if x:
return x
x = check_flavor()
if x:
return x
return None
</code></pre>
<p>This seems like a lot of baggage code. Instead of each 2-line if statement, I'd rather do something like:</p>
<pre><code>x and return x
</code></pre>
<p>But that is invalid Python. Am I missing a simple, elegant solution here? Incidentally, in this situation, those four check methods may be expensive, so I do not want to call them multiple times.</p> | 36,117,603 | 18 | 10 | null | 2016-03-20 18:11:44.38 UTC | 38 | 2021-09-21 13:43:31.6 UTC | 2017-11-29 20:50:32.6 UTC | null | 100,297 | null | 5,754,160 | null | 1 | 224 | python|if-statement | 41,068 | <p>You could use a loop:</p>
<pre><code>conditions = (check_size, check_color, check_tone, check_flavor)
for condition in conditions:
result = condition()
if result:
return result
</code></pre>
<p>This has the added advantage that you can now make the number of conditions variable.</p>
<p>You could use <a href="https://docs.python.org/3/library/functions.html#map" rel="noreferrer"><code>map()</code></a> + <a href="https://docs.python.org/3/library/functions.html#filter" rel="noreferrer"><code>filter()</code></a> (the Python 3 versions, use the <a href="https://docs.python.org/2/library/future_builtins.html" rel="noreferrer"><code>future_builtins</code> versions</a> in Python 2) to get the first such matching value:</p>
<pre><code>try:
# Python 2
from future_builtins import map, filter
except ImportError:
# Python 3
pass
conditions = (check_size, check_color, check_tone, check_flavor)
return next(filter(None, map(lambda f: f(), conditions)), None)
</code></pre>
<p>but if this is more readable is debatable.</p>
<p>Another option is to use a generator expression:</p>
<pre><code>conditions = (check_size, check_color, check_tone, check_flavor)
checks = (condition() for condition in conditions)
return next((check for check in checks if check), None)
</code></pre> |
10,858,990 | Why use JUnit for testing? | <p>Maybe my question is a newbie one, but I can not really understand the circumstances under which I would use <a href="/questions/tagged/junit" class="post-tag" title="show questions tagged 'junit'" rel="tag">junit</a>?</p>
<p>Whether I write simple applications or larger ones I test them with the <code>System.out</code> statements and it seams quite easy to me. </p>
<p>Why create test-classes with JUnit, unnecessary folders in the project if we still have to call the same methods, check what they return and we then have an overhead of annotating everything? </p>
<p>Why not write a class and test it at once with <code>System.out</code> but not create Test-classes?</p>
<p>PS. I have never worked on large projects I am just learning. </p>
<p>So what is the purpose?</p> | 10,859,000 | 11 | 3 | null | 2012-06-02 00:54:05.9 UTC | 45 | 2019-03-12 15:18:37.263 UTC | 2012-06-04 19:03:19.163 UTC | null | 411,902 | null | 1,005,184 | null | 1 | 132 | java|unit-testing|junit|tdd | 70,888 | <p>That's not testing, that's "looking manually at output" (known in the biz as LMAO). More formally it's known as "looking manually for abnormal output" (LMFAO). <sup>(See note below)</sup></p>
<p>Any time you change code, you must run the app and LMFAO for all code affected by those changes. Even in small projects, this is problematic and error-prone.</p>
<p>Now scale up to 50k, 250k, 1m LOC or more, and LMFAO any time you make a code change. Not only is it unpleasant, it's impossible: you've scaled up the combinations of inputs, outputs, flags, conditions, and it's difficult to exercise all possible branches.</p>
<p>Worse, LMFAO might mean visiting pages upon pages of web app, running reports, poring over millions of log lines across dozens of files and machines, reading generated and delivered emails, checking text messages, checking the path of a robot, filling a bottle of soda, aggregating data from a hundred web services, checking the audit trail of a financial transaction... you get the idea. "Output" doesn't mean a few lines of text, "output" means aggregate system behavior.</p>
<p><img src="https://willjessop4.files.wordpress.com/2010/01/sad_panda.jpg" width="200"/></p>
<p>Lastly, unit and behavior tests <em>define</em> system behavior. Tests can be run by a continuous integration server and checked for correctness. Sure, so can <code>System.out</code>s, but the CI server isn't going to know if one of them is wrong–and if it does, they're unit tests, and you might as well use a framework.</p>
<p>No matter how good we think we are, humans aren't good unit test frameworks or CI servers.</p>
<hr>
<p>Note: LMAO <em>is</em> testing, but in a <em>very</em> limited sense. It isn't repeatable in any meaningful way across an entire project or as part of a process. It's akin to developing incrementally in a REPL, but never formalizing those incremental tests.</p> |
25,408,158 | Best way to move messages off DLQ in Amazon SQS? | <p>What is the best practice to move messages from a dead letter queue back to the original queue in Amazon SQS?</p>
<p>Would it be</p>
<ol>
<li>Get message from DLQ</li>
<li>Write message to queue</li>
<li>Delete message from DLQ</li>
</ol>
<p>Or is there a simpler way? </p>
<p>Also, will AWS eventually have a tool in the console to move messages off the DLQ?</p> | 70,207,838 | 12 | 5 | null | 2014-08-20 15:03:17.4 UTC | 27 | 2022-04-25 06:52:40.14 UTC | 2014-08-28 16:17:39.907 UTC | null | 55,900 | null | 55,900 | null | 1 | 130 | amazon-web-services|amazon-sqs | 87,676 | <p>On <a href="https://aws.amazon.com/about-aws/whats-new/2021/12/amazon-sqs-dead-letter-queue-management-experience-queues/" rel="noreferrer">Dec 1 2021</a> AWS released the ability to redrive messages from a DLQ back to the source queue(or custom queue).</p>
<blockquote>
<p>With dead-letter queue redrive to source queue, you can simplify and enhance your error-handling workflows for <strong>standard queues</strong>.</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/GQ20y.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/GQ20y.jpg" alt="DLQ redrive" /></a></p>
<p>Source:</p>
<p><a href="https://i.stack.imgur.com/GQ20y.jpg" rel="noreferrer">Introducing Amazon Simple Queue Service dead-letter queue redrive to source queues
</a></p> |
25,014,110 | System.Net.WebException: The remote name could not be resolved: | <p>I am testing an endpoint that I am experiencing some issues with.</p>
<p>I am simply using <code>HttpClient</code> in a loop that performs a request each hour.</p>
<pre><code>var httpClient = new HttpClient();
var message = httpClient.GetAsync(url).Result;
Console.WriteLine(message.StatusCode);
</code></pre>
<p>Once in a while I am getting this exception:</p>
<blockquote>
<p>System.Net.Http.HttpRequestException: An error occurred while sending
the request. ---> System.Net.WebException: The remote name could not
be resolved: 'xxx'</p>
</blockquote>
<p>The experience is that right after the exception, the URL can be accessed. In a browser you simply refresh the page and all is good.</p>
<p>I still haven't got any reports from users experiencing it so I am wondering if it's just a local issue here but could use a little information to help diagnose.</p>
<p>Is there a way to check if <em>The remote name could not be resolved</em> is caused by an DNS issue or by a web server issue from the exceptions? Can I get more information out of <code>HttpCLient</code> or do I need more advanced diagnostic tools?</p> | 25,014,282 | 4 | 6 | null | 2014-07-29 11:23:03.953 UTC | 13 | 2022-09-22 16:35:18.53 UTC | 2016-11-01 22:24:25.157 UTC | null | 66,173 | null | 871,985 | null | 1 | 44 | c#|.net|system.net.webexception | 188,026 | <p>It's <em>probably</em> caused by a local network connectivity issue (but also a DNS error is possible). Unfortunately <code>HResult</code> is generic, however you can determine the exact issue catching <code>HttpRequestException</code> and then inspecting <code>InnerException</code>: if it's a <code>WebException</code> then you can check the <code>WebException.Status</code> property, for example <code>WebExceptionStatus.NameResolutionFailure</code> should indicate a DNS resolution problem.</p>
<hr>
<p>It may happen, there isn't much you can do.</p>
<p>What I'd suggest to always wrap that (network related) code in a loop with a <code>try</code>/<code>catch</code> block (as also suggested <a href="https://stackoverflow.com/a/24041546/1207195">here</a> for other <em>fallible</em> operations). Handle known exceptions, wait a little (say 1000 msec) and try again (for say 3 times). Only if failed all times then you can quit/report an error to your users. Very raw example like this:</p>
<pre><code>private const int NumberOfRetries = 3;
private const int DelayOnRetry = 1000;
public static async Task<HttpResponseMessage> GetFromUrlAsync(string url) {
using (var client = new HttpClient()) {
for (int i=1; i <= NumberOfRetries; ++i) {
try {
return await client.GetAsync(url);
}
catch (Exception e) when (i < NumberOfRetries) {
await Task.Delay(DelayOnRetry);
}
}
}
}
</code></pre> |
46,580,522 | composer install from two composer.json file | <p>I have multiple <code>composer.json</code> having multiple seperate dependency and want to install all the dependency in the both <code>composer.json</code> using single <code>composer install</code> command. </p>
<p>The location is like this:</p>
<pre><code>| - composer.json
| - Custom
| - Package1
| - composer.json
</code></pre>
<p>First <strong>composer.json</strong></p>
<pre><code>{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"require": {
"php": ">=5.6.4",
"barryvdh/laravel-debugbar": "^2.3",
"laravel/framework": "5.4.*",
"laravel/tinker": "~1.0",
"laravelcollective/html": "^5.4.0"
},
"require-dev": {
"fzaninotto/faker": "~1.4",
"mockery/mockery": "0.9.*",
"phpunit/phpunit": "~5.7",
"symfony/css-selector": "3.1.*",
"symfony/dom-crawler": "3.1.*"
},
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/",
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"post-root-package-install": [
"php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"php artisan key:generate"
],
"post-install-cmd": [
"Illuminate\\Foundation\\ComposerScripts::postInstall",
"php artisan optimize"
],
"post-update-cmd": [
"Illuminate\\Foundation\\ComposerScripts::postUpdate",
"php artisan optimize"
]
},
"config": {
"preferred-install": "dist",
"sort-packages": true,
"optimize-autoloader": true
}
}
</code></pre>
<p>Second <strong>composer.json</strong> inside Package1 directory</p>
<pre><code>{
"name": "custom/package1",
"description": "",
"require": {
"php": ">=5.6",
"composer/installers": "~1.0",
"lavary/laravel-menu": "1.7.1"
},
"autoload": {
"psr-4": {
"Custom\\Package1\\": ""
}
}
}
</code></pre>
<p>I want to install the <code>lavary/laravel-menu</code> inside the <code>Package1</code> to the main vendor directory where all the default packages are installed.</p>
<pre><code>|- vendor //<==want here
| - composer.json
| - Custom
| - Package1
| - vendor //<== not here
| - composer.json
</code></pre>
<p>I have tested this solution:</p>
<blockquote>
<p><a href="https://stackoverflow.com/a/27735674">https://stackoverflow.com/a/27735674</a></p>
</blockquote>
<p>like this:</p>
<pre><code>{
"config": {
"vendor-dir": "../../vendor/"
}
}
</code></pre>
<p>This installs the packages but we need to get into the second composer.json instead of main composer.json and removes the installed package from first composer.json.</p>
<p><strong>How can i install the all the dependency from the main composer.json without getting into the second or multiple composer.json in single vendor directory?</strong></p> | 46,584,076 | 2 | 13 | null | 2017-10-05 07:50:50.657 UTC | 8 | 2022-08-22 10:45:11.21 UTC | null | null | null | null | 3,887,342 | null | 1 | 12 | php|laravel-5|composer-php|vendor | 13,148 | <p>After some research and suggestion i figured out there are multiple ways to achieve this solution. </p>
<ol>
<li>Using external package to maintain the dependency.</li>
</ol>
<p>Thanks to <a href="https://stackoverflow.com/users/1941241/rickdenhaan"><strong>rickdenhaan</strong></a> to let me know about </p>
<p><strong>Composer Merge Plugin</strong></p>
<blockquote>
<p><a href="https://github.com/wikimedia/composer-merge-plugin" rel="noreferrer">https://github.com/wikimedia/composer-merge-plugin</a></p>
</blockquote>
<p>First we need to require this package:</p>
<pre><code>composer require wikimedia/composer-merge-plugin
</code></pre>
<p>Then my <strong>composer.json</strong> becomes like this:</p>
<pre><code>{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"require": {
"php": ">=5.6.4",
"barryvdh/laravel-debugbar": "^2.3",
"laravel/framework": "5.4.*",
"laravel/tinker": "~1.0",
"wikimedia/composer-merge-plugin": "^1.4"
},
"require-dev": {
"fzaninotto/faker": "~1.4",
"mockery/mockery": "0.9.*",
"phpunit/phpunit": "~5.7",
"symfony/css-selector": "3.1.*",
"symfony/dom-crawler": "3.1.*"
},
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"post-root-package-install": [
"php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"php artisan key:generate"
],
"post-install-cmd": [
"Illuminate\\Foundation\\ComposerScripts::postInstall",
"php artisan optimize"
],
"post-update-cmd": [
"Illuminate\\Foundation\\ComposerScripts::postUpdate",
"php artisan optimize"
]
},
"config": {
"preferred-install": "dist",
"sort-packages": true,
"optimize-autoloader": true
},
"extra": {
"merge-plugin": {
"include": [
"Custom/*/composer.json"
],
"recurse": true,
"replace": false,
"ignore-duplicates": true,
"merge-dev": true,
"merge-extra": false,
"merge-extra-deep": false,
"merge-scripts": true
}
}
}
</code></pre>
<p>Now,
run </p>
<pre><code>composer install
</code></pre>
<p>or</p>
<pre><code> composer update
</code></pre>
<p>Then your <code>composer.json</code> in each of the directory will be merged into default <code>vendor</code> directory.</p>
<ol start="2">
<li><p>Next solution could be to publish the package to the packagist and require in the composer.json and during composer install all the dependency will be installed.</p>
<p>Like the <a href="https://github.com/AsgardCms/Platform/blob/3.0/composer.json#L20" rel="noreferrer"><strong>Asgardcms</strong></a> has done.</p></li>
<li><p>Adding the private repository to the composer.json.</p>
<blockquote>
<p><a href="https://stackoverflow.com/questions/28625311/configuring-composer-json-with-private-bitbucket-mercurial-repository/37180271#37180271">Configuring composer.json with private bitbucket mercurial repository</a></p>
</blockquote></li>
<li><p>This option needs to add the composer.json of metapackage to the main composer.json file.</p></li>
</ol>
<p>(I am not sure about the option but thanks to <a href="https://stackoverflow.com/users/3596137/jparkinson1991"><strong>JParkinson1991</strong></a> Someone who knows this solution could add explaination on this option. Adding just to let someone know this solution exists.)</p>
<p>Here is the example solution:</p>
<blockquote>
<p><a href="https://stackoverflow.com/questions/19582390/php-composer-how-do-i-combine-composer-json-files/19582417#19582417">PHP & Composer, how do I combine composer.json files</a></p>
</blockquote>
<p>In this the first solution suits my case. Hope this helps someone who spent alot of time searching.</p> |
40,817,362 | Sending JSON in POST request with Retrofit2 | <p>I'm using Retrofit to integrate my Web services and I do not understand how to send a JSON object to the server using a POST request. I'm currently stuck, here is my code:</p>
<h2>Activity:-</h2>
<pre><code>@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit retrofit = new Retrofit.Builder().baseUrl(url).
addConverterFactory(GsonConverterFactory.create()).build();
PostInterface service = retrofit.create(PostInterface.class);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("email", "[email protected]");
jsonObject.put("password", "1234");
} catch (JSONException e) {
e.printStackTrace();
}
final String result = jsonObject.toString();
}
</code></pre>
<h2>PostInterface:-</h2>
<pre><code>public interface PostInterface {
@POST("User/DoctorLogin")
Call<String> getStringScalar(@Body String body);
}
</code></pre>
<h2>Request JSON:-</h2>
<pre><code>{
"email":"[email protected]",
"password":"1234"
}
</code></pre>
<h2>Response JSON:-</h2>
<pre><code>{
"error": false,
"message": "User Login Successfully",
"doctorid": 42,
"active": true
}
</code></pre> | 40,817,747 | 4 | 14 | null | 2016-11-26 10:29:00.677 UTC | 4 | 2019-12-06 10:50:22.92 UTC | 2016-11-26 13:23:22.067 UTC | null | 812,680 | user5102362 | null | null | 1 | 18 | android|json|retrofit2 | 62,114 | <p>Use these in gradle </p>
<pre><code>compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'
</code></pre>
<blockquote>
<p>Use these two POJO class ........</p>
<p>LoginData.class</p>
</blockquote>
<pre><code>public class LoginData {
private String email;
private String password;
public LoginData(String email, String password) {
this.email = email;
this.password = password;
}
/**
*
* @return
* The email
*/
public String getEmail() {
return email;
}
/**
*
* @param email
* The email
*/
public void setEmail(String email) {
this.email = email;
}
/**
*
* @return
* The password
*/
public String getPassword() {
return password;
}
/**
*
* @param password
* The password
*/
public void setPassword(String password) {
this.password = password;
}
}
</code></pre>
<blockquote>
<p>LoginResult.class</p>
</blockquote>
<pre><code>public class LoginResult {
private Boolean error;
private String message;
private Integer doctorid;
private Boolean active;
/**
*
* @return
* The error
*/
public Boolean getError() {
return error;
}
/**
*
* @param error
* The error
*/
public void setError(Boolean error) {
this.error = error;
}
/**
*
* @return
* The message
*/
public String getMessage() {
return message;
}
/**
*
* @param message
* The message
*/
public void setMessage(String message) {
this.message = message;
}
/**
*
* @return
* The doctorid
*/
public Integer getDoctorid() {
return doctorid;
}
/**
*
* @param doctorid
* The doctorid
*/
public void setDoctorid(Integer doctorid) {
this.doctorid = doctorid;
}
/**
*
* @return
* The active
*/
public Boolean getActive() {
return active;
}
/**
*
* @param active
* The active
*/
public void setActive(Boolean active) {
this.active = active;
}
}
</code></pre>
<blockquote>
<p>Use API like this</p>
</blockquote>
<pre><code>public interface RetrofitInterface {
@POST("User/DoctorLogin")
Call<LoginResult> getStringScalar(@Body LoginData body);
}
</code></pre>
<blockquote>
<p>use call like this ....</p>
</blockquote>
<pre><code>Retrofit retrofit = new Retrofit.Builder()
.baseUrl("Your domain URL here")
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitInterface service = retrofit.create(RetrofitInterface .class);
Call<LoginResult> call=service.getStringScalar(new LoginData(email,password));
call.enqueue(new Callback<LoginResult>() {
@Override
public void onResponse(Call<LoginResult> call, Response<LoginResult> response) {
//response.body() have your LoginResult fields and methods (example you have to access error then try like this response.body().getError() )
}
@Override
public void onFailure(Call<LoginResult> call, Throwable t) {
//for getting error in network put here Toast, so get the error on network
}
});
</code></pre>
<p><strong>EDIT:-</strong> </p>
<blockquote>
<p>put this inside the <code>success()</code> ....</p>
</blockquote>
<pre><code>if(response.body().getError()){
Toast.makeText(getBaseContext(),response.body().getMessage(),Toast.LENGTH_SHORT).show();
}else {
//response.body() have your LoginResult fields and methods (example you have to access error then try like this response.body().getError() )
String msg = response.body().getMessage();
int docId = response.body().getDoctorid();
boolean error = response.body().getError();
boolean activie = response.body().getActive()();
}
</code></pre>
<p>Note :- Always use POJO classes , it remove the JSON data parsing in the retrofit .</p> |
13,688,159 | How to override maximum 32x32 mouse size in Windows like this program can | <p>I'd like for my program to be able to override the maximum imposed mouse size of 32x32 much like the program in the picture attached does, the cursor pictured is 72x72. This is a capture from <code>ProcMon</code> showing what's going on when the cursors change. </p>
<p>However, if I try to change the registry values for the cursor files myself and then push the changes using </p>
<p><code>SystemParametersInfo(SPI.SPI_SETCURSORS, 0, IntPtr.Zero, SPIF.SPIF_SENDCHANGE);</code></p>
<p>then the cursor will change, but it's still limited to the 32x32 maximum size. How was this program able to get around that restriction? Also, the cursors remain after the program ends, so it can't be something it's doing while running, but must override a setting somewhere.</p>
<p><img src="https://i.stack.imgur.com/atGOX.png" alt="enter image description here"></p>
<p>Thanks for your help, I haven't been able to find ANYTHING like this on the net, so I don't even know if anyone will have the answer.</p>
<p>EDIT: I see some access to a file called <code>C:\Windows\SysWOW64\Imageres.dll</code>. They're only reads, but maybe these cursors are stored in here, or they modified this file somehow. But I figured it might get someone with more experience than myself off on the right track. </p>
<p>EDIT 2: I believe the sizes are dictated by the SM_CXCURSOR and SM_CYCURSOR variables. If I could find a way to set these, I might be in business. Going to write a quick program to get me those values on the PC with the program running and huge mouse cursor and see what it returns...</p>
<p>EDIT 3: No luck; the PC with the huge cursor returns 32x32 for it's SM_CXCURSOR and SM_CYCURSOR.</p> | 20,151,176 | 4 | 11 | null | 2012-12-03 17:03:57.963 UTC | 8 | 2017-09-12 07:22:33.563 UTC | 2012-12-03 18:23:49.117 UTC | null | 1,233,949 | null | 1,233,949 | null | 1 | 18 | c#|registry|mouse|accessibility | 12,912 | <p>Using <code>SetSystemCursor</code> it is possible to set a cursor to an image of much larger size than the standard cursor.</p>
<p>Here is a class I have for resizing the system cursors:</p>
<pre><code>using System;
using System.Drawing;
using System.Reflection;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication1
{
class SystemCursors
{
[DllImport("user32.dll")]
static extern bool SetSystemCursor(IntPtr hcur, uint id);
enum CursorShift
{
Centered,
LowerRight,
}
public static void SetSystemCursorsSize(int newSize)
{
ResizeCursor(System.Windows.Forms.Cursors.AppStarting, newSize, CursorShift.LowerRight);
ResizeCursor(System.Windows.Forms.Cursors.Arrow, newSize, CursorShift.LowerRight);
ResizeCursor(System.Windows.Forms.Cursors.Cross, newSize, CursorShift.Centered);
ResizeCursor(System.Windows.Forms.Cursors.Hand, newSize, CursorShift.LowerRight);
ResizeCursor(System.Windows.Forms.Cursors.Help, newSize, CursorShift.LowerRight);
ResizeCursor(System.Windows.Forms.Cursors.HSplit, newSize, CursorShift.Centered);
ResizeCursor(System.Windows.Forms.Cursors.IBeam, newSize, CursorShift.Centered);
ResizeCursor(System.Windows.Forms.Cursors.No, newSize, CursorShift.LowerRight);
ResizeCursor(System.Windows.Forms.Cursors.NoMove2D, newSize, CursorShift.LowerRight);
ResizeCursor(System.Windows.Forms.Cursors.NoMoveHoriz, newSize, CursorShift.LowerRight);
ResizeCursor(System.Windows.Forms.Cursors.NoMoveVert, newSize, CursorShift.LowerRight);
ResizeCursor(System.Windows.Forms.Cursors.PanEast, newSize, CursorShift.Centered);
ResizeCursor(System.Windows.Forms.Cursors.PanNE, newSize, CursorShift.Centered);
ResizeCursor(System.Windows.Forms.Cursors.PanNorth, newSize, CursorShift.Centered);
ResizeCursor(System.Windows.Forms.Cursors.PanNW, newSize, CursorShift.Centered);
ResizeCursor(System.Windows.Forms.Cursors.PanSE, newSize, CursorShift.Centered);
ResizeCursor(System.Windows.Forms.Cursors.PanSouth, newSize, CursorShift.Centered);
ResizeCursor(System.Windows.Forms.Cursors.PanSW, newSize, CursorShift.Centered);
ResizeCursor(System.Windows.Forms.Cursors.PanWest, newSize, CursorShift.Centered);
ResizeCursor(System.Windows.Forms.Cursors.SizeAll, newSize, CursorShift.Centered);
ResizeCursor(System.Windows.Forms.Cursors.SizeNESW, newSize, CursorShift.Centered);
ResizeCursor(System.Windows.Forms.Cursors.SizeNS, newSize, CursorShift.Centered);
ResizeCursor(System.Windows.Forms.Cursors.SizeNWSE, newSize, CursorShift.Centered);
ResizeCursor(System.Windows.Forms.Cursors.SizeWE, newSize, CursorShift.Centered);
ResizeCursor(System.Windows.Forms.Cursors.UpArrow, newSize, CursorShift.Centered);
ResizeCursor(System.Windows.Forms.Cursors.VSplit, newSize, CursorShift.Centered);
ResizeCursor(System.Windows.Forms.Cursors.WaitCursor, newSize, CursorShift.LowerRight);
}
private static void ResizeCursor(System.Windows.Forms.Cursor cursor,
int newSize, CursorShift cursorShift)
{
Bitmap cursorImage = GetSystemCursorBitmap(cursor);
cursorImage = ResizeCursorBitmap(cursorImage, new Size(newSize, newSize), cursorShift);
SetCursor(cursorImage, getResourceId(cursor));
}
public static Bitmap GetSystemCursorBitmap(System.Windows.Forms.Cursor cursor)
{
Bitmap bitmap = new Bitmap(
cursor.Size.Width, cursor.Size.Height,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics graphics = Graphics.FromImage(bitmap);
cursor.Draw(graphics,
new Rectangle(new Point(0, 0), cursor.Size));
bitmap = Crop(bitmap);
return bitmap;
}
private static Bitmap Crop(Bitmap bmp)
{
//code from http://stackoverflow.com/a/10392379/935052
int w = bmp.Width;
int h = bmp.Height;
Func<int, bool> allWhiteRow = row =>
{
for (int i = 0; i < w; ++i)
if (bmp.GetPixel(i, row).A != 0)
return false;
return true;
};
Func<int, bool> allWhiteColumn = col =>
{
for (int i = 0; i < h; ++i)
if (bmp.GetPixel(col, i).A != 0)
return false;
return true;
};
int topmost = 0;
for (int row = 0; row < h; ++row)
{
if (allWhiteRow(row))
topmost = row;
else break;
}
int bottommost = 0;
for (int row = h - 1; row >= 0; --row)
{
if (allWhiteRow(row))
bottommost = row;
else break;
}
int leftmost = 0, rightmost = 0;
for (int col = 0; col < w; ++col)
{
if (allWhiteColumn(col))
leftmost = col;
else
break;
}
for (int col = w - 1; col >= 0; --col)
{
if (allWhiteColumn(col))
rightmost = col;
else
break;
}
if (rightmost == 0) rightmost = w; // As reached left
if (bottommost == 0) bottommost = h; // As reached top.
int croppedWidth = rightmost - leftmost;
int croppedHeight = bottommost - topmost;
if (croppedWidth == 0) // No border on left or right
{
leftmost = 0;
croppedWidth = w;
}
if (croppedHeight == 0) // No border on top or bottom
{
topmost = 0;
croppedHeight = h;
}
try
{
var target = new Bitmap(croppedWidth, croppedHeight);
using (Graphics g = Graphics.FromImage(target))
{
g.DrawImage(bmp,
new RectangleF(0, 0, croppedWidth, croppedHeight),
new RectangleF(leftmost, topmost, croppedWidth, croppedHeight),
GraphicsUnit.Pixel);
}
return target;
}
catch (Exception ex)
{
throw new Exception(
string.Format("Values are topmost={0} btm={1} left={2} right={3} croppedWidth={4} croppedHeight={5}", topmost, bottommost, leftmost, rightmost, croppedWidth, croppedHeight),
ex);
}
}
private static Bitmap ResizeCursorBitmap(Bitmap bitmap, Size size, CursorShift cursorShift)
{
if (size.Width > 32)
{
//shifting must occur
Bitmap intermediateBitmap = new Bitmap(64, 64);
Graphics intermediateGraphics = Graphics.FromImage(intermediateBitmap);
if (cursorShift == CursorShift.LowerRight)
//place the mouse cursor in the lower right hand quadrant of the bitmap
intermediateGraphics.DrawImage(bitmap,
intermediateBitmap.Width / 2, intermediateBitmap.Height / 2);
else if (cursorShift == CursorShift.Centered)
intermediateGraphics.DrawImage(bitmap,
intermediateBitmap.Width / 2 - bitmap.Width / 2,
intermediateBitmap.Height / 2 - bitmap.Height / 2);
//now we have a shifted bitmap; use it to draw the resized cursor
//Bitmap finalBitmap = new Bitmap(intermediateBitmap, size); //normal quality
Bitmap finalBitmap = new Bitmap(size.Width, size.Height);
Graphics finalGraphics = Graphics.FromImage(finalBitmap);
finalGraphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
finalGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
finalGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
finalGraphics.DrawImage(intermediateBitmap, 0, 0, finalBitmap.Width, finalBitmap.Height);
return finalBitmap;
}
else
{
Bitmap newBitmap = new Bitmap(bitmap, size);
return newBitmap;
}
}
private static uint getResourceId(System.Windows.Forms.Cursor cursor)
{
FieldInfo fi = typeof(System.Windows.Forms.Cursor).GetField(
"resourceId", BindingFlags.NonPublic | BindingFlags.Instance);
object obj = fi.GetValue(cursor);
return Convert.ToUInt32((int)obj);
}
private static void SetCursor(Bitmap bitmap, uint whichCursor)
{
IntPtr ptr = bitmap.GetHicon();
bool retval = SetSystemCursor(ptr, whichCursor);
}
}
}
</code></pre>
<p>It works by getting the current system cursor as provided in <code>System.Windows.Forms.Cursors</code> and making an image from it with <code>Cursor.Draw</code>. The image is then resized to the desired size. This requires shifting the cursor image, either to the lower right hand corner (like for arrow pointers) or centering the cursor image inside the larger image (like for Cross and IBeam).</p>
<p>You can use your own image for the cursor if desired, bypassing all the resizing code. Just supply the Bitmap to <code>SetCursor</code>.</p>
<p>Once the new cursor image is ready, the last piece of data needed is the ID of the cursor we are trying to replace. Each <code>System.Windows.Forms.Cursor</code> does contain this information, but in a private variable, so reflection is used to get the value. If you prefer to avoid reflection, you could build a table of these values instead. See <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms648395%28v=vs.85%29.aspx" rel="noreferrer">MSDN SetSystemCursor</a> for a list of values.</p>
<p>To use the class just call</p>
<pre><code>SystemCursors.SetSystemCursorsSize(128);
</code></pre> |
13,697,607 | MySQL LEFT JOIN using MAX & GROUP BY on joined table? | <p>I've got two tables (members and activities) and I'm trying to query the members with the latest activity for each member. I've got it working with two queries (one to get the members and a second with a max(id) and group by(member) on the activities) and some code to merge the data. I'm SURE it can be done with a single query, but I can't quite work it out. Any ideas?</p>
<p>members table</p>
<pre><code>id, name
1, Shawn
2, bob
3, tom
</code></pre>
<p>activities table</p>
<pre><code>id, member_id, code, timestamp, description
1, 1, 123, 15000, baked a cake
2, 1, 456, 20000, ate dinner
3, 2, 789, 21000, drove home
4, 1, 012, 22000, ate dessert
</code></pre>
<p>desired result:</p>
<pre><code>id, name, activity_code, activity_timestamp, activity_description
1, shawn, 012, 22000, ate dessert
2, bob, 789, 21000, drove home
3, tom, null, null, null
</code></pre> | 13,698,334 | 3 | 0 | null | 2012-12-04 06:55:49.68 UTC | 14 | 2012-12-04 15:15:33.073 UTC | null | null | null | null | 181,953 | null | 1 | 23 | mysql | 27,542 | <p>The "latest per group" problem is <em>extremely</em> common in SQL. There are countless examples of solutions to this very problem on this site alone.</p>
<p>If your timestamps are uniqe per member activity:</p>
<pre><code>SELECT
m.id,
m.name,
a.code activity_code,
a.timestamp activity_timestamp,
a.description activity_description
FROM
members m
INNER JOIN activities a ON a.member_id = m.id
WHERE
a.timestamp = (SELECT MAX(timestamp) FROM activities WHERE member_id = m.id)
</code></pre>
<p>alternatively, if your activity ID is increasing monotonically with time:</p>
<pre><code> ...
WHERE
a.id = (SELECT MAX(id) FROM activities WHERE member_id = m.id)
</code></pre>
<p>You don't need to group. But the query will benefit from an index on <code>activities</code> over <code>(member_id, timestamp)</code> or <code>(member_id, id)</code>, respectively.</p>
<hr>
<p>EDIT</p>
<p>To show any members who have not logged an activity, use a left join like this.</p>
<pre><code>SELECT
m.id,
m.name,
a.code activity_code,
a.timestamp activity_timestamp,
a.description activity_description
FROM
members m
LEFT JOIN activities a ON
a.member_id = m.id
AND a.timestamp = (SELECT MAX(timestamp) FROM activities WHERE member_id = m.id)
</code></pre>
<p>Note that there is no <code>WHERE</code> clause. Semantically, WHERE is applied <em>after</em> the joins are done. So a WHERE clause would remove the rows that the LEFT JOIN added, effectively giving in the same result as the original INNER JOIN.</p>
<p>But if you apply the additional predicate right in the join condition, the LEFT JOIN will work as expected.</p> |
20,379,027 | JavaScript reduce the size and quality of image with based64 encoded code | <p>I have the based64 encoded code of an image. Now I want to reduce the size and quality of the image. How can I do this in JavaScript or jQuery?</p>
<p><strong>Resolve here is the working code : Index.php</strong>
Here is javascript code which worked form me </p>
<pre><code><html>
<head>
<title>JavaScript Image Resize</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style>
body {
font-size: 16px;
font-family: Arial;
}
</style>
<script type="text/javascript">
function _resize(img, maxWidth, maxHeight)
{
var ratio = 1;
var canvas = document.createElement("canvas");
canvas.style.display="none";
document.body.appendChild(canvas);
var canvasCopy = document.createElement("canvas");
canvasCopy.style.display="none";
document.body.appendChild(canvasCopy);
var ctx = canvas.getContext("2d");
var copyContext = canvasCopy.getContext("2d");
if(img.width > maxWidth)
ratio = maxWidth / img.width;
else if(img.height > maxHeight)
ratio = maxHeight / img.height;
canvasCopy.width = img.width;
canvasCopy.height = img.height;
try {
copyContext.drawImage(img, 0, 0);
} catch (e) {
document.getElementById('loader').style.display="none";
alert("There was a problem - please reupload your image");
return false;
}
canvas.width = img.width * ratio;
canvas.height = img.height * ratio;
// the line to change
//ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);
// the method signature you are using is for slicing
ctx.drawImage(canvasCopy, 0, 0, canvas.width, canvas.height);
var dataURL = canvas.toDataURL("image/png");
document.body.removeChild(canvas);
document.body.removeChild(canvasCopy);
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
};
function resize() {
var photo = document.getElementById("photo");
if(photo.files!=undefined){
var loader = document.getElementById("loader");
loader.style.display = "inline";
var file = photo.files[0];
document.getElementById("orig").value = file.fileSize;
var preview = document.getElementById("preview");
var r = new FileReader();
r.onload = (function(previewImage) {
return function(e) {
var maxx = 500;
var maxy = 500;
previewImage.src = e.target.result;
var k = _resize(previewImage, maxx, maxy);
if(k!=false) {
document.getElementById('base64').value= k;
document.getElementById('upload').submit();
} else {
alert('problem - please attempt to upload again');
}
};
})(preview);
r.readAsDataURL(file);
} else {
alert("Seems your browser doesn't support resizing");
}
return false;
}
</script>
</head>
<body>
<div align="center">
<h2>Image Resize Demo</h2>
<input type="file" name="photo" id="photo">
<br>
<br>
<input type="button" onClick="resize();" value="Resize">
<img src="loader.gif" id="loader" />
<img src="" alt="Image preview" id="preview">
<form name="upload" id="upload" method='post' action='show.php'>
<textarea name="base64" id="base64" rows='10' cols='90'></textarea>
<input type="hidden" id="orig" name="orig" value=""/>
</form>
</div>
</body>
</html>
</code></pre>
<p><strong>Show.php file</strong></p>
<pre><code><html>
<head>
<title>JavaScript file upload</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style>
body {
font-size: 16px;
font-family: Arial;
}
#preview {
display:none;
}
#base64 {
display:none;
}
</style>
</head>
<body>
<?php
$base64size = strlen($_POST['base64']);
$f = base64_decode($_POST['base64']);
$name = microtime(true).".png";
file_put_contents("./$name", $f);
#header("Content-type: image/png");
#header("Content-Disposition: attachment; filename=\"shrunk.png\"");
#echo $f;
#die();
?>
<h2>Shrunk file</h2>
<p>Original file was: <?=$_POST['orig'];?> bytes</p>
<p>Transmitted size was: <?=$base64size;?> bytes (due to base64)</p>
<p>New file is: <?=filesize("./$name");?> bytes</p>
<p><img src="<?=$name;?>"/></p>
</body>
</html>
</code></pre> | 20,382,559 | 3 | 2 | null | 2013-12-04 15:14:30.423 UTC | 14 | 2022-06-27 17:57:59.18 UTC | 2013-12-12 06:18:14.42 UTC | null | 1,113,027 | null | 1,113,027 | null | 1 | 27 | javascript|jquery|image-processing | 82,882 | <p>You can use canvas, put image into it, scale it and get image src with new base64 code.</p>
<p>Here's the function doing that, it returns promise object, as image needs to be loaded (cached) first before drawing canvas out of it and getting its encoded src.</p>
<pre><code>function resizeBase64Img(base64, width, height) {
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var context = canvas.getContext("2d");
var deferred = $.Deferred();
$("<img/>").attr("src", "data:image/gif;base64," + base64).load(function() {
context.scale(width/this.width, height/this.height);
context.drawImage(this, 0, 0);
deferred.resolve($("<img/>").attr("src", canvas.toDataURL()));
});
return deferred.promise();
}
</code></pre>
<p>Can be used like this:</p>
<pre><code>resizeBase64Img(oldBase64, 100, 100).then(function(newImg){
$("body").append(newImg);
});
</code></pre>
<p>here's the <a href="http://jsfiddle.net/paulitto/Sk7LA/1/">jsfiddle</a></p> |
24,337,271 | Base64 / SVG HTML image is not displayed | <p>I tried to use this icon</p>
<pre><code><img src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxNi4wLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+DQo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4Ig0KCSB3aWR0aD0iMTI2cHgiIGhlaWdodD0iMTI2cHgiIHZpZXdCb3g9IjAgMCAxMjYgMTI2IiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCAxMjYgMTI2IiB4bWw6c3BhY2U9InByZXNlcnZlIj4NCjxnPg0KCTxyZWN0IHg9IjEuMDk1IiB5PSI5OC4yMjQiIHdpZHRoPSIxMjMuODEiIGhlaWdodD0iMTkuMjc1Ii8+DQoJPHJlY3QgeD0iMS4wOTUiIHk9Ijg1Ljc0IiB3aWR0aD0iMTIzLjgxIiBoZWlnaHQ9IjUuMjA1Ii8+DQoJPHBhdGggZD0iTTE4LjQwNCw5NS43MjFjMC43NjcsMCwxLjM4OS0wLjYyMywxLjM4OS0xLjM5cy0wLjYyMi0xLjM4OC0xLjM4OS0xLjM4OEgzLjQ4MWMtMC43NjcsMC0xLjM4OCwwLjYyMS0xLjM4OCwxLjM4OA0KCQlzMC42MjIsMS4zOSwxLjM4OCwxLjM5SDE4LjQwNHoiLz4NCgk8cGF0aCBkPSJNNDQuNDMzLDk1LjcyMWMwLjc2NywwLDEuMzg4LTAuNjIzLDEuMzg4LTEuMzlzLTAuNjIyLTEuMzg4LTEuMzg4LTEuMzg4SDI5LjUxYy0wLjc2NywwLTEuMzg5LDAuNjIxLTEuMzg5LDEuMzg4DQoJCXMwLjYyMiwxLjM5LDEuMzg5LDEuMzlINDQuNDMzeiIvPg0KCTxwYXRoIGQ9Ik03MC40NjEsOTUuNzIxYzAuNzY3LDAsMS4zODgtMC42MjMsMS4zODgtMS4zOXMtMC42MjItMS4zODgtMS4zODgtMS4zODhINTUuNTM5Yy0wLjc2NywwLTEuMzg4LDAuNjIxLTEuMzg4LDEuMzg4DQoJCXMwLjYyMiwxLjM5LDEuMzg4LDEuMzlINzAuNDYxeiIvPg0KCTxwYXRoIGQ9Ik05Ni40OSw5NS43MjFjMC43NjcsMCwxLjM4OS0wLjYyMywxLjM4OS0xLjM5cy0wLjYyMi0xLjM4OC0xLjM4OS0xLjM4OEg4MS41NjdjLTAuNzY3LDAtMS4zODgsMC42MjEtMS4zODgsMS4zODgNCgkJczAuNjIyLDEuMzksMS4zODgsMS4zOUg5Ni40OXoiLz4NCgk8cGF0aCBkPSJNMTIyLjUxOSw5NS43MjFjMC43NjcsMCwxLjM4OS0wLjYyMywxLjM4OS0xLjM5cy0wLjYyMi0xLjM4OC0xLjM4OS0xLjM4OGgtMTQuOTIzYy0wLjc2NywwLTEuMzg4LDAuNjIxLTEuMzg4LDEuMzg4DQoJCXMwLjYyMiwxLjM5LDEuMzg4LDEuMzlIMTIyLjUxOXoiLz4NCgk8cGF0aCBkPSJNNy40MSw4MC45aDUzLjQ0MmMwLjg2MywwLDEuNTYyLTAuNjk5LDEuNTYyLTEuNTYyVjM5LjU0M2MwLTAuODYyLTAuNjk5LTEuNTYzLTEuNTYyLTEuNTYzSDQ1LjMxNHYtNi41MzkNCgkJYzAtMC44NjEtMC42OTgtMS41NjItMS41NjEtMS41NjJIMjMuNDI4Yy0wLjg2MywwLTEuNTYyLDAuNy0xLjU2MiwxLjU2MnY2LjU0SDcuNDFjLTAuODYyLDAtMS41NjIsMC43LTEuNTYyLDEuNTYzdjM5Ljc5NQ0KCQlDNS44NDgsODAuMjAxLDYuNTQ3LDgwLjksNy40MSw4MC45eiBNMzQuNDkyLDU3Ljg3NGgtMS43OTZ2LTYuNzY4aDEuNzk2VjU3Ljg3NHogTTI2LjU2MywzNC41NzRoMTQuMDU1djMuNDA2SDI2LjU2M1YzNC41NzR6DQoJCSBNMTAuNTQ0LDQyLjY3OGg0Ny4xNzN2MTEuOThIMzYuOTQydi00LjAwNmMwLTAuODYzLTAuNjk5LTEuNTYzLTEuNTYyLTEuNTYzaC0zLjU4MmMtMC44NjMsMC0xLjU2MiwwLjY5OS0xLjU2MiwxLjU2M3Y0LjAwNg0KCQlIMTAuNTQ0VjQyLjY3OHoiLz4NCgk8cGF0aCBkPSJNNjguNzM0LDgwLjloNDkuOTU4YzAuODA3LDAsMS40Ni0wLjY1MywxLjQ2LTEuNDZWMTcuNTM0YzAtMC44MDYtMC42NTMtMS40NTktMS40Ni0xLjQ1OWgtMTQuNTI0VjkuOTYxDQoJCWMwLTAuODA3LTAuNjUzLTEuNDYtMS40Ni0xLjQ2aC0xOWMtMC44MDcsMC0xLjQ2LDAuNjUzLTEuNDYsMS40NnY2LjExNUg2OC43MzRjLTAuODA3LDAtMS40NiwwLjY1My0xLjQ2LDEuNDU5Vjc5LjQ0DQoJCUM2Ny4yNzQsODAuMjQ3LDY3LjkyNyw4MC45LDY4LjczNCw4MC45eiBNODYuNjM4LDEyLjg5aDEzLjEzOXYzLjE4Nkg4Ni42MzhWMTIuODl6Ii8+DQo8L2c+DQo8L3N2Zz4NCg==5324e483b5f25ab4badb7c52c102103e"/>
</code></pre>
<p>from this page<br />
<a href="http://www.flaticon.com/free-icon/baggage-on-conveyor-band_48876">http://www.flaticon.com/free-icon/baggage-on-conveyor-band_48876</a></p>
<p>I just copy and paste the html code (Base64 / svg) into my website.<br />
But the icon is not displayed. why?</p>
<p>Here is an example
<a href="http://jsfiddle.net/Lsr4s/">http://jsfiddle.net/Lsr4s/</a></p>
<p><strong>UPDATE:</strong><br />
I dont get it. I copy another image/icon and it is broken too, but the base64 code has no "=" jsfiddle.net/TYb59 Is the flatIcon.com page so buggy?</p>
<p>Can I fix this images/icons?</p> | 24,337,403 | 5 | 2 | null | 2014-06-21 00:54:46.383 UTC | 11 | 2021-12-01 00:25:43.967 UTC | 2014-06-30 11:34:47.467 UTC | user3767923 | null | null | 2,136,202 | null | 1 | 26 | html|image|svg|base64 | 69,234 | <p>The base64 code that you have copied is broken. Close to the end there is <code>==</code> in the middle of the code. That is a filler that is placed at the end of a base64 code.</p>
<p>Remove the part after <code>==</code>, and it will work fine.</p>
<pre><code><img src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxNi4wLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+DQo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4Ig0KCSB3aWR0aD0iMTI2cHgiIGhlaWdodD0iMTI2cHgiIHZpZXdCb3g9IjAgMCAxMjYgMTI2IiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCAxMjYgMTI2IiB4bWw6c3BhY2U9InByZXNlcnZlIj4NCjxnPg0KCTxyZWN0IHg9IjEuMDk1IiB5PSI5OC4yMjQiIHdpZHRoPSIxMjMuODEiIGhlaWdodD0iMTkuMjc1Ii8+DQoJPHJlY3QgeD0iMS4wOTUiIHk9Ijg1Ljc0IiB3aWR0aD0iMTIzLjgxIiBoZWlnaHQ9IjUuMjA1Ii8+DQoJPHBhdGggZD0iTTE4LjQwNCw5NS43MjFjMC43NjcsMCwxLjM4OS0wLjYyMywxLjM4OS0xLjM5cy0wLjYyMi0xLjM4OC0xLjM4OS0xLjM4OEgzLjQ4MWMtMC43NjcsMC0xLjM4OCwwLjYyMS0xLjM4OCwxLjM4OA0KCQlzMC42MjIsMS4zOSwxLjM4OCwxLjM5SDE4LjQwNHoiLz4NCgk8cGF0aCBkPSJNNDQuNDMzLDk1LjcyMWMwLjc2NywwLDEuMzg4LTAuNjIzLDEuMzg4LTEuMzlzLTAuNjIyLTEuMzg4LTEuMzg4LTEuMzg4SDI5LjUxYy0wLjc2NywwLTEuMzg5LDAuNjIxLTEuMzg5LDEuMzg4DQoJCXMwLjYyMiwxLjM5LDEuMzg5LDEuMzlINDQuNDMzeiIvPg0KCTxwYXRoIGQ9Ik03MC40NjEsOTUuNzIxYzAuNzY3LDAsMS4zODgtMC42MjMsMS4zODgtMS4zOXMtMC42MjItMS4zODgtMS4zODgtMS4zODhINTUuNTM5Yy0wLjc2NywwLTEuMzg4LDAuNjIxLTEuMzg4LDEuMzg4DQoJCXMwLjYyMiwxLjM5LDEuMzg4LDEuMzlINzAuNDYxeiIvPg0KCTxwYXRoIGQ9Ik05Ni40OSw5NS43MjFjMC43NjcsMCwxLjM4OS0wLjYyMywxLjM4OS0xLjM5cy0wLjYyMi0xLjM4OC0xLjM4OS0xLjM4OEg4MS41NjdjLTAuNzY3LDAtMS4zODgsMC42MjEtMS4zODgsMS4zODgNCgkJczAuNjIyLDEuMzksMS4zODgsMS4zOUg5Ni40OXoiLz4NCgk8cGF0aCBkPSJNMTIyLjUxOSw5NS43MjFjMC43NjcsMCwxLjM4OS0wLjYyMywxLjM4OS0xLjM5cy0wLjYyMi0xLjM4OC0xLjM4OS0xLjM4OGgtMTQuOTIzYy0wLjc2NywwLTEuMzg4LDAuNjIxLTEuMzg4LDEuMzg4DQoJCXMwLjYyMiwxLjM5LDEuMzg4LDEuMzlIMTIyLjUxOXoiLz4NCgk8cGF0aCBkPSJNNy40MSw4MC45aDUzLjQ0MmMwLjg2MywwLDEuNTYyLTAuNjk5LDEuNTYyLTEuNTYyVjM5LjU0M2MwLTAuODYyLTAuNjk5LTEuNTYzLTEuNTYyLTEuNTYzSDQ1LjMxNHYtNi41MzkNCgkJYzAtMC44NjEtMC42OTgtMS41NjItMS41NjEtMS41NjJIMjMuNDI4Yy0wLjg2MywwLTEuNTYyLDAuNy0xLjU2MiwxLjU2MnY2LjU0SDcuNDFjLTAuODYyLDAtMS41NjIsMC43LTEuNTYyLDEuNTYzdjM5Ljc5NQ0KCQlDNS44NDgsODAuMjAxLDYuNTQ3LDgwLjksNy40MSw4MC45eiBNMzQuNDkyLDU3Ljg3NGgtMS43OTZ2LTYuNzY4aDEuNzk2VjU3Ljg3NHogTTI2LjU2MywzNC41NzRoMTQuMDU1djMuNDA2SDI2LjU2M1YzNC41NzR6DQoJCSBNMTAuNTQ0LDQyLjY3OGg0Ny4xNzN2MTEuOThIMzYuOTQydi00LjAwNmMwLTAuODYzLTAuNjk5LTEuNTYzLTEuNTYyLTEuNTYzaC0zLjU4MmMtMC44NjMsMC0xLjU2MiwwLjY5OS0xLjU2MiwxLjU2M3Y0LjAwNg0KCQlIMTAuNTQ0VjQyLjY3OHoiLz4NCgk8cGF0aCBkPSJNNjguNzM0LDgwLjloNDkuOTU4YzAuODA3LDAsMS40Ni0wLjY1MywxLjQ2LTEuNDZWMTcuNTM0YzAtMC44MDYtMC42NTMtMS40NTktMS40Ni0xLjQ1OWgtMTQuNTI0VjkuOTYxDQoJCWMwLTAuODA3LTAuNjUzLTEuNDYtMS40Ni0xLjQ2aC0xOWMtMC44MDcsMC0xLjQ2LDAuNjUzLTEuNDYsMS40NnY2LjExNUg2OC43MzRjLTAuODA3LDAtMS40NiwwLjY1My0xLjQ2LDEuNDU5Vjc5LjQ0DQoJCUM2Ny4yNzQsODAuMjQ3LDY3LjkyNyw4MC45LDY4LjczNCw4MC45eiBNODYuNjM4LDEyLjg5aDEzLjEzOXYzLjE4Nkg4Ni42MzhWMTIuODl6Ii8+DQo8L2c+DQo8L3N2Zz4NCg=="/>
</code></pre>
<p>Demo: <a href="http://jsfiddle.net/Lsr4s/2/" rel="noreferrer">http://jsfiddle.net/Lsr4s/2/</a></p>
<h3>Edit:</h3>
<p>Downloading the svg file from the site and base64 encoding it gives exactly the same result. If there is no signature that you can use to easily fix the code, that is what you would need to do.</p>
<p>I used C# code like this to base64 encode the image to a text file:</p>
<pre><code>File.WriteAllText(@"d:\temp\baggage19.txt", Convert.ToBase64String(File.ReadAllBytes(@"d:\temp\baggage19.svg")));
</code></pre> |
24,049,931 | Making an IObservable<T> that uses async/await return completed tasks in original order | <p>Suppose you have a list of 100 urls and you want to download them, parse the response and push the results through an IObservable:</p>
<pre><code>public IObservable<ImageSource> GetImages(IEnumerable<string> urls)
{
return urls
.ToObservable()
.Select(async url =>
{
var bytes = await this.DownloadImage(url);
var image = await this.ParseImage(bytes);
return image;
});
}
</code></pre>
<p>I have some problems with this. </p>
<p>One is that it's bad etiquette to hammer a server with 100 requests at the same time -- ideally you would rate limit to maybe 6 requests at a given moment. However, if I add a <code>Buffer</code> call, due to the async lambda in <code>Select</code>, everything still fires at the same time.</p>
<p>Moreover, the results will come back in a different order than the input sequence of URLs, which is bad, because the images are part of an animation that will be displayed on the UI.</p>
<p>I've tried all kinds of things, and I have a solution that's working, but it feels convoluted:</p>
<pre><code>public IObservable<ImageSource> GetImages(IEnumerable<string> urls)
{
var semaphore = new SemaphoreSlim(6);
return Observable.Create<ImageSource>(async observable =>
{
var tasks = urls
.Select(async url =>
{
await semaphore.WaitAsync();
var bytes = await this.DownloadImage(url);
var image = await this.ParseImage(url);
})
.ToList();
foreach (var task in tasks)
{
observable.OnNext(await task);
}
observable.OnCompleted();
});
}
</code></pre>
<p>It works, but now I'm doing <code>Observable.Create</code> instead of just <code>IObservable.Select</code>, and I have to mess with the semaphore. Also, other animations that run on the UI stop when this is running (they're basically just <code>DispatcherTimer</code> instances), so I think I must be doing something wrong.</p> | 24,051,914 | 2 | 2 | null | 2014-06-05 00:49:39.7 UTC | 9 | 2020-11-16 20:22:19.067 UTC | null | null | null | null | 424,131 | null | 1 | 11 | c#|system.reactive | 6,368 | <p>Give this a try:</p>
<pre><code>urls.ToObservable()
.Select(url => Observable.FromAsync(async () => {
var bytes = await this.DownloadImage(url);
var image = await this.ParseImage(bytes);
return image;
}))
.Merge(6 /*at a time*/);
</code></pre>
<h3>What are we doing here?</h3>
<p>For each URL, we're creating a <em>Cold Observable</em> (i.e. one that won't do anything at all, until somebody calls Subscribe). <code>FromAsync</code> returns an Observable that, when you Subscribe to it, runs the async block you gave it. So, we're Selecting the URL into an object that will do the work for us, but only if we ask it later.</p>
<p>Then, our result is an <code>IObservable<IObservable<Image>></code> - a stream of Future results. We want to flatten that stream, into just a stream of results, so we use <code>Merge(int)</code>. The merge operator will subscribe to <code>n</code> items at a time, and as they come back, we'll subscribe to more. Even if url list is very large, the items that Merge are buffering are only a URL and a Func object (i.e. the description of <em>what</em> to do), so relatively small.</p> |
24,043,904 | Creating and playing a sound in swift | <p>So what I want to do is create and play a sound in swift that will play when I press a button, I know how to do it in Objective-C, but does anyone know how to in Swift?</p>
<p>It would be like this for Objective-C:</p>
<pre><code>NSURL *soundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"mysoundname" ofType:@"wav"]];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL, &mySound);
</code></pre>
<p>And then to play it I would do:</p>
<pre><code>AudioServicesPlaySystemSound(Explosion);
</code></pre>
<p>Does anyone know how I could do this?</p> | 24,073,071 | 24 | 4 | null | 2014-06-04 17:33:10.56 UTC | 52 | 2022-02-08 06:09:50.82 UTC | 2014-06-04 17:44:37.25 UTC | null | 1,295,344 | null | 3,662,667 | null | 1 | 104 | ios|objective-c|audio|swift | 119,844 | <p>Here's a bit of code I've got added to FlappySwift that works:</p>
<pre><code>import SpriteKit
import AVFoundation
class GameScene: SKScene {
// Grab the path, make sure to add it to your project!
var coinSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "coin", ofType: "wav")!)
var audioPlayer = AVAudioPlayer()
// Initial setup
override func didMoveToView(view: SKView) {
audioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: nil)
audioPlayer.prepareToPlay()
}
// Trigger the sound effect when the player grabs the coin
func didBeginContact(contact: SKPhysicsContact!) {
audioPlayer.play()
}
}
</code></pre> |
28,704,984 | How to speed up a complex image processing? | <p>Every user will be able to upload 100 TIFF (black and white) images.</p>
<p><strong>The process requires:</strong></p>
<ol>
<li><p>Convert <code>tif</code> to <code>jpg</code>.</p>
</li>
<li><p>Resize image to xx.</p>
</li>
<li><p>Crop image to 200px.</p>
</li>
<li><p>Add a text watermark.</p>
</li>
</ol>
<p>Here is my PHP code:</p>
<pre><code>move_uploaded_file($image_temp,$destination_folder.$image_name);
$image_name_only = strtolower($image_info["filename"]);
$name=$destination_folder.$image_name_only.".jpg";
$thumb=$destination_folder."thumb_".$image_name_only.".jpg";
$exec = '"C:\Program Files\ImageMagick-6.9.0-Q16\convert.exe" '.$destination_folder.$image_name. ' '.$name.' 2>&1';
exec($exec, $exec_output, $exec_retval);
$exec = '"C:\Program Files\ImageMagick-6.9.0-Q16\convert.exe" '.$name. ' -resize 1024x '.$name;
exec($exec, $exec_output, $exec_retval);
$exec = '"C:\Program Files\ImageMagick-6.9.0-Q16\convert.exe" '.$name. ' -thumbnail 200x200! '.$thumb;
exec($exec, $exec_output, $exec_retval);
$exec = '"C:\Program Files\ImageMagick-6.9.0-Q16\convert.exe" '.$name. " -background White label:ش.پ12355 -append ".$name;
exec($exec, $exec_output, $exec_retval);
</code></pre>
<p>This code works. But the average processing time for every image is 1 second.
So for 100 images it will probably take around 100 seconds.</p>
<p>How can I speed up this whole process (convert, resize, crop, watermark)?</p>
<p><strong>EDIT</strong></p>
<blockquote>
<p>I have a Server G8:Ram:32G,CPU:Intel Xeon E5-2650(4 Process)</p>
<p>version:ImageMagick 6.9.0-3 Q16 x64</p>
<p>FEATURES:OpenMP</p>
</blockquote>
<pre><code>convert logo: -resize 500% -bench 10 1.png
Performance[1]: 10i 0.770ips 1.000e 28.735u 0:12.992
Performance[2]: 10i 0.893ips 0.537e 26.848u 0:11.198
Performance[3]: 10i 0.851ips 0.525e 27.285u 0:11.756
Performance[4]: 10i 0.914ips 0.543e 26.489u 0:10.941
Performance[5]: 10i 0.967ips 0.557e 25.803u 0:10.341
Performance[6]: 10i 0.797ips 0.509e 27.737u 0:12.554
Performance[7]: 10i 0.963ips 0.556e 25.912u 0:10.389
Performance[8]: 10i 0.863ips 0.529e 26.707u 0:11.586
</code></pre>
<p>Resource limits:</p>
<blockquote>
<p>Width: 100MP;Height: 100MP;Area: 17.16GP;Memory: 7.9908GiB;Map: 15.982GiB;Disk: unlimited;File: 1536;Thread: 8;Throttle: 0;Time: unlimited</p>
</blockquote> | 28,708,634 | 4 | 5 | null | 2015-02-24 19:51:28.72 UTC | 9 | 2022-02-10 16:25:42.367 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | user4397664 | null | null | 1 | 12 | php|image|imagemagick|converter|imagemagick-convert | 11,825 | <h2>0. Two approaches</h2>
<p>Basically, this challenge can be tackled in two different ways, or a combination of the two:</p>
<ol>
<li>Construct your commands as clever as possible.</li>
<li>Trade speed-up gains for quality losses.</li>
</ol>
<p>The next few sections discuss the both approaches.</p>
<h2>1. Check which ImageMagick you've got: 'Q8', 'Q16', 'Q32' or 'Q64'?</h2>
<p>First, check for your exact ImageMagick version and run:</p>
<pre><code>convert -version
</code></pre>
<p>In case your ImageMagick has a <code>Q16</code> (or even <code>Q32</code> or <code>Q64</code>, which is possible, but overkill!) in its version string:
This means, all of ImageMagick's internal functions treat all images as having 16 bit (or 32 or 64 bit) channel depths.
This gives you a better quality in image processing.
But it also requires double memory as compared to <code>Q8</code>.
So at the same time it means a performance degradation.</p>
<p>Hence: you could test what performance benefits you'll achieve by switching to a <code>Q8</code>-build.
(The <code>Q</code> is symbol for the <em>'quantum depth'</em> supported by a ImageMagick build.)</p>
<p>You'll pay your possible <code>Q8</code>-performance gains with quality loss, though.
Just check what speed up you achieve with <code>Q8</code> over <code>Q16</code>, and what quality losses you suffer.
Then decide whether you can live with the drawbacks or not...</p>
<p>In any case <code>Q16</code> will use twice as much RAM per image to process, and <code>Q32</code> will again use twice the amount of <code>Q16</code>.
This is independent from the actual bits-per-pixels seen in the input files.
16-bit image files, when saved, will also consume more disk space than 8-bit ones.</p>
<p>With <code>Q16</code> or <code>Q32</code> requiring more memory, you always have to ensure that you have enough of it.
Because <em>exceeding</em> your physical memory would be very bad news.
If a larger <code>Q</code> makes a process swap to disk, performance will plummet.
A <code>1074 x 768</code> pixel image (<code>width x height</code>) will require the following amounts of virtual memory, depending on the quantum depth:</p>
<pre><code>Quantum Virtual Memory
Depth (consumed by 1 image 1024x768)
------- ------------------------------
8 3.840 kiB (=~ 3,75 MiB)
16 7.680 kiB (=~ 7,50 MiB)
32 15.360 kiB (=~ 14,00 MiB)
</code></pre>
<p>Also keep in mind, that some 'optimized' processing pipelines (see below) will need to keep several copies of an image in virtual memory!
Once virtual memory cannot be satisfied by available RAM, the system will start to swap and claim "memory" from the disk.
In that case, all clever command pipeline optimization is of course gone, and starts to knock over to the very reverse.</p>
<p>ImageMagick's birthday was in the aera when CPUs could handle only 1 bit at a time.
That was decades ago.
Since then CPU architecture has changed a lot.
16-bit operations used to take twice as long as 8-bit operations, or even longer.
Then 16-bit processors arrived.
16-bit ops became standard.
CPUs were optimised for 16-bit:
Suddenly some 8-bit operations could take even longer than 16-bit equivalents.</p>
<p>Nowadays, 64bit CPUs are common.
So the <code>Q8</code> vs. <code>Q16</code> vs. <code>Q32</code> argument in real terms may even be void.
Who knows?
I'm not aware of any serious benchmarking about this.
It would be interesting if someone (with really deep knowhow about CPUs and about benchmarking real world programs) would run with such a project one day.</p>
<p><sub>Yes, I see you are using <code>Q16</code> on Windows.
But I still wanted to mention it, for completeness' sake...
In the future there will be other users reading this question and the answers given.</sub></p>
<p><sub>Very likely, since your input TIFFs are black+white only, the image quality output of a <code>Q8</code> build will be good enough for your workflow.
(I just don't know if it would also be significantly faster:
this largely also depends on the hardware resources you are running this on...)</sub></p>
<p><sub>In addition, if your installation sports support <code>HDRI</code> (<em>high dynamic resolution images</em>), this may also cause some speed penalty.
Who knows?
So building IM with configure options <code>--disable-hdri --with-quantum-depth=8</code> may or may not lead to speed improvements.
Nobody has ever tested this in a serious way...
The only thing we know about this:
these options will decrease image quality.
However most people will not even notice this, unless they take really close looks and make direct image-by-image comparisons...</sub></p>
<p> </p>
<h2>2. Check your ImageMagick's capabilities</h2>
<p>Next, check if your ImageMagick installation comes with <a href="http://en.wikipedia.org/wiki/OpenCL" rel="nofollow noreferrer">OpenCL</a> and/or <a href="http://en.wikipedia.org/wiki/OpenCL" rel="nofollow noreferrer">OpenMP</a> support:</p>
<pre><code>convert -list configure | grep FEATURES
</code></pre>
<p>If it does (like mine), you should see something like this:</p>
<pre><code>FEATURES DPC HDRI OpenCL OpenMP Modules
</code></pre>
<p>OpenCL (for <em><strong>C</strong></em> omputing <em><strong>L</strong></em> anguage) utilizes ImageMagick's <em>parallel computing</em> features (if compiled-in).
This will make use of your computer's GPU additionally to the CPU for image processing operations.</p>
<p>OpenMP (for <em><strong>M</strong></em> ulti-<em><strong>P</strong></em> rocessing) does something similar:
it allows ImageMagick to execute in parallel on all the cores of your system.
So if you have a quad-core system, and resize an image, the resizing happens on 4 cores (or even 8 if you have hyperthreading).</p>
<p>The command</p>
<pre><code>convert -version
</code></pre>
<p>prints some basic info about supported features.
If OpenCL/OpenMP are available, you will see one of them (or both) in the output.</p>
<p>If none of the two show up:
look into getting the most recent version of ImageMagick that has OpenCL and/or OpenMP support compiled in.</p>
<p>If you build the package yourself from the sources, make sure OpenCL/OpenMP are used.
Do this by including the appropriate parameters into your 'configure' step:</p>
<pre><code>./configure [...other options-] --enable-openmp --enable-opencl
</code></pre>
<p>ImageMagick's documentation about OpenMP and OpenCL is here:</p>
<ul>
<li><strong><a href="http://www.imagemagick.org/script/openmp.php" rel="nofollow noreferrer">Parallel Execution With OpenMP</a></strong>.
Read it carefully.
Because OpenMP is not a silver bullet, and it does not work under all circumstances...</li>
<li><strong><a href="http://www.imagemagick.org/script/opencl.php" rel="nofollow noreferrer">Parallel Execution With OpenCL</a></strong>.
The same as above applies here.
Additionally, not all ImageMagick operations are OpenCL-enabled.
The link here has a list of those which are.
<code>-resize</code> is one of them.</li>
</ul>
<p>Hints and instructions to build ImageMagick from sources and configure the build, explaining various options, are here:</p>
<ul>
<li><strong><a href="https://imagemagick.org/www/script/advanced-unix-installation.php" rel="nofollow noreferrer">ImageMagick Advanced Unix Installation</a></strong></li>
</ul>
<p>This page also includes a short discussion of the <code>--with-quantum-depth</code> configure option.</p>
<h2>3. Benchmark your ImageMagick</h2>
<p>You can now also use the builtin <code>-bench</code> option to make ImageMagick run a benchmark for your command.
For example:</p>
<pre><code>convert logo: -resize 500% -bench 10 logo.png
[....]
Performance[4]: 10i 1.489ips 1.000e 6.420u 0:06.510
</code></pre>
<p>Above command with <code>-resize 500%</code> tells ImageMagick to run the <code>convert</code> command and scale the built-in IM <code>logo:</code> image by 500% in each direction.
The <code>-bench 10</code> part tells it to run that same command 10 times in a loop and then print the performance results:</p>
<ul>
<li>Since I have OpenMP enabled, I have 4 threads (<code>Performance[4]:</code>).</li>
<li>It reports that it ran 10 iterations (<code>10i</code>).</li>
<li>The speed was nearly 1.5 iterations per second (<code>1.489ips</code>).</li>
<li>Total user-alotted time was 6.420 seconds.</li>
</ul>
<p>If your result includes <code>Performance[1]:</code>, and only one line, then your system does not have OpenMP enabled.
(You <em>may</em> be able to switch it on, if your build does support it: run <code>convert -limit thread 2</code>.)</p>
<h2>4. Tweak your ImageMagick's resource limits</h2>
<p>Find out how your system's ImageMagick is set up regarding <em>resource limits</em>.
Use this command:</p>
<pre>
identify -list resource
File Area Memory Map Disk Thread Time
--------------------------------------------------------------------
384 8.590GB 4GiB 8GiB unlimited 4 unlimited
</pre>
<p>Above shows my current system's settings (not the defaults -- I did tweak them in the past).
The numbers are the maximum amount of each resource ImageMagick will use.
You can use each of the keywords in the column headers to pimp your system.
For this, use <code>convert -limit <resource> <number></code> to <em>set</em> it to a new limit.</p>
<p>Maybe <em>your</em> result looks more like this:</p>
<pre>
identify -list resource
File Area Memory Map Disk Thread Time
--------------------------------------------------------------------
192 4.295GB 2GiB 4GiB unlimited 1 unlimited
</pre>
<ul>
<li>The <code>files</code> defines the max concurrently opened files which ImageMagick can use.</li>
<li>The <code>memory</code>, <code>map</code>, <code>area</code> and <code>disk</code> resource limits are defined in Bytes.
For <em>setting</em> them to different values you can use SI prefixes, .e.g 500MB).</li>
</ul>
<p>When you <em><strong>do</strong></em> have OpenMP for ImageMagick on your system, you can run.</p>
<pre><code>convert -limit thread 2
</code></pre>
<p>This enable 2 parallel threads as a first step.
Then re-run the benchmark and see if it really makes a difference, and if so how much.
After that you could set the limit to 4 or even 8 and repeat the excercise....</p>
<h2>5. Use Magick Pixel Cache (MPC) and/or Magick Persistent Registry (MPR)</h2>
<p><strong>Finally</strong>, you can experiment with a special internal format of ImageMagick's pixel cache.
This format is called <code>MPC</code> (Magick Pixel Cache).
It only exists in memory.</p>
<p>When MPC is created, the processed input image is kept in RAM as an uncompressed raster format.
So basically, MPC is the native <em>in-memory</em> uncompressed file format of ImageMagick.
It is simply a direct memory dump to disk.
A read is a fast memory map from disk to memory as needed (similar to memory page swapping).
But no image decoding is needed.</p>
<p><em>(More technical details: MPC as a format is not portable.
It also isn't suitable as a long-term archive format.
Its only suitability is as an intermediate format for high-performance image processing.
It requires two files to support one image.)</em></p>
<p>If you still want to save this format to disk, be aware of this:</p>
<ul>
<li>Image <em>attributes</em> are written to a file with the extension <em>.mpc</em>.</li>
<li>Image <em>pixels</em> are written to a file with the extension <em>.cache</em>.</li>
</ul>
<p>Its main advantage is experienced when...</p>
<ol>
<li>...processing very large images, or when</li>
<li>...applying several operations on one and the same image in <em>"opertion pipelines"</em>.</li>
</ol>
<p>MPC was designed especially for workflow patterns which match the criteria <em>"read many times, write once"</em>.</p>
<p>Some people say that for such operations the performance improves here, but I have no personal experience with it.</p>
<p>Convert your base picture to MPC first:</p>
<pre><code>convert input.jpeg input.mpc
</code></pre>
<p>and only then run:</p>
<pre><code>convert input.mpc [...your long-long-long list of crops and operations...]
</code></pre>
<p>Then see if this saves you significantly on time.</p>
<p>Most likely you can use this MPC format even "inline" (using the special <code>mpc:</code> notation, see below).</p>
<p>The MPR format (<em>memory persistent register</em>) does something similar.
It reads the image into a named memory register.
Your process pipeline can also read the image again from that register, should it need to access it multiple times.
The image persists in the register the current command pipeline exits.</p>
<p>But I've never applied this technique to a real world problem, so I can't say how it works out in real life.</p>
<h2>6. Construct a suitable IM processing pipeline to do all tasks in one go</h2>
<p>As you describe your process, it is composed of 4 distinguished steps:</p>
<ol>
<li>Convert a TIFF to a JPEG.</li>
<li>Resize the JPEG image to xx (?? what value ??)</li>
<li>Crop the JPEG to 200px.</li>
<li>Add a text watermark.</li>
</ol>
<p><strong>Please tell if I understand correctly your intentions from reading your code snippets:</strong></p>
<ul>
<li>You have 1 input file, a TIFF.</li>
<li>You want 2 final output files:
<ol>
<li>1 thumbnail JPEG, sized 200x200 pixels;</li>
<li>1 labelled JPEG, with a width of 1024 pixels (height keeping aspect ratio of input TIFF);</li>
<li>1 (unlabelled) JPEG is only an intermediate file which you do not really want to keep.</li>
</ol>
</li>
</ul>
<p>Basically, each step uses its own command -- 4 different commands in total.
This can be sped up considerably by using a single command pipeline which performs all the steps on its own.</p>
<p>Moreover, you seem to not really need to <em>keep</em> the unlabelled JPEG as an end result -- yet your one command to generate it as an intermediate temporary file saves it to disk. We can try to skip this step altogether then, and try to achieve the final result without this extra write to disk.</p>
<p>There are different approaches possible to this change.
I'll show you (and other readers) only one for now -- and only for the CLI, not for PHP.
I'm not a PHP guy -- it's your own job to 'translate' my CLI method into appropriate PHP calls.</p>
<p><strong>(But by all means: please test with my commands first, really using the CLI, to see if the effort is worth while translating the approach to PHP!)</strong></p>
<p>But please make first sure that you <em>really</em> understand the architecture and structure of more complex ImageMagick's command lines!
For this goal, please refer to this <strong>other answer of mine</strong>:</p>
<ul>
<li><strong><a href="https://stackoverflow.com/a/26940206/359307">ImageMagick Command-Line Option Order (and Categories of Command-Line Parameters)</a></strong></li>
</ul>
<p>Your 4 steps translate into the following individual ImageMagick commands:</p>
<pre><code>convert image.tiff image.jpg
convert image.jpg -resize 1024x image-1024.jpg
convert image-1024.jpg -thumbnail 200x200 image-thumb.jpg
convert -background white image-1024.jpg label:12345 -append image-labelled.jpg
</code></pre>
<p>Now to transform this workflow into one single pipeline command...
The following command does this.
It should execute faster (regardless of what your results are when following my above steps <strong>0.--4.</strong>):</p>
<pre><code>convert image.tiff \
-respect-parentheses \
+write mpr:XY \
\( mpr:XY +write image-1024.jpg \) \
\( mpr:XY -thumbnail 200x200 +write image-thumb.jpg \) \
\( mpr:XY -background white label:12345 -append +write image-labelled.jpg \) \
null:
</code></pre>
<p><strong>Explanations:</strong></p>
<ul>
<li><strong><code>-respect-parentheses</code></strong> :
required to really make <em>independent from each other</em> the sub-commands executed inside the <code>\( .... \)</code> parentheses.</li>
<li><strong><code>+write mpr:XY</code></strong> :
used to write the input file to an MPR memory register.
<strong><code>XY</code></strong> is just a label (you can use anything), needed to later re-call the same image.</li>
<li><strong><code>+write image-1024.jpg</code></strong> :
writes result of subcommand executed inside the first parentheses pair to disk.</li>
<li><strong><code>+write image-thumb.jpg</code></strong> :
writes result of subcommand executed inside the second parentheses pair to disk.</li>
<li><strong><code>+write image-labelled.jpg</code></strong> :
writes result of subcommand executed inside the third parentheses pair to disk.</li>
<li><strong><code>null:</code></strong> :
terminates the command pipeline.
Required because we otherwise would end with the last subcommand's closing parenthesis.</li>
</ul>
<h2>7. Benchmarking 4 individual commands vs. the single pipeline</h2>
<p>In order to get a rough feeling about my suggestion, I did run the commands below.</p>
<p>The first one runs the sequence of the 4 individual commands 100 times (and saves all resulting images under different file names).</p>
<pre><code>time for i in $(seq -w 1 100); do
convert image.tiff \
image-indiv-run-${i}.jpg
convert image-indiv-run-${i}.jpg -sample 1024x \
image-1024-indiv-run-${i}.jpg
convert image-1024-indiv-run-${i}.jpg -thumbnail 200x200 \
image-thumb-indiv-run-${i}.jpg
convert -background white image-1024-indiv-run-${i}.jpg label:12345 -append \
image-labelled-indiv-run-${i}.jpg
echo "DONE: run indiv $i ..."
done
</code></pre>
<p>My result for <em><strong>4 individual commands</strong></em> (repeated 100 times!) is this:</p>
<pre><code>real 0m49.165s
user 0m39.004s
sys 0m6.661s
</code></pre>
<p>The second command times the single pipeline:</p>
<pre><code>time for i in $(seq -w 1 100); do
convert image.tiff \
-respect-parentheses \
+write mpr:XY \
\( mpr:XY -resize 1024x \
+write image-1024-pipel-run-${i}.jpg \) \
\( mpr:XY -thumbnail 200x200 \
+write image-thumb-pipel-run-${i}.jpg \) \
\( mpr:XY -resize 1024x \
-background white label:12345 -append \
+write image-labelled-pipel-run-${i}.jpg \) \
null:
echo "DONE: run pipeline $i ..."
done
</code></pre>
<p>The result for <em><strong>single pipeline</strong></em> (repeated 100 times!) is this:</p>
<pre><code>real 0m29.128s
user 0m28.450s
sys 0m2.897s
</code></pre>
<p><em><strong>As you can see, the single pipeline is about 40% faster than the 4 individual commands!</strong></em></p>
<p>Now you can also invest in multi-CPU, much RAM, fast SSD hardware to speed things up even more :-)</p>
<p>But first translate this CLI approach into PHP code...</p>
<hr />
<p>There are a few more things to be said about this topic.
But my time runs out for now.
I'll probably return to this answer in a few days and update it some more...</p>
<hr />
<p><sub><strong>Update:</strong> I had to update this answer with new numbers for the benchmarking:
initially I had forgotten to include the <code>-resize 1024x</code> operation (<em>stupid me!</em>) into the pipelined version.
Having included it, the performance gain is still there, but not as big any more.</sub></p>
<hr />
<h2>8. Use <code>-clone 0</code> to copy image within memory</h2>
<p>Here is another alternative to try instead of the <code>mpr:</code> approach with a named memory register as suggested above.</p>
<p>It uses (again within 'side processing inside parentheses') the <code>-clone 0</code> operation.
The way this works is this:</p>
<ol>
<li><code>convert</code> reads the input TIFF from disk once and loads it into memory.</li>
<li>Each <code>-clone 0</code> operator makes a copy of the first loaded image (because it has index <code>0</code> in the current image stack).</li>
<li>Each "within-parenthesis" sub-pipeline of the total command pipeline performs some operation on the clone.</li>
<li>Each <code>+write</code> operation saves the respective result to disk.</li>
</ol>
<p>So here is the command to benchmark this:</p>
<pre><code>time for i in $(seq -w 1 100); do
convert image.tiff \
-respect-parentheses \
\( -clone 0 -thumbnail 200x200 \
+write image-thumb-pipel-run-${i}.jpg \) \
\( -clone 0 -resize 1024x \
-background white label:12345 -append \
+write image-labelled-pipel-run-${i}.jpg \) \
null:
echo "DONE: run pipeline $i ..."
done
</code></pre>
<p>My result:</p>
<pre><code>real 0m19.432s
user 0m18.214s
sys 0m1.897s
</code></pre>
<p>To my surprise, this is faster than the version which used <code>mpr:</code> !</p>
<h2>9. Use <code>-scale</code> or <code>-sample</code> instead of <code>-resize</code></h2>
<p>This alternative will most likely speed up your resizing sub-operation.
But it will likely lead to a somewhat worse image quality (you'll have to verify, if this difference is noticeable).</p>
<p>For some background info about the difference between <code>-resize</code>, <code>-sample</code> and <code>-scale</code> see the following answer:</p>
<ul>
<li><strong><a href="https://stackoverflow.com/a/13078621/359307">What is the difference between sample/resample/scale/resize/adaptive-resize/thumbnail in ImageMagick convert?</a></strong></li>
</ul>
<p>I tried it too:</p>
<pre><code>time for i in $(seq -w 1 100); do
convert image.tiff \
-respect-parentheses \
\( -clone 0 -thumbnail 200x200 \
+write image-thumb-pipel-run-${i}.jpg \) \
\( -clone 0 -scale 1024x \
-background white label:12345 -append \
+write image-labelled-pipel-run-${i}.jpg \) \
null:
echo "DONE: run pipeline $i ..."
done
</code></pre>
<p>My result:</p>
<pre><code>real 0m16.551s
user 0m16.124s
sys 0m1.567s
</code></pre>
<p>This is the fastest result so far (I combined it with the <code>+clone</code> variant).</p>
<p>Of course, this modification can also be applied to your initial method running 4 different commands.</p>
<h2>10. Emulate the <code>Q8</code> build by adding <code>-depth 8</code> to the commands.</h2>
<p>I did not actually run and measure this, but the complete command would be.</p>
<pre><code>time for i in $(seq -w 1 100); do
convert image.tiff \
-respect-parentheses \
\( -clone 0 -thumbnail 200x200 -depth 8 \
+write d08-image-thumb-pipel-run-${i}.jpg \) \
\( -clone 0 -scale 1024x -depth 8 \
-background white label:12345 -append \
+write d08-image-labelled-pipel-run-${i}.jpg \) \
null:
echo "DONE: run pipeline $i ..."
done
</code></pre>
<p>This modification is also applicable to your initial "I run 4 different commands"-method.</p>
<h2>11. Combine it with GNU <code>parallel</code>, as suggested by Mark Setchell</h2>
<p>This of course is only applicable and reasonable for you, if your overall work process allows for such parallelization.</p>
<p>For my little benchmark testing it is applicable.
For your web service, it may be that you know of only one job at a time...</p>
<pre><code>time for i in $(seq -w 1 100); do \
cat <<EOF
convert image.tiff \
\( -clone 0 -scale 1024x -depth 8 \
-background white label:12345 -append \
+write d08-image-labelled-pipel-run-${i}.jpg \) \
\( -clone 0 -thumbnail 200x200 -depth 8 \
+write d08-image-thumb-pipel-run-${i}.jpg \) \
null:
echo "DONE: run pipeline $i ..."
EOF
done | parallel --will-cite
</code></pre>
<p><strong>Results:</strong></p>
<pre><code>real 0m6.806s
user 0m37.582s
sys 0m6.642s
</code></pre>
<p>The apparent contradiction between <code>user</code> and <code>real</code> time can be explained:
the <code>user</code> time represents the sum of all time ticks which where clocked on 8 different CPU cores.</p>
<p>From the point of view of the user looking onto his watch, it was much faster: less than 10 seconds.</p>
<h2>12. Summary</h2>
<p>Pick your own preferences -- combine different methods:</p>
<ol>
<li><p>Some speedup can be gained (with identical image quality as currently) by <em><strong>constructing a more clever command pipeline</strong></em>.
Avoid running various commands (where each <code>convert</code> leads to a new process, and has to read its input from disk).
Pack all image manipulations into one single process.
Make use of the "parenthesized side processing".
Make use of <code>-clone</code> or <code>mbr:</code> or <code>mbc:</code> or even combine each of these.</p>
</li>
<li><p>Some speedups can be additionally be gained by <em><strong>trading image quality with performance</strong></em>:
Some of your choices are:</p>
<ol>
<li><code>-depth 8</code> (has to be declared on the OP's system) vs. <code>-depth 16</code> (the default on the OP's system)</li>
<li><code>-resize 1024</code> vs. <code>-sample 1024x</code> vs. <code>-scale 1024x</code></li>
</ol>
</li>
<li><p>Make use of GNU <code>parallel</code> if your workflow permits this.</p>
</li>
</ol> |
16,327,461 | What is the difference between iteration and traversing? | <p>The past few weeks I have been learning about iterators. I still do not understand the main difference between iterating through a link list and traversing through one. I know that traversing means to go through (visiting every element) the link list, and when iterating you basically do the same thing, but what is different, and why cannot you iterate through everything (standard library data-structures)?</p> | 16,327,676 | 5 | 1 | null | 2013-05-01 22:24:10.25 UTC | 10 | 2013-12-12 18:30:16.917 UTC | 2013-12-12 18:30:16.917 UTC | null | 1,968 | null | 2,045,232 | null | 1 | 19 | c++|data-structures|iteration|terminology|traversal | 12,526 | <p>“Traversal” just means walking through (all or some) elements of a data structure.</p>
<p>Historically, “iteration” in computer science is a special form of recursion for which no additional stack space is needed<sup>1</sup> – in other words, <a href="http://en.wikipedia.org/wiki/Tail_recursion" rel="noreferrer">tail recursion</a>. This form is computationally exactly equivalent to what we now colloquially know as “iteration”, namely a finite loop (such as a <code>for</code> loop with a fixed lower and upper bound).</p>
<p>Now this makes iteration especially well suited (compared to general recursion) for traversing linear data structures<sup>2</sup>. Note that it does not work for <em>all</em> containers (e.g. general graphs) because here you need to remember the already visited nodes (e.g. using <a href="http://en.wikipedia.org/wiki/Depth-first_search" rel="noreferrer">depth-first search</a>, which is defined recursively in terms of adjacent nodes, rather than via the C++ concept of iterators).</p>
<p>It is in this context that the term “iteration” is used in C++ applied to containers.</p>
<p>In summary: not every traversal is an iteration but every iteration (over a data structure) is a traversal. However, it’s worth noting that many people make no such distinction and use the terms interchangeably.</p>
<hr>
<p><sup>1</sup> In particular this is the usage of Gerald Sussman of <a href="http://en.wikipedia.org/wiki/Structure_and_Interpretation_of_Computer_Programs" rel="noreferrer"><em>SICP</em></a> fame.</p>
<p><sup>2</sup> But seemingly non-linear data structures such as trees can be linearised for the purpose of iteration by applying the <a href="http://en.wikipedia.org/wiki/Maze_solving_algorithm#Wall_follower" rel="noreferrer">right-hand rule (wall-following algorithm)</a> and can thus be traversed <em>without</em> a stack.</p> |
16,041,229 | CSS overflow:hidden with floats | <p>I read the <a href="https://www.w3schools.com/css/tryit.asp?filename=trycss_navbar_horizontal_float" rel="noreferrer">following code on w3schools</a> and do not understand how the <code>overflow</code> property would impact whether text appears to the right of the <code>ul</code> or not. </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
}
li {
float: left;
}
a {
display: block;
width: 60px;
background-color: #dddddd;
padding: 8px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
<p><b>Note:</b> overflow:hidden is added to the ul element to prevent li elements from going outside of the list.</p></code></pre>
</div>
</div>
</p>
<p>I know that <code>overflow:hidden</code> is used to handle content that goes outside of the box but don't understand how it applies in this instance.</p> | 16,056,509 | 5 | 0 | null | 2013-04-16 15:37:22.307 UTC | 18 | 2019-09-18 14:31:12.533 UTC | 2017-06-22 15:44:50.563 UTC | null | 1,047,823 | null | 1,798,677 | null | 1 | 26 | html|css|overflow | 37,162 | <p>I try to end the confusion:</p>
<p><code>ul</code> is a block-level element as is the <code>p</code> element (they stretch to 100% of the parent width). That is why per default the <code>p</code> will appear below the <code>ul</code> if no width or display is declared on those elements.</p>
<p>Now in your example the <code>ul</code> contains only floated elements. This makes it collapse to a height of <code>0px</code> (It still has 100% width though as you can see in the example). The adjacent <code>p</code> will appear to the right of the floated <code>li</code>s because they are considered as normal floated elements.</p>
<p>Now declaring <code>overflow</code> (any value other than <code>visible</code>) establishes a new <a href="https://developer.mozilla.org/en-US/docs/CSS/Block_formatting_context">block formatting context</a>, which makes the <code>ul</code> contains its children. Suddenly the <code>ul</code> "reappears", not having size <code>0px</code> anymore. The <code>p</code> is getting pushed to the bottom. You could also declare <code>position:absolute</code> to achieve the same "clearing" effect (with the side effect that now the <code>ul</code> is taken out of the normal element flow - the <code>p</code>s will be overlapped by the <code>ul</code>.)</p>
<p><strong><a href="http://jsfiddle.net/Mvv8w/4/">See the example fiddle</a></strong></p>
<p>If you are into the technical stuff, compare the according paragraphs of the CSS spec:</p>
<p><a href="http://www.w3.org/TR/CSS21/visudet.html#normal-block">§10.6.3 Block-level non-replaced elements in normal flow when 'overflow' computes to 'visible'</a><br>
and<br>
<a href="http://www.w3.org/TR/CSS21/visudet.html#root-height">§10.6.7 'Auto' heights for block formatting context roots</a>. (Thanks to BoltClock for digging out the links).</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>ul{
list-style-type:none;
margin:0; padding:0;
background-color:#dddddd;
border:2px solid red;
}
li{
float:left;
}
a{
display:block;
width:60px;
background-color:#555;
color:white;
}
p{
margin:0;
outline:2px dotted blue;
}
#two{
clear:both;
overflow:hidden;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code>No overflow:
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
<p>Notice the collapsed ul - no background-color visible, collapsed border and this paragraph treats the lis as regular floats </p>
<br>
With overflow: hidden
<ul id="two">
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
<p>the ul reappeared - it now contains the child li's - the float is cleared</p></code></pre>
</div>
</div>
</p> |
16,075,446 | How to protect the Apps Script code in a Google spreadsheet? | <p>I have written some code for my Google spreadsheet with the script editor.</p>
<p>I want to share this spreadsheet with my clients but I don't want to share the code I have written.</p>
<p>This code adds a menu to my spreadsheet which contains useful functions that should work/run when my clients open this spreadsheet with condition applied that: they shouldn't be able to see its code.</p>
<p>This is easy with Excel, but with Google spreadsheet I don't know. . I have searched a lot on Google but they all gives the idea about how to share a spreadsheet. For example in "View" mode, but in that case there is a problem: my menu function, which adds a menu, is "onOpen" and doesn't start when my clients open it.</p>
<p>How to implement this in Google Spreadsheet?</p> | 48,082,209 | 6 | 3 | null | 2013-04-18 05:53:34.947 UTC | 21 | 2021-05-11 17:53:24.89 UTC | 2015-12-23 04:11:34.963 UTC | user3717023 | null | null | 1,283,171 | null | 1 | 42 | google-apps-script|google-sheets | 43,348 | <h1>Short Answer</h1>
<p><a href="https://developers.google.com/apps-script/add-ons/publish" rel="nofollow noreferrer">Publish</a> your script as an editor add-on or as a Google Workspace add-on. Bear in mind that you could make it private, by selecting unlisted or making it available only for your G Suite / Google Workspace organization.</p>
<h1>Explanation</h1>
<p>Add-ons were added on 2014. This is better than using a library because there will be nothing shared from your add-on.</p>
<p>Please note that</p>
<ul>
<li>it's not possible to access Google Apps Script server-side code by using Chrome Developer Tools or another similar software.</li>
<li>there are some restrictions for add-ons, study them carefully as maybe this alternative will not work for you.</li>
<li>nowadays add-ons require a Google Cloud Project and an oAuth consent screen. If the add-on will be shared with external users it will requires an oAuth verification and an app review.</li>
</ul>
<p>If publishing as add-on is not an option for you, you should rethink your solution considering the use of a web application, using the Apps Script API or the Google Sheets API.</p>
<h1>References</h1>
<ul>
<li><a href="https://stackoverflow.com/q/37806779/1595451">Get code from my google spreadsheet addon after publishing</a></li>
<li><a href="https://stackoverflow.com/q/32878136/1595451">Google Apps Script Add-On Source Code/Security</a></li>
<li><a href="https://gsuite-developers.googleblog.com/2014/03/add-ons.html" rel="nofollow noreferrer">Build add-ons for Google Docs and Sheets</a></li>
<li><a href="https://developers.google.com/apps-script/add-ons/" rel="nofollow noreferrer">Develop Add-ons for Google Sheets, Docs, Slides, Forms, and Gmail</a></li>
<li><a href="https://plus.google.com/communities/117193953428311185494" rel="nofollow noreferrer">Developing Add-ons for G Suite G+ Community</a></li>
</ul> |
27,330,446 | Getting a fatal error in git for multiple stage entries | <p>Using Git version 2.2.0 with unity game engine on OS X, and wanted to commit my code. I added everything and did not get an error message. then commit -m , and got this error message:</p>
<pre><code>fatal: multiple stage entries for merged file 'Assets/Prefabs/Resources'
</code></pre>
<p>Not noticing it I pushed, that didn't give an error message, in fact said <code>Everything up-to-date</code>
So I checked bitbucket (where the repo is held) and it didn't show my commit. so I checked my local log and that also does not show my commit.</p>
<p>I've looked into google for an answer... and nothing. what is this error? and how can I fix it?</p> | 27,481,661 | 7 | 6 | null | 2014-12-06 10:00:08.32 UTC | 51 | 2019-01-02 16:17:05.77 UTC | 2014-12-06 19:08:10.01 UTC | null | 1,371,285 | null | 1,371,285 | null | 1 | 241 | git | 63,295 | <p>The first workaround, which seems to work with recent versions of Git (2.3+, Q2+ 2015) is mentioned in <a href="https://stackoverflow.com/users/2403277/grant">grant</a>'s <a href="https://stackoverflow.com/a/29261818/6309">more up-to-date answer</a>:</p>
<ol>
<li><p>Delete the index</p>
<pre><code>$ rm .git/index
</code></pre></li>
<li><p>Add all</p>
<pre><code>$ git add -A
</code></pre></li>
<li><p>Commit</p>
<pre><code>$ git commit -a
</code></pre></li>
</ol>
<hr>
<p>Original answer (late 2014)<br>
The usual workaround is to:</p>
<ul>
<li>clone again the remote repo into a new local repo</li>
<li><p>add the changes from the first repo to the second one:</p>
<pre><code>$ cd /patH/to/second/cloned/repo
$ git --work-tree=/path/to/first/repo add .
</code></pre></li>
</ul>
<p>You can see this error message in <a href="https://github.com/git/git/blob/9abc44b681a669c67d071d858c8aad21f65a0956/read-cache.c#L1484" rel="noreferrer"><code>read-cache.c</code></a>, discussed in this patch ("<a href="http://git.661346.n2.nabble.com/PATCH-read-cache-c-Ensure-unmerged-entries-are-removed-td7616733i40.html" rel="noreferrer"><code>read-cache.c</code>: Ensure unmerged entries are removed</a> "), and introduced in the <a href="https://github.com/git/git/commit/15999d0be8179fb7a2e6eafb931d25ed65df50aa" rel="noreferrer">Git 2.2 commit</a>.<br>
Since this is so recent, it is possible that <em>downgrading</em> Git to 2.1 would be enough to not be affected by that patch.</p>
<p>The <a href="https://stackoverflow.com/users/1371285/daniel-toebe">OP Daniel Toebe</a> adds <a href="https://stackoverflow.com/questions/27330446/getting-a-fatal-error-in-git-for-multiple-stage-entries/27481661#comment43579939_27481661">in the comments</a>:</p>
<blockquote>
<p>The issue happened on my macbook, which decided to fail on me, and another computer mishap put me way behind on my projects.</p>
</blockquote> |
19,699,122 | Mock private method in the same class that is being tested | <p>I have a Java class named, <code>MyClass</code>, that I want to test with JUnit. The public method, <code>methodA</code>, that I want to test calls a private method, <code>methodB</code>, in the same class to determine which conditional path to follow. My goal is to write JUnit tests for the different paths in <code>methodA</code>. Also, <code>methodB</code> calls a service, so I do not want it to actually be executed when I run the JUnit tests.</p>
<p>What is the best way to mock <code>methodB</code> and control its return so that I can test different paths for 'methodA'?</p>
<p>I prefer to use JMockit when writing mocks, so I am specifically interested in any answer that applies to JMockit.</p>
<p>Here is my example class:</p>
<pre><code>public class MyClass {
public String methodA(CustomObject object1, CustomObject object2) {
if(methodB(object1, object2)) {
// Do something.
return "Result";
}
// Do something different.
return "Different Result";
}
private boolean methodB(CustomObject custObject1, CustomObject custObject2) {
/* For the sake of this example, assume the CustomObject.getSomething()
* method makes a service call and therefore is placed in this separate
* method so that later an integration test can be written.
*/
Something thing1 = cobject1.getSomething();
Something thing2 = cobject2.getSomething();
if(thing1 == thing2) {
return true;
}
return false;
}
}
</code></pre>
<p>This is what I have so far:</p>
<pre><code>public class MyClassTest {
MyClass myClass = new MyClass();
@Test
public void test_MyClass_methodA_enters_if_condition() {
CustomObject object1 = new CustomObject("input1");
CustomObject object2 = new CustomObject("input2");
// How do I mock out methodB here to return true?
assertEquals(myClass.methodA(object1, object2), "Result");
}
@Test
public void test_MyClass_methodA_skips_if_condition() {
CustomObject object1 = new CustomObject("input1");
CustomObject object2 = new CustomObject("input2");
// How do I mock out methodB here to return false?
assertEquals(myClass.methodA(object1, object2), "Different Result");
}
}
</code></pre>
<p>Thanks!</p> | 19,704,395 | 5 | 4 | null | 2013-10-31 05:34:49.05 UTC | 7 | 2013-11-08 15:05:06.303 UTC | 2013-10-31 05:51:46.78 UTC | null | 2,796,738 | null | 2,796,738 | null | 1 | 18 | java|unit-testing|junit|mocking|jmockit | 56,928 | <p>To give the answer you asked for (using JMockit's partial mocking):</p>
<pre><code>public class MyClassTest
{
@Tested MyClass myClass;
@Test
public void test_MyClass_methodA_enters_if_condition() {
final CustomObject object1 = new CustomObject("input1");
final CustomObject object2 = new CustomObject("input2");
new NonStrictExpectations(myClass) {{
invoke(myClass, "methodB", object1, object2); result = true;
}};
assertEquals("Result", myClass.methodA(object1, object2));
}
@Test
public void test_MyClass_methodA_skips_if_condition() {
final CustomObject object1 = new CustomObject("input1");
final CustomObject object2 = new CustomObject("input2");
new NonStrictExpectations(myClass) {{
invoke(myClass, "methodB", object1, object2); result = false;
}};
assertEquals("Different Result", myClass.methodA(object1, object2));
}
}
</code></pre>
<p>However, I would <em>not</em> recommend doing it like that. In general, <code>private</code> methods should not be mocked. Instead, mock the actual external dependency of your unit under test (the <code>CustomObject</code> in this case):</p>
<pre><code>public class MyTestClass
{
@Tested MyClass myClass;
@Mocked CustomObject object1;
@Mocked CustomObject object2;
@Test
public void test_MyClass_methodA_enters_if_condition() {
new NonStrictExpectations() {{
Something thing = new Something();
object1.getSomething(); result = thing;
object2.getSomething(); result = thing;
}};
assertEquals("Result", myClass.methodA(object1, object2));
}
@Test
public void test_MyClass_methodA_skips_if_condition() {
new NonStrictExpectations() {{
object1.getSomething(); result = new Something();
object2.getSomething(); result = new Something();
}};
assertEquals("Different Result", myClass.methodA(object1, object2));
}
}
</code></pre> |
19,608,175 | Direct download link to ASP.NET MVC 5 for VS 2012 | <p>I'm looking for a direct link to ASP.NET MVC 5 install package for Visual Studio 2012, in downloads of asp.net i found only packages with Azure, but i need package without it.</p> | 19,611,776 | 4 | 6 | null | 2013-10-26 15:02:51.903 UTC | 2 | 2015-09-25 07:12:14.493 UTC | null | null | null | null | 1,093,582 | null | 1 | 14 | asp.net-mvc|asp.net-mvc-5 | 54,294 | <p>Per <a href="https://stackoverflow.com/a/19124665/132528">this Stackoverflow answer</a>, and <a href="https://connect.microsoft.com/VisualStudio/feedback/details/806348/razor-intellisense-does-not-work-in-visual-studio-2012-after-upgrading-to-mvc-5-razor-3" rel="nofollow noreferrer">one of the responses to this Razor Intellisense bug</a>, Microsoft does not plan on shipping tooling for VS2012 and MVC5 until November 2013.</p>
<p><strong>UPDATE</strong></p>
<p>Per IT Hit WebDav's comments, I wanted to update that <a href="http://blogs.msdn.com/b/webdev/archive/2013/11/18/announcing-release-of-asp-net-and-web-tools-2013-1-for-visual-studio-2012.aspx" rel="nofollow noreferrer">Microsoft has released ASP.NET and Web Tools 2013.1 for VS2012</a>.</p> |
4,976,566 | What do GC_FOR_MALLOC, GC_EXPLICIT, and other GC_* mean in Android Logcat? | <p>If you see the Android logs, you may see a lot of those things.</p>
<p>What do they mean, knowing those may help us doing better memory allocations.</p>
<p>Example:</p>
<pre><code> 28470 dalvikvm D GC_FOR_MALLOC freed 665 objects / 239992 bytes in 71ms
28470 dalvikvm D GC_FOR_MALLOC freed 673 objects / 240288 bytes in 87ms
21940 dalvikvm D GC_EXPLICIT freed 4802 objects / 185320 bytes in 78ms
28470 dalvikvm D GC_FOR_MALLOC freed 666 objects / 240536 bytes in 63ms
</code></pre> | 4,976,731 | 3 | 0 | null | 2011-02-12 05:41:06.98 UTC | 47 | 2013-10-16 10:12:10.873 UTC | 2011-06-13 10:31:25.653 UTC | null | 11,238 | null | 11,238 | null | 1 | 64 | android|garbage-collection|logcat | 31,451 | <p><strong>GC_FOR_MALLOC</strong> means that the GC was triggered because there wasn't enough memory left on the heap to perform an allocation. Might be triggered when new objects are being created.</p>
<p><strong>GC_EXPLICIT</strong> means that the garbage collector has been explicitly asked to collect, instead of being triggered by high water marks in the heap. Happens all over the place, but most likely when a thread is being killed or when a binder communication is taken down.</p>
<p>There are a few others as well:</p>
<p><strong>GC_CONCURRENT</strong> Triggered when the heap has reached a certain amount of objects to collect.</p>
<p><strong>GC_EXTERNAL_ALLOC</strong> means that the the VM is trying to reduce the amount of memory used for collectable objects, to make room for more non-collectable.</p>
<p><strong>Update:</strong> There has been a name-change of the first event in later versions of Android. It's now called "GC_FOR_ALLOC".
There is also a new event available, although very rare in modern phones:
<strong>GC_BEFORE_OOM</strong> means that the system is running really low on memory, and that there is a final GC performed, in order to avoid calling the low memory killer.</p> |
9,225,748 | Why does the async keyword exist | <p>Browsing through the channel 9 msdn videos I found the following unanswered comment and was hoping someone could possibly explain it? </p>
<blockquote>
<p>I dont get the point of the async keyword. Why not just allow the
await keyword anytime the method returns Task, just like iterators
can yield return on any method that returns an IEnumerable.</p>
</blockquote>
<p>I'm sure there is a good reason, I'd just like to understand why the above suggestion was not possible.</p> | 9,225,932 | 4 | 5 | null | 2012-02-10 09:46:28.3 UTC | 8 | 2020-05-02 08:24:11.757 UTC | 2012-08-07 12:30:05.75 UTC | null | 314,661 | null | 314,661 | null | 1 | 44 | c#|.net|asynchronous|async-ctp | 3,676 | <p>It was introduced mainly to avoid backward compatibility issues. If the <code>async</code>-ness of a method must be inferred by the compiler (that would be through the detection of <code>await</code> keywords), then there are subtle scenarios where existing code would suddenly be treated differently, notably when you have identifiers (variable or function names called <code>await</code>).</p>
<p>A full explanation is here: <a href="https://docs.microsoft.com/en-us/archive/blogs/ericlippert/asynchrony-in-c-5-part-six-whither-async" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/archive/blogs/ericlippert/asynchrony-in-c-5-part-six-whither-async</a></p> |
18,621,990 | Bash get exit status of command when 'set -e' is active? | <p>I generally have <code>-e</code> set in my Bash scripts, but occasionally I would like to run a command and get the return value.</p>
<p>Without doing the <code>set +e; some-command; res=$?; set -e</code> dance, how can I do that?</p> | 18,622,662 | 5 | 2 | null | 2013-09-04 19:16:46.62 UTC | 9 | 2021-08-29 01:23:13.133 UTC | null | null | null | null | 71,522 | null | 1 | 70 | bash | 9,360 | <p>From the <code>bash</code> manual:</p>
<blockquote>
<p>The shell does not exit if the command that fails is [...] part of any command executed in a && or || list [...].</p>
</blockquote>
<p>So, just do:</p>
<pre><code>#!/bin/bash
set -eu
foo() {
# exit code will be 0, 1, or 2
return $(( RANDOM % 3 ))
}
ret=0
foo || ret=$?
echo "foo() exited with: $ret"
</code></pre>
<p>Example runs:</p>
<pre><code>$ ./foo.sh
foo() exited with: 1
$ ./foo.sh
foo() exited with: 0
$ ./foo.sh
foo() exited with: 2
</code></pre>
<p>This is the canonical way of doing it.</p> |
18,299,669 | MVC 4 ViewModel not being sent back to Controller | <p>I can't seem to figure out how to send back the entire ViewModel to the controller to the 'Validate and Save' function.</p>
<p>Here is my controller: </p>
<pre><code>[HttpPost]
public ActionResult Send(BitcoinTransactionViewModel transaction)
{
}
</code></pre>
<p>Here is the form in the view:</p>
<pre><code><li class="check">
<h3>Transaction Id</h3>
<p>@Html.DisplayFor(m => m.Transaction.TransactionId)</p>
</li>
<li class="money">
<h3>Deposited Amount</h3>
<p>@Model.Transaction.Amount.ToString() BTC</p>
</li>
<li class="time">
<h3>Time</h3>
<p>@Model.Transaction.Time.ToString()</p>
</li>
@using (Html.BeginForm("Send", "DepositDetails", FormMethod.Post, new { transaction = Model }))
{
@Html.HiddenFor(m => m.Token);
@Html.HiddenFor(m => m.Transaction.TransactionId);
@Html.TextBoxFor(m => m.WalletAddress, new { placeholder = "Wallet Address", maxlength = "34" })
<input type="submit" value="Send" />
@Html.ValidationMessage("walletAddress", new { @class = "validation" })
}
</code></pre>
<p>When i click on submit, the conroller contains the correct value of the walletAddress field but <code>transaction.Transaction.Time</code>, <code>transaction.Transaction.Location</code>, <code>transaction.Transaction.TransactionId</code> are empty.</p>
<p>Is there a way i could pass the entire Model back to the controller?</p>
<p>Edit:</p>
<p>When i dont even receive the <code>walletAddress</code> in the controller. Everything gets nulled!
When i remove this line alone: <code>@Html.HiddenFor(m => m.Transaction.TransactionId);</code>
it works and i get the Token property on the controller, but when i add it back, all the properties of the <code>transaction</code> object on the controller are NULL.</p>
<p>Here is the BitcoinTransactionViewModel:</p>
<pre><code>public class BitcoinTransactionViewModel
{
public string Token { get; set; }
public string WalletAddress { get; set; }
public BitcoinTransaction Transaction { get; set; }
}
public class BitcoinTransaction
{
public int Id { get; set; }
public BitcoinTransactionStatusTypes Status { get; set; }
public int TransactionId { get; set; }
public decimal Amount { get; set; }
public DateTime Time { get; set; }
public string Location { get; set; }
}
</code></pre>
<p>Any ideas?</p>
<p><strong>EDIT: I figured it out, its in the marked answer below...</strong></p> | 19,765,380 | 9 | 0 | null | 2013-08-18 13:37:10.023 UTC | 10 | 2016-02-05 08:29:17.96 UTC | 2013-11-04 10:05:43.81 UTC | null | 1,176,547 | null | 1,176,547 | null | 1 | 29 | c#|asp.net-mvc|asp.net-mvc-4 | 83,094 | <p>OK, I've been working on something else and bumpend into the same issue all over again.
Only this time I figured out how to make it work!</p>
<p><em>Here's the answer for anyone who might be interested:</em></p>
<p>Apparently, there is a naming convention. Pay attention:</p>
<p><strong>This doesn't work:</strong></p>
<pre><code>// Controller
[HttpPost]
public ActionResult Send(BitcoinTransactionViewModel transaction)
{
}
// View
@using (Html.BeginForm("Send", "DepositDetails", FormMethod.Post, new { transaction = Model }))
{
@Html.HiddenFor(m => m.Token);
@Html.HiddenFor(m => m.Transaction.TransactionId);
.
.
</code></pre>
<p><strong>This works:</strong></p>
<pre><code>// Controller
[HttpPost]
public ActionResult Send(BitcoinTransactionViewModel **RedeemTransaction**)
{
}
// View
@using (Html.BeginForm("Send", "DepositDetails", FormMethod.Post, new { **RedeemTransaction** = Model }))
{
@Html.HiddenFor(m => m.Token);
@Html.HiddenFor(m => m.Transaction.TransactionId);
.
.
</code></pre>
<p>In other words - a naming convention error! There was a naming ambiguity between the <code>Model.Transaction</code> property and my <code>transaction</code> form field + controller parameter. Unvelievable.</p>
<p>If you're experiencing the same problems make sure that your controller parameter name is unique - try renaming it to MyTestParameter or something like this... </p>
<p>In addition, if you want to send form values to the controller, you'll need to include them as hidden fields, and you're good to go.</p> |
20,316,299 | Formatting output of Counter | <p>I have used Counter to count the number of occurrence of the list items. I have trouble in displaying it nicely. For the below code,</p>
<pre><code>category = Counter(category_list)
print category
</code></pre>
<p>the following is the output,</p>
<pre><code>Counter({'a': 8508, 'c': 345, 'w': 60})
</code></pre>
<p>I have to display the above result as follows,</p>
<pre><code>a 8508
c 345
w 60
</code></pre>
<p>I tried to iterate over the counter object but I'm unsuccessful. Is there a way to print the output of the Counter operation nicely?</p> | 20,316,330 | 5 | 2 | null | 2013-12-01 19:35:50.347 UTC | 6 | 2021-10-11 15:19:30.39 UTC | 2016-01-20 08:31:34.273 UTC | null | 2,301,450 | user835281 | null | null | 1 | 29 | python | 46,968 | <p><code>Counter</code> is essentially a dictionary, thus it has keys and corresponding values - just like the ordinary dictionary.
From the <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="noreferrer">documentation</a>:</p>
<blockquote>
<p>A Counter is a <em>dict</em> subclass for counting hashable objects. It is an
unordered collection where elements are stored as dictionary keys and
their counts are stored as dictionary values.</p>
</blockquote>
<p>You can use this code:</p>
<pre><code>>>> category = Counter({'a': 8508, 'c': 345, 'w': 60})
>>> category.keys()
dict_keys(['a', 'c', 'w'])
>>> for key, value in category.items():
... print(key, value)
...
a 8508
c 345
w 60
</code></pre>
<p>However, <a href="https://stackoverflow.com/q/15479928/2301450">you shouldn't rely on the order of keys in dictionaries</a>.</p>
<p><a href="http://docs.python.org/3/library/collections.html#collections.Counter.most_common" rel="noreferrer"><code>Counter.most_common</code></a> is very useful. Citing the documentation I linked:</p>
<blockquote>
<p>Return a list of the n most common elements and their counts <strong>from the
most common to the least</strong>. If <em>n</em> is not specified, <em>most_common()</em> returns
all elements in the counter. Elements with equal counts are ordered
arbitrarily.</p>
</blockquote>
<p>(emphasis added)</p>
<pre><code>>>> category.most_common()
[('a', 8508), ('c', 345), ('w', 60)]
>>> for value, count in category.most_common():
... print(value, count)
...
a 8508
c 345
w 60
</code></pre> |
15,168,771 | Pointer to a string in C? | <pre><code>char *ptrChar;
</code></pre>
<p>I know that <code>ptrChar</code> is a pointer to <strong>char</strong>. What's the command for a pointer to <strong>string</strong>?</p>
<p><strong>Edit:</strong> If it's the same (ptr to char vs. ptr to string) — what does the variable definition below represent?</p>
<pre><code>char (*ptr)[N];
</code></pre>
<p>I'm confused.</p> | 15,168,795 | 3 | 2 | null | 2013-03-01 23:42:21.073 UTC | 21 | 2022-08-18 18:36:24.563 UTC | 2016-08-05 23:37:47.807 UTC | null | 15,168 | null | 1,980,750 | null | 1 | 15 | c|string|pointers | 155,276 | <p>The same notation is used for pointing at a single character or the first character of a null-terminated string:</p>
<pre><code>char c = 'Z';
char a[] = "Hello world";
char *ptr1 = &c;
char *ptr2 = a; // Points to the 'H' of "Hello world"
char *ptr3 = &a[0]; // Also points to the 'H' of "Hello world"
char *ptr4 = &a[6]; // Points to the 'w' of "world"
char *ptr5 = a + 6; // Also points to the 'w' of "world"
</code></pre>
<p>The values in <code>ptr2</code> and <code>ptr3</code> are the same; so are the values in <code>ptr4</code> and <code>ptr5</code>. If you're going to treat some data as a string, it is important to make sure it is null terminated, and that you know how much space there is for you to use. Many problems are caused by not understanding what space is available and not knowing whether the string was properly null terminated.</p>
<p>Note that all the pointers above can be dereferenced as if they were an array:</p>
<pre><code> *ptr1 == 'Z'
ptr1[0] == 'Z'
*ptr2 == 'H'
ptr2[0] == 'H'
ptr2[4] == 'o'
*ptr4 == 'w'
ptr4[0] == 'w'
ptr4[4] == 'd'
ptr5[0] == ptr3[6]
*(ptr5+0) == *(ptr3+6)
</code></pre>
<hr>
<h3>Late addition to question</h3>
<blockquote>
<p>What does <code>char (*ptr)[N];</code> represent?</p>
</blockquote>
<p>This is a more complex beastie altogether. It is a pointer to an array of <code>N</code> characters. The type is quite different; the way it is used is quite different; the size of the object pointed to is quite different.</p>
<pre><code>char (*ptr)[12] = &a;
(*ptr)[0] == 'H'
(*ptr)[6] == 'w'
*(*ptr + 6) == 'w'
</code></pre>
<p>Note that <code>ptr + 1</code> points to undefined territory, but points 'one array of 12 bytes' beyond the start of <code>a</code>. Given a slightly different scenario:</p>
<pre><code>char b[3][12] = { "Hello world", "Farewell", "Au revoir" };
char (*pb)[12] = &b[0];
</code></pre>
<p>Now:</p>
<pre><code>(*(pb+0))[0] == 'H'
(*(pb+1))[0] == 'F'
(*(pb+2))[5] == 'v'
</code></pre>
<p>You probably won't come across pointers to arrays except by accident for quite some time; I've used them a few times in the last 25 years, but so few that I can count the occasions on the fingers of one hand (and several of those have been answering questions on Stack Overflow). Beyond knowing that they exist, that they are the result of taking the address of an array, and that you probably didn't want it, you don't really need to know more about pointers to arrays.</p> |
15,243,798 | Advantages of using Bundle instead of direct Intent putExtra() in Android | <p>In my android application I'm always using direct <code>putExtra()</code> function of <code>Intent</code> class to pass any number of value to new <code>Activity</code>.<br/>
Like this:</p>
<pre><code>Intent i = new Intent(this, MyActivity.class);
i.putExtra(ID_EXTRA1, "1");
i.putExtra(ID_EXTRA2, "111");
startActivity(i);
</code></pre>
<p>I know about <code>Bundle</code> in Android and I have seen people are using <code>Bundle</code> for passing values to new <code>Activity</code>.<br/>
Like this:</p>
<pre><code>Intent intent = new Intent(this, MyActivity.class);
Bundle extras = new Bundle();
extras.putString("EXTRA_USERNAME","my_username");
extras.putString("EXTRA_PASSWORD","my_password");
intent.putExtras(extras);
startActivity(intent);
</code></pre>
<p>Here I have 2 doubts.<br/>Why should I use <code>Bundle</code> if I can pass values to new <code>Activity</code> by putting it directly to <code>Intent</code>?<br/>
What are the advantages of using <code>Bundle</code> instead of direct <code>Intent</code> <code>putExtra()</code>?</p> | 15,243,947 | 4 | 0 | null | 2013-03-06 09:44:56.553 UTC | 26 | 2020-10-18 11:51:13.477 UTC | null | null | null | null | 1,866,804 | null | 1 | 84 | android|android-intent|android-activity|bundle|extra | 40,273 | <p>It makes little (if any difference). The code using an additional bundle is slightly heavier (it won't make any difference in any practical application) and slightly easier to manage, being more general.</p>
<p>If one day you decide that - before sending information inside an intent - you want to serialize the data to database - it will be a bit cleaner to have a bundle that you can serialize, add to an intent and then feed to a PendingBundle - all with one object.</p>
<p><strong>[update]</strong></p>
<p>A clarification (because of some other answers).</p>
<p>Extras <strong>is</strong> an additional bundle that each Intent might carry (but doesn't have to), so there is no alternative between using a bundle or not using it. You are using a bundle either way.</p>
<p>The first time you use <code>putExtra</code>, a <code>mExtras</code> bundle inside Intent is initialized and all the following putExtra are delegated to it. The bundle itself is inaccessible to you (this is by design, to avoid certain kind of bugs).</p>
<p>putExtras <strong>does not</strong> put your bundle inside Intent. Instead, it copies it over to the current intent bundle (or creates one, as with <code>putExtra</code>). This is why it's slightly heavier (you have two bundles instead of one and pay the price of copying).</p>
<p>The crux is - if you use <code>putExtras</code>, you still cannot access the real bundle inside the intent. BUT - you have a copy for whatever else you might want to do with it. Like keep around to copy into another intent (if you send a lot of similar intents).</p> |
8,041,206 | Android Fragment onCreateView vs. onActivityCreated | <p>I know that a fragment's view hierarchy has to be inflated in onCreateView, but what other functionality can be in onCreateView vs. what should wait for onActivityCreated? My current implementation uses separate activities for everything, and a typical activity does most of its work in its onCreate method, including inflating the view, setting the content view, initializing the various widgets with data, setting up listeners, etc.</p>
<p>So can this probably all be moved into onCreateView, or should some functions be put into an onActivityCreated method instead?</p> | 8,199,357 | 2 | 0 | null | 2011-11-07 19:00:52.4 UTC | 31 | 2020-08-03 19:48:16.373 UTC | 2012-04-16 03:07:37.1 UTC | null | 1,197,795 | null | 446,874 | null | 1 | 75 | android|android-fragments|lifecycle|android-activity|android-lifecycle | 39,016 | <p>If your view is static, then moving any code to the onActivityCreated method is not necessary. But when you - for instance, fill some lists from the adapter, then you should do it in the onActivityCreated method as well as restoring the view state when setRetainInstance used to do so. </p>
<p>Also accessing the view hierarchy of the parent activity must be done in the onActivityCreated, not sooner.</p> |
8,535,635 | Can Doxygen easily be configured to recognise TODO and FIXME lines? | <p>I've just installed and setup an instance of Doxygen, but out of the box it only finds TODO tags in code when marked in a block like:</p>
<pre><code>/**
* @todo Foo
*/
</code></pre>
<p>It doesn't seem to find:</p>
<pre><code>// TODO Foo
// FIXME Bar
// @todo Baz
</code></pre>
<p>Most IDE's and bug trackers which handle parsing are fine with them, is there an easy way to configure Doxygen to find them and list them as ToDo items?</p> | 8,726,335 | 1 | 4 | null | 2011-12-16 14:34:40.813 UTC | 8 | 2019-04-22 06:30:01.143 UTC | null | null | null | null | 28,884 | null | 1 | 28 | doxygen|todo | 19,253 | <p>There are a number of examples and methods we can use:</p>
<ul>
<li><p>For a one line comment with valid doxygen commands (e.g. <code>\todo</code>) you would use</p>
<pre><code>/// \todo Some (optional) text
</code></pre>
<p>Note the three forward slashes, not the usual two. See point three on the second list in the <a href="http://www.doxygen.nl/manual/docblocks.html" rel="noreferrer">special documentation blocks</a> section of the doxygen documentation. This can be used to add new todo items to your source code.</p></li>
<li><p>Generally one can define custom tags (like <code>FIXME</code>) by defining an alias in the Doxygen configuration file. For example</p>
<pre><code>ALIASES += FIXME="\todo"
</code></pre>
<p>which will allow you to write <code>\FIXME</code> in your source code and the comments prefixed with <code>\FIXME</code> will be included in you todo list in the final documentation. The problem here is that you have to prefix your aliases with the <code>\</code> (or <code>@</code>) symbol and begin the comment with three leading forward slashes which, if you want to leave the <code>FIXME</code>s in your code as they are, is not an option.</p></li>
<li><p>Finally, an alternative method, and what I think you are looking for, would be to preprocess your source files using the <a href="http://www.doxygen.nl/manual/config.html#cfg_input_filter" rel="noreferrer"><code>INPUT_FILTER</code></a> configuration file option. This option defines a command that is applied to each of your source files before doxygen builds the documentation, so we can define a command which replaces instances of <code>TODO</code> and <code>FIXME</code> with valid doxygen markup.</p>
<pre><code> INPUT_FILTER = "sed -e 's/\/\/.*FIXME/\/\/\/ \\todo/'"
</code></pre>
<p>This filter replaces all instances of <code>// FIXME</code> (with any amount (or none) of whitespace between <code>//</code> and <code>FIXME</code>) with <code>/// \todo</code>. This substitution is made internally by doxygen only: your source files are not modified on disk.</p></li>
</ul>
<p>Note: This last point was inspired by the accepted answer to the question <a href="https://stackoverflow.com/a/3143600/623518">Getting doxygen and MSVC TODO tags to work together</a>. However, that answer used the <code>FILE_VERSION_FILTER</code> configuration option rather than <code>INPUT_FILTER</code>. I think that the latter (<code>INPUT_FILTER</code>) is actually more appropriate here. Also, the <code>sed</code> command used in that answer does not work for me.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.