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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4,149,276 | How to convert "camelCase" to "Camel Case"? | <p>I’ve been trying to get a JavaScript regex command to turn something like <code>"thisString"</code> into <code>"This String"</code> but the closest I’ve gotten is replacing a letter, resulting in something like <code>"Thi String"</code> or <code>"This tring"</code>. Any ideas?</p>
<p>To clarify I can handle the simplicity of capitalizing a letter, I’m just not as strong with RegEx, and splitting <code>"somethingLikeThis"</code> into <code>"something Like This"</code> is where I’m having trouble.</p> | 4,149,393 | 12 | 3 | null | 2010-11-10 21:30:59.047 UTC | 38 | 2022-04-29 17:48:07.923 UTC | 2019-08-15 17:10:10.833 UTC | null | 4,642,212 | null | 453,211 | null | 1 | 202 | javascript|regex | 88,881 | <pre><code>"thisStringIsGood"
// insert a space before all caps
.replace(/([A-Z])/g, ' $1')
// uppercase the first character
.replace(/^./, function(str){ return str.toUpperCase(); })
</code></pre>
<p>displays </p>
<pre><code>This String Is Good
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>(function() {
const textbox = document.querySelector('#textbox')
const result = document.querySelector('#result')
function split() {
result.innerText = textbox.value
// insert a space before all caps
.replace(/([A-Z])/g, ' $1')
// uppercase the first character
.replace(/^./, (str) => str.toUpperCase())
};
textbox.addEventListener('input', split);
split();
}());</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#result {
margin-top: 1em;
padding: .5em;
background: #eee;
white-space: pre;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
Text to split
<input id="textbox" value="thisStringIsGood" />
</div>
<div id="result"></div></code></pre>
</div>
</div>
</p> |
4,444,477 | How to tell if a string contains a certain character in JavaScript? | <p>I have a page with a textbox where a user is supposed to enter a 24 character (letters and numbers, case insensitive) registration code. I used <code>maxlength</code> to limit the user to entering 24 characters.</p>
<p>The registration codes are typically given as groups of characters separated by dashes, but I would like for the user to enter the codes without the dashes.</p>
<p>How can I write my JavaScript code without jQuery to check that a given string that the user inputs does not contain dashes, or better yet, only contains alphanumeric characters?</p> | 4,444,497 | 21 | 4 | null | 2010-12-14 21:35:13.307 UTC | 61 | 2022-03-06 05:35:12.5 UTC | 2017-12-26 11:26:56.493 UTC | null | 680,421 | null | 238,260 | null | 1 | 413 | javascript|string | 951,303 | <p>To find "hello" in <code>your_string</code></p>
<pre><code>if (your_string.indexOf('hello') > -1)
{
alert("hello found inside your_string");
}
</code></pre>
<p>For the alpha numeric you can use a regular expression:</p>
<p><a href="http://www.regular-expressions.info/javascript.html" rel="noreferrer">http://www.regular-expressions.info/javascript.html</a></p>
<p><a href="https://stackoverflow.com/questions/336210/regular-expression-for-alphanumeric-and-underscores">Alpha Numeric Regular Expression</a></p> |
4,224,606 | How to check whether a script is running under Node.js? | <p>I have a script I am requiring from a Node.js script, which I want to keep JavaScript engine independent.</p>
<p>For example, I want to do <code>exports.x = y;</code> only if it’s running under Node.js. How can I perform this test?</p>
<hr>
<p>When posting this question, I didn’t know the Node.js modules feature is based on <a href="http://www.commonjs.org/" rel="noreferrer">CommonJS</a>.</p>
<p>For the specific example I gave, a more accurate question would’ve been:</p>
<p>How can a script tell whether it has been required as a CommonJS module?</p> | 5,197,219 | 22 | 8 | null | 2010-11-19 11:41:39.187 UTC | 41 | 2022-08-01 13:56:06.24 UTC | 2019-09-16 18:31:44.207 UTC | null | 4,642,212 | null | 299,920 | null | 1 | 178 | javascript|node.js|commonjs | 107,589 | <p><strong>By looking for CommonJS support</strong>, this is how the <a href="http://underscorejs.org/" rel="noreferrer">Underscore.js</a> library does it:</p>
<p>Edit: to your updated question:</p>
<pre><code>(function () {
// Establish the root object, `window` in the browser, or `global` on the server.
var root = this;
// Create a reference to this
var _ = new Object();
var isNode = false;
// Export the Underscore object for **CommonJS**, with backwards-compatibility
// for the old `require()` API. If we're not in CommonJS, add `_` to the
// global object.
if (typeof module !== 'undefined' && module.exports) {
module.exports = _;
root._ = _;
isNode = true;
} else {
root._ = _;
}
})();
</code></pre>
<p>Example here retains the Module pattern.</p> |
4,210,042 | How do I exclude a directory when using `find`? | <p>How do I exclude a specific directory when searching for <code>*.js</code> files using <code>find</code>?</p>
<pre><code>find . -name '*.js'
</code></pre> | 4,210,072 | 46 | 0 | null | 2010-11-17 22:57:02.213 UTC | 535 | 2022-09-23 23:38:27.287 UTC | 2022-07-10 23:00:39.287 UTC | null | 365,102 | null | 143,269 | null | 1 | 1,896 | linux|shell|find | 1,484,910 | <p>Use the <code>-prune</code> primary. For example, if you want to exclude <code>./misc</code>:</p>
<pre><code>find . -path ./misc -prune -o -name '*.txt' -print
</code></pre>
<p>To exclude multiple directories, OR them between parentheses.</p>
<pre><code>find . -type d \( -path ./dir1 -o -path ./dir2 -o -path ./dir3 \) -prune -o -name '*.txt' -print
</code></pre>
<p>And, to exclude directories with a specific name at any level, use the <code>-name</code> primary instead of <code>-path</code>.</p>
<pre class="lang-sh prettyprint-override"><code>find . -type d -name node_modules -prune -o -name '*.json' -print
</code></pre> |
14,483,083 | How to get notifications when the headphones are plugged in/out? Mac | <p>I'd like to get notified when headphones are plugged in or out in the headphone jack.<br>
I've searched around for this on stackoverflow but I can't seem to find what I'm looking for for the Mac, I can only find for iOS.<br>
So, do you have any ideas on how to perform this? What I want to do with this is: when headphones are plugged out I want to programmatically pause iTunes (iOS-like feature).<br>
Thank you!</p> | 14,490,863 | 2 | 6 | null | 2013-01-23 15:22:37.753 UTC | 10 | 2020-10-29 18:58:08.203 UTC | 2013-01-23 22:50:57.873 UTC | null | 474,896 | null | 848,311 | null | 1 | 14 | objective-c|macos|cocoa|core-audio|headphones | 6,550 | <p>You can observe changes using the <code>CoreAudio</code> framework. </p>
<p>Both headphones and the speakers are data sources on the same audio output device (of type built-in). One of both will be on the audio device based on headphones being plugged in or not. </p>
<p>To get notifications you listen to changes of the active datasource on the built-in output device.</p>
<h3>1. Get the built-in output device</h3>
<p>To keep this short we'll use the default output device. In most cases this is the built-in output device. In real-life applications you'll want to loop all available devices to find it, because the default device could be set to a different audio device (soundflower or airplay for example).</p>
<pre><code>AudioDeviceID defaultDevice = 0;
UInt32 defaultSize = sizeof(AudioDeviceID);
const AudioObjectPropertyAddress defaultAddr = {
kAudioHardwarePropertyDefaultOutputDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
AudioObjectGetPropertyData(kAudioObjectSystemObject, &defaultAddr, 0, NULL, &defaultSize, &defaultDevice);
</code></pre>
<h3>2. Read its current data source</h3>
<p>The current datasource on a device is identified by an ID of type <code>UInt32</code>.</p>
<pre><code>AudioObjectPropertyAddress sourceAddr;
sourceAddr.mSelector = kAudioDevicePropertyDataSource;
sourceAddr.mScope = kAudioDevicePropertyScopeOutput;
sourceAddr.mElement = kAudioObjectPropertyElementMaster;
UInt32 dataSourceId = 0;
UInt32 dataSourceIdSize = sizeof(UInt32);
AudioObjectGetPropertyData(defaultDevice, &sourceAddr, 0, NULL, &dataSourceIdSize, &dataSourceId);
</code></pre>
<h3>3. Observe for changes to the data source</h3>
<pre><code>AudioObjectAddPropertyListenerBlock(_defaultDevice, &sourceAddr, dispatch_get_current_queue(), ^(UInt32 inNumberAddresses, const AudioObjectPropertyAddress *inAddresses) {
// move to step 2. to read the updated value
});
</code></pre>
<h3>Determine the data source type</h3>
<p>When you have the data source id as <code>UInt32</code> you can query the audio object for properties using a value transformer. For example to get the source name as string use <code>kAudioDevicePropertyDataSourceNameForIDCFString</code>. This will result in the string "Internal Speaker" or "Headphones". However this might differ based on user locale.</p>
<p>An easier way is to compare the data source id directly:</p>
<pre><code>if (dataSourceId == 'ispk') {
// Recognized as internal speakers
} else if (dataSourceId == 'hdpn') {
// Recognized as headphones
}
</code></pre>
<p>However I couldn't find any constants defined for these values, so this is kind of undocumented.</p> |
14,920,459 | Placing ViewPager as a row in ListView | <p>I try to use ViewPager as a row ins ListView but a get a bizarre behaviuor - Only the first row works, but when I scroll the list it disappears. When I scroll an empty row, suddenly the row above is being viewed.
It seems like Android creates a single pager and use it for all rows.</p>
<p>This is what I see when I launch the app:</p>
<p><img src="https://i.stack.imgur.com/GYCxg.jpg" alt="screen shot"></p>
<p>This is my row layout:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/white"
android:orientation="vertical"
android:paddingBottom="2dp" >
<TextView
android:id="@+id/textViewFriendName"
style="@style/TextStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/myFriendsBg"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:text="TextView" />
<View style="@style/DividerHorizontalStyle_gray" />
<android.support.v4.view.ViewPager
android:id="@+id/pagerMyFriendHabits"
android:layout_width="match_parent"
android:layout_height="@dimen/DefaultImageHeight" />
<View style="@style/DividerHorizontalStyle" />
</LinearLayout>
</code></pre>
<p>This is my List adapter:</p>
<pre><code>public class MyFriendsAdapter extends BaseAdapter implements OnClickListener {
private ArrayList<UiD_UserFriend> mItems;
private Context mContext;
private FragmentManager mFragmentManager;
public MyFriendsAdapter(Context context, ArrayList<UiD_UserFriend> items, FragmentManager fragmentManager) {
mContext = context;
mItems = items;
mFragmentManager = fragmentManager;
}
@Override
public int getCount() {
return mItems.size();
}
@Override
public Object getItem(int position) {
return mItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View currentView, ViewGroup viewGroup) {
Holder holder = null;
if (currentView == null) {
currentView = View.inflate(mContext, R.layout.view_list_item_myfriends, null);
holder = new Holder();
holder.textViewUserName = (TextView) currentView.findViewById(R.id.textViewFriendName);
holder.mMyFriendspager = (ViewPager) currentView.findViewById(R.id.pagerMyFriendHabits);
currentView.setTag(holder);
} else {
holder = (Holder) currentView.getTag();
}
holder.textViewUserName.setText(mItems.get(position).getmName());
MyFriendPagerAdapter tempMyFriendPagerAdapter = new MyFriendPagerAdapter(mFragmentManager, mItems.get(position).getFriendHabits());
holder.mMyFriendspager.setAdapter(tempMyFriendPagerAdapter);
return currentView;
}
class Holder {
TextView textViewUserName;
ViewPager mMyFriendspager;
}
}
</code></pre>
<p>This is my pager adapter:</p>
<pre><code>public class MyFriendPagerAdapter extends FragmentPagerAdapter {
private ArrayList<UiD_Habit> mHabits;
public MyFriendPagerAdapter(FragmentManager fm, ArrayList<UiD_Habit> habits) {
super(fm);
mHabits = habits;
}
@Override
public Fragment getItem(int index) {
return new FragmentMyFriendPage(mHabits.get(index));
}
@Override
public int getCount() {
return mHabits.size();
}
}
</code></pre> | 15,071,212 | 4 | 2 | null | 2013-02-17 11:11:32.653 UTC | 12 | 2017-10-03 04:06:18.677 UTC | 2017-10-03 04:06:18.677 UTC | null | 1,402,846 | null | 475,472 | null | 1 | 16 | android|android-layout|listview|android-fragments|android-widget | 11,564 | <p>Whenever you need to dynamically add pagers, you need to set an ID for each pager using <code>ViewPager.setId()</code>.</p> |
14,737,773 | Replacing occurrences of a number in multiple columns of data frame with another value in R | <p><strong>ETA:</strong> the point of the below, by the way, is to not have to iterate through my entire set of column vectors, just in case that was a proposed solution (just do what is known to work once at a time).</p>
<hr>
<p>There's plenty of examples of replacing values in a <em>single</em> vector of a data frame in R with some other value.</p>
<ul>
<li><a href="https://stackoverflow.com/questions/5824173/replace-a-value-in-a-data-frame-based-on-a-conditional-if-statement-in-r">Replace a value in a data frame based on a conditional (<code>if</code>) statement in R</a></li>
<li><a href="https://stackoverflow.com/questions/11817371/replace-numbers-in-data-frame-column-in-r">replace numbers in data frame column in r [duplicate]</a></li>
</ul>
<p>And also how to replace all values of <code>NA</code> with something else:</p>
<ul>
<li><a href="http://r.789695.n4.nabble.com/How-to-replace-all-lt-NA-gt-values-in-a-data-frame-with-another-not-0-value-td2125458.html" rel="noreferrer">How to replace all values in a data.frame with another ( not 0) value</a></li>
</ul>
<p>What I'm looking for is analogous to the last question, but basically trying to replace one value with another. I'm having trouble generating a data frame of logical values mapped to my actual data frame for cases where multiple columns meet a criteria, or simply trying to do the actions from the first two questions on more than one column.</p>
<p>An example:</p>
<pre><code>data <- data.frame(name = rep(letters[1:3], each = 3), var1 = rep(1:9), var2 = rep(3:5, each = 3))
data
name var1 var2
1 a 1 3
2 a 2 3
3 a 3 3
4 b 4 4
5 b 5 4
6 b 6 4
7 c 7 5
8 c 8 5
9 c 9 5
</code></pre>
<p>And say I want all of the values of <code>4</code> in <code>var1</code> and <code>var2</code> to be <code>10</code>.</p>
<p>I'm sure this is elementary and I'm just not thinking through it properly. I have been trying things like:</p>
<pre><code>data[data[, 2:3] == 4, ]
</code></pre>
<p>That doesn't work, but if I do the same with <code>data[, 2]</code> instead of <code>data[, 2:3]</code>, things work fine. It seems that logical test (like <code>is.na()</code>) work on multiple rows/columns, but that numerical comparisons aren't playing as nicely?</p>
<p>Thanks for any suggestions!</p> | 14,737,832 | 4 | 0 | null | 2013-02-06 20:05:51.933 UTC | 9 | 2016-11-11 16:33:16.337 UTC | 2017-05-23 12:10:38.383 UTC | null | -1 | null | 495,990 | null | 1 | 27 | r|replace|indexing | 53,692 | <p>you want to search through the whole data frame for any value that matches the value you're trying to replace. the same way you can run a logical test like replacing all missing values with 10..</p>
<pre><code>data[ is.na( data ) ] <- 10
</code></pre>
<p>you can also replace all 4s with 10s.</p>
<pre><code>data[ data == 4 ] <- 10
</code></pre>
<p>at least i think that's what you're after?</p>
<p>and let's say you wanted to ignore the first row (since it's all letters)</p>
<pre><code># identify which columns contain the values you might want to replace
data[ , 2:3 ]
# subset it with extended bracketing..
data[ , 2:3 ][ data[ , 2:3 ] == 4 ]
# ..those were the values you're going to replace
# now overwrite 'em with tens
data[ , 2:3 ][ data[ , 2:3 ] == 4 ] <- 10
# look at the final data
data
</code></pre> |
14,670,394 | Does Firebase allow an app to start in offline mode? | <p>I'm thinking of using firebase to write a mobile app using PhoneGap and the HTML5 Application Cache.</p>
<p>Lets suppose each user has a list of TODO items. If the app is started when the phone is offline, will it be able to load data from the previous session and sync when a connection is established? If so I'm wondering how this is implemented because I couldn't find a reference to localStorage in firebase.js.</p> | 14,670,601 | 3 | 0 | null | 2013-02-03 07:32:20.64 UTC | 16 | 2020-07-15 00:04:22.167 UTC | null | null | null | null | 94,078 | null | 1 | 32 | offline|offline-caching|offlineapps|firebase | 15,919 | <p>The short answer is: not yet.</p>
<p>Once an app has connected to Firebase, the client will cache data locally and be able to access data where there is an outstanding "on" callback even after a network connection is lost. However, this data is not persisted to disk, the "offline mode" will only work while the app is still running.</p>
<p>Full offline support will be coming in the future.</p>
<p><em>edit 2016 :</em> full offline support is now possible for native iOS and Android apps: <a href="https://www.firebase.com/blog/2015-05-29-announcing-mobile-offline-support.html" rel="noreferrer">https://www.firebase.com/blog/2015-05-29-announcing-mobile-offline-support.html</a> </p> |
14,643,836 | Dynamic class in Angular.js | <p>I want to dynamically add a css class to an <code><li></code> element I am looping over.
The loop is like this:</p>
<pre><code><li ng-repeat="todo in todos" ng-class="{{todo.priority}}">
<a href="#/todos/{{todo.id}}">{{todo.title}}</a>
<p>{{todo.description}}</p>
</li>
</code></pre>
<p>In my todo model, I have the property priority which can be "urgent", "not-so-important" or "normal" and I just want to assign the class for each element.</p>
<p>I know I can do this for a boolean with something like <code>ng-class="{'urgent': todo.urgent}"</code>
But my variable is not a boolean, but has three values.
How would I do this?
Note also that I do not want to use <code>ng-style="..."</code> since my class will alter several visual things.</p> | 14,644,299 | 4 | 0 | null | 2013-02-01 10:05:57.5 UTC | 12 | 2020-06-18 17:21:42.667 UTC | null | null | null | null | 1,267,056 | null | 1 | 54 | class|dynamic|angularjs | 85,692 | <p>You can simply assign a function as an expression and return proper class from there.
<strong>Edit: there is also better solution for dynamic classes. Please see note below.</strong></p>
<p>Snippet from view:</p>
<p><code><div ng-class="appliedClass(myObj)">...</div></code></p>
<p>and in the controller:</p>
<pre><code>$scope.appliedClass = function(myObj) {
if (myObj.someValue === "highPriority") {
return "special-css-class";
} else {
return "default-class"; // Or even "", which won't add any additional classes to the element
}
}
</code></pre>
<h2>Better way of doing this</h2>
<p>I've recently learned about another approach. You pass in an object which has properties corresponding to the classes you operate on, and the values are expressions or boolean variables. A simple example:</p>
<p><code>ng-class="{ active: user.id == activeId }"</code></p>
<p>In this case <code>active</code> class will be added to the element as long as <code>user.id</code> matches <code>activeId</code> from the <code>$scope</code> object!</p> |
14,714,877 | Mismatch Detected for 'RuntimeLibrary' | <p>I downloaded and extracted Crypto++ in C:\cryptopp. I used Visual Studio Express 2012 to build all the projects inside (as instructed in readme), and everything was built successfully. Then I made a test project in some other folder and added cryptolib as a dependency. After that, I added the include path so I can easily include all the headers. When I tried to compile, I got an error about unresolved symbols.</p>
<p>To remedy that, I added <code>C:\cryptopp\Win32\Output\Debug\cryptlib.lib</code> to link additional dependencies. Now I get this error:</p>
<pre><code>Error 1 error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in program.obj C:\Data\Work\C++ VS\CryptoTest\CryptoTest\cryptlib.lib(cryptlib.obj) CryptoTest
Error 2 error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in program.obj C:\Data\Work\C++ VS\CryptoTest\CryptoTest\cryptlib.lib(iterhash.obj) CryptoTest
Error 3 error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in program.obj C:\Data\Work\C++ VS\CryptoTest\CryptoTest\cryptlib.lib(sha.obj) CryptoTest
Error 4 error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in program.obj C:\Data\Work\C++ VS\CryptoTest\CryptoTest\cryptlib.lib(pch.obj) CryptoTest
Error 5 error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in program.obj C:\Data\Work\C++ VS\CryptoTest\CryptoTest\cryptlib.lib(misc.obj) CryptoTest
Error 6 error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in program.obj C:\Data\Work\C++ VS\CryptoTest\CryptoTest\cryptlib.lib(queue.obj) CryptoTest
Error 7 error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in program.obj C:\Data\Work\C++ VS\CryptoTest\CryptoTest\cryptlib.lib(algparam.obj) CryptoTest
Error 8 error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in program.obj C:\Data\Work\C++ VS\CryptoTest\CryptoTest\cryptlib.lib(filters.obj) CryptoTest
Error 9 error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in program.obj C:\Data\Work\C++ VS\CryptoTest\CryptoTest\cryptlib.lib(fips140.obj) CryptoTest
Error 10 error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in program.obj C:\Data\Work\C++ VS\CryptoTest\CryptoTest\cryptlib.lib(cpu.obj) CryptoTest
Error 11 error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in program.obj C:\Data\Work\C++ VS\CryptoTest\CryptoTest\cryptlib.lib(mqueue.obj) CryptoTest
</code></pre>
<p>I also get:</p>
<pre><code>Error 12 error LNK2005: "public: __thiscall std::_Container_base12::_Container_base12(void)" (??0_Container_base12@std@@QAE@XZ) already defined in cryptlib.lib(cryptlib.obj) C:\Data\Work\C++ VS\CryptoTest\CryptoTest\msvcprtd.lib(MSVCP110D.dll) CryptoTest
Error 13 error LNK2005: "public: __thiscall std::_Container_base12::~_Container_base12(void)" (??1_Container_base12@std@@QAE@XZ) already defined in cryptlib.lib(cryptlib.obj) C:\Data\Work\C++ VS\CryptoTest\CryptoTest\msvcprtd.lib(MSVCP110D.dll) CryptoTest
Error 14 error LNK2005: "public: void __thiscall std::_Container_base12::_Orphan_all(void)" (?_Orphan_all@_Container_base12@std@@QAEXXZ) already defined in cryptlib.lib(cryptlib.obj) C:\Data\Work\C++ VS\CryptoTest\CryptoTest\msvcprtd.lib(MSVCP110D.dll) CryptoTest
Error 15 error LNK2005: "public: __thiscall std::locale::id::id(unsigned int)" (??0id@locale@std@@QAE@I@Z) already defined in cryptlib.lib(iterhash.obj) C:\Data\Work\C++ VS\CryptoTest\CryptoTest\msvcprtd.lib(MSVCP110D.dll) CryptoTest
Warning 16 warning LNK4098: defaultlib 'LIBCMTD' conflicts with use of other libs; use /NODEFAULTLIB:library C:\Data\Work\C++ VS\CryptoTest\CryptoTest\LINK CryptoTest
Error 17 error LNK1169: one or more multiply defined symbols found C:\Data\Work\C++ VS\CryptoTest\Debug\CryptoTest.exe 1 1 CryptoTest
</code></pre>
<p>The code I tried to compile was simple (I got this from another site):</p>
<pre><code>#include <iostream>
#include <string>
#include "sha.h"
#include "hex.h"
using namespace std;
string SHA256(string data) {
byte const* pbData = (byte*) data.data();
unsigned int nDataLen = data.size();
byte abDigest[32];
CryptoPP::SHA256().CalculateDigest(abDigest, pbData, nDataLen);
return string((char*)abDigest);
}
int main(void) {
return 0;
}
</code></pre>
<p>Any ideas how to fix this? I really only need SHA-256 right now, nothing else.
I am using Windows 7 64 bit, and I downloaded VS C++ today, so it should be the newest version.</p> | 18,635,749 | 4 | 3 | null | 2013-02-05 19:00:39.19 UTC | 43 | 2019-12-03 11:26:03.61 UTC | 2015-10-24 01:58:21.83 UTC | null | 608,639 | null | 2,007,674 | null | 1 | 148 | c++|hash|compilation|sha256|crypto++ | 144,803 | <p>(This is already answered in comments, but since it lacks an actual <em>answer</em>, I'm writing this.)</p>
<p>This problem arises in newer versions of Visual C++ (the older versions usually just silently linked the program and it would crash and burn at run time.) It means that some of the libraries you are linking with your program (or even some of the source files inside your program itself) are <em>using different versions of the CRT (the C RunTime library.)</em></p>
<p>To correct this error, you need to go into your <code>Project Properties</code> (and/or those of the libraries you are using,) then into <code>C/C++</code>, then <code>Code Generation</code>, and check the value of <code>Runtime Library</code>; this should be exactly the same for <em>all</em> the files and libraries you are linking together. (The rules are a little more relaxed for linking with DLLs, but I'm not going to go into the "why" and into more details here.)</p>
<p>There are currently four options for this setting:</p>
<ol>
<li>Multithreaded Debug</li>
<li>Multithreaded Debug DLL</li>
<li>Multithreaded Release</li>
<li>Multithreaded Release DLL</li>
</ol>
<p>Your particular problem seems to stem from you linking a library built with "Multithreaded Debug" (i.e. static multithreaded debug CRT) against a program that is being built using the "Multithreaded Debug <em>DLL</em>" setting (i.e. dynamic multithreaded debug CRT.) You should change this setting either in the library, or in your program. For now, I suggest changing this in your program.</p>
<p>Note that since Visual Studio projects use different sets of project settings for debug and release builds (and 32/64-bit builds) you should make sure the settings match in all of these project configurations.</p>
<p>For (some) more information, you can see these (linked from a comment above):</p>
<ol>
<li><a href="http://msdn.microsoft.com/en-us/library/6wtdswk0%28v=vs.110%29.aspx" rel="noreferrer">Linker Tools Warning LNK4098</a> on MSDN</li>
<li><a href="http://msdn.microsoft.com/en-us/library/2kzt1wy3%28v=vs.110%29.aspx" rel="noreferrer">/MD, /ML, /MT, /LD (Use Run-Time Library)</a> on MSDN</li>
<li><a href="https://bugzilla.mozilla.org/show_bug.cgi?id=732124" rel="noreferrer">Build errors with VC11 Beta - mixing MTd libs with MDd exes fail to link</a> on Bugzilla@Mozilla</li>
</ol>
<p><strong>UPDATE</strong>: (This is in response to a comment that asks for the reason that this much care must be taken.)</p>
<p>If two pieces of code that we are linking together are themselves linking against and using the standard library, then the standard library must be the same for both of them, unless <em>great</em> care is taken about how our two code pieces interact and pass around data. Generally, I would say that for almost all situations just use the exact same version of the standard library runtime (regarding debug/release, threads, and obviously the version of Visual C++, among other things like iterator debugging, etc.)</p>
<p>The most important part of the problem is this: <em>having the same idea about the size of objects on either side of a function call</em>.</p>
<p>Consider for example that the above two pieces of code are called <code>A</code> and <code>B</code>. A is <em>compiled</em> against one version of the standard library, and B against another. In A's view, some random object that a standard function returns to it (e.g. a block of memory or an iterator or a <code>FILE</code> object or whatever) has some specific size and layout (remember that structure layout is determined and fixed at compile time in C/C++.) For any of several reasons, B's idea of the size/layout of the same objects is different (it can be because of additional debug information, natural evolution of data structures over time, etc.)</p>
<p>Now, if A calls the standard library and gets an object back, then passes that object to B, and B touches that object in any way, chances are that B will mess that object up (e.g. write the wrong field, or past the end of it, etc.)</p>
<p>The above isn't the only kind of problems that can happen. Internal global or static objects in the standard library can cause problems too. And there are more obscure classes of problems as well.</p>
<p>All this gets weirder in some aspects when using DLLs (dynamic runtime library) instead of libs (static runtime library.)</p>
<p>This situation can apply to any library used by two pieces of code that work together, but the standard library gets used by most (if not almost all) programs, and that increases the chances of clash.</p>
<p>What I've described is obviously a watered down and simplified version of the actual mess that awaits you if you mix library versions. I hope that it gives you an idea of why you shouldn't do it!</p> |
3,036,397 | How to reset IIS (or otherwise clear cache) when restarting a web application? | <p>I'm working on an ASP.NET app that keeps a lot of data cached. This data remains cached when I restart the app, so I have to reset IIS if I want to rerun the code that gets the data, otherwise it's just taken from the cache. Is there a way that I can automate this?</p> | 3,036,498 | 2 | 1 | null | 2010-06-14 10:14:49.413 UTC | 3 | 2010-06-14 10:32:21.477 UTC | null | null | null | null | 181,771 | null | 1 | 5 | asp.net|visual-studio-2008|iis|caching | 45,034 | <p>Running <code>iisreset</code> from an elevated (on Vista/Win7/Win2008) command prompt will restart IIS and all hosted applications. This is very quick if you keep the command prompt open: up arrow and enter to repeat last command.</p> |
33,905,687 | Error: File path too long on windows, keep below 240 characters | <p>So, I made some changes to my build.gradle(app) file and android studio gives me this error (open the image in new tab for better viewing):
<a href="https://i.stack.imgur.com/ZYlIc.jpg"><img src="https://i.stack.imgur.com/ZYlIc.jpg" alt="Error description from Logcat"></a></p>
<p>My build.gradle(app) file (this is not the edited file, I deleted new lines of code and still no luck/solution.):
<a href="https://i.stack.imgur.com/5VbsA.jpg"><img src="https://i.stack.imgur.com/5VbsA.jpg" alt="Build.gradle"></a></p>
<p>Everything was quite working well until I made some changes in the build.gradle(app) file, but then I deleted those new lines of codes and android studio is still keep giving me the error.
The error relates to the <strong>compile 'com.google.android.gms:play-services:8.3.0'</strong>.
I have tried deleting/renaming those png images inside the stated folder,but then when I rebuild the project, the png images are automatically downloaded.
My build.gradle(project) file contains <strong>classpath 'com.android.tools.build:gradle:1.5.0'</strong>. I want to know what causes this error, and how to fix it? Many thanks.</p> | 33,911,791 | 14 | 1 | null | 2015-11-24 23:17:05.073 UTC | 27 | 2020-12-29 13:08:13.86 UTC | 2016-01-28 01:07:17.147 UTC | null | 5,039,732 | null | 5,039,732 | null | 1 | 69 | android|android-gradle-plugin|google-play-services | 67,606 | <p>I just ran into the same issue. I don't know a fix for your exact problem, but I found a work around; I see your project has a deep file path hierarchy. Why not just move your project up from a lower level? </p>
<p>Ex: <code>C:\Projects\YourProject</code></p>
<p>That fixed the problem for me.</p> |
53,631,992 | AWS Cloudformation: Conditionally create properties of resources | <p>I know that it is possible via the use of <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/conditions-section-structure.html" rel="noreferrer">Conditions</a> to conditionally (what else?) create resources.</p>
<p>I am trying to find a way though to conditionally create properties of resources; </p>
<p>in my case I am creating several <code>EC2</code> instances in a subnet with default public ip assignment = <code>false</code>. </p>
<p>Sometimes though for debugging purposes I want my instances to get public IPs. </p>
<p>Now I have to comment in/out the SG/Subnet and the <code>NetworkInterfaces</code> properties below (those do not go together)</p>
<pre><code> myEC2:
Type: AWS::EC2::Instance
Metadata:
Comment: My EC2 Instance
AWS::CloudFormation::Init:
config:
commands:
01_provision:
command:
!Sub |
sed -i "s/somestring/${somevar}/" /some/path/
CreationPolicy:
ResourceSignal:
Timeout: PT4M
Properties:
ImageId: !FindInMap [ MyAamiMap, 'myami', amiid ]
InstanceType: "t2.2xlarge"
# SubnetId: !Ref SBNDemo1
# SecurityGroupIds: [!Ref SGInternalDemo]
NetworkInterfaces:
- AssociatePublicIpAddress: "true"
DeviceIndex: "0"
GroupSet:
- Ref: "SGInternalDemo"
SubnetId:
Ref: "SBNDemo1"
UserData:
"Fn::Base64":
!Sub |
#!/bin/bash -xe
# Start cfn-init
/usr/local/bin/cfn-init -s ${AWS::StackId} -r myEC2 --region ${AWS::Region} || echo 'Failed to run cfn-init'
# All done so signal success
/usr/local/bin/cfn-signal -e $? --stack ${AWS::StackId} --resource myEC2 --region ${AWS::Region}
</code></pre>
<p>Any suggestions?</p> | 55,273,157 | 2 | 1 | null | 2018-12-05 12:08:59.37 UTC | 9 | 2019-03-21 03:03:37.14 UTC | null | null | null | null | 2,409,793 | null | 1 | 33 | amazon-web-services|amazon-cloudformation | 20,558 | <p>This might be a little late, but I recently had a same question.</p>
<p>From <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-conditions.html#w2ab1c21c24c21c39b8c10" rel="noreferrer">AWS docs</a>, you can use <strong>Fn::If</strong> to set properties accordingly.</p>
<p>The template will look like:</p>
<pre><code>Properties:
ImageId: !FindInMap [ MyAamiMap, 'myami', amiid ]
InstanceType: "t2.2xlarge"
# SubnetId: !Ref SBNDemo1
# SecurityGroupIds: [!Ref SGInternalDemo]
NetworkInterfaces:
!If
- YourCondition
-
AssociatePublicIpAddress: "true"
DeviceIndex: "0"
GroupSet:
- Ref: "SGInternalDemo"
SubnetId:
Ref: "SBNDemo1"
- !Ref "AWS::NoValue"
</code></pre>
<p>AWS::NoValue means there will be no NetworkInterfaces properties set. </p> |
38,585,848 | Programmatically removes files/folder resides in docker container | <p>I am currently exploring on how we can remove the file/folder resides inside docker container programmatically . I know we can copy files from container to host using docker cp. However, I am looking for something like docker mv or docker rm which allows me to move or remove files/folders inside docker.</p>
<p>The scenario is, We are writing the automated test cases in Java and for one case we need to copy the log file from the server's log folder to assert the log written by the test case. We are using the docker cp to copy the log files. However it contains the log of old test cases as well. So I was thinking if I can remove the log files before executing my test case. It make sure the log I have copied is written by my test case only. Is there any other way around?</p> | 38,591,846 | 3 | 0 | null | 2016-07-26 09:20:21.857 UTC | 4 | 2016-07-26 13:53:58.807 UTC | 2016-07-26 09:27:24.487 UTC | null | 2,056,961 | null | 2,056,961 | null | 1 | 33 | docker | 67,398 | <p>You can use below command to remove the files from program running on host</p>
<pre><code>docker exec <container> rm -rf <YourFile>
</code></pre>
<p>However if old files exist because the container were never removed, then general practice is to remove the container once the all test suite execution is complete, </p>
<p>New job should create the new container.</p> |
31,338,117 | CQRS - is it allowed to call the read side from the write side? | <p>I started with reading about CQRS and I'm little confused.</p>
<p>Is it allowed to call the read side within the write side for getting additional informations?</p>
<p><a href="http://cqrs.nu/Faq/command-handlers">http://cqrs.nu/Faq/command-handlers</a> here they say it is not allowed, but in the cqrs journey code I found that they call a service 'IPricingService' which internally uses a DAO service class.</p>
<p>So what I must do to get additional informations inside my aggregation root?</p> | 31,339,148 | 4 | 0 | null | 2015-07-10 10:07:29.147 UTC | 13 | 2021-08-10 11:39:02.77 UTC | null | null | null | null | 5,049,599 | null | 1 | 28 | cqrs | 7,173 | <p>CQRS Journey should not be seen as a manual. This is just a story of some team fighting their way to CQRS and having all limitations of using only Microsoft stack. Per se you should not use your read model in the command handlers or domain logic. But you can query your read model from the client to fetch the data you need in for your command and to validate the command.</p>
<p>Since I got some downvotes on this answer, I need to point, that what I wrote is the established practice within the pattern. Neither read side accesses the write side, not write side gets data from the read side.</p>
<p>However, the definition of "client" could be a subject of discussion. For example, I would not trust a public facing JS browser application to be a proper "client". Instead, I would use my REST API layer to be the "client" in CQRS and the web application would be just a UI layer for this client. In this case, the REST API service call processing will be a legitimate read side reader since it needs to validate all what UI layer send to prevent forgery and validate some business rules. When this work is done, the command is formed and sent over to the write side. The validations and everything else is synchronous and command handling is then asynchronous.</p>
<p>UPDATE: In the light of some disagreements below, I would like to point to <a href="http://udidahan.com/2009/12/09/clarified-cqrs/">Udi's article from 2009</a> talking about CQRS in general, commands and validation in particular.</p> |
54,057,011 | Google Colab session timeout | <p>In the <a href="https://research.google.com/colaboratory/faq.html" rel="noreferrer">FAQs</a> it is mentioned that</p>
<blockquote>
<p>Virtual machines are recycled when idle for a while, and have a maximum lifetime enforced by the system.</p>
</blockquote>
<p>Are the maximum lifetime and idle times fixed or variable? Is there any way to predict them?</p> | 54,059,837 | 4 | 0 | null | 2019-01-05 22:48:10.753 UTC | 19 | 2021-09-22 10:46:42.683 UTC | 2021-03-29 13:36:45.843 UTC | null | 4,685,471 | null | 2,821,756 | null | 1 | 40 | google-colaboratory | 66,394 | <p>It's 90 minutes if you close the browser. 12 hours if you keep the browser open. Additionally, if you close your browser with a code cell is running, if that same cell has not finished, when you reopen the browser it will still be running (the current executing cell keeps running even after browser is closed)</p> |
40,527,124 | Single Sign On (SSO) using JWT | <p>I have read several articles about sso but could not find an answer in my mind.
I have a scenario like below:</p>
<p><strong>Scenario:</strong></p>
<ul>
<li>My company wants to have sso mechanism using jwt.</li>
<li>Company has 2 different domains like <strong>abc.com</strong> as <strong>abc</strong> and <strong>xyz.com</strong> as <strong>xyz</strong>. </li>
<li>Also there is a <strong>masterdomain</strong> that manages clients authentication. </li>
<li>User <strong>X</strong> wants to log in <strong>abc</strong> at first. </li>
<li><strong>abc</strong> sends credentials to <strong>masterdomain</strong> and <strong>masterdomain</strong> authenticates user then create a signed jwt in order to send back to <strong>abc</strong>.</li>
<li><strong>abc</strong> keeps this jwt in a cookie. </li>
<li>After a while if a login to <strong>abc</strong> is attempted at the same computer, system does not ask for credentials and automatically login the user.</li>
</ul>
<p><strong>Question:</strong></p>
<p>If user tries to open a page in <strong>xyz</strong> domain, how does the system understand that the user loggedin before? I mean <strong>xyz</strong> domain cannot reach the cookie of <strong>abc</strong> which has the jwt. What information should be sent to <strong>xyz</strong> that indicates the user <strong>X</strong> is trying to login? </p>
<p>Thanks in advance</p> | 40,555,970 | 1 | 0 | null | 2016-11-10 12:01:54.123 UTC | 10 | 2016-11-11 20:47:57.197 UTC | null | null | null | null | 2,711,669 | null | 1 | 22 | cross-domain|single-sign-on|jwt | 16,613 | <p>You can store the JWT authentication token in a cookie / localStorage of a intermediate domain connected to the home page using an iframe</p>
<p><a href="https://i.stack.imgur.com/ZkbOU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZkbOU.png" alt="cross domain sso" /></a></p>
<p>Scenario</p>
<blockquote>
<ul>
<li><p><strong>abc</strong> sends credentials to <strong>masterdomain</strong> and <strong>masterdomain</strong> authenticates user then create a signed jwt in order to send back to abc.</p>
</li>
<li><p><s>abc</s> <strong>masterdomain</strong> keeps this jwt in a cookie.</p>
</li>
<li><p>After a while if a login to <strong>abc</strong> is attempted at the same computer, system does not ask for credentials and automatically login the user.</p>
</li>
</ul>
</blockquote>
<p>Finally when the user enters in the second domain <strong>xyz</strong>, the jwt is recovered from <strong>masterdomain</strong> storage using the iframe, and automatically login the user</p>
<p><strong>CORS</strong> is not a problem because <strong>masterdomain.com</strong> have access to its storage and communication between iframes is allowed if origin and destination are recognized (see <a href="http://blog.teamtreehouse.com/cross-domain-messaging-with-postmessage" rel="noreferrer">http://blog.teamtreehouse.com/cross-domain-messaging-with-postmessage</a>)</p>
<p>To simplify development, we have released recently an opensource project <strong>cross domain SSO with JWT</strong> at <a href="https://github.com/Aralink/ssojwt" rel="noreferrer">https://github.com/Aralink/ssojwt</a></p> |
33,660,794 | Import Oracle .dmp file using SQL Developer | <p>I want to import a <code>.dmp</code> file exported from another database, and I was wondering if anyone have experience on using GUI import option for <code>.dmp</code> file from SQL Developer? I have searched a lot of documents, but I couldn't find any detail. I can use SYS or SYSTEM user to import.</p> | 33,661,813 | 2 | 0 | null | 2015-11-11 22:09:19.84 UTC | 4 | 2019-10-15 09:05:28.613 UTC | 2019-06-20 14:20:25.117 UTC | null | 2,311,867 | null | 1,850,923 | null | 1 | 13 | oracle|oracle-sqldeveloper | 70,731 | <p>what was this another database? was it oracle database?
if yes
the dmp file can be file exported by </p>
<ol>
<li>DataPump <a href="http://docs.oracle.com/cd/B19306_01/server.102/b14215/dp_export.htm" rel="noreferrer">expdp</a> util and you need import it by using <a href="http://docs.oracle.com/cd/B19306_01/server.102/b14215/dp_import.htm" rel="noreferrer">impdp</a> util </li>
<li>the file can be exported by <a href="https://docs.oracle.com/cd/B10501_01/server.920/a96652/ch01.htm" rel="noreferrer">exp</a> util and you can import it by <a href="https://docs.oracle.com/cd/B10501_01/server.920/a96652/ch02.htm" rel="noreferrer">imp</a> util</li>
<li>how to use this DataPump utils via SQL Developer UI see <a href="http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/sqldev/r31/datapump_OBE/datapump.html" rel="noreferrer">here</a> </li>
</ol> |
27,457,326 | Compressing a folder with many duplicated files | <p>I have a pretty big folder (~10GB) that contains many duplicated files throughout it's directory tree. Many of these files are duplicated up 10 times. The duplicated files don't reside side by side, but within different sub-directories.</p>
<p>How can I compress the folder to a make it small enough?</p>
<p>I tried to use Winrar in "Best" mode, but it didn't compress it at all. (Pretty strange)</p>
<p>Will zip\tar\cab\7z\ any other compression tool do a better job?</p>
<p>I don't mind letting the tool work for a few hours - but not more.</p>
<p>I rather not do it programmatically myself </p> | 52,771,612 | 6 | 0 | null | 2014-12-13 09:18:45.503 UTC | 11 | 2021-06-11 11:38:12.65 UTC | null | null | null | null | 972,014 | null | 1 | 20 | compression|tar|rar|winrar|winzip | 12,881 | <p>Best options in your case is 7-zip.
Here is the options:</p>
<pre><code>7za a -r -t7z -m0=lzma2 -mx=9 -mfb=273 -md=29 -ms=8g -mmt=off -mmtf=off -mqs=on -bt -bb3 archife_file_name.7z /path/to/files
</code></pre>
<p><code>a</code> - add files to archive</p>
<p><code>-r</code> - Recurse subdirectories</p>
<p><code>-t7z</code> - Set type of archive (7z in your case)</p>
<p><code>-m0=lzma2</code> - Set compression method to <strong>LZMA2</strong>. LZMA is default and general compression method of 7z format. The main features of LZMA method:</p>
<ul>
<li>High compression ratio</li>
<li>Variable dictionary size (up to 4 GB)</li>
<li>Compressing speed: about 1 MB/s on 2 GHz CPU</li>
<li>Decompressing speed: about 10-20 MB/s on 2 GHz CPU</li>
<li>Small memory requirements for decompressing (depend from dictionary size)</li>
<li>Small code size for decompressing: about 5 KB</li>
<li>Supporting multi-threading and P4's hyper-threading</li>
</ul>
<p><code>-mx=9</code> - Sets level of compression. x=0 means Copy mode (no compression). x=9 - Ultra</p>
<p><code>-mfb=273</code> - Sets number of fast bytes for LZMA. It can be in the range from 5 to 273. The default value is 32 for normal mode and 64 for maximum and ultra modes. Usually, a big number gives a little bit better compression ratio and slower compression process.</p>
<p><code>-md=29</code> - Sets Dictionary size for LZMA. You must specify the size in bytes, kilobytes, or megabytes. The maximum value for dictionary size is 1536 MB, but 32-bit version of 7-Zip allows to specify up to 128 MB dictionary. Default values for LZMA are 24 (16 MB) in normal mode, 25 (32 MB) in maximum mode (-mx=7) and 26 (64 MB) in ultra mode (-mx=9). If you do not specify any symbol from the set [b|k|m|g], the dictionary size will be calculated as DictionarySize = 2^Size bytes. For decompressing a file compressed by LZMA method with dictionary size N, you need about N bytes of memory (RAM) available.</p>
<p>I use <code>md=29</code> because on my server there is 16Gb only RAM available. using this settings 7-zip takes only 5Gb on any directory size archiving. If I use bigger dictionary size - system goes to swap.</p>
<p><code>-ms=8g</code> - Enables or disables <strong>solid mode</strong>. The default mode is <code>s=on</code>. In solid mode, files are grouped together. Usually, compressing in solid mode improves the compression ratio. In your case this is very important to make solid block size as big as possible.</p>
<p>Limitation of the solid block size usually decreases compression ratio. The updating of solid .7z archives can be slow, since it can require some recompression.</p>
<p><code>-mmt=off</code> - Sets <strong>multithreading mode to OFF</strong>. You need to switch it off because we need similar or identical files to be processed by same 7-zip thread in one soled block. Drawback is slow archiving. Does not matter how many CPUs or cores your system have.</p>
<p><code>-mmtf=off</code> - Set <strong>multithreading mode for filters to OFF</strong>.</p>
<p><code>-myx=9</code> - Sets level of file analysis to maximum, analysis of all files (Delta and executable filters).</p>
<p><code>-mqs=on</code> - Sort files by type in solid archives. To store identical files together.</p>
<p><code>-bt</code> - show execution time statistics
<code>-bb3</code> - set output log level</p> |
59,317,249 | ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 1 is different from 3) | <p>I have written code using matmul, but I am getting the following error: </p>
<pre><code> "ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 1 is different from 3)"
</code></pre>
<p>Code:</p>
<pre><code> R = [[0.40348195], [0.38658295], [0.82931052]]
V = [0.33452744, 0.33823673, 0.32723583]
print("Rt_p: ", R)
B = np.matmul(V,np.transpose(R))/pow(LA.norm(R), 2)
print("B", B)
</code></pre> | 59,317,314 | 2 | 0 | null | 2019-12-13 06:29:33.733 UTC | 1 | 2022-03-25 09:37:57.957 UTC | 2019-12-13 06:30:28.667 UTC | null | 10,239,789 | null | 8,998,072 | null | 1 | 13 | python|python-3.x|numpy | 102,502 | <p>You are transposing a Matrix with 3 rows and 1 column to a Matrix with 3 columns and 1 row.
Then you are multiplying it with a similar Matrix (also 3 columns 1 row) which is incorrect mathematically. So you can either remove the transpose function or define your R Matrix as 1 row 3 columns and then transpose it. Check <a href="https://en.wikipedia.org/wiki/Matrix_multiplication" rel="nofollow noreferrer">this</a> for further information.</p> |
34,865,348 | vuejs set a radio button checked if statement is true | <p>I am trying to make a radio button checked using vuejs v-for only if my if-statement is true. Is there a way to use vuejs' v-if/v-else for this type of problem? </p>
<p>in php and html I can achieve this by doing the following:</p>
<pre class="lang-html prettyprint-override"><code><input type="radio" <? if(portal.id == currentPortalId) ? 'checked="checked"' : ''?>>
</code></pre>
<p>Below is what I have so far using vuejs: </p>
<pre class="lang-html prettyprint-override"><code> <div v-for="portal in portals">
<input type="radio" id="{{portal.id}}" name="portalSelect"
v-bind:value="{id: portal.id, name: portal.name}"
v-model="newPortalSelect"
v-on:change="showSellers"
v-if="{{portal.id == currentPortalId}}"
checked="checked">
<label for="{{portal.id}}">{{portal.name}}</label>
</div>
</code></pre>
<p>I know the v-if statement here is for checking whether to show or hide the input. </p>
<p>Any help would be very much appreciated.</p> | 34,865,436 | 5 | 0 | null | 2016-01-18 22:35:54.14 UTC | 11 | 2021-07-01 15:45:26.867 UTC | 2019-12-19 15:43:40.213 UTC | null | 693,349 | null | 5,807,584 | null | 1 | 55 | vue.js | 138,054 | <p>You could bind the <code>checked</code> attribute like this:</p>
<pre class="lang-html prettyprint-override"><code><div v-for="portal in portals">
<input type="radio"
id="{{portal.id}}"
name="portalSelect"
v-bind:value="{id: portal.id, name: portal.name}"
v-model="newPortalSelect"
v-on:change="showSellers"
:checked="portal.id == currentPortalId">
<label for="{{portal.id}}">{{portal.name}}</label>
</div>
</code></pre>
<p>Simple example: <a href="https://jsfiddle.net/b4k6tpj9/" rel="noreferrer">https://jsfiddle.net/b4k6tpj9/</a></p> |
35,256,008 | AutoMapper Migrating from static API | <p><a href="https://github.com/AutoMapper/AutoMapper/wiki/Migrating-from-static-API" rel="noreferrer">https://github.com/AutoMapper/AutoMapper/wiki/Migrating-from-static-API</a></p>
<p>this change breaks my system.</p>
<p>Before update, I use:</p>
<p>===> Startup.cs</p>
<pre><code>public class Startup
{
public Startup(IHostingEnvironment env)
{
...
MyAutoMapperConfiguration.Configure();
}
}
</code></pre>
<p>===> MyAutoMapperConfiguration.cs</p>
<pre><code>public class MyAutoMapperConfiguration
{
public static void Configure()
{
Mapper.Initialize(a =>
{
a.AddProfile<AbcMappingProfile>();
a.AddProfile<XyzMappingProfile>();
a.AddProfile<QweMappingProfile>();
});
}
}
</code></pre>
<p>===> AbcMappingProfile.cs</p>
<pre><code>public class AbcMappingProfile : Profile
{
protected override void Configure()
{
Mapper.CreateMap<AbcEditViewModel, Abc>();
Mapper.CreateMap<Abc, AbcEditViewModel>();
...
}
}
</code></pre>
<p>ERROR:</p>
<p>'Mapper.CreateMap()' is obsolete: 'The static API will be removed in version 5.0. Use a MapperConfiguration instance and store statically as needed. Use CreateMapper to create a mapper instanace.'</p>
<p>I can use Mapper.Map. Now How can I use it</p> | 35,256,077 | 4 | 0 | null | 2016-02-07 16:29:36.023 UTC | 10 | 2019-10-29 02:39:24.69 UTC | null | null | null | null | 5,891,846 | null | 1 | 29 | c#|asp.net|automapper | 28,989 | <p>Instead of:</p>
<pre><code>Mapper.CreateMap<AbcEditViewModel, Abc>();
</code></pre>
<p>The new syntax is:</p>
<pre><code>var config = new MapperConfiguration(cfg => {
cfg.CreateMap<AbcEditViewModel, Abc>();
});
</code></pre>
<p>Then:</p>
<pre><code>IMapper mapper = config.CreateMapper();
var source = new AbcEditViewModel();
var dest = mapper.Map<AbcEditViewModel, Abct>(source);
</code></pre>
<p>(<a href="https://lostechies.com/jimmybogard/2016/01/21/removing-the-static-api-from-automapper/">Source with more examples</a>)</p> |
50,122,867 | Gradle build fails: Unable to find method 'org.gradle.api.tasks.testing.Test.getTestClassesDirs()Lorg/gradle/api/file/FileCollection;' | <p>When i am trying to compile a imported <a href="https://github.com/iammert/AndroidArchitecture.git" rel="noreferrer">project</a> from github, my gradle build always fails with the following exeption.</p>
<pre><code>Unable to find method 'org.gradle.api.tasks.testing.Test.getTestClassesDirs()Lorg/gradle/api/file/FileCollection;'
Possible causes for this unexpected error include:<ul><li>Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
Re-download dependencies and sync project (requires network)</li><li>The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem.
Stop Gradle build processes (requires restart)</li><li>Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.</li></ul>In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes
</code></pre>
<p>I followed the instructions given but it didn't work out. Additionally i couldn't get any further information about the error by searching it in the internet</p>
<p>app\build.gradle: </p>
<pre><code> apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "iammert.com.androidarchitecture"
minSdkVersion 21
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dataBinding {
enabled = true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
/*androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})*/
// testCompile 'junit:junit:4.12'
//support lib
implementation rootProject.ext.supportLibAppCompat
implementation rootProject.ext.supportLibDesign
implementation rootProject.ext.archRuntime
implementation rootProject.ext.archExtension
annotationProcessor rootProject.ext.archCompiler
implementation rootProject.ext.roomRuntime
annotationProcessor rootProject.ext.roomCompiler
implementation rootProject.ext.okhttp
implementation rootProject.ext.retrofit
implementation rootProject.ext.gsonConverter
//dagger
annotationProcessor rootProject.ext.daggerCompiler
implementation rootProject.ext.dagger
implementation rootProject.ext.daggerAndroid
implementation rootProject.ext.daggerAndroidSupport
annotationProcessor rootProject.ext.daggerAndroidProcessor
//ui
implementation rootProject.ext.picasso
}
</code></pre>
<p>\build.gradle:</p>
<pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
maven { url 'https://maven.google.com' }
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
maven { url 'https://maven.google.com' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
ext {
supportLibVersion = '25.3.1'
daggerVersion = '2.11'
retrofitVersion = '2.1.0'
gsonConverterVersion = '2.1.0'
okhttpVersion = '3.8.0'
picassoVersion = '2.5.2'
archVersion = '1.0.0-alpha1'
supportLibAppCompat = "com.android.support:appcompat-v7:$supportLibVersion"
supportLibDesign = "com.android.support:design:$supportLibVersion"
archRuntime = "android.arch.lifecycle:runtime:$archVersion"
archExtension = "android.arch.lifecycle:extensions:$archVersion"
archCompiler = "android.arch.lifecycle:compiler:$archVersion"
roomRuntime = "android.arch.persistence.room:runtime:$archVersion"
roomCompiler = "android.arch.persistence.room:compiler:$archVersion"
dagger = "com.google.dagger:dagger:$daggerVersion"
daggerCompiler = "com.google.dagger:dagger-compiler:$daggerVersion"
daggerAndroid = "com.google.dagger:dagger-android:$daggerVersion"
daggerAndroidSupport = "com.google.dagger:dagger-android-support:$daggerVersion"
daggerAndroidProcessor = "com.google.dagger:dagger-android-processor:$daggerVersion"
retrofit = "com.squareup.retrofit2:retrofit:$retrofitVersion"
gsonConverter = "com.squareup.retrofit2:converter-gson:$gsonConverterVersion"
okhttp = "com.squareup.okhttp3:okhttp:$okhttpVersion"
picasso = "com.squareup.picasso:picasso:$picassoVersion"
}
</code></pre>
<p>gradle\gradle-wrapper.properties:</p>
<pre><code>#Thu May 18 17:31:31 EEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.0-milestone-1-all.zip
</code></pre>
<p>Does anyone know why this error occures?</p> | 50,151,053 | 11 | 0 | null | 2018-05-01 19:49:14.37 UTC | 9 | 2021-12-01 10:54:48.453 UTC | null | null | null | null | 5,131,883 | null | 1 | 65 | android|gradle | 129,442 | <p>I had to change the distributionUrl in the <code>gradle-wrapper.properties</code> to <code>distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip</code> to get the build running again. This seems to be a similar problem <a href="https://stackoverflow.com/questions/37655814/gradle-sync-failed-unable-to-find-method">Gradle sync failed: Unable to find method</a>.</p> |
32,084,607 | Android Studio - Appcompat build fail values-v23/styles_bases.xml | <p>I'll start from what I want to achieve: building the googlecast-manager example provided here: <a href="https://github.com/googlecast/GameManagerSamples" rel="noreferrer">https://github.com/googlecast/GameManagerSamples</a>
I followed instructions here: <a href="https://developers.google.com/cast/docs/android_sender" rel="noreferrer">https://developers.google.com/cast/docs/android_sender</a></p>
<p>So first I downloaded from github the project, then with the Android SDK Manager I downloaded Android Support Libraries and Google play Services. Then in my project, I went to "Open Modules Setting->Add" then went to "Android SDK\extras\android\support\v7\appcompat" and added it.</p>
<p>Then first step to ensure it's working is to build it. So I right clicked on appcompat->"Compile Module Appcompat" but it fails with 2 errors:</p>
<ol>
<li><blockquote>
<p>Error:(20, -1) android-apt-compiler: [appcompat] D:\Android
SDK\extras\android\support\v7\appcompat\res\values-v23\styles_base.xml:20:
error: Error retrieving parent for item: No resource found that
matches the given name 'android:Widget.Material.Button.Colored'.</p>
</blockquote></li>
<li><blockquote>
<p>Error:(19, -1) android-apt-compiler: [appcompat] D:\Android
SDK\extras\android\support\v7\appcompat\res\values-v23\styles_base_text.xml:19:
error: Error retrieving parent for item: No resource found that
matches the given name
'android:TextAppearance.Material.Widget.Button.Inverse'.</p>
</blockquote></li>
</ol>
<p>Doing the same for Google Play works like a charm.</p>
<p>I've tried to find videos/other similar issues but it's either too complicated or not my problem.</p>
<p>Here is the AndroidManifest.xml of appcompat:</p>
<pre><code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="android.support.v7.appcompat">
<uses-sdk android:minSdkVersion="9"
android:targetSdkVersion="19"/>
<application />
</code></pre>
<p></p>
<p>Here is what is installed from the Android SDK Manager:
<a href="https://i.stack.imgur.com/V4dMl.png" rel="noreferrer"><img src="https://i.stack.imgur.com/V4dMl.png" alt="SDK Manager top"></a>
<a href="https://i.stack.imgur.com/oKAFH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/oKAFH.png" alt="SDK Manager bottom"></a></p> | 32,138,927 | 13 | 0 | null | 2015-08-19 00:21:48.623 UTC | 5 | 2017-02-16 09:38:23.73 UTC | 2016-06-28 08:38:28.21 UTC | null | 693,387 | null | 3,556,705 | null | 1 | 29 | android|android-studio|intellij-idea|android-appcompat | 78,682 | <p>I also encountered the same problem and now have fixed it. What you just have to do is </p>
<ol>
<li><strong>Inside your Android Studio</strong>
<ol>
<li>press <kbd>Shift</kbd> button two times, a search box will appear type <strong>build.gradle</strong></li>
<li>choose <strong>build.gradle module:app</strong> from the suggestion.</li>
<li>major version of <code>compileSdkVersion</code> and <code>support libraries</code> under <code>dependencies</code> should be same as following code depict.</li>
</ol></li>
<li><strong>Inside Eclipse</strong><br>
find <code>build.gradle module:app</code> and do the same.</li>
</ol>
<p><strong>Note:</strong> download and install properly the latest <code>API</code> which is now <code>API 23</code>.</p>
<pre><code>apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.0"
defaultConfig {
applicationId "com.example.inzi.app"
minSdkVersion 9
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.0'
}
</code></pre> |
39,392,853 | Is there a type for "Class" in Typescript? And does "any" include it? | <p>In Java, you can give a <a href="https://stackoverflow.com/a/4873003/2725515">class to a method</a> as a parameter using the type "Class". I didn't find anything similar in the typescript docs - is it possible to hand a class to a method? And if so, does the type "any" include such class-types?</p>
<p>Background: I'm having an issue with Webstorm, telling me that I cannot hand over a class to <code>@ViewChild(...)</code> in Angular 2. However, the Typescript compiler does not complain. The signature of <code>@ViewChild()</code> seems to be <code>"Type<any> | Function | string"</code>, so I wonder if any includes Classes or not.</p> | 39,393,087 | 7 | 0 | null | 2016-09-08 13:54:22.517 UTC | 20 | 2021-12-17 17:34:18.513 UTC | 2017-05-23 12:32:29.923 UTC | null | -1 | null | 2,725,515 | null | 1 | 86 | angular|typescript | 99,171 | <p>The equivalent for what you're asking in typescript is the type <code>{ new(): Class }</code>, for example:</p>
<pre><code>class A {}
function create(ctor: { new(): A }): A {
return new ctor();
}
let a = create(A); // a is instanceof A
</code></pre>
<p>(<a href="https://www.typescriptlang.org/play/#src=class%20A%20%7B%7D%0D%0A%0D%0Afunction%20create(ctor%3A%20%7B%20new()%3A%20A%7D)%3A%20A%20%7B%0D%0A%09return%20new%20ctor()%3B%0D%0A%7D%0D%0A%0D%0Alet%20a%20%3D%20create(A)%3B%20%2F%2F%20a%20is%20instanceof%20A" rel="noreferrer">code in playground</a>)</p>
<p>The code above will allow only classes whose constructor has no argument. If you want any class, use <code>new (...args: any[]) => Class</code></p> |
37,576,620 | Laravel Eloquent With() With() | <p>How do I go about using multiple Eloquent With()'s?</p>
<p>PortalPlaylistElement Model</p>
<pre><code>class PortalPlaylistElement extends Model
{
public $primaryKey = 'code';
public $incrementing = false;
public $timestamps = false;
public function AirtimePlaylists()
{
return $this->hasOne('App\AirtimePlaylist','id','playlist_id');
}
}
</code></pre>
<p>AirtimePlaylistContent Model</p>
<pre><code>class AirtimePlaylistContent extends Model
{
protected $table = 'cc_playlistcontents';
}
</code></pre>
<p>AirtimePlaylistModel</p>
<pre><code>class AirtimePlaylist extends Model
{
protected $table = 'cc_playlist';
public function PortalPlaylistElements()
{
return $this->belongsTo('App\PortalPlaylistElement','playlist_id');
}
public function AirtimePlaylistContents()
{
return $this->hasMany('App\AirtimePlaylistContent','playlist_id');
}
}
</code></pre>
<p>I have no problems with:</p>
<pre><code>AirtimePlaylist::with('AirtimePlaylistContents')->get());
</code></pre>
<p>or</p>
<pre><code>PortalPlaylistElement::with('AirtimePlaylists')->get();
</code></pre>
<p>But I'd like to get all AirtimePlaylistContents, in an AirtimePlaylist that belongs to a PortalPlaylistElement.</p>
<p>In essence, (Pseudo code)</p>
<pre><code>PortalPlaylistElement::with('AirtimePlaylists')::with('AirtimePlaylistContents')->get();
</code></pre> | 37,576,704 | 3 | 0 | null | 2016-06-01 18:52:03.777 UTC | 2 | 2020-01-06 11:29:20.227 UTC | null | null | null | null | 1,079,477 | null | 1 | 12 | laravel|eloquent | 61,956 | <p>You need <a href="https://laravel.com/docs/5.2/eloquent-relationships#eager-loading" rel="noreferrer">Nested Eager Looading</a> </p>
<pre><code>PortalPlaylistElement::with('AirtimePlaylists.AirtimePlaylistContents')->get();
</code></pre> |
37,249,439 | Chartjs v2.0: stacked bar chart | <p>I need to get a chart like this:</p>
<p><a href="https://i.stack.imgur.com/hEOeY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/hEOeY.png" alt="Example Chart"></a></p>
<p>I find <a href="http://fiddle.jshell.net/leighking2/b233c2f0/" rel="noreferrer">this example</a> but it uses old version of <code>ChartJs</code>. I try it using v2.0 but I don't get it.</p>
<p>Can someone post a example?</p> | 37,251,245 | 3 | 0 | null | 2016-05-16 08:14:21.187 UTC | 6 | 2020-08-20 15:04:32.917 UTC | 2017-12-13 06:59:51.493 UTC | null | 5,159,481 | null | 1,827,284 | null | 1 | 36 | chart.js | 63,805 | <p>With v2.1.x, you can achieve this using the <code>stacked</code> option</p>
<pre><code>...
options: {
scales:{
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
...
</code></pre>
<hr>
<p><strong>Stack Snippet</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var config = {
type: 'bar',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
type: 'line',
label: 'Dataset 2',
data: [-65, -10, -80, -81, -56, -85, 40],
borderColor: 'black',
fill: false
}, {
type: 'bar',
label: 'Dataset 1',
backgroundColor: "red",
data: [65, 0, 80, 81, 56, 85, 40],
}, {
type: 'bar',
label: 'Dataset 3',
backgroundColor: "blue",
data: [-65, 0, -80, -81, -56, -85, -40]
}]
},
options: {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
};
var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.0/Chart.bundle.min.js"></script>
<canvas id="myChart"></canvas></code></pre>
</div>
</div>
</p> |
31,577,096 | ConcurrentHashMap, which concurrent features improved in JDK8 | <p>Can any concurrent expert explain in ConcurrentHashMap, which concurrent features improved comparing with which in previous JDKs</p> | 31,581,438 | 2 | 0 | null | 2015-07-23 02:17:14.983 UTC | 9 | 2017-09-07 03:34:02.637 UTC | null | null | null | null | 1,223,304 | null | 1 | 12 | concurrency|java-8|concurrenthashmap | 2,719 | <p>Well, the <code>ConcurrentHashMap</code> has been entirely rewritten. Before Java 8, each <code>ConcurrentHashMap</code> had a “concurrency level” which was fixed at construction time. For compatibility reasons, there is still a <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html#ConcurrentHashMap-int-float-int-">constructor accepting such a level</a> though not using it in the original way. The map was split into as many segments, as its concurrency level, each of them having its own lock, so in theory, there could be up to <em>concurrency level</em> concurrent updates, if they all happened to target different segments, which depends on the hashing.</p>
<p>In Java 8, each hash bucket can get updated individually, so as long as there are no hash collisions, there can be as many concurrent updates as its current capacity. This is in line with the new features like the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html#compute-K-java.util.function.BiFunction-"><code>compute</code></a> methods which guaranty atomic updates, hence, locking of at least the hash bucket which gets updated. In the best case, they lock indeed only that single bucket.</p>
<p>Further, the <code>ConcurrentHashMap</code> benefits from the general hash improvements applied to all kind of hash maps. When there are hash collisions for a certain bucket, the implementation will resort to a sorted map like structure within that bucket, thus degrading to a <code>O(log(n))</code> complexity rather than the <code>O(n)</code> complexity of the old implementation when searching the bucket.</p> |
35,748,734 | DJANGO - local variable 'form' referenced before assignment | <p>I'm trying to make a form get information from the user and use this information to send a email. Here's my code:</p>
<pre><code>#forms.py
from django import forms
class ContactForm(forms.Form):
nome = forms.CharField(required=True)
email = forms.EmailField(required=True)
msg = forms.CharField(
required=True,
widget=forms.Textarea
)
#views.py
from django.shortcuts import render, redirect, get_object_or_404, HttpResponseRedirect, render_to_response
from django.core.mail import send_mail
from .forms import ContactForm
def contato(request):
form_class = ContactForm
if request.method == 'POST':
form = form_class(request.POST)
if form.is_valid():
nome = request.POST.get('nome')
email = request.POST.get('email')
msg = request.POST.get('msg')
send_mail('Subject here', msg, email, ['[email protected]'], fail_silently=False)
return HttpResponseRedirect('blog/inicio')
return render(request, 'blog/inicio.html', {'form': form})
#contato.html
{% extends "blog/base.html" %}
{% block content %}
<form role="form" action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}
</code></pre>
<p>and when I try to enter in contact page I get this error:</p>
<pre><code>local variable 'form' referenced before assignment
</code></pre>
<p><a href="https://i.stack.imgur.com/utld3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/utld3.png" alt="enter image description here"></a></p>
<p>It is saying tha the error is in this line of views.py:</p>
<pre><code>return render(request, 'blog/inicio.html', {'form': form})
</code></pre>
<p>I'm a little new on Django, can you please help me?</p> | 35,748,798 | 4 | 0 | null | 2016-03-02 13:35:01.273 UTC | 6 | 2022-01-23 09:45:17.423 UTC | 2016-03-02 14:17:38.62 UTC | null | 1,762,988 | null | 5,255,892 | null | 1 | 10 | python|django|forms|django-forms | 39,456 | <p>You define the <code>form</code> variable in this <code>if request.method == 'POST':</code> block.
If you access the <code>view</code> with a GET request <code>form</code> gets not defined.
You should change the view to something like this:</p>
<pre><code>def contato(request):
form_class = ContactForm
# if request is not post, initialize an empty form
form = form_class(request.POST or None)
if request.method == 'POST':
if form.is_valid():
nome = request.POST.get('nome')
email = request.POST.get('email')
msg = request.POST.get('msg')
send_mail('Subject here', msg, email, ['[email protected]'], fail_silently=False)
return HttpResponseRedirect('blog/inicio')
return render(request, 'blog/inicio.html', {'form': form})
</code></pre> |
51,222,559 | Formik & yup form validation not working as expected with VirtualizedSelect | <p>I created a form with formik in order to have form validations.
I have used the components Formik, Form, Field form formik and configured them:</p>
<pre><code> import { Formik, Form, Field } from "formik";
import { object, string } from "yup";
import isEmpty from "lodash/isEmpty";
import FormikSelectInput from "../common/FormikSelectInput";
class App extends Component {
render() {
const options = this.props.categories.map(c => {
return { label: c.name, value: c.name };
});
return (
<Formik
validationSchema={object().shape({
category: string().required("Category is required.")
})}
initialValues={this.props.obj}
onSubmit={(values, actions) => {
console.log(values);
}}
render={({ errors, dirty, isSubmitting, setFieldValue }) => (
<Form>
<Field
name="category"
label="Categories"
value={this.props.obj.category.name}
options={options}
component={FormikSelectInput}
/>
<button
type="submit"
className="btn btn-default"
disabled={isSubmitting || !isEmpty(errors) || !dirty}
>
Save
</button>
</Form>
)}
/>
);
}
}
//Prop Types validation
App.propTypes = {
obj: PropTypes.object.isRequired,
categories: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired
};
const getElementByID = (items, id) => {
let res = items.filter(l => l.id === id);
return res.length ? res[0] : null; //since filter returns an array we need to check for res.length
};
//Redux connect
const mapStateToProps = ({ objects, categories }, ownProps) => {
let obj = {
id: "",
name: "",
category: { id: "", name: "" }
};
return {
obj: getElementByID(objects, ownProps.match.params.id) || obj,
categories: categories
};
};
export default connect(
mapStateToProps,
{...}
)(App);
</code></pre>
<p>And I have a custom component 'FormikSelectInput':</p>
<pre><code>import React, { Component } from "react";
import classnames from "classnames";
import VirtualizedSelect from "react-virtualized-select";
import "react-select/dist/react-select.css";
import "react-virtualized/styles.css";
import "react-virtualized-select/styles.css";
const InputFeedback = ({ children }) => (
<span className="text-danger">{children}</span>
);
const Label = ({ error, children, ...props }) => {
return <label {...props}>{children}</label>;
};
class FormikSelectInput extends Component {
constructor(props) {
super(props);
this.state = { selectValue: this.props.value };
}
render() {
const {
field: { name, ...field }, // { name, value, onChange, onBlur }
form: { touched, errors }, // also values, setXXXX, handleXXXX, dirty, isValid, status, etc.
className,
label,
...props
} = this.props;
const error = errors[name];
const touch = touched[name];
const classes = classnames(
"form-group",
{
"animated shake error": !!error
},
className
);
console.log("props", props);
return (
<div className={classes}>
<Label htmlFor={name} error={error}>
{label}
</Label>
<VirtualizedSelect
name={name}
id={name}
className="form-control"
{...field}
{...props}
onChange={(selectValue) => this.setState(() => {
this.props.form.setFieldValue('category',selectValue)
return { selectValue }
})}
value={this.state.selectValue}
/>
{touch && error && <InputFeedback>{error}</InputFeedback>}
</div>
);
}
}
export default FormikSelectInput;
</code></pre>
<p>My component is working and I am able to select an option, but why formik together with 'yup' validation showing me an error when I empty the select field. </p>
<p>When I clear my select field I get an ERROR - 'category must be a <code>string</code> type, but the final value was: <code>null</code>. If "null" is intended as an empty value be sure to mark the schema as <code>.nullable()</code>'</p>
<p><a href="https://i.stack.imgur.com/bThkd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bThkd.png" alt="enter image description here"></a></p>
<p>My code is based on the <a href="https://keyholesoftware.com/2017/10/23/the-joy-of-forms-with-react-and-formik/?subscribe=success#blog_subscription-6" rel="noreferrer">this example</a>.</p> | 51,233,885 | 2 | 0 | null | 2018-07-07 11:05:07.12 UTC | null | 2022-02-15 15:17:31.63 UTC | 2018-07-08 13:41:08.093 UTC | null | 6,261,230 | null | 6,261,230 | null | 1 | 22 | javascript|reactjs|react-select|formik | 51,525 | <p>It looks like the field is expecting the string to be required based on your <code>validationSchema</code>.</p>
<p>The error helped point me in the right direction. Here's the docs for Yup <code>.nullable()</code>: <a href="https://github.com/jquense/yup#mixednullableisnullable-boolean--true-schema" rel="noreferrer">https://github.com/jquense/yup#mixednullableisnullable-boolean--true-schema</a></p>
<p>Try adding .nullable() to the chain of validations.</p>
<p><code>validationSchema={object().shape({
category: string().required("Category is required.").nullable()
})}
</code></p>
<p>Hope this helps.
<a href="https://i.stack.imgur.com/8bOCQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8bOCQ.png" alt="enter image description here"></a></p> |
21,384,067 | Unable to load dll file - exception 0x8007007E | <p>I'm working with National Instruments Measurement Studio in C#, and I've come across a bit of a problem in deploying my application to a particular computer (running Windows 7). I've tried asking on the National Instruments forums, but haven't got any solutions yet - could anyone here give me some tips?</p>
<p>Essentially, I have deployed this application several times on a number of computers, but in this particular case I receive an error when running the program -</p>
<blockquote>
<p>"System.DllNotFoundException: Unable to load DLL 'nianlys.dll': The specified module could not be found. (Exception from HRESULT: 0x80070007E)</p>
</blockquote>
<ul>
<li><p>I have ensured that nianlys.dll is present in C:\Program Files
(x86)\National Instruments\Shared\Analysis.</p></li>
<li><p>I have ensured that libiomp5md.dll and LV110000_BLASLAPACK.dll, the files from mkl.msm (nianlys.dll has a dependency on mkl.msm), are present. nianlys.dll also has a dependency on nimetautils.msm, but I'm not sure which dlls are included in this.</p></li>
<li><p>I have ensured the program is installed by running the setup.exe as an administrator (as opposed to running the .msi that is generated, see <a href="http://forums.ni.com/t5/Measurement-Studio-for-NET/unable-to-load-dll-nianlys-dll/m-p/596323/highlight/true#M5940" rel="nofollow noreferrer">here</a>).</p></li>
<li><p>I have ensured the computer in question is up to date with updates to the .net framework via windows update.</p></li>
<li><p>I have tried reinstalling the program several times, sometimes with a freshly-recompiled installer.</p></li>
<li><p>I have tried adding in the 64 bit nianlys.msm into the setup project manually - this throws an error because the TargetPlatform property of the setup project is set to x86. The 32 bit version is, of course, already present in the detected dependencies.</p></li>
<li><p>Interestingly, taking a copy of nianlys.dll from C:\Program Files (x86)\National Instruments\Shared\Analysis and inserting it into the directory the program is installed in throws up a different error - in this case, the error is:</p>
<blockquote>
<p>"An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)"</p>
</blockquote></li>
<li><p>Taking a copy of the 64 bit version of nianlys.dll from another computer (default location C:\Program Files\National Instruments\Shared\Analysis) and inserting it into the directory the program is installed in throws up a third type of error - "System.DllNotFoundException: Unable to load DLL 'nianlys.dll': A dynamic link library (DLL) initialization routine failed. (Exception from HRESULT: 0x8007045A)". It should be noted that this .dll was present before installing the program on the machines that the program works on, but is <em>not</em> present on the target computer that is throwing up problems.</p></li>
<li><p>Taking the same 64 bit nianlys.dll and inserting it into the location it was found on on another computer, C:\Program Files\National Instruments\Shared\Analysis, does not solve the original error.</p></li>
<li><p>Even more interestingly, I have tried to reproduce the error on a computer on which the program works - removing the x64 version of nianlys.dll throws up the original HRESULT: 0x80070007E error, whereas removing the x86 version causes a windows installer to appear when running the program.</p></li>
<li><p>On a computer upon which the program works with no problems, the windows task manager does not seem to indicate that the program is 32 bit (with the *32 suffix on the program name), despite the target platform being set to x86. It seems from all this that there is some issue with the nianlys.dll being used in both its x64 and x86 versions, despite the target platform only being x86.</p></li>
</ul>
<p>I'm running out of ideas about what kind of thing I could try to solve this problem.</p> | 21,384,313 | 2 | 0 | null | 2014-01-27 14:59:14.693 UTC | 1 | 2019-04-09 07:45:10.597 UTC | 2018-12-21 10:40:45.017 UTC | null | 1,033,581 | null | 2,823,789 | null | 1 | 3 | c#|.net|dll | 51,070 | <p>I suspect that even though the <em>setup</em> is for X86, the project itself is <em>AnyCPU</em> and thus runs as a 64bit process on 64bit systems and as a 32bit process on 32bit systems. As you said your DLL is in the Program Files (x86) folder I assume it is 32bit only, so you should compile your application explicitly as x86, too. It is your bullet #7 that leads me to this conclusion.</p>
<p>Just copying the <code>nianlys.dll</code> 64bit DLL doesn't seem to work as it seems to rely on other DLLs it then can't find. (bullet #8).</p> |
45,213,279 | How to avoid using relative path imports (/../../../redux/action/action1) in create-react-app | <p>I've been using create-react-app package for creating a react website. I was using relative paths throughout my app for importing components, resources, redux etc. eg, <code>import action from '../../../redux/action</code></p>
<p>I have tried using <a href="https://www.npmjs.com/package/module-alias" rel="noreferrer">module-alis</a> npm package but with no success. Is there any plugin that I can use to import based on the folder name or alias i.e. an absolute path?</p>
<p>Eg., <code>import action from '@redux/action'</code> or <code>import action from '@resource/css/style.css'</code></p> | 45,214,138 | 9 | 1 | null | 2017-07-20 11:22:49.33 UTC | 24 | 2022-03-05 11:27:37.39 UTC | 2020-02-10 22:29:44.403 UTC | null | 203,371 | null | 2,622,795 | null | 1 | 98 | reactjs|import|create-react-app|relative-path|absolute-path | 62,287 | <p>Create a file called <code>.env</code> in the project root and write there:</p>
<pre><code>NODE_PATH=src
</code></pre>
<p>Then restart the development server. You should be able to import anything inside <code>src</code> without relative paths.</p>
<p>Note I would not recommend calling your folder <code>src/redux</code> because now it is confusing whether <code>redux</code> import refers to your app or the library. Instead you can call your folder <code>src/app</code> and import things from <code>app/...</code>.</p>
<p>We intentionally don't support custom syntax like <code>@redux</code> because it's not compatible with Node resolution algorithm. </p> |
7,433,412 | With FireMonkey and its cross-platforms, where should I store my application data? | <p>Usually, with Windows, I save my application's data in the user folder (<strong>%appdata%</strong>).</p>
<p>For that, I use the function <code>ExpandEnvironmentStrings</code> which is linked to Windows to get the folder I need, and I store inside a subfolder my <em>inifile</em>.</p>
<p>Is there any best practice to manage that and be compliant with all the supported platforms (Windows 32b, 64b & Mac)?</p>
<hr>
<p>I successfully tested like that:</p>
<pre><code>procedure TfrmMain.SaveSettings;
var
fnINI: TFileName;
ini : TIniFile;
begin
fnINI := IncludeTrailingPathDelimiter(GetHomePath) + IncludeTrailingPathDelimiter(APP_NAME) + ChangeFileExt(APP_NAME, '.ini');
if ForceDirectories(ExtractFilePath(fnINI)) then
begin
ini := TIniFile.Create(fnINI);
try
ini.WriteString(INI_CONNECTION, INI_IP, edtIP.Text);
finally
ini.Free;
end;
end;
end;
</code></pre> | 7,433,598 | 1 | 5 | null | 2011-09-15 15:28:53.197 UTC | 10 | 2016-01-16 19:12:20.083 UTC | 2016-01-16 19:12:20.083 UTC | null | 4,370,109 | null | 596,852 | null | 1 | 23 | delphi|directory|delphi-xe2|firemonkey | 3,367 | <p>Haven't tried XE2 but probably you could use <a href="http://docwiki.embarcadero.com/VCL/en/SysUtils.GetHomePath" rel="noreferrer">SysUtils.GetHomePath</a>. Also check <code>IOUtils</code> where you can find useful records (<a href="http://docwiki.embarcadero.com/VCL/en/IOUtils.TFile" rel="noreferrer">TFile</a>, <a href="http://docwiki.embarcadero.com/VCL/XE2/en/IOUtils.TPath" rel="noreferrer">TPath</a>, <a href="http://docwiki.embarcadero.com/VCL/XE2/en/IOUtils.TDirectory" rel="noreferrer">TDirectory</a>) for managing files, paths and directories. They should support different platforms.</p> |
7,278,409 | HTML5 drag and drop to move a div anywhere on the screen? | <p>The title is pretty self explanatory.</p>
<p>All the demos I've found consist in dropping a div to a certain location. E.G a trashcan. I need to make a draggable div that can be dropped anywhere on the screen.</p>
<p>Is it possible to do this with HTML5? if not how should I do it?</p> | 7,290,395 | 1 | 2 | null | 2011-09-02 01:30:29.477 UTC | 16 | 2020-07-02 12:49:03.133 UTC | 2011-09-02 01:35:58.973 UTC | null | 535,967 | null | 535,967 | null | 1 | 27 | html|drag-and-drop | 66,457 | <p>It's quite straightforward really:</p>
<ol>
<li>In the <code>dragstart</code> event calculate the offset between where the user clicked on the draggable element and the top left corner</li>
<li>Make sure the <code>dragover</code> event is applied to the entire document so the element can be dropped anywhere</li>
<li>In the <code>drop</code> event, use the offset you calculated with the <code>clientX</code> and <code>clientY</code> of the drop to work out where to position the element</li>
</ol>
<p><a href="http://jsfiddle.net/robertc/kKuqH/" rel="noreferrer">Here's one</a> I <a href="https://stackoverflow.com/questions/6230834/html5-drag-and-drop-anywhere-on-the-screen">prepared earlier</a>. For bonus points you can update the top and left position of the element in the <a href="https://stackoverflow.com/questions/2438320/html5-dragover-drop-how-get-current-x-y-coordinates">dragover event</a>, this is useful if the bit you're allowing to be dragged isn't the whole element that needs to be moved.</p> |
22,835,289 | How to get tkinter canvas to dynamically resize to window width? | <p>I need to get a canvas in tkinter to set its width to the width of the window, and then dynamically re-size the canvas when the user makes the window smaller/bigger. </p>
<p>Is there any way of doing this (easily)?</p> | 22,837,522 | 4 | 0 | null | 2014-04-03 10:50:26.29 UTC | 20 | 2021-11-05 19:05:59.367 UTC | 2017-03-15 01:04:08.557 UTC | null | 3,924,118 | null | 3,334,697 | null | 1 | 46 | python|canvas|python-3.x|tkinter|autoresize | 125,071 | <p>I thought I would add in some extra code to expand on <a href="https://stackoverflow.com/a/22835732/3357935">@fredtantini's answer</a>, as it doesn't deal with how to update the shape of widgets drawn on the <code>Canvas</code>.</p>
<p>To do this you need to use the <code>scale</code> method and tag all of the widgets. A complete example is below.</p>
<pre><code>from Tkinter import *
# a subclass of Canvas for dealing with resizing of windows
class ResizingCanvas(Canvas):
def __init__(self,parent,**kwargs):
Canvas.__init__(self,parent,**kwargs)
self.bind("<Configure>", self.on_resize)
self.height = self.winfo_reqheight()
self.width = self.winfo_reqwidth()
def on_resize(self,event):
# determine the ratio of old width/height to new width/height
wscale = float(event.width)/self.width
hscale = float(event.height)/self.height
self.width = event.width
self.height = event.height
# resize the canvas
self.config(width=self.width, height=self.height)
# rescale all the objects tagged with the "all" tag
self.scale("all",0,0,wscale,hscale)
def main():
root = Tk()
myframe = Frame(root)
myframe.pack(fill=BOTH, expand=YES)
mycanvas = ResizingCanvas(myframe,width=850, height=400, bg="red", highlightthickness=0)
mycanvas.pack(fill=BOTH, expand=YES)
# add some widgets to the canvas
mycanvas.create_line(0, 0, 200, 100)
mycanvas.create_line(0, 100, 200, 0, fill="red", dash=(4, 4))
mycanvas.create_rectangle(50, 25, 150, 75, fill="blue")
# tag all of the drawn widgets
mycanvas.addtag_all("all")
root.mainloop()
if __name__ == "__main__":
main()
</code></pre> |
22,739,920 | Where to start with creating Minecraft client mods | <p>I've looked all over the net and YouTube and for some reason this is some top secret information or something but I'm trying to find out where to get started on making a Minecraft client mod, preferably something that can be put into a pack like feed the beast or technicpack for simplicity for users but either way is fine.</p>
<p>How would I go about creating a mod? I'm familiar with eclipse and java programming itself but I don't know where to start writing a plugin.</p>
<p>I've tried setting up Minecraft Forge but for some reason it is so incredibly confusing and very messy. can't I just include some Minecraft library, start with a simple boilerplate and go from there? (Like developing for Bukkit)</p> | 22,752,339 | 1 | 0 | null | 2014-03-30 03:29:04.543 UTC | 19 | 2018-08-26 18:02:29.55 UTC | 2014-09-14 15:01:52.377 UTC | null | 3,622,940 | null | 3,200,040 | null | 1 | 22 | java|eclipse|minecraft|minecraft-forge | 24,011 | <h1>Choosing a modding method</h1>
<p>When creating minecraft client mods my research has found that different methods of creating mods. of the choices listed here, they have different perks:</p>
<ul>
<li><strong>Source modding</strong>: Confusing to install mods, difficult to develop for, highest probability of breaking (especially after an update), but allows for the most features to be added.</li>
<li><strong>ModLoader</strong>: Easier to use, limited features, not used often, unable to find support?</li>
<li><strong><a href="http://www.minecraftforge.net/" rel="noreferrer">Minecraft Forge</a></strong>: Slightly more difficult to develop, more extendable, large API, easy to install mods, frequently used <em>(FTB, Technic)</em></li>
</ul>
<p>Minecraft Forge is probably one of the better options as of right now (March 2014) so here is a short intro to getting started:</p>
<h1>Setting up Minecraft Forge with Eclipse (Mac & PC)</h1>
<ol>
<li>Download & install <a href="http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html" rel="noreferrer"><strong>Java Development Kit 7</strong></a> (Also works w/ JDK 8, but not JDK 9+)</li>
<li>Download & install <a href="https://www.eclipse.org/downloads/packages/eclipse-standard-432/keplersr2" rel="noreferrer"><strong>eclipse</strong></a> (or other Java IDE such as IntelliJ, etc.)</li>
<li>Download <strong>Src (MDK)</strong> files of <a href="http://files.minecraftforge.net/" rel="noreferrer"><strong>Minecraft Forge</strong></a> for the version of Minecraft you want to develop. (<em>I Suggest Recommended</em>)</li>
<li>Extract the files to a folder of your choosing (ex. <code>/Library/Java/</code>). <strong>Windows:</strong> <strong>Shift + Right Click</strong> into the white space of the folder and select "<strong>Open command window here</strong>" OR for <strong>Mac</strong>: open Terminal and navigate to the directory of the extracted files.</li>
<li>Run this command. <strong>Windows:</strong> <code>gradlew setupDecompWorkspace</code> OR <strong>Mac:</strong> <code>./gradlew setupDecompWorkspace</code></li>
<li>If previous command finishes successfully, run the following. <strong>Windows:</strong> <code>gradlew eclipse</code> OR <strong>Mac:</strong> <code>./gradlew eclipse</code> (Note: You can substitute the name of another IDE. Ex. <code>gradlew idea</code>)</li>
<li>Open Eclipse. If this is your <em>first time</em> using eclipse you will get a popup saying "Select a workspace". If this is the case, browse to the extracted files, select the "eclipse" folder and press "OK". If this is <em>NOT your first time</em> using eclipse, go to <strong>File > Switch Workspace > other...</strong> and select the eclipse folder inside the folder where you extracted the forge files.</li>
<li>That's all, you should now have a forge environment ready to go to start creating mods.</li>
</ol>
<h1>Getting forge to work the way you would expect it to</h1>
<h3> There are no sounds playing in minecraft?</h3>
<ul>
<li>Go into the eclipse directory and copy the "assets" folder and paste it up one directory (where gradlew.bat is).</li>
</ul>
<h3> I didn't get a login screen so my username isn't there</h3>
<ul>
<li><strong>Single-Player</strong><br />
To add your username go into eclipse and navigate to "Run > Run Configurations.. > java Application > client > Arguments" and under "Program arguments:" add the following replacing "steve" with your username <code> --username steve</code>.</li>
<li><strong>Multi-Player</strong><br />
For testing in a multi-player you <strong>must</strong> authenticate yourself or the server wont allow you on. You do basically the same thing as you would in single player but instead of '--username steve' you would replace it with your Minecraft account email address and add your password as so replacing <code>312mine!</code> with your own password <code>--username [email protected] --password 321mine!</code>.<br />
<em><strong>note</strong> You can use the authenticated version in single-player as well but it's not necessary.</em></li>
</ul>
<h1>Helpful resources</h1>
<ul>
<li><strong>Video Tutorial for Setting up Minecraft Forge:</strong> <a href="http://youtu.be/ZCCyGJxEFNM" rel="noreferrer">http://youtu.be/ZCCyGJxEFNM</a></li>
<li><strong>Basic Modding:</strong> <a href="http://www.minecraftforge.net/wiki/Basic_Modding" rel="noreferrer">http://www.minecraftforge.net/wiki/Basic_Modding</a> <em>Slightly Outdated</em>
(1)</li>
<li><strong>Mod development Support:</strong> <a href="http://www.minecraftforum.net/forum/140-modification-development/" rel="noreferrer">http://www.minecraftforum.net/forum/140-modification-development/</a></li>
<li><strong>More Support:</strong> <a href="http://www.minecraftforum.net/forum/56-mapping-and-modding/" rel="noreferrer">http://www.minecraftforum.net/forum/56-mapping-and-modding/</a>
(1)</li>
</ul>
<hr />
<p><em>(1) Links Curtousy of <a href="https://stackoverflow.com/users/2536842/dylan-meeus">Dylan Meeus</a></em></p> |
41,870,968 | Dumping numpy array into an excel file | <p>I am trying to dump numpy array into an excel file using savetxt method, but I am getting this weird error on the console:</p>
<pre><code>.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e')
Process finished with exit code 1
</code></pre>
<p>And this is the details of the numpy array which i want to dump:</p>
<pre><code>[[[ 0.47185326 0.07954808 0.02773202 ..., 0.05631305 0.08299649
0.03780528]
[ 0.62651747 0.06029205 0.01570348 ..., 0.03766847 0.06287122
0.02287979]
[ 0.72675145 0.04626036 0.0107195 ..., 0.02535284 0.04664176
0.01519825]
...,
[ 0.10476404 0.57678992 0.04675674 ..., 0.02255989 0.06741234
0.0170289 ]
[ 0.13148287 0.47490281 0.06038339 ..., 0.03263607 0.07844847
0.02505469]
[ 0.14134221 0.35699606 0.07600202 ..., 0.04766588 0.09139989
0.0386818 ]]]
Type of first_layer_output : <class 'numpy.ndarray'>
Shape of first_layer_output : (1, 921600, 10)
</code></pre>
<p>And I am using savetxt this way:</p>
<pre><code>np.savetxt('test.csv', first_layer_output, delimiter=',')
</code></pre>
<p>I am not sure what's wrong here, thus any help will be appreciated :)</p> | 41,875,701 | 2 | 0 | null | 2017-01-26 10:03:59.957 UTC | 2 | 2018-05-24 10:29:40.68 UTC | null | null | null | null | 4,730,816 | null | 1 | 13 | python|arrays|excel|numpy | 76,251 | <p>you could use pandas, its really easy friendly to use.</p>
<pre><code>import pandas as pd
## convert your array into a dataframe
df = pd.DataFrame (array)
## save to xlsx file
filepath = 'my_excel_file.xlsx'
df.to_excel(filepath, index=False)
</code></pre>
<p>hope it helps!</p> |
2,670,871 | MySQL Group Results by day using timestamp | <p>I need to take the following query and pull the total order counts and sum of the orders grouped by day. I'm storing everything using timestamps.</p>
<pre><code>SELECT
COUNT(id) as order_count,
SUM(price + shipping_price) as order_sum,
DAY(FROM_UNIXTIME(created)) as day
FROM `order`
WHERE '.implode(' AND ', $where).'
</code></pre>
<p>I need to group by DAY but when I do for this past weekend's sales it takes my order_count and makes it 1 instead of 3. How can I pull the above values grouped by day?</p>
<p>NOTE: The implode is used ONLY to define the time period (WHERE created >= TIMESTAMP AND <= TIMESTAMP)</p>
<p><strong>Update</strong></p>
<p>Without GROUP BY <code>day</code></p>
<pre><code>Array (
[order_count] => 3
[order_sum] => 69.70
[day] => 17
)
</code></pre>
<p>With GROUP BY <code>day</code></p>
<pre><code>Array (
[order_count] => 1
[order_sum] => 24.90
[day] => 17
)
</code></pre>
<p>I need this query to return each day that had sales, how many orders, and the sum of those sales. I'm missing a piece of the puzzle here somewhere....</p> | 2,670,906 | 3 | 1 | null | 2010-04-19 21:03:27.797 UTC | 8 | 2018-01-15 14:08:28.453 UTC | 2010-04-20 14:01:36.98 UTC | null | 197,606 | null | 197,606 | null | 1 | 33 | mysql|timestamp | 41,874 | <p>Are you just forgetting to add <code>GROUP BY ...</code> at the end?</p>
<pre><code>SELECT
COUNT(id) as order_count,
SUM(price + shipping_price) as order_sum,
DAY(FROM_UNIXTIME(created)) as order_day
FROM `order`
WHERE '.implode(' AND ', $where).'
GROUP BY order_day
</code></pre>
<h2>NOTE:</h2>
<p>You cannot use <code>as day</code> for your day column because <code>day</code> is a MySQL function. Use something like <code>order_day</code>.</p>
<h2>Of Unicorns</h2>
<p>Per @OMG Unicorn's comment, you can use:</p>
<pre><code>DAY(FROM_UNIXTIME(created)) as `day`
</code></pre>
<p>So long as wrap <code>day</code> in <strong>`</strong> backticks.</p> |
3,145,700 | Javascript inheritance - instanceof not working? | <p>I'm writing a simple platform game using javascript and html5. I'm using javascript in an OO manner. To get inheritance working i'm using the following;</p>
<pre><code>// http://www.sitepoint.com/blogs/2006/01/17/javascript-inheritance/
function copyPrototype(descendant, parent) {
var sConstructor = parent.toString();
var aMatch = sConstructor.match(/\s*function (.*)\(/);
if (aMatch != null) { descendant.prototype[aMatch[1]] = parent; }
for (var m in parent.prototype) {
descendant.prototype[m] = parent.prototype[m];
}
};
</code></pre>
<p>For the sake of this post consider the following example;</p>
<pre><code>function A() {
this.Name = 'Class A'
}
A.prototype.PrintName = function () {
alert(this.Name);
}
function B() {
this.A();
}
copyPrototype(B, A);
function C() {
this.B();
}
copyPrototype(C, B);
var instC = new C();
if (instC instanceof A)
alert ('horray!');
</code></pre>
<p>As I understand it I would expect to see a horray alert box, because C is an instance of C & B & A. Am I wrong? Or am I just using the wrong method to check? Or has copyPrototype knackered the instanceof operator?</p>
<p>Thanks as always for taking the time to read this!</p>
<p>Shaw.</p> | 25,168,207 | 4 | 0 | null | 2010-06-30 00:17:12.33 UTC | 10 | 2014-08-07 13:20:14.86 UTC | 2013-11-20 11:47:55.703 UTC | null | 192,305 | null | 192,305 | null | 1 | 16 | javascript|oop|inheritance|instanceof | 16,966 | <p>These days you shouldn't need .prototype = new Thing(), I think I'm late to the party but you can just use Object.create on the prototype of the parent and then override the methods you're interested in overriding. An example:</p>
<pre><code>var IDataSource = function(){
throw new Error("Not implemented, interface only");
};
IDataSource.prototype.getData = function(){
throw new Error("Not implemented.");
};
var BasicDataSource = function(){};
BasicDataSource.prototype = Object.create(IDataSource.prototype);
BasicDataSource.prototype.getData = function(){
//[do some stuff, get some real data, return it]
return "bds data";
};
var MockDataSource = function(){};
MockDataSource.prototype = Object.create(IDataSource.prototype);
MockDataSource.prototype.getData = function(){
//[DONT DO some stuff return mock json]
return "mds data";
};
MockDataSource.prototype.getDataTwo = function(){
//[DONT DO some stuff return mock json]
return "mds data2";
};
var MockDataSource2 = function(){};
MockDataSource2.prototype = Object.create(MockDataSource.prototype);
var bds = new BasicDataSource();
console.log("bds is NOT MockDataSource:", bds instanceof MockDataSource);
console.log("bds is BasicDataSource:", bds instanceof BasicDataSource);
console.log("bds is an IDataSource:", bds instanceof IDataSource);
console.log("bds Data:", bds.getData());
var mds = new MockDataSource();
console.log("mds is MockDataSource:", mds instanceof MockDataSource);
console.log("mds is NOT a BasicDataSource:", mds instanceof BasicDataSource);
console.log("mds is an IDataSource:", mds instanceof IDataSource);
console.log("mds Data:", mds.getData());
console.log("mds Data2:",mds.getDataTwo());
var mds2 = new MockDataSource2();
console.log("mds2 is MockDataSource2:", mds2 instanceof MockDataSource2);
console.log("mds2 is MockDataSource:", mds2 instanceof MockDataSource);
console.log("mds2 is NOT a BasicDataSource:", mds2 instanceof BasicDataSource);
console.log("mds2 is an IDataSource:", mds2 instanceof IDataSource);
console.log("mds2 Data:", mds2.getData());
console.log("mds2 Data2:",mds2.getDataTwo());
</code></pre>
<p>If you run this code in node you will get: </p>
<pre><code>bds is NOT MockDataSource: false
bds is BasicDataSource: true
bds is an IDataSource: true
bds Data: bds data
mds is MockDataSource: true
mds is NOT a BasicDataSource: false
mds is an IDataSource: true
mds Data: mds data
mds Data2: mds data2
mds2 is MockDataSource2: true
mds2 is MockDataSource: true
mds2 is NOT a BasicDataSource: false
mds2 is an IDataSource: true
mds2 Data: mds data
mds2 Data2: mds data2
</code></pre>
<p>No worry about parameters to constructors or any such craziness.</p> |
2,612,152 | drawRect not being called in my subclass of UIImageView | <p>I have subclassed UIImageView and tried to override drawRect so I could draw on top of the image using Quartz 2D. I know this is a dumb newbie question, but I'm not seeing what I did wrong. Here's the interface:</p>
<pre><code>#import <UIKit/UIKit.h>
@interface UIImageViewCustom : UIImageView {
}
- (void)drawRect:(CGRect)rect;
@end
</code></pre>
<p>And the implementation:</p>
<pre><code>#import "UIImageViewCustom.h"
@implementation UIImageViewCustom
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
}
return self;
}
- (void)drawRect:(CGRect)rect {
// do stuff
}
- (void)dealloc {
[super dealloc];
}
@end
</code></pre>
<p>I set a breakpoint on <code>drawRect</code> and it never hits, leading me to think it never gets called at all. Isn't it supposed to be called when the view first loads? Have I incorrectly overridden it?</p> | 2,612,185 | 4 | 2 | null | 2010-04-10 03:40:28.42 UTC | 11 | 2014-12-11 07:11:38.583 UTC | 2010-04-10 18:16:58.903 UTC | null | 30,461 | null | 3,279 | null | 1 | 42 | iphone|objective-c|cocoa-touch|uikit | 24,956 | <p>It'll only get called if the view is visible, and dirty. Maybe the problem is in the code that creates the view, or in your Nib, if that's how you're creating it?</p>
<p>You'll also sometimes see breakpoints failing to get set properly if you're trying to debug a "Release" build.</p>
<hr>
<p>I somehow missed the first time that you're subclassing UIImageView. From the docs:</p>
<blockquote>
<p>Special Considerations</p>
<p>The UIImageView class is optimized to
draw its images to the display.
UIImageView will not call drawRect: in a
subclass. If your subclass needs
custom drawing code, it is recommended
you use UIView as the base class.</p>
</blockquote>
<p>So there you have it. Given how easy it is to draw an image into your view using [UIImage drawInRect:], or by using CALayer, there's probably no good reason to subclass UIImageView anyway.</p> |
3,016,974 | How to get text in QlineEdit when QpushButton is pressed in a string? | <p>I am trying to implement a function. My code is given below.</p>
<p>I want to get the text in lineedit with objectname 'host' in a string say 'shost' when the user clicks the pushbutton with name 'connect'. How can I do this? I tried and failed. How do I implement this function?</p>
<pre><code>import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
le = QLineEdit()
le.setObjectName("host")
le.setText("Host")
pb = QPushButton()
pb.setObjectName("connect")
pb.setText("Connect")
layout.addWidget(le)
layout.addWidget(pb)
self.setLayout(layout)
self.connect(pb, SIGNAL("clicked()"),self.button_click)
self.setWindowTitle("Learning")
def button_click(self):
#i want the text in lineedit with objectname
#'host' in a string say 'shost'. when the user click
# the pushbutton with name connect.How do i do it?
# I tried and failed. How to implement this function?
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
</code></pre>
<p>Now how do I implement the function "button_click" ? I have just started with pyQt!</p> | 3,018,000 | 4 | 0 | null | 2010-06-10 17:42:23.02 UTC | 12 | 2021-10-23 12:52:53.603 UTC | 2020-08-26 07:31:57.267 UTC | null | 2,119,941 | null | 363,661 | null | 1 | 51 | python|pyqt5|pyqt4|qlineedit | 211,272 | <p>My first suggestion is to use Qt Designer to create your GUIs. Typing them out yourself sucks, takes more time, and you will definitely make more mistakes than Qt Designer.</p>
<p>Here are some <a href="https://web.archive.org/web/20130704101140/http://www.diotavelli.net/PyQtWiki/Tutorials" rel="noreferrer">PyQt tutorials</a> to help get you on the right track. The first one in the list is where you should start.</p>
<p>A good guide for figuring out what methods are available for specific classes is the <a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/classes.html" rel="noreferrer">PyQt4 Class Reference</a>. In this case, you would look up <code>QLineEdit</code> and see the there is a <code>text</code> method.</p>
<p>To answer your specific question:</p>
<p>To make your GUI elements available to the rest of the object, preface them with <code>self.</code></p>
<pre><code>import sys
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QDialog, QApplication, QPushButton, QLineEdit, QFormLayout
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.le = QLineEdit()
self.le.setObjectName("host")
self.le.setText("Host")
self.pb = QPushButton()
self.pb.setObjectName("connect")
self.pb.setText("Connect")
layout = QFormLayout()
layout.addWidget(self.le)
layout.addWidget(self.pb)
self.setLayout(layout)
self.connect(self.pb, SIGNAL("clicked()"),self.button_click)
self.setWindowTitle("Learning")
def button_click(self):
# shost is a QString object
shost = self.le.text()
print shost
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
</code></pre> |
29,298,346 | XMPP SASL SCRAM-SHA1 Authentication | <p>Recently, I was able to get MD5 authentication working for XMPP streams in Swift IOS following the instructions on the following two websites (I used the CC-MD5 function of Apple's CommonCrypto C library for the actual hashing):</p>
<p><a href="http://wiki.xmpp.org/web/SASLandDIGEST-MD5" rel="nofollow noreferrer">http://wiki.xmpp.org/web/SASLandDIGEST-MD5</a></p>
<p><a href="http://www.deusty.com/2007/09/example-please.html" rel="nofollow noreferrer">http://www.deusty.com/2007/09/example-please.html</a></p>
<p>I'm searching for a similar explanation for how to get other hashed SASL authentication schemes working, especially SCRAM-SHA1. I have found the official <a href="https://www.rfc-editor.org/rfc/rfc5802" rel="nofollow noreferrer">RFC5802</a> document but I'm having a lot of trouble understanding it (it is not specific to XMPP either). I would appreciate a simpler explanation or some simple readable code (C, PHP, C++, Javascript, Java) specific to XMPP authentication that doesn't use libraries for anything other than the actual hashing.</p>
<p>I'm interested in understanding the process and am not looking to use the ios XMPP-Framework. Any help would be appreciated.</p> | 29,299,946 | 1 | 1 | null | 2015-03-27 10:21:58.917 UTC | 12 | 2016-10-26 12:27:02.333 UTC | 2021-10-07 07:59:29.08 UTC | null | -1 | null | 4,577,867 | null | 1 | 14 | authentication|xmpp|sasl|sasl-scram | 15,360 | <h2>SCRAM-SHA-1</h2>
<p>The basic overview of how this mechanism works is:</p>
<ul>
<li>The client sends the username it wants to authenticate as.</li>
<li>The server sends back the salt for that user and the number of iterations (either by generating them or looking them up in its database for the given username).</li>
<li>The client hashes the password with the given salt for the given number of iterations.</li>
<li>The client sends the result back.</li>
<li>The server does a variation of the hashing and sends it result back to the client, so the client can also verify that the server had the password/a hash of the password.</li>
</ul>
<p>The cryptographic algorithms you'll need are SHA-1, HMAC with SHA-1 and <a href="https://www.rfc-editor.org/rfc/rfc2898" rel="noreferrer">PBKDF2</a> with SHA-1. You should look up how to use them in your language/framework, as I don't recommend implementing them from scratch.</p>
<h3>In detail</h3>
<ol>
<li><p>First normalize the password (using <a href="https://www.rfc-editor.org/rfc/rfc4013" rel="noreferrer">SASLprep</a>), this will be <code>normalizedPassword</code>. This is to ensure the UTF8 encoding can't contain variations of the same password.</p>
</li>
<li><p>Pick a random string (for example 32 hex encoded bytes). This will be <code>clientNonce</code>.</p>
</li>
<li><p>The <code>initialMessage</code> is <code>"n=" .. username .. ",r=" .. clientNonce</code> (I'm using <code>..</code> for string concatenation).</p>
</li>
<li><p>The client prepends the GS2 header (<code>"n,,"</code>) to the initialMessage and base64-encodes the result. It sends this as its first message:</p>
<pre class="lang-xml prettyprint-override"><code> <auth xmlns="urn:ietf:params:xml:ns:xmpp-sasl" mechanism="SCRAM-SHA-1">
biwsbj1yb21lbyxyPTZkNDQyYjVkOWU1MWE3NDBmMzY5ZTNkY2VjZjMxNzhl
</auth>
</code></pre>
</li>
<li><p>The server responds with a challenge. The data of the challenge is base64 encoded:</p>
<pre class="lang-xml prettyprint-override"><code> <challenge xmlns="urn:ietf:params:xml:ns:xmpp-sasl">
cj02ZDQ0MmI1ZDllNTFhNzQwZjM2OWUzZGNlY2YzMTc4ZWMxMmIzOTg1YmJkNGE4ZTZmODE0YjQyMmFiNzY2NTczLHM9UVNYQ1IrUTZzZWs4YmY5MixpPTQwOTY=
</challenge>
</code></pre>
</li>
<li><p>The client base64 decodes it:</p>
<pre><code> r=6d442b5d9e51a740f369e3dcecf3178ec12b3985bbd4a8e6f814b422ab766573,s=QSXCR+Q6sek8bf92,i=4096
</code></pre>
</li>
<li><p>The client parses this:</p>
<ul>
<li><code>r=</code> This is the <code>serverNonce</code>. The client MUST ensure that it starts with the <code>clientNonce</code> it sent in its initial message.</li>
<li><code>s=</code> This is the <code>salt</code>, base64 encoded (yes, this is base64-encoded twice!)</li>
<li><code>i=</code> This is the number of iterations, <code>i</code>.</li>
</ul>
</li>
<li><p>The client computes:</p>
<pre><code> clientFinalMessageBare = "c=biws,r=" .. serverNonce
saltedPassword = PBKDF2-SHA-1(normalizedPassword, salt, i)
clientKey = HMAC-SHA-1(saltedPassword, "Client Key")
storedKey = SHA-1(clientKey)
authMessage = initialMessage .. "," .. serverFirstMessage .. "," .. clientFinalMessageBare
clientSignature = HMAC-SHA-1(storedKey, authMessage)
clientProof = clientKey XOR clientSignature
serverKey = HMAC-SHA-1(saltedPassword, "Server Key")
serverSignature = HMAC-SHA-1(serverKey, authMessage)
clientFinalMessage = clientFinalMessageBare .. ",p=" .. base64(clientProof)
</code></pre>
</li>
<li><p>The client base64 encodes the <code>clientFinalMessage</code> and sends it as a response:</p>
<pre class="lang-xml prettyprint-override"><code> <response xmlns="urn:ietf:params:xml:ns:xmpp-sasl">
Yz1iaXdzLHI9NmQ0NDJiNWQ5ZTUxYTc0MGYzNjllM2RjZWNmMzE3OGVjMTJiMzk4NWJiZDRhOGU2ZjgxNGI0MjJhYjc2NjU3MyxwPXlxbTcyWWxmc2hFTmpQUjFYeGFucG5IUVA4bz0=
</response>
</code></pre>
</li>
<li><p>If everything went well, you'll get a <code><success></code> response from the server:</p>
<pre class="lang-xml prettyprint-override"><code> <success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>
dj1wTk5ERlZFUXh1WHhDb1NFaVc4R0VaKzFSU289
</success>
</code></pre>
</li>
<li><p>Base64 decoded this contains:</p>
<pre><code> v=pNNDFVEQxuXxCoSEiW8GEZ+1RSo=
</code></pre>
</li>
<li><p>The client MUST make sure the value of <code>v</code> is the base64 encoding of the <code>serverSignature</code>.</p>
</li>
</ol>
<h3>Extras</h3>
<p>This is the basic version of the algorithm. You can extend it to do:</p>
<ul>
<li><p>Channel binding. This mixes in some information from the TLS connection to the procedure to prevent MitM attacks.</p>
</li>
<li><p>Hashed storage. If the server always sends the same <code>salt</code> and <code>i</code> values, then the client can store only <code>saltedPassword</code> instead of the user's password. This is more secure (as the client doesn't need to store the password, just a hard to reverse salted hash) and faster, as the client doesn't need to do all the key stretching every time.</p>
<p>The server can also use hashed storage: the server can store only <code>salt</code>, <code>i</code>, <code>storedKey</code> and <code>serverKey</code>. More info on that <a href="https://prosody.im/doc/plain_or_hashed" rel="noreferrer">here</a>.</p>
</li>
<li><p>Possibly, also adding SCRAM-SHA-256 (though server support seems non-existent).</p>
</li>
</ul>
<h3>Pitfalls</h3>
<p>Some common pitfalls:</p>
<ul>
<li>Don't assume anything about the length of the nonces or <code>salt</code> (though if you generate them, make sure they are long enough and cryptographically random).</li>
<li>The <code>salt</code> is base64 encoded and can contain any data (embedded <code>NUL</code>s).</li>
<li>Not using SASLprep may work fine for people using ASCII passwords, but it may completely break logging in for people using other scripts.</li>
<li>The <code>initialMessage</code> part of the <code>authMessage</code> does not include the GS2 header (in most situations, this is <code>"n,,"</code>).</li>
</ul>
<h3>Test vectors</h3>
<p>If you want to test your implementation, here are all the intermediate results for the example from the RFC:</p>
<ul>
<li><p>Username: <code>user</code></p>
</li>
<li><p>Password: <code>pencil</code></p>
</li>
<li><p>Client generates the random nonce <code>fyko+d2lbbFgONRv9qkxdawL</code></p>
</li>
<li><p>Initial message: <code>n,,n=user,r=fyko+d2lbbFgONRv9qkxdawL</code></p>
</li>
<li><p>Server generates the random nonce <code>3rfcNHYJY1ZVvWVs7j</code></p>
</li>
<li><p>Server replies: <code>r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j,s=QSXCR+Q6sek8bf92,i=4096</code></p>
</li>
<li><p>The salt (hex): <code>4125c247e43ab1e93c6dff76</code></p>
</li>
<li><p>Client final message bare: <code>c=biws,r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j</code></p>
</li>
<li><p>Salted password (hex): <code>1d96ee3a529b5a5f9e47c01f229a2cb8a6e15f7d</code></p>
</li>
<li><p>Client key (hex): <code>e234c47bf6c36696dd6d852b99aaa2ba26555728</code></p>
</li>
<li><p>Stored key (hex): <code>e9d94660c39d65c38fbad91c358f14da0eef2bd6</code></p>
</li>
<li><p>Auth message: <code>n=user,r=fyko+d2lbbFgONRv9qkxdawL,r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j,s=QSXCR+Q6sek8bf92,i=4096,c=biws,r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j</code></p>
</li>
<li><p>Client signature (hex): <code>5d7138c486b0bfabdf49e3e2da8bd6e5c79db613</code></p>
</li>
<li><p>Client proof (hex): <code>bf45fcbf7073d93d022466c94321745fe1c8e13b</code></p>
</li>
<li><p>Server key (hex): <code>0fe09258b3ac852ba502cc62ba903eaacdbf7d31</code></p>
</li>
<li><p>Server signature (hex): <code>ae617da6a57c4bbb2e0286568dae1d251905b0a4</code></p>
</li>
<li><p>Client final message: <code>c=biws,r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j,p=v0X8v3Bz2T0CJGbJQyF0X+HI4Ts=</code></p>
</li>
<li><p>Server final message: <code>v=rmF9pqV8S7suAoZWja4dJRkFsKQ=</code></p>
</li>
<li><p>Server's server signature (hex): <code>ae617da6a57c4bbb2e0286568dae1d251905b0a4</code></p>
</li>
</ul> |
46,530,960 | NetBeans 8.2 does not open on Mac OS | <p>I am trying to start NetBeans 8.2 on a Macbook Pro and it's not working.</p>
<p>It shows the splash screen, then after a while it shuts down without starting anything.</p>
<p>Running from the command-line I can see this error:</p>
<pre><code>Oct 02, 2017 7:40:28 PM org.netbeans.ProxyURLStreamHandlerFactory register
SEVERE: No way to find original stream handler for jar protocol
java.lang.reflect.InaccessibleObjectException: Unable to make field transient java.net.URLStreamHandler java.net.URL.handler accessible: module java.base does not "opens java.net" to unnamed module @7823a2f9
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:337)
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:281)
at java.base/java.lang.reflect.Field.checkCanSetAccessible(Field.java:175)
at java.base/java.lang.reflect.Field.setAccessible(Field.java:169)
at org.netbeans.ProxyURLStreamHandlerFactory.register(ProxyURLStreamHandlerFactory.java:82)
at org.netbeans.JarClassLoader.<clinit>(JarClassLoader.java:141)
at org.netbeans.MainImpl.execute(MainImpl.java:178)
at org.netbeans.MainImpl.main(MainImpl.java:85)
at org.netbeans.Main.main(Main.java:83)
</code></pre>
<p>Looks like Java 9 got bundled with it and it's causing an error. The documentation implies that NetBeans 8.2 uses JDK 8!?</p>
<p>How to use my own java to run NetBeans, or how to get NetBeans to start without this error?</p> | 46,556,172 | 5 | 0 | null | 2017-10-02 17:52:37.32 UTC | 7 | 2020-01-23 23:52:58.903 UTC | null | null | null | null | 1,007,991 | null | 1 | 10 | netbeans | 40,613 | <p>Yes, NetBeans 8.2 does use JDK 1.8, and specifically does not support JDK 1.9. </p>
<p>It's unclear from the OP which version of Java is desired to run with NetBeans, but the version of NetBeans to use is governed by the version of Java to be used:</p>
<p>[1] For Java 8, use Netbeans 8.2. Note that <strong>Java 9 is not supported</strong>. You can download NetBeans 8.2 bundled with JDK 8u141 for Mac OS here:</p>
<p><a href="http://www.oracle.com/technetwork/articles/javase/jdk-netbeans-jsp-142931.html" rel="noreferrer">http://www.oracle.com/technetwork/articles/javase/jdk-netbeans-jsp-142931.html</a></p>
<p>Once it has been installed it no specific configuration for Java should be necessary.</p>
<p>[2] For Java 9 you must use a Development Build of NetBeans. That can be downloaded from <a href="http://bits.netbeans.org/download/trunk/nightly/latest/" rel="noreferrer">http://bits.netbeans.org/download/trunk/nightly/latest/</a> but be sure that <strong>Mac OS X</strong> is selected from the <strong>Platform</strong> drop list before clicking <strong>Download</strong>.</p>
<p>For any version of NetBeans you can specify your own version of Java as follows:</p>
<ul>
<li><p>Start NetBeans and select <strong>Java Platforms</strong> from the <strong>Tools</strong> menu.</p></li>
<li><p>Click the <strong>Add Platform...</strong> button.</p></li>
<li><p>Complete the wizard to locate the version of Java you want to use.</p></li>
</ul>
<p>One final point: there is no problem having multiple versions of NetBeans installed and running concurrently using different JDKs, typically NetBeans 8.2 with JDK 1.8 and NetBeans Dev Build with JDK 1.9.</p>
<p>~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~</p>
<p>Update:</p>
<p>If NetBeans closes itself down on startup it may have an invalid JDK path. To change the JDK that NetBeans uses:</p>
<ul>
<li><p>Locate the file <strong>netbeans.conf</strong>. It should be in the <strong>etc</strong> directory under the NetBeans installation directory.</p></li>
<li><p>Edit that file in a text editor. Locate the line containing the property <strong>netbeans_jdkhome</strong>. On my Windows 10 installation it looks like this:</p>
<p><strong>netbeans_jdkhome="C:\Java\jdk1.8.0_121"</strong></p></li>
<li><p>Change the value for that property to specify the path to the desired JDK, save the file and restart NetBeans.</p></li>
</ul> |
37,248,580 | How to group data in Angular 2? | <p>How can I group data in Angular 2 with TypeScript. I am aware that this is done using "group by" filter in Angular 1.X, but not getting how to group data in Angular 2. I have this array:</p>
<pre><code>import {Employee} from './employee';
export var employees: Employee[];
employees = [
{ id: 1, firstName: "John", lastName: "Sonmez", department: 1, age: 24, address: "24/7, Working hours apartment, Cal. US", contactNumber: "+968546215789" },
{ id: 2, firstName: "Mark", lastName: "Seaman", department: 2, age: 25, address: "32-C, Happy apartments, Block-9C, Cal. US", contactNumber: "+968754216984" },
{ id: 3, firstName: "Jamie", lastName: "King", department: 3, age: 32, address: "54/II, Glorydale apartment, Cal. US", contactNumber: "+967421896326" },
{ id: 5, firstName: "Jacob", lastName: "Ridley", department: 5, age: 24, address: "24/7, Working hours apartment, Cal. US", contactNumber: "+968546215789" },
{ id: 6, firstName: "Peter", lastName: "Parker", department: 3, age: 25, address: "32-C, Happy apartments, Block-9C, Cal. US", contactNumber: "+968754216984" },
{ id: 7, firstName: "Martin", lastName: "Luther", department: 4, age: 32, address: "54/II, Glorydale apartment, Cal. US", contactNumber: "+967421896326" },
{ id: 8, firstName: "Raghav", lastName: "Kumar", department: 1, age: 34, address: "51/C Shivalik, Cal. US", contactNumber: "+967842569842" },
{ id: 9, firstName: "Narayan", lastName: "Sonmez", department: 3, age: 24, address: "24/7, Working hours apartment, Cal. US", contactNumber: "+968546215789" },
{ id: 10, firstName: "Russell", lastName: "Andre", department: 2, age: 25, address: "32-C, Happy apartments, Block-9C, Cal. US", contactNumber: "+968754216984" },
{ id: 11, firstName: "Ramona", lastName: "King", department: 4, age: 32, address: "54/II, Glorydale apartment, Cal. US", contactNumber: "+967421896326" },
{ id: 12, firstName: "Andre", lastName: "Russell", department: 1, age: 34, address: "51/C Shivalik, Cal. US", contactNumber: "+967842569842" },
{ id: 13, firstName: "Nathan", lastName: "Leon", department: 1, age: 24, address: "24/7, Working hours apartment, Cal. US", contactNumber: "+968546215789" },
{ id: 14, firstName: "Brett", lastName: "Lee", department: 5, age: 25, address: "32-C, Happy apartments, Block-9C, Cal. US", contactNumber: "+968754216984" },
{ id: 15, firstName: "Tim", lastName: "Cook", department: 2, age: 32, address: "54/II, Glorydale apartment, Cal. US", contactNumber: "+967421896326" },
{ id: 16, firstName: "Steve", lastName: "Jobs", department: 5, age: 34, address: "51/C Shivalik, Cal. US", contactNumber: "+967842569842" }
];
</code></pre>
<p>and I am looking to count the employees by department, like</p>
<blockquote>
<p>Department 1 has 4 employees</p>
</blockquote>
<p>and so on.</p>
<p>Joining the department id with actual department (so that I can get the department name) is another story I need to figure out.</p> | 37,250,267 | 4 | 0 | null | 2016-05-16 07:14:47.287 UTC | 8 | 2020-07-26 05:04:25.8 UTC | 2017-12-01 08:59:51.877 UTC | null | 3,885,376 | null | 1,546,629 | null | 1 | 29 | angular|typescript1.7 | 29,591 | <p>I would create <a href="https://angular.io/docs/ts/latest/guide/pipes.html#custom-pipes" rel="noreferrer">a custom pipe</a> to do that as described below:</p>
<pre class="lang-typescript prettyprint-override"><code>@Pipe({name: 'groupBy'})
export class GroupByPipe implements PipeTransform {
transform(value: Array<any>, field: string): Array<any> {
const groupedObj = value.reduce((prev, cur)=> {
(prev[cur[field]] = prev[cur[field]] || []).push(cur);
return prev;
}, {});
return Object.keys(groupedObj).map(key => ({ key, value: groupedObj[key] }));
}
}
</code></pre>
<p>And then on your template you can write:</p>
<pre class="lang-typescript prettyprint-override"><code><div *ngFor="let item of employees | groupBy: 'department'">
Department {{ item.key }} has {{ item.value.length }} employees
</div>
</code></pre>
<p>See also corresponding plunker <a href="https://plnkr.co/edit/49fWY1rMbSZtNQ3H" rel="noreferrer">https://plnkr.co/edit/49fWY1rMbSZtNQ3H</a></p> |
318,160 | What is the difference between the KeyCode and KeyData properties on the .NET WinForms key event argument objects? | <p>The two key event argument classes <code>KeyEventArgs</code> and <code>PreviewKeyDownEventArgs</code> each have two properties, <code>KeyCode</code> and <code>KeyData</code>, which are both of the enumeration type Keys.</p>
<p>What is the difference between these two properties? Do the values in them ever differ from each other? If so, when and why?</p> | 318,177 | 2 | 0 | null | 2008-11-25 17:17:28.803 UTC | 10 | 2015-05-20 06:50:34.713 UTC | 2015-05-13 10:02:58.067 UTC | null | 2,130,976 | Turbulent Intellect | 2,729 | null | 1 | 50 | .net|winforms|events|event-handling | 8,425 | <p><code>KeyCode</code> is an enumeration that represents all the possible keys on the keyboard. <code>KeyData</code> is the <code>KeyCode</code> combined with the modifiers (Ctrl, Alt and/or Shift).</p>
<p>Use <code>KeyCode</code> when you don't care about the modifiers, <code>KeyData</code> when you do. </p> |
787,436 | How to set width to 100% in WPF | <p>Is there any way how to tell component in <strong>WPF</strong> to take 100% of available space? </p>
<p>Like </p>
<pre><code>width: 100%;
</code></pre>
<p>in CSS </p>
<p>I've got this XAML, and I don't know how to force Grid to take 100% width.</p>
<pre><code><ListBox Name="lstConnections">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Background="LightPink">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Path=User}" Margin="4"></TextBlock>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=Password}" Margin="4"></TextBlock>
<TextBlock Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Text="{Binding Path=Host}" Margin="4"></TextBlock>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</code></pre>
<p>Result looks like </p>
<p><a href="http://foto.darth.cz/pictures/wpf_width.jpg">alt text http://foto.darth.cz/pictures/wpf_width.jpg</a></p>
<p>I made it pink so it's obvious how much space does it take. I need to make the pink grid 100% width.</p> | 787,463 | 2 | 3 | null | 2009-04-24 20:20:11.94 UTC | 16 | 2021-01-19 12:20:45.177 UTC | 2016-05-02 10:03:07.313 UTC | null | 5,035,500 | null | 72,583 | null | 1 | 71 | wpf|width|autosize | 143,855 | <p>It is the container of the <code>Grid</code> that is imposing on its width. In this case, that's a <code>ListBoxItem</code>, which is left-aligned by default. You can set it to stretch as follows:</p>
<pre><code><ListBox>
<!-- other XAML omitted, you just need to add the following bit -->
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</code></pre> |
2,822,525 | How can I convert Perl one-liners into complete scripts? | <p>I find a lot of Perl one-liners online. Sometimes I want to convert these one-liners into a script, because otherwise I'll forget the syntax of the one-liner.</p>
<p>For example, I'm using the following command (from <a href="http://support.nagios.com/knowledgebase/faqs/index.php?option=com_content&view=article&id=52&catid=35&faq_id=70&expand=false&showdesc=true" rel="noreferrer">nagios.com</a>):</p>
<pre><code>tail -f /var/log/nagios/nagios.log | perl -pe 's/(\d+)/localtime($1)/e'
</code></pre>
<p>I'd to replace it with something like this:</p>
<pre><code>tail -f /var/log/nagios/nagios.log | ~/bin/nagiostime.pl
</code></pre>
<p>However, I can't figure out the best way to quickly throw this stuff into a script. Does anyone have a quick way to throw these one-liners into a Bash or Perl script?</p> | 2,822,721 | 6 | 2 | null | 2010-05-12 20:30:21.637 UTC | 10 | 2010-05-16 00:11:30.393 UTC | 2010-05-16 00:11:30.393 UTC | null | 2,766,176 | null | 110,223 | null | 1 | 18 | perl|command-line | 3,927 | <p>You can convert any Perl one-liner into a full script by passing it through the <code>B::Deparse</code> compiler backend that generates Perl source code:</p>
<pre><code>perl -MO=Deparse -pe 's/(\d+)/localtime($1)/e'
</code></pre>
<p>outputs:</p>
<pre><code>LINE: while (defined($_ = <ARGV>)) {
s/(\d+)/localtime($1);/e;
}
continue {
print $_;
}
</code></pre>
<p>The advantage of this approach over decoding the command line flags manually is that this is exactly the way Perl interprets your script, so there is no guesswork. <code>B::Deparse</code> is a core module, so there is nothing to install.</p> |
2,998,503 | How do I change Process Template on an existing Team Project in TFS 2010? | <p>How do I change process template to MSF for Agile on an already existing team project in TFS 2010?</p>
<p>We have upgraded our TFS 2008 to 2010, and now I would also like to change the process template to MSF for Agile (currently CMMI).
We haven't used the workitem functionality much so if some information gets lost in the conversion doesn't matter.</p> | 2,999,219 | 6 | 0 | null | 2010-06-08 14:57:27.107 UTC | 10 | 2014-01-06 11:51:35.463 UTC | 2014-01-06 11:51:35.463 UTC | null | 759,866 | null | 207,831 | null | 1 | 28 | tfs-process-template | 34,130 | <p>Once you've created a Team Project, you unfortunately can't just upload a new process template. As Robaticus says, you'll have to download the XML for the template and modify it, then re-upload it. The power tool lets you create NEW templates for NEW team projects, but it won't modify an existing one. </p>
<p>Instead, you can use the <strong>witadmin.exe</strong> tool (on any computer with Team Explorer installed, under \Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE, or just from a Visual Studio Command Prompt) to export the current workitem definitions and re-import them once you've made your changes.</p>
<p>Luckily, if you're not using workitem tracking much, then this might not be too difficult. You might be able to just delete all the existing workitem types and then re-upload the new types. </p>
<p>If this is too much trouble, consider how much you want to retain your source control history. It might be worth creating a new Team Project with the Agile template and then just moving all your source code into it.</p> |
2,596,714 | Why does Python print unicode characters when the default encoding is ASCII? | <p>From the Python 2.6 shell:</p>
<pre><code>>>> import sys
>>> print sys.getdefaultencoding()
ascii
>>> print u'\xe9'
é
>>>
</code></pre>
<p>I expected to have either some gibberish or an Error after the print statement, since the "é" character isn't part of ASCII and I haven't specified an encoding. I guess I don't understand what ASCII being the default encoding means.</p>
<p><strong>EDIT</strong></p>
<p><a href="https://stackoverflow.com/questions/2596714/why-does-python-print-unicode-characters-when-the-default-encoding-is-ascii/21968640#21968640">I moved the edit to the <strong>Answers</strong> section and accepted it as suggested.</a></p> | 21,968,640 | 6 | 7 | null | 2010-04-08 00:03:08.577 UTC | 97 | 2018-08-02 21:44:03.643 UTC | 2018-08-02 21:44:03.643 UTC | null | 56,974 | null | 56,974 | null | 1 | 142 | python|unicode|encoding|ascii|python-2.x | 83,794 | <p>Thanks to bits and pieces from various replies, I think we can stitch up an explanation. </p>
<p>By trying to print an unicode string, u'\xe9', Python implicitly try to encode that string using the encoding scheme currently stored in sys.stdout.encoding. Python actually picks up this setting from the environment it's been initiated from. If it can't find a proper encoding from the environment, only then does it revert to its <em>default</em>, ASCII.</p>
<p>For example, I use a bash shell which encoding defaults to UTF-8. If I start Python from it, it picks up and use that setting:</p>
<pre><code>$ python
>>> import sys
>>> print sys.stdout.encoding
UTF-8
</code></pre>
<p>Let's for a moment exit the Python shell and set bash's environment with some bogus encoding:</p>
<pre><code>$ export LC_CTYPE=klingon
# we should get some error message here, just ignore it.
</code></pre>
<p>Then start the python shell again and verify that it does indeed revert to its default ascii encoding.</p>
<pre><code>$ python
>>> import sys
>>> print sys.stdout.encoding
ANSI_X3.4-1968
</code></pre>
<p>Bingo! </p>
<p>If you now try to output some unicode character outside of ascii you should get a nice error message</p>
<pre><code>>>> print u'\xe9'
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9'
in position 0: ordinal not in range(128)
</code></pre>
<hr>
<p>Lets exit Python and discard the bash shell. </p>
<p>We'll now observe what happens after Python outputs strings. For this we'll first start a bash shell within a graphic terminal (I use Gnome Terminal) and we'll set the terminal to decode output with ISO-8859-1 aka latin-1 (graphic terminals usually have an option to <em>Set Character Encoding</em> in one of their dropdown menus). Note that this doesn't change the actual <em>shell environment's</em> encoding, it only changes the way the <em>terminal</em> itself will decode output it's given, a bit like a web browser does. You can therefore change the terminal's encoding, independantly from the shell's environment. Let's then start Python from the shell and verify that sys.stdout.encoding is set to the shell environment's encoding (UTF-8 for me):</p>
<pre><code>$ python
>>> import sys
>>> print sys.stdout.encoding
UTF-8
>>> print '\xe9' # (1)
é
>>> print u'\xe9' # (2)
é
>>> print u'\xe9'.encode('latin-1') # (3)
é
>>>
</code></pre>
<p>(1) python outputs binary string as is, terminal receives it and tries to match its value with latin-1 character map. In latin-1, 0xe9 or 233 yields the character "é" and so that's what the terminal displays.</p>
<p>(2) python attempts to <em>implicitly</em> encode the Unicode string with whatever scheme is currently set in sys.stdout.encoding, in this instance it's "UTF-8". After UTF-8 encoding, the resulting binary string is '\xc3\xa9' (see later explanation). Terminal receives the stream as such and tries to decode 0xc3a9 using latin-1, but latin-1 goes from 0 to 255 and so, only decodes streams 1 byte at a time. 0xc3a9 is 2 bytes long, latin-1 decoder therefore interprets it as 0xc3 (195) and 0xa9 (169) and that yields 2 characters: Ã and ©.</p>
<p>(3) python encodes unicode code point u'\xe9' (233) with the latin-1 scheme. Turns out latin-1 code points range is 0-255 and points to the exact same character as Unicode within that range. Therefore, Unicode code points in that range will yield the same value when encoded in latin-1. So u'\xe9' (233) encoded in latin-1 will also yields the binary string '\xe9'. Terminal receives that value and tries to match it on the latin-1 character map. Just like case (1), it yields "é" and that's what's displayed. </p>
<p>Let's now change the terminal's encoding settings to UTF-8 from the dropdown menu (like you would change your web browser's encoding settings). No need to stop Python or restart the shell. The terminal's encoding now matches Python's. Let's try printing again:</p>
<pre><code>>>> print '\xe9' # (4)
>>> print u'\xe9' # (5)
é
>>> print u'\xe9'.encode('latin-1') # (6)
>>>
</code></pre>
<p>(4) python outputs a <em>binary</em> string as is. Terminal attempts to decode that stream with UTF-8. But UTF-8 doesn't understand the value 0xe9 (see later explanation) and is therefore unable to convert it to a unicode code point. No code point found, no character printed. </p>
<p>(5) python attempts to <em>implicitly</em> encode the Unicode string with whatever's in sys.stdout.encoding. Still "UTF-8". The resulting binary string is '\xc3\xa9'. Terminal receives the stream and attempts to decode 0xc3a9 also using UTF-8. It yields back code value 0xe9 (233), which on the Unicode character map points to the symbol "é". Terminal displays "é".</p>
<p>(6) python encodes unicode string with latin-1, it yields a binary string with the same value '\xe9'. Again, for the terminal this is pretty much the same as case (4).</p>
<p>Conclusions:
- Python outputs non-unicode strings as raw data, without considering its default encoding. The terminal just happens to display them if its current encoding matches the data.
- Python outputs Unicode strings after encoding them using the scheme specified in sys.stdout.encoding.
- Python gets that setting from the shell's environment.
- the terminal displays output according to its own encoding settings.
- the terminal's encoding is independant from the shell's.</p>
<hr>
<p><strong>More details on unicode, UTF-8 and latin-1:</strong></p>
<p>Unicode is basically a table of characters where some keys (code points) have been conventionally assigned to point to some symbols. e.g. by convention it's been decided that key 0xe9 (233) is the value pointing to the symbol 'é'. ASCII and Unicode use the same code points from 0 to 127, as do latin-1 and Unicode from 0 to 255. That is, 0x41 points to 'A' in ASCII, latin-1 and Unicode, 0xc8 points to 'Ü' in latin-1 and Unicode, 0xe9 points to 'é' in latin-1 and Unicode. </p>
<p>When working with electronic devices, Unicode code points need an efficient way to be represented electronically. That's what encoding schemes are about. Various Unicode encoding schemes exist (utf7, UTF-8, UTF-16, UTF-32). The most intuitive and straight forward encoding approach would be to simply use a code point's value in the Unicode map as its value for its electronic form, but Unicode currently has over a million code points, which means that some of them require 3 bytes to be expressed. To work efficiently with text, a 1 to 1 mapping would be rather impractical, since it would require that all code points be stored in exactly the same amount of space, with a minimum of 3 bytes per character, regardless of their actual need.</p>
<p>Most encoding schemes have shortcomings regarding space requirement, the most economic ones don't cover all unicode code points, for example ascii only covers the first 128, while latin-1 covers the first 256. Others that try to be more comprehensive end up also being wasteful, since they require more bytes than necessary, even for common "cheap" characters. UTF-16 for instance, uses a minimum of 2 bytes per character, including those in the ascii range ('B' which is 65, still requires 2 bytes of storage in UTF-16). UTF-32 is even more wasteful as it stores all characters in 4 bytes. </p>
<p>UTF-8 happens to have cleverly resolved the dilemma, with a scheme able to store code points with a variable amount of byte spaces. As part of its encoding strategy, UTF-8 laces code points with flag bits that indicate (presumably to decoders) their space requirements and their boundaries.</p>
<p><strong>UTF-8 encoding of unicode code points in the ascii range (0-127):</strong></p>
<pre><code>0xxx xxxx (in binary)
</code></pre>
<ul>
<li>the x's show the actual space reserved to "store" the code point during encoding </li>
<li>The leading 0 is a flag that indicates to the UTF-8 decoder that this code point will only require 1 byte. </li>
<li>upon encoding, UTF-8 doesn't change the value of code points in that specific range (i.e. 65 encoded in UTF-8 is also 65). Considering that Unicode and ASCII are also compatible in the same range, it incidentally makes UTF-8 and ASCII also compatible in that range.</li>
</ul>
<p>e.g. Unicode code point for 'B' is '0x42' or 0100 0010 in binary (as we said, it's the same in ASCII). After encoding in UTF-8 it becomes:</p>
<pre><code>0xxx xxxx <-- UTF-8 encoding for Unicode code points 0 to 127
*100 0010 <-- Unicode code point 0x42
0100 0010 <-- UTF-8 encoded (exactly the same)
</code></pre>
<p><strong>UTF-8 encoding of Unicode code points above 127 (non-ascii):</strong></p>
<pre><code>110x xxxx 10xx xxxx <-- (from 128 to 2047)
1110 xxxx 10xx xxxx 10xx xxxx <-- (from 2048 to 65535)
</code></pre>
<ul>
<li>the leading bits '110' indicate to the UTF-8 decoder the beginning of a code point encoded in 2 bytes, whereas '1110' indicates 3 bytes, 11110 would indicate 4 bytes and so forth.</li>
<li>the inner '10' flag bits are used to signal the beginning of an inner byte.</li>
<li>again, the x's mark the space where the Unicode code point value is stored after encoding.</li>
</ul>
<p>e.g. 'é' Unicode code point is 0xe9 (233).</p>
<pre><code>1110 1001 <-- 0xe9
</code></pre>
<p>When UTF-8 encodes this value, it determines that the value is larger than 127 and less than 2048, therefore should be encoded in 2 bytes:</p>
<pre><code>110x xxxx 10xx xxxx <-- UTF-8 encoding for Unicode 128-2047
***0 0011 **10 1001 <-- 0xe9
1100 0011 1010 1001 <-- 'é' after UTF-8 encoding
C 3 A 9
</code></pre>
<p>The 0xe9 Unicode code points after UTF-8 encoding becomes 0xc3a9. Which is exactly how the terminal receives it. If your terminal is set to decode strings using latin-1 (one of the non-unicode legacy encodings), you'll see é, because it just so happens that 0xc3 in latin-1 points to à and 0xa9 to ©.</p> |
2,659,952 | Maximum length of HTTP GET request | <p>What's the maximum length of an HTTP <a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods" rel="noreferrer">GET</a> request?</p>
<p>Is there a response error defined that the server can/should return if it receives a GET request that exceeds this length?</p>
<p>This is in the context of a web service API, although it's interesting to see the browser limits as well.</p> | 2,659,995 | 7 | 4 | null | 2010-04-17 20:32:25.23 UTC | 110 | 2021-02-26 12:19:52.937 UTC | 2020-01-22 23:34:52.007 UTC | null | 63,550 | null | 116 | null | 1 | 560 | web-services|http | 616,765 | <p>The limit is dependent on both the server and the client used (and if applicable, also the proxy the server or the client is using).</p>
<p>Most web servers have a limit of 8192 bytes (8 KB), which is usually configurable somewhere in the server configuration. As to the client side matter, the HTTP 1.1 specification even warns about this. Here's an extract of <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.2.1" rel="noreferrer">chapter 3.2.1</a>:</p>
<blockquote>
<p><em>Note: Servers ought to be cautious about depending on URI lengths above 255 bytes, because some older client or proxy implementations might not properly support these lengths.</em></p>
</blockquote>
<p>The limit in Internet Explorer and Safari is about 2 KB, in Opera about 4 KB and in Firefox about 8 KB. We may thus assume that 8 KB is the maximum possible length and that 2 KB is a more affordable length to rely on at the server side and that 255 bytes is the safest length to assume that the entire URL will come in.</p>
<p>If the limit is exceeded in either the browser or the server, most will just truncate the characters outside the limit without any warning. <em>Some</em> servers however may send an <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.15" rel="noreferrer">HTTP 414 error</a>.</p>
<p>If you need to send large data, then better use POST instead of GET. Its limit is <em>much</em> higher, but more dependent on the server used than the client. Usually up to around 2 GB is allowed by the average web server.</p>
<p>This is also configurable somewhere in the server settings. The average server will display a server-specific error/exception when the POST limit is exceeded, usually as an HTTP 500 error.</p> |
3,174,392 | Is it Pythonic to use bools as ints? | <p><code>False</code> is equivalent to <code>0</code> and <code>True</code> is equivalent <code>1</code> so it's possible to do something like this:</p>
<pre><code>def bool_to_str(value):
"""value should be a bool"""
return ['No', 'Yes'][value]
bool_to_str(True)
</code></pre>
<p>Notice how value is <code>bool</code> but is used as an <code>int</code>.</p>
<p>Is this this kind of use Pythonic or should it be avoided?</p> | 3,175,293 | 7 | 1 | null | 2010-07-04 10:43:12.597 UTC | 16 | 2016-12-23 10:43:10.903 UTC | 2010-07-04 13:51:47.11 UTC | null | 5,883 | null | 5,883 | null | 1 | 71 | boolean|python | 10,284 | <p>I'll be the odd voice out (since all answers are decrying the use of the fact that <code>False == 0</code> and <code>True == 1</code>, as the language guarantees) as I claim that the use of this fact to simplify your code is perfectly fine.</p>
<p>Historically, logical true/false operations tended to simply use <code>0</code> for false and <code>1</code> for true; in the course of Python 2.2's life-cycle, Guido noticed that too many modules started with assignments such as <code>false = 0; true = 1</code> and this produced boilerplate and useless variation (the latter because the capitalization of true and false was all over the place -- some used all-caps, some all-lowercase, some cap-initial) and so introduced the <code>bool</code> subclass of <code>int</code> and its <code>True</code> and <code>False</code> constants.</p>
<p>There was quite some pushback at the time since many of us feared that the new type and constants would be used by Python newbies to <em>restrict</em> the language's abilities, but Guido was adamant that we were just being pessimistic: nobody would ever understand Python so badly, for example, as to avoid the perfectly natural use of <code>False</code> and <code>True</code> as list indices, or in a summation, or other such perfectly clear and useful idioms.</p>
<p>The answers to this thread prove we were right: as we feared, a total misunderstanding of the roles of this type and constants <em>has</em> emerged, and people <em>are</em> avoiding, and, worse!, urging others to avoid, perfectly natural Python constructs in favor of useless gyrations.</p>
<p>Fighting against the tide of such misunderstanding, I urge everybody to <em>use Python as Python</em>, <strong>not</strong> trying to force it into the mold of other languages whose functionality and preferred style are quite different. <strong>In Python</strong>, True and False are 99.9% like 1 and 0, differing <em>exclusively</em> in their <code>str(...)</code> (and thereby <code>repr(...)</code>) form -- for <em>every</em> other operation except stringification, just feel free to use them without contortions. That goes for indexing, arithmetic, bit operations, etc, etc, etc.</p> |
2,992,376 | How to set upload_max_filesize in .htaccess? | <p>I have try to put these 2 lines</p>
<pre><code>php_value post_max_size 30M
php_value upload_max_filesize 30M
</code></pre>
<p>In my root <code>.htaccess</code> file but that brings me "internal server error" message.</p>
<p>php5 is running on the server</p>
<p>I don't have access to php.ini so I think <code>htaccess</code> is my only chance.<br />
Can you tell me where the mistake is?</p> | 2,992,438 | 7 | 1 | null | 2010-06-07 19:14:54.913 UTC | 25 | 2022-06-03 05:27:49.607 UTC | 2022-06-03 05:27:49.607 UTC | null | 19,123,103 | null | 220,839 | null | 1 | 100 | php|.htaccess | 353,840 | <p><code>php_value upload_max_filesize 30M</code> is correct.</p>
<p>You will have to contact your hosters -- some don't allow you to change values in php.ini</p> |
3,083,798 | How to disable mouse right click on a web page? | <p>I want to disable mouse right click on an HTML page.
I have a page where user has to enter the details.
I don't want the user to see the menu thats get displayed with the mouse right click. Rather I want to display a custom menu. I know there are some plugins available to do that. But my requirement does not need any plugins.</p> | 3,083,820 | 10 | 9 | null | 2010-06-21 10:20:32.63 UTC | 7 | 2018-10-28 09:03:19.293 UTC | 2011-01-24 08:45:12.97 UTC | null | 351,754 | null | 351,754 | null | 1 | 22 | javascript|html|mouse|right-click | 109,221 | <p>It's unprofessional, anyway this will work with javascript enabled:</p>
<pre><code>document.oncontextmenu = document.body.oncontextmenu = function() {return false;}
</code></pre>
<p>You may also want to show a message to the user before returning false.</p>
<p>However I have to say that this should not be done generally because it limits users options without resolving the issue (in fact the context menu can be very easily enabled again.).</p>
<p>The following article better explains <strong>why</strong> this should not be done and what other actions can be taken to solve common related issues:
<a href="http://articles.sitepoint.com/article/dont-disable-right-click" rel="noreferrer">http://articles.sitepoint.com/article/dont-disable-right-click</a></p> |
33,847,477 | Querying a Global Secondary Index in dynamodb Local | <p>I am creating a table and GSI in DynamoDB, using these parameters, as per the documentation: </p>
<p><code>configId</code> is the primary key of the table, and I am using the <code>publisherId</code> as the primary key for the GSI. (I've removed some unnecessary configuration parameters for brevity)</p>
<pre><code>var params = {
TableName: 'Configs',
KeySchema: [
{
AttributeName: 'configId',
KeyType: 'HASH',
}
],
AttributeDefinitions: [
{
AttributeName: 'configId',
AttributeType: 'S',
},
{
AttributeName: 'publisherId',
AttributeType: 'S',
}
],
GlobalSecondaryIndexes: [
{
IndexName: 'publisher_index',
KeySchema: [
{
AttributeName: 'publisherId',
KeyType: 'HASH',
}
]
}
]
};
</code></pre>
<p>I am querying this table using this:</p>
<pre><code>{ TableName: 'Configs',
IndexName: 'publisher_index',
KeyConditionExpression: 'publisherId = :pub_id',
ExpressionAttributeValues: { ':pub_id': { S: '700' } } }
</code></pre>
<p>but I keep getting the error: </p>
<blockquote>
<p>"ValidationException: One or more parameter values were invalid: Condition parameter type does not match schema type"</p>
</blockquote>
<p>In the docs it specifies that the primary <code>KeyType</code> can either be <code>HASH</code> or <code>RANGE</code>, and that you set the <code>AttributeType</code> in the <code>AttributeDefinitions</code> field. I am sending the <code>publisherId</code> as <code>String</code>, not sure what I am missing here.</p>
<p>Is the issue in the way I am creating the table, or the way I am querying?
Thanks</p> | 36,810,004 | 5 | 1 | null | 2015-11-21 19:11:29.513 UTC | 9 | 2021-06-13 22:14:17.923 UTC | 2018-09-05 19:13:27.703 UTC | null | 271,697 | null | 1,709,123 | null | 1 | 38 | node.js|amazon-dynamodb|aws-sdk | 43,872 | <p>Try to change <code>ExpressionAttributeValues</code> from this</p>
<pre><code>{
TableName: 'Configs',
IndexName: 'publisher_index',
KeyConditionExpression: 'publisherId = :pub_id',
ExpressionAttributeValues: { ':pub_id': { S: '700' } }
}
</code></pre>
<p>to</p>
<pre><code>{
TableName: 'Configs',
IndexName: 'publisher_index',
KeyConditionExpression: 'publisherId = :pub_id',
ExpressionAttributeValues: { ':pub_id': '700'}
}
</code></pre>
<p>From <code>{ ':pub_id': { S: '700' } }</code> to <code>{ ':pub_id': '700'}</code>.</p>
<p>I had the same problem and I spent 2 days for this. The official documentation in misleading.</p> |
45,397,433 | How to Uninstall Laravel? | <p>I am facing fatal errors regarding Artisan. I think I couldn't install laravel complete due to slow internet. Now I want to remove Laravel from root and want to have fresh installation.
Can anyone help me?</p> | 45,397,723 | 3 | 1 | null | 2017-07-30 07:30:22.437 UTC | 6 | 2020-08-04 08:57:48.397 UTC | null | null | null | null | 4,291,982 | null | 1 | 17 | laravel | 84,993 | <p>if you have installed it globally you can simply remove it by <code>composer global remove laravel/installer</code> </p>
<p>If you have installed it via composer project you simply remove the directory.</p> |
10,443,829 | How to create a before delete trigger in SQL Server? | <p>I want to create a before delete trigger. When I delete a record from a table that record has to be inserted into a history table. How can I do this in SQL Server?</p> | 10,443,862 | 4 | 0 | null | 2012-05-04 06:31:33.603 UTC | 2 | 2022-01-31 08:44:27.687 UTC | 2015-08-22 09:11:32.963 UTC | user756519 | 4,370,109 | null | 1,374,263 | null | 1 | 29 | sql-server|triggers | 86,563 | <p>In this situation, you're probably better off doing a regular "after" trigger. This is the most common approach to this type of situation. </p>
<p>Something like </p>
<pre><code>CREATE TRIGGER TRG_AUD_DEL
ON yourTable
FOR DELETE
AS
INSERT INTO my_audit_table (col1, col2, ...)
SELECT col1, col2...
FROM DELETED
</code></pre>
<p>What will happen is, when a record (or records!) are deleted from your table, the deleted row will be inserted into <code>my_audit_table</code> The <code>DELETED</code> table is a virtual table that contains the record(s) as they were immediately prior to the delete.</p>
<p>Also, note that the trigger runs as part of the implicit transaction on the delete statement, so if your delete fails and rolls back, the trigger will also rollback. </p> |
10,733,121 | BroadcastReceiver when wifi or 3g network state changed | <p>I have an app which updates the database whenever the phone is connected to WiFi. I have implemented a <code>Service</code> and <code>BroadcastReceiver</code> which will run the <code>Service</code> (it will tell me what network is in use), but the problem is I don't know what to add in the <code>manifest</code> file to start <code>BroadcastReceiver</code> when the network state changes or when it connects to some kind of network</p> | 10,733,191 | 5 | 0 | null | 2012-05-24 07:35:46.193 UTC | 16 | 2018-07-30 14:04:43.633 UTC | 2018-04-01 01:11:55.46 UTC | null | 6,618,622 | null | 1,129,530 | null | 1 | 34 | android|android-service | 57,098 | <p>You need </p>
<pre><code><intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
<action android:name="android.net.wifi.STATE_CHANGE"/>
</intent-filter>
</code></pre>
<p>In your <code>receiver</code> tag. </p>
<p>Or if you want more control over it, before registering <code>BroadcastReceiver</code> set these up: </p>
<pre><code>final IntentFilter filters = new IntentFilter();
filters.addAction("android.net.wifi.WIFI_STATE_CHANGED");
filters.addAction("android.net.wifi.STATE_CHANGE");
super.registerReceiver(yourReceiver, filters);
</code></pre>
<p><strong>WIFI_STATE_CHANGED</strong></p>
<p>Broadcast <code><intent-action></code> indicating that Wi-Fi has been enabled, disabled, enabling, disabling, or unknown. One extra provides this state as an int. Another extra provides the previous state, if available.</p>
<p><strong>STATE_CHANGE</strong></p>
<p>Broadcast <code><intent-action></code> indicating that the state of Wi-Fi connectivity has changed. One extra provides the new state in the form of a NetworkInfo object. If the new state is CONNECTED, additional extras may provide the BSSID and WifiInfo of the access point. as a String</p>
<p>Also, you'll need to specify the right permissions inside <code>manifest</code> tag:</p>
<pre><code><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
</code></pre>
<p>To check connectivity, you can use <code>ConnectivityManager</code> as it tells you what type of connection is available. </p>
<pre><code>ConnectivityManager conMngr = (ConnectivityManager)this.getSystemService(this.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = conMngr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = conMngr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
</code></pre> |
5,793,751 | What are the technical differences between the Thread Safe and Non Thread safe PHP Windows Installation Packages? | <p>I'm currently about to install PHP for an Apache/Windows-based development environment, but it seems I'm about to fall at the first hurdle: Choosing the right package to install.</p>
<p><a href="http://windows.php.net/download/" rel="noreferrer">PHP is available in no less than <em>four</em> flavours</a>:</p>
<ul>
<li>VC9 x86 Non Thread Safe </li>
<li>VC9 x86 Thread Safe </li>
<li>VC6 x86 Non Thread Safe</li>
<li>VC6 x86 Thread Safe</li>
</ul>
<p>What's the difference between these versions in a <em>practical</em> sense?</p>
<p>If this wasn't complicated enough, version 5.3 of PHP is only available in VC9 (with 5.2 coming with the VC6 packages). And yet, according to the PHP site, you should <strong>not</strong> use VC9 with Apache... So why does Apache get the older version?</p>
<p>It's all very confusing and I'd like some help understanding the choices.</p> | 5,797,523 | 2 | 1 | null | 2011-04-26 17:00:05.463 UTC | 22 | 2013-11-05 19:57:26.183 UTC | 2013-11-05 19:53:02.85 UTC | null | 275,567 | null | 199,700 | null | 1 | 39 | php|windows|apache | 20,205 | <p>After a lot of research, I've managed to find my own answers to this question.</p>
<p>In its most basic form, the answer is: <em><strong>What version of PHP you should install comes down what webserver you are running.</strong></em></p>
<p>Here's a deeper explanation of the terms used in picking a version of PHP based on what I learned:</p>
<hr />
<h1><strong>VC6 vs VC9</strong></h1>
<p>Firstly, different versions of Apache for Windows are compiled with different compilers. For example, the versions on <a href="http://httpd.apache.org" rel="noreferrer">Apache.org</a> are designed to be compiled using <strong>Microsoft Visual C++ 6</strong>, also known as <strong>VC6</strong>. This compiler is very popular, but also very old. (It dates back to 1998.)</p>
<p>There are different versions of Apache made for different compilers. For example, the versions available for download from <a href="http://www.apachelounge.com/download/" rel="noreferrer">ApacheLounge.com</a> are designed to be compiled with the popular and more much recent compiler, <strong>Microsoft Visual C++ 9</strong> from 2008. Also known as <strong>VC9</strong>.</p>
<p>(Note: These two compilers are the two most popular options. So while it's possible to have a VC7, VC8, etc. compiled version of Apache, it's unlikely that you'll come across them.)</p>
<p>The use of this more recent compiler (VC9) is important because the latest versions of PHP are only being distributed in VC9 form (although older versions are still available for VC6).</p>
<p>On top of that, according to ApacheLounge there are numerous improvements when using a version of Apache compiled with VC9, "in areas like Performance, MemoryManagement and Stability".</p>
<p>If that wasn't enough, the developers of PHP made the following statement on their site:</p>
<blockquote>
<p>Windows users: please mind that we do
no longer provide builds created with
Visual Studio C++ 6 (VC6). It is
impossible to maintain a high quality
and safe build of PHP for Windows
using this unmaintained compiler.</p>
<p><strong>We recommend the VC9 Apache builds as
provided by ApacheLounge</strong>.</p>
<p>All PHP users should note that the PHP
5.2 series is NOT supported anymore. All users are strongly encouraged to
upgrade to PHP 5.3.6.</p>
</blockquote>
<p>In all, this is an extremely compelling argument to use VC9 versions of Apache and PHP, if you ask me.</p>
<p>So if you're using a version of Apache from the <a href="http://httpd.apache.org/" rel="noreferrer">official Apache site</a>, it will be compiled with VC6, and as such, you should use the older version of PHP for that compiler. If you're using a version of Apache compiled with VC9, like the one available on <a href="http://www.apachelounge.com/download/" rel="noreferrer">ApacheLounge.com</a>, you can use the latest version of PHP (for VC9).</p>
<p>For me, running a local development environment, it would be preferable to have the latest version of PHP, so a VC9 version of Apache is required, so I can use the VC9 version of PHP.</p>
<h1><strong>Thread Safe vs Non Thread Safe</strong></h1>
<p>Once again this comes down to your webserver. By default Apache is installed on Windows as <strong>Module</strong>, but it can be changed to run as <strong>FastCGI</strong>. There's plenty of differences between the two, but essentially FastCGI is more modern, faster, more robust, and more resource hungry. For someone running a local development environment, FastCGI might be overkill, but apparently lots of hosting companies run as FastCGI for the reasons I've stated, so there are good arguments for doing so in a development environment.</p>
<p>If you're running Apache (or IIS) as FastCGI (or CGI) then you want the <strong>Non Thread Safe</strong> version of PHP. If you're running Apache as default (as a Module), then you'll want the more traditional <strong>Thread Safe</strong> version.</p>
<p>Please note: This all only applies to Windows users.</p>
<hr />
<p>I'm not going to bother with FastCGI (unless someone convinces me otherwise), so for me, I want the <strong>VC9 Thread Safe version of PHP</strong>.</p>
<p>And that's it.</p>
<p><strong>Further reading:</strong></p>
<ul>
<li><a href="http://windows.php.net/" rel="noreferrer">Official statement regarding PHP and VC6</a></li>
<li><a href="http://www.iis-aid.com/articles/my_word/difference_between_php_thread_safe_and_non_thread_safe_binaries" rel="noreferrer">Difference between PHP thread safe and non thread safe binaries</a></li>
<li><a href="http://en.wikipedia.org/wiki/FastCGI" rel="noreferrer">FastCGI at Wikipedia</a></li>
<li><a href="http://www.iis.net/download/fastcgi" rel="noreferrer">FastCGI for IIS</a></li>
<li><a href="http://en.wikipedia.org/wiki/Visual_C++" rel="noreferrer">Visual C++ at Wikipedia</a></li>
<li><a href="http://www.websiteadministrator.com.au/articles/install_guides/installing_php535-supplement01-Compile-Your-Own-Php.html" rel="noreferrer">Compile your own PHP (explanation of VC6/VC9)</a></li>
</ul> |
5,631,010 | How to create a temporary table in SSIS control flow task and then use it in data flow task? | <p>I have a control flow where I create a temp database and table in a with a T-SQL Command. When I add a dataflow I would like to query the table but I can't because the table doesn't exist to grab information from. When I try I get errors about logging in because the database doesn't exist (yet). I have delay validation to true. </p>
<p>If I create the database and table manually then add the dataflow with query and drop the database it sticks but it doesn't seem like a clean solution. </p>
<p>If there is a better way to create a temporary staging database and query it in dataflows please let me know.</p> | 6,160,015 | 2 | 1 | null | 2011-04-12 06:03:03.167 UTC | 21 | 2017-09-11 20:01:54.333 UTC | 2011-05-28 05:45:44.987 UTC | user756519 | null | null | 281,781 | null | 1 | 46 | ssis | 159,018 | <h2>Solution:</h2>
<p>Set the property <strong><code>RetainSameConnection</code></strong> on the <em><code>Connection Manager</code></em> to <strong><code>True</code></strong> so that temporary table created in one Control Flow task can be retained in another task.</p>
<p>Here is a sample SSIS package written in <em><code>SSIS 2008 R2</code></em> that illustrates using temporary tables.</p>
<h2>Walkthrough:</h2>
<p>Create a stored procedure that will create a temporary table named <code>##tmpStateProvince</code> and populate with few records. The sample SSIS package will first call the stored procedure and then will fetch the temporary table data to populate the records into another database table. The sample package will use the database named <em><code>Sora</code></em> Use the below create stored procedure script.</p>
<pre><code>USE Sora;
GO
CREATE PROCEDURE dbo.PopulateTempTable
AS
BEGIN
SET NOCOUNT ON;
IF OBJECT_ID('TempDB..##tmpStateProvince') IS NOT NULL
DROP TABLE ##tmpStateProvince;
CREATE TABLE ##tmpStateProvince
(
CountryCode nvarchar(3) NOT NULL
, StateCode nvarchar(3) NOT NULL
, Name nvarchar(30) NOT NULL
);
INSERT INTO ##tmpStateProvince
(CountryCode, StateCode, Name)
VALUES
('CA', 'AB', 'Alberta'),
('US', 'CA', 'California'),
('DE', 'HH', 'Hamburg'),
('FR', '86', 'Vienne'),
('AU', 'SA', 'South Australia'),
('VI', 'VI', 'Virgin Islands');
END
GO
</code></pre>
<p>Create a table named <em><code>dbo.StateProvince</code></em> that will be used as the destination table to populate the records from temporary table. Use the below create table script to create the destination table.</p>
<pre><code>USE Sora;
GO
CREATE TABLE dbo.StateProvince
(
StateProvinceID int IDENTITY(1,1) NOT NULL
, CountryCode nvarchar(3) NOT NULL
, StateCode nvarchar(3) NOT NULL
, Name nvarchar(30) NOT NULL
CONSTRAINT [PK_StateProvinceID] PRIMARY KEY CLUSTERED
([StateProvinceID] ASC)
) ON [PRIMARY];
GO
</code></pre>
<p>Create an SSIS package using <em><code>Business Intelligence Development Studio (BIDS)</code></em>. Right-click on the <em>Connection Managers</em> tab at the bottom of the package and click <em><code>New OLE DB Connection...</code></em> to create a new connection to access <em>SQL Server 2008 R2</em> database.</p>
<p><img src="https://i.stack.imgur.com/dGifG.png" alt="Connection Managers - New OLE DB Connection" /></p>
<p>Click <em><code>New...</code></em> on <em>Configure OLE DB Connection Manager</em>.</p>
<p><img src="https://i.stack.imgur.com/L136h.png" alt="Configure OLE DB Connection Manager - New" /></p>
<p>Perform the following actions on the <em>Connection Manager</em> dialog.</p>
<ul>
<li>Select <em><code>Native OLE DB\SQL Server Native Client 10.0</code></em> from <em>Provider</em> since the package will connect to <em>SQL Server 2008 R2 database</em></li>
<li>Enter the <em>Server name</em>, like <em><code>MACHINENAME\INSTANCE</code></em></li>
<li>Select <code>Use Windows Authentication</code> from <em>Log on to the server</em> section or whichever you prefer.</li>
<li>Select the database from <em><code>Select or enter a database name</code></em>, the sample uses the database name <strong><code>Sora</code></strong>.</li>
<li>Click <em><code>Test Connection</code></em></li>
<li>Click <em><code>OK</code></em> on the <em>Test connection succeeded</em> message.</li>
<li>Click <em><code>OK</code></em> on <em>Connection Manager</em></li>
</ul>
<p><img src="https://i.stack.imgur.com/KpmC0.png" alt="Connection Manager" /></p>
<p>The newly created data connection will appear on <em>Configure OLE DB Connection Manager</em>. Click <em><code>OK</code></em>.</p>
<p><img src="https://i.stack.imgur.com/kbelS.png" alt="Configure OLE DB Connection Manager - Created" /></p>
<p>OLE DB connection manager <strong><code>KIWI\SQLSERVER2008R2.Sora</code></strong> will appear under the <em>Connection Manager</em> tab at the bottom of the package. Right-click the connection manager and click <em><code>Properties</code></em></p>
<p><img src="https://i.stack.imgur.com/Vpy1c.png" alt="Connection Manager Properties" /></p>
<p>Set the property <em><code>RetainSameConnection</code></em> on the connection <em><code>KIWI\SQLSERVER2008R2.Sora</code></em> to the value <strong><code>True</code></strong>.</p>
<p><img src="https://i.stack.imgur.com/XiZTT.png" alt="RetainSameConnection Property on Connection Manager" /></p>
<p>Right-click anywhere inside the package and then click <em><code>Variables</code></em> to view the variables pane. Create the following variables.</p>
<ul>
<li><p>A new variable named <em><code>PopulateTempTable</code></em> of data type <em><code>String</code></em> in the package scope <em><code>SO_5631010</code></em> and set the variable with the value <strong><code>EXEC dbo.PopulateTempTable</code></strong>.</p>
</li>
<li><p>A new variable named <em><code>FetchTempData</code></em> of data type <em><code>String</code></em> in the package scope <em><code>SO_5631010</code></em> and set the variable with the value <strong><code>SELECT CountryCode, StateCode, Name FROM ##tmpStateProvince</code></strong></p>
</li>
</ul>
<p><img src="https://i.stack.imgur.com/s91ba.png" alt="Variables" /></p>
<p>Drag and drop an <em><code>Execute SQL Task</code></em> on to the <em>Control Flow</em> tab. Double-click the Execute SQL Task to view the <em>Execute SQL Task Editor</em>.</p>
<p>On the <em><code>General</code></em> page of the <em>Execute SQL Task Editor</em>, perform the following actions.</p>
<ul>
<li>Set the <em>Name</em> to <em><code>Create and populate temp table</code></em></li>
<li>Set the <em>Connection Type</em> to <em><code>OLE DB</code></em></li>
<li>Set the <em>Connection</em> to <em><code>KIWI\SQLSERVER2008R2.Sora</code></em></li>
<li>Select <em><code>Variable</code></em> from <em>SQLSourceType</em></li>
<li>Select <em><code>User::PopulateTempTable</code></em> from <em>SourceVariable</em></li>
<li>Click <em><code>OK</code></em></li>
</ul>
<p><img src="https://i.stack.imgur.com/qZHBe.png" alt="Execute SQL Task Editor" /></p>
<p>Drag and drop a <em><code>Data Flow Task</code></em> onto the <em>Control Flow</em> tab. Rename the Data Flow Task as <em><code>Transfer temp data to database table</code></em>. Connect the green arrow from the <em>Execute SQL Task</em> to the <em>Data Flow Task</em>.</p>
<p><img src="https://i.stack.imgur.com/ExXsf.png" alt="Control Flow Tab" /></p>
<p>Double-click the <em><code>Data Flow Task</code></em> to switch to <em>Data Flow</em> tab. Drag and drop an <em><code>OLE DB Source</code></em> onto the <em>Data Flow</em> tab. Double-click <em>OLE DB Source</em> to view the <em>OLE DB Source Editor</em>.</p>
<p>On the <em><code>Connection Manager</code></em> page of the <em>OLE DB Source Editor</em>, perform the following actions.</p>
<ul>
<li>Select <em><code>KIWI\SQLSERVER2008R2.Sora</code></em> from <em>OLE DB Connection Manager</em></li>
<li>Select <em><code>SQL command from variable</code></em> from <em>Data access mode</em></li>
<li>Select <em><code>User::FetchTempData</code></em> from <em>Variable name</em></li>
<li>Click <em><code>Columns</code></em> page</li>
</ul>
<p><img src="https://i.stack.imgur.com/Z84yZ.png" alt="OLE DB Source Editor - Connection Manager" /></p>
<p>Clicking <em><code>Columns</code></em> page on <em>OLE DB Source Editor</em> will display the following error because the table <strong><code>##tmpStateProvince</code></strong> specified in the source command variable does not exist and SSIS is unable to read the column definition.</p>
<p><img src="https://i.stack.imgur.com/uFILb.png" alt="Error message" /></p>
<p>To fix the error, execute the statement <strong><code>EXEC dbo.PopulateTempTable</code></strong> using <em>SQL Server Management Studio (SSMS)</em> on the database <em><code>Sora</code></em> so that the stored procedure will create the temporary table. After executing the stored procedure, click <em><code>Columns</code></em> page on <em>OLE DB Source Editor</em>, you will see the column information. Click <em><code>OK</code></em>.</p>
<p><img src="https://i.stack.imgur.com/sZqJ3.png" alt="OLE DB Source Editor - Columns" /></p>
<p>Drag and drop <em><code>OLE DB Destination</code></em> onto the <em>Data Flow</em> tab. Connect the green arrow from <em>OLE DB Source</em> to <em>OLE DB Destination</em>. Double-click <em><code>OLE DB Destination</code></em> to open <em>OLE DB Destination Editor</em>.</p>
<p>On the <em><code>Connection Manager</code></em> page of the <em>OLE DB Destination Editor</em>, perform the following actions.</p>
<ul>
<li>Select <em><code>KIWI\SQLSERVER2008R2.Sora</code></em> from <em>OLE DB Connection Manager</em></li>
<li>Select <em><code>Table or view - fast load</code></em> from <em>Data access mode</em></li>
<li>Select <em><code>[dbo].[StateProvince]</code></em> from <em>Name</em> of the table or the view</li>
<li>Click <em><code>Mappings</code></em> page</li>
</ul>
<p><img src="https://i.stack.imgur.com/vtKdi.png" alt="OLE DB Destination Editor - Connection Manager" /></p>
<p>Click <em><code>Mappings</code></em> page on the <em>OLE DB Destination Editor</em> would automatically map the columns if the input and output column names are same. Click <em><code>OK</code></em>. Column <em><code>StateProvinceID</code></em> does not have a matching input column and it is defined as an <code>IDENTITY</code> column in database. Hence, no mapping is required.</p>
<p><img src="https://i.stack.imgur.com/Mz8WH.png" alt="OLE DB Destination Editor - Mappings" /></p>
<p><em>Data Flow</em> tab should look something like this after configuring all the components.</p>
<p><img src="https://i.stack.imgur.com/wEecB.png" alt="Data Flow tab" /></p>
<p>Click the <code>OLE DB Source</code> on <em>Data Flow</em> tab and press <strong>F4</strong> to view <code>Properties</code>. Set the property <em><code>ValidateExternalMetadata</code></em> to False so that SSIS would not try to check for the existence of the temporary table during validation phase of the package execution.</p>
<p><img src="https://i.stack.imgur.com/Xg7rf.png" alt="Set ValidateExternalMetadata" /></p>
<p>Execute the query <code>select * from dbo.StateProvince</code> in the <em>SQL Server Management Studio (SSMS)</em> to find the number of rows in the table. It should be empty before executing the package.</p>
<p><img src="https://i.stack.imgur.com/0ZuyW.png" alt="Rows in table before package execution" /></p>
<p>Execute the package. Control Flow shows successful execution.</p>
<p><img src="https://i.stack.imgur.com/Zpcg1.png" alt="Package Execution - Control Flow tab" /></p>
<p>In Data Flow tab, you will notice that the package successfully processed <strong>6</strong> rows. The stored procedure created early in this posted inserted <strong>6</strong> rows into the temporary table.</p>
<p><img src="https://i.stack.imgur.com/ZUXHr.png" alt="Package Execution - Data Flow tab" /></p>
<p>Execute the query <code>select * from dbo.StateProvince</code> in the <em>SQL Server Management Studio (SSMS)</em> to find the <strong>6</strong> rows successfully inserted into the table. The data should match with rows founds in the stored procedure.</p>
<p><img src="https://i.stack.imgur.com/tHbLo.png" alt="Rows in table after package execution" /></p>
<p>The above example illustrated how to create and use temporary table within a package.</p> |
21,838,205 | android sqlite CREATE TABLE IF NOT EXISTS | <p>Having a little problem with creating new tables. When I use the CREATE TABLE command my new tables form as they should, but when I exit the activity the app crashes and I get a TABLE ALREADY EXISTS in the logcat. If I use CREATE TABLE IF NOT EXISTS the new table isn't formed but just adds my new rows of data to a previous table and it doesn't crash. What is wrong with this? I would like to add the table without it giving me the already exists and I would like it to add without it adding rows to a different table.</p>
<p>SqliteHelper Class:</p>
<pre><code>public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String TABLE_NAME = MainActivity.NameName;
public static final String COLUMN_ID = "_id";
public static final String COLUMN_COMMENT = "comment";
public static final String COLUMN_LAT = "lat";
public static final String COLUMN_LONG = "long";
public static final String COLUMN_RADI = "radi";
private static final String DATABASE_NAME = "spraylogs.db";
private static final int DATABASE_VERSION = 1;
public static final String NEWTABLE = "CREATE TABLE "
+ TABLE_COMMENTS + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_COMMENT
+ " text not null," + COLUMN_LAT+ "," + COLUMN_LONG + "," + COLUMN_RADI + ");";
public static final String SaveIt = "CREATE TABLE IF NOT EXISTS "
+ TABLE_COMMENTS + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_COMMENT
+ " text not null," + COLUMN_LAT+ "," + COLUMN_LONG + "," + COLUMN_RADI + ");";
MySQLiteHelper(Context context) {
super(context, context.getExternalFilesDir(null).getAbsolutePath() + "/" + DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + NEWTABLE);
onCreate(db);
}
}
</code></pre> | 21,838,388 | 2 | 0 | null | 2014-02-17 19:58:18.687 UTC | 3 | 2017-08-13 08:53:01.033 UTC | 2016-09-08 09:35:15.51 UTC | null | 6,617,272 | null | 1,936,916 | null | 1 | 17 | android|sql|sqlite|create-table | 48,332 | <p>That's how it's supposed to work. <code>CREATE TABLE</code> will throw an exception if the table already exists. <code>CREATE TABLE IF NOT EXISTS</code> will create the table if it doesn't exist, or ignore the command if it does. If you want it to delete the old table, use <code>DELETE TABLE IF EXISTS</code> before <code>CREATE TABLE</code>. If you want to change the schema, use <code>ALTER TABLE</code>, not <code>CREATE TABLE</code>.</p> |
35,504,605 | Calling a class method from the constructor | <p>I'm getting an error when calling a class method from its constructor. Is it possible to call a method from the constructor? I tried calling the base class method from the constructor of a derived class but I am still getting an error.</p>
<pre><code>'use strict';
class Base {
constructor() {
this.val = 10;
init();
}
init() {
console.log('this.val = ' + this.val);
}
};
class Derived extends Base {
constructor() {
super();
}
};
var d = new Derived();
</code></pre>
<blockquote>
<p>➜ js_programs node class1.js
/media/vi/DATA/programs/web/js/js_programs/class1.js:7
init();
^</p>
<p>ReferenceError: init is not defined
at Derived.Base (/media/vi/DATA/programs/web/js/js_programs/class1.js:7:9)
at Derived (/media/vi/DATA/programs/web/js/js_programs/class1.js:18:14)
at Object. (/media/vi/DATA/programs/web/js/js_programs/class1.js:23:9)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Function.Module.runMain (module.js:467:10)
at startup (node.js:136:18)
at node.js:963:3 ➜ js_programs</p>
</blockquote> | 35,504,660 | 2 | 1 | null | 2016-02-19 11:49:24.303 UTC | 7 | 2020-02-12 14:14:38.61 UTC | 2017-11-20 02:24:23.61 UTC | null | 660,828 | null | 571,156 | null | 1 | 34 | javascript|ecmascript-6 | 37,423 | <p>You're calling the <em>function</em> <code>init()</code>, not the <em>method</em> <code>init</code> of either <code>Base</code> or the current object. No such function exists in the current scope or any parent scopes. You need to refer to your object:</p>
<pre><code>this.init();
</code></pre> |
43,344,819 | Reading response headers with Fetch API | <p>I'm in a Google Chrome extension with permissions for <code>"*://*/*"</code> and I'm trying to make the switch from XMLHttpRequest to the <a href="https://developers.google.com/web/updates/2015/03/introduction-to-fetch" rel="noreferrer">Fetch API</a>.</p>
<p>The extension stores user-input login data that used to be put directly into the XHR's open() call for HTTP Auth, but under Fetch can no longer be used directly as a parameter. For HTTP Basic Auth, circumventing this limitation is trivial, as you can manually set an Authorization header:</p>
<pre><code>fetch(url, {
headers: new Headers({ 'Authorization': 'Basic ' + btoa(login + ':' + pass) })
} });
</code></pre>
<p><a href="https://en.wikipedia.org/wiki/Digest_access_authentication#Example_with_explanation" rel="noreferrer">HTTP Digest Auth</a> however requires more interactivity; you need to read parameters that the server sends you with its 401 response to craft a valid authorization token. I've tried reading the <code>WWW-Authenticate</code> response header field with this snippet:</p>
<pre><code>fetch(url).then(function(resp) {
resp.headers.forEach(function(val, key) { console.log(key + ' -> ' + val); });
}
</code></pre>
<p>But all I get is this output:</p>
<pre><code>content-type -> text/html; charset=iso-8859-1
</code></pre>
<p>Which by itself is correct, but that's still missing around 6 more fields according to Chrome's Developer Tools. If I use <code>resp.headers.get("WWW-Authenticate")</code> (or any of the other fields for that matter), i get only <code>null</code>.</p>
<p>Any chance of getting to those other fields using the Fetch API?</p> | 44,816,592 | 9 | 0 | null | 2017-04-11 11:37:21.953 UTC | 25 | 2022-06-02 08:20:17.73 UTC | null | null | null | null | 902,773 | null | 1 | 121 | javascript|google-chrome-extension | 115,126 | <p>There is a restriction to access response headers when you are using Fetch API over CORS. Due to this restriction, you can access only following standard headers:</p>
<ul>
<li><code>Cache-Control</code></li>
<li><code>Content-Language</code></li>
<li><code>Content-Type</code></li>
<li><code>Expires</code></li>
<li><code>Last-Modified</code></li>
<li><code>Pragma</code></li>
</ul>
<p>When you are writing code for Google Chrome extension, you are using <a href="https://enable-cors.org/" rel="noreferrer">CORS</a>, hence you can't access all headers. If you control the server, you can return custom information in the response <code>body</code> instead of <code>headers</code></p>
<p>More info on this restriction - <a href="https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types" rel="noreferrer">https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types</a></p> |
71,591,971 | How can I fix the "zsh: command not found: python" error? (macOS Monterey 12.3, Python 3.10, Atom IDE, and atom-python-run 0.9.7) | <p>Since I got the <a href="https://en.wikipedia.org/wiki/MacOS_Monterey" rel="noreferrer">macOS v12.3</a> (Monterey) update (not sure it's related though), I have been getting this error when I try to run my Python code in the terminal:</p>
<p><img src="https://i.stack.imgur.com/DJho7.png" alt="Python not found error" /></p>
<p>I am using Python 3.10.3, <a href="https://en.wikipedia.org/wiki/Atom_(text_editor)" rel="noreferrer">Atom</a> IDE, and run the code in the terminal via atom-python-run package (which used to work perfectly fine). The settings for the package go like this:</p>
<p><img src="https://i.stack.imgur.com/DT98c.jpg" alt="atom-python-run-settings" /></p>
<p>The <code>which</code> command in the terminal returns the following (which is odd, because earlier it would return something to just <code>which python</code>):</p>
<p><img src="https://i.stack.imgur.com/kSd1s.png" alt="Which Python" /></p>
<p>I gather the error occurs because the terminal calls for <code>python</code> instead of <code>python3</code>, but I am super new to any coding and have no idea why it started now and how to fix it. Nothing of these has worked for me:</p>
<ul>
<li>I deleted and then reinstalled the Python interpreter from python.org.</li>
<li>I tried <code>alias python='python3'</code> (which I saw in one of the threads here).</li>
<li>I tried <code>export PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"</code> (which I found <a href="https://osxdaily.com/2018/05/24/command-not-found-mac-terminal-error-fix/" rel="noreferrer">here</a>).</li>
<li>To reset zsh and paths, I deleted all associated hidden files in <code>/local/users/</code> and ran the terminal once again.</li>
<li>I deleted everything and reinstalled Mac OS X and the Python interpreter only to get the same error.</li>
</ul> | 71,621,142 | 12 | 1 | null | 2022-03-23 18:02:02.23 UTC | 24 | 2022-09-19 22:43:36.193 UTC | 2022-06-26 21:06:46.24 UTC | null | 63,550 | null | 18,559,642 | null | 1 | 76 | python|macos|terminal|atom-editor|macos-monterey | 113,221 | <p>OK, after a couple of days trying, this is what has worked for me:</p>
<ol>
<li>I reinstalled Monterey (not sure it was essential, but I just figured I had messed with terminal and <code>$PATH</code> too much).</li>
<li>I installed <code>python</code> via <code>brew</code> rather than from the official website.
It would still return <code>command not found</code> error.</li>
<li>I ran <code>echo "alias python=/usr/bin/python3" >> ~/.zshrc</code> in terminal to alias <code>python</code> with <code>python3</code>.</li>
</ol>
<p>Problem solved.</p>
<p>As far as I get it, there is no more pre-installed python 2.x in macOS as of 12.3 hence the error. I still find it odd though that <code>atom-python-run</code> would call for <code>python</code> instead of <code>python3</code> despite the settings.</p> |
54,050,320 | Error: `data` must be a data frame, or other object coercible by `fortify()`, not an S3 object with class Date | <p>I tried to create a stacked bar plot in R, but unfortunately I have several problems. R gives me the following error:</p>
<blockquote>
<p>Error: <code>data</code> must be a data frame, or other object coercible by
<code>fortify()</code>, not an S3 object with class Date</p>
</blockquote>
<p>I searched for a while, but I can't find a solution. Thank you for helping.</p>
<pre><code>options(stringsAsFactors = FALSE)
input <- "C:\\Users\\CPOD1_time.csv" CPOD1_time <- read.csv(input, sep=";")
CPOD1_time = as.Date(CPOD1_time$date, format = "%d.%m.%Y")
library(lubridate)
library(ggplot2)
p<- ggplot(CPOD1_time, aes(x=date, y=number, fill=time)) +
geom_bar(stat="identity") +theme_bw() + geom_text(aes(y=number), vjust=1.6,
size=3.5)
print(p)
dput(CPOD1_time)
structure(c(17742, 17743, 17744, 17745, 17746, 17747, 17748,
17749, 17750, 17751, 17752, 17753, 17754, 17755, 17756, 17757,
17758, 17759, 17760, 17761, 17762, 17763, 17764, 17765, 17766,
17767, 17768, 17769, 17770, 17771, 17772, 17773, 17774, 17775,
17776, 17742, 17743, 17744, 17745, 17746, 17747, 17748, 17749,
17750, 17751, 17752, 17753, 17754, 17755, 17756, 17757, 17758,
17759, 17760, 17761, 17762, 17763, 17764, 17765, 17766, 17767,
17768, 17769, 17770, 17771, 17772, 17773, 17774, 17775, 17776,
17742, 17743, 17744, 17745, 17746, 17747, 17748, 17749, 17750,
17751, 17752, 17753, 17754, 17755, 17756, 17757, 17758, 17759,
17760, 17761, 17762, 17763, 17764, 17765, 17766, 17767, 17768,
17769, 17770, 17771, 17772, 17773, 17774, 17775, 17776, 17742,
17743, 17744, 17745, 17746, 17747, 17748, 17749, 17750, 17751,
17752, 17753, 17754, 17755, 17756, 17757, 17758, 17759, 17760,
17761, 17762, 17763, 17764, 17765, 17766, 17767, 17768, 17769,
17770, 17771, 17772, 17773, 17774, 17775, 17776), class = "Date")
as.data.frame(CPOD1_time)
date time number
1 30.07.2018 1 0.00000000
2 31.07.2018 1 0.00000000
3 01.08.2018 1 0.00000000
4 02.08.2018 1 0.62500000
5 03.08.2018 1 0.00000000
6 04.08.2018 1 0.00000000
7 05.08.2018 1 0.00000000
8 06.08.2018 1 3.26086957
9 07.08.2018 1 0.00000000
10 08.08.2018 1 0.00000000
11 09.08.2018 1 0.00000000
12 10.08.2018 1 0.00000000
13 11.08.2018 1 0.00000000
14 12.08.2018 1 0.00000000
15 13.08.2018 1 0.00000000
16 14.08.2018 1 0.00000000
17 15.08.2018 1 0.69767442
18 16.08.2018 1 0.00000000
19 17.08.2018 1 0.00000000
20 18.08.2018 1 0.71428571
21 19.08.2018 1 0.71428571
22 20.08.2018 1 0.71428571
23 21.08.2018 1 0.71428571
24 22.08.2018 1 0.00000000
25 23.08.2018 1 3.65853658
26 24.08.2018 1 0.50000000
27 25.08.2018 1 3.00751880
28 26.08.2018 1 1.50375940
29 27.08.2018 1 3.00751880
30 28.08.2018 1 3.75939850
31 29.08.2018 1 0.00000000
32 30.08.2018 1 1.53846154
33 31.08.2018 1 7.69230769
34 01.09.2018 1 5.38461539
35 02.09.2018 1 2.30769231
36 30.07.2018 2 0.16064257
37 31.07.2018 2 0.13100437
38 01.08.2018 2 0.26315789
39 02.08.2018 2 0.19823789
40 03.08.2018 2 0.06622517
41 04.08.2018 2 0.00000000
42 05.08.2018 2 0.00000000
43 06.08.2018 2 0.46927374
44 07.08.2018 2 0.26936027
45 08.08.2018 2 0.33821872
46 09.08.2018 2 0.20385051
47 10.08.2018 2 0.06825939
48 11.08.2018 2 0.27366020
49 12.08.2018 2 0.41284404
50 13.08.2018 2 0.13808976
51 14.08.2018 2 0.06936416
52 15.08.2018 2 0.62717770
53 16.08.2018 2 1.19158878
54 17.08.2018 2 0.07033998
55 18.08.2018 2 0.35335689
56 19.08.2018 2 0.14218010
57 20.08.2018 2 0.85714286
58 21.08.2018 2 0.28742515
59 22.08.2018 2 0.79422383
60 23.08.2018 2 2.10399033
61 24.08.2018 2 1.52727273
62 25.08.2018 2 1.90012180
63 26.08.2018 2 2.50000000
64 27.08.2018 2 0.29556650
65 28.08.2018 2 2.82527881
66 29.08.2018 2 2.31631382
67 30.08.2018 2 2.55319149
68 31.08.2018 2 2.41813602
69 01.09.2018 2 2.05063291
70 02.09.2018 2 2.57309942
71 30.07.2018 3 0.00000000
72 31.07.2018 3 0.00000000
73 01.08.2018 3 0.00000000
74 02.08.2018 3 0.00000000
75 03.08.2018 3 0.00000000
76 04.08.2018 3 0.00000000
77 05.08.2018 3 0.00000000
78 06.08.2018 3 0.00000000
79 07.08.2018 3 0.00000000
80 08.08.2018 3 0.00000000
81 09.08.2018 3 0.66666667
82 10.08.2018 3 0.00000000
83 11.08.2018 3 0.00000000
84 12.08.2018 3 4.13793103
85 13.08.2018 3 0.00000000
86 14.08.2018 3 0.00000000
87 15.08.2018 3 0.71428571
88 16.08.2018 3 2.79069767
89 17.08.2018 3 0.00000000
90 18.08.2018 3 0.00000000
91 19.08.2018 3 0.00000000
92 20.08.2018 3 0.00000000
93 21.08.2018 3 0.72289157
94 22.08.2018 3 0.00000000
95 23.08.2018 3 0.00000000
96 24.08.2018 3 0.00000000
97 25.08.2018 3 0.00000000
98 26.08.2018 3 0.00000000
99 27.08.2018 3 0.00000000
100 28.08.2018 3 0.00000000
101 29.08.2018 3 0.00000000
102 30.08.2018 3 9.23076923
103 31.08.2018 3 0.00000000
104 01.09.2018 3 2.30769231
105 02.09.2018 3 0.00000000
106 30.07.2018 4 0.00000000
107 31.07.2018 4 0.17964072
108 01.08.2018 4 0.17647059
109 02.08.2018 4 0.00000000
110 03.08.2018 4 0.00000000
111 04.08.2018 4 0.00000000
112 05.08.2018 4 0.00000000
113 06.08.2018 4 0.00000000
114 07.08.2018 4 0.32432432
115 08.08.2018 4 0.00000000
116 09.08.2018 4 0.00000000
117 10.08.2018 4 0.31168831
118 11.08.2018 4 1.54241645
119 12.08.2018 4 0.75757576
120 13.08.2018 4 11.89066059
121 14.08.2018 4 1.03703704
122 15.08.2018 4 7.73722628
123 16.08.2018 4 8.09638554
124 17.08.2018 4 1.56769596
125 18.08.2018 4 1.27058823
126 19.08.2018 4 0.55813954
127 20.08.2018 4 0.27522936
128 21.08.2018 4 0.68181818
129 22.08.2018 4 1.88340807
130 23.08.2018 4 2.78761062
131 24.08.2018 4 1.71428571
132 25.08.2018 4 0.39045553
133 26.08.2018 4 0.25751073
134 27.08.2018 4 0.25531915
135 28.08.2018 4 0.25263158
136 29.08.2018 4 0.24896266
137 30.08.2018 4 0.36960986
138 31.08.2018 4 1.09979633
139 01.09.2018 4 0.48387097
140 02.09.2018 4 0.00000000
</code></pre> | 54,050,582 | 1 | 8 | null | 2019-01-05 08:29:34.19 UTC | 3 | 2019-01-05 14:02:05.54 UTC | 2019-01-05 14:02:05.54 UTC | null | 10,323,798 | null | 10,756,799 | null | 1 | 15 | r|ggplot2 | 72,077 | <p>Try this:
Workflow is as follows:</p>
<pre><code> library(tidyverse)
library(lubridate)
#`df` is `CPOD_Time` saved as `df<-as.data.frame(CPOD_Time)`
df<-as.data.frame(CPOD_Time)
</code></pre>
<p>Then the plot:</p>
<pre><code>df %>%
rename(Time=time,Number=number,Date=date) %>%
mutate(Date=str_replace_all(Date,"\\D","-"),Date=as.character(Date),
Date=dmy(Date)) %>%
ggplot(aes(x=Date, y=Number, fill=Time)) +
geom_bar(stat="identity") +theme_bw() +
geom_text(aes(label=Number), vjust=1.6,size=3.5)
</code></pre> |
26,773,932 | Global variable is undefined at the module level | <p>(There are many similar and more generic questions, been trying the solutions from them after reading through them, can't get them working so asking here as a more situation-specific version of what I'm seeing)</p>
<p>I think I am really miss-understanding how Python does OOP due to my more C#/C++ background. So here's what I'm trying to do right this moment. </p>
<p>I'm starting with two modules to set up the rest of my project, partially as a sanity-check and proof-of-concept. One module logs things to a file as I go while also storing data from multiple modules (to eventually package them all and dump them on request) Doing all this in PyCharm and mentioning the error warnings it suggests by the way, and using Python 2.7</p>
<pre><code>Module 1:
src\helpers\logHelpers.py
class LogHelpers:
class log:
def classEnter():
#doing stuff
def __init__(self):
self.myLog = LogHelpers.log() #forgot to mention this was here initially
[..] various logging functions and variables to summarize what's happening
__builtin__.mylogger = LogHelpers
Module 2:
src\ULTs\myULTs.py
mylogger.myLog.classEnter()
</code></pre>
<p>(both the modules and the root src\ have an empty <strong>init</strong>.py file in them)</p>
<p>So according to the totally awesome response here ( <a href="https://stackoverflow.com/questions/15959534/python-visibility-of-global-variables-from-imported-modules">Python - Visibility of global variables in imported modules</a> ) at this stage this should be working, but 'mylogger' becomes an 'unresolved reference'</p>
<p>So that was one approach. I also tried the more straight forward global one ( <a href="https://stackoverflow.com/questions/142545/python-how-to-make-a-cross-module-variable">Python: How to make a cross-module variable?</a> )</p>
<pre><code>Module 1:
src\helpers\logHelpers.py
class LogHelpers:
class log:
def classEnter(self):
#doing stuff
def __init__(self):
self.myLog = LogHelpers.log() #forgot to mention this was here initially
[..] various logging functions and variables to summarize what's happening
mylogger = LogHelpers
__init__.py
__all__ = ['LogHelpers', hexlogger]
from .logHelpers import *
Module 2:
src\ULTs\myULTs.py
from helpers import mylogger
mylogger.myLog.classEnter()
</code></pre>
<p>This version gets a "parameter 'self' unfilled" error on the classEnter, which various reports seem to indicate means that mylogger is un-initialized (misleading error code but that's what it seems to mean)</p>
<p>And then I tried this.. </p>
<pre><code>Module 1:
src\helpers\logHelpers.py
class LogHelpers:
class log:
def classEnter(self):
#doing stuff
def __init__(self):
self.myLog = LogHelpers.log() #forgot to mention this was here initially
[..] various logging functions and variables to summarize what's happening
__mylogger = LogHelpers
__init__.py
__all__ = ['LogHelpers', hexlogger]
from .logHelpers import *
Module 2:
src\ULTs\myULTs.py
from helpers import mylogger
def someFunction(self):
global mylogger
mylogger.myLog.classEnter()
</code></pre>
<p>And this version gets the 'Global variable is undefined at the module level' error when I hover of global mylogger.</p>
<p>Then there is the idea of each other module tracking its own instance of a class apparently, if I end up having to I can go with that method and coordinate them.. but that's kind of a hack considering what I'm trying to do.</p>
<p>That's kind of where I'm at, that's the gist of what I'm trying to do... I'm reading through as many similar questions as I can but all of them seem to come back to these kinda of solutions (which don't seem to be working) or saying 'don't do that' (which is generally good advice but I'm not really grocking the preferred Pythony way of keeping multiple ongoing non-static classes organized for a large project - other than shoving them all in one directory)</p>
<p>Thoughts? (How badly am I mangling Python here?)</p>
<p>[EDIT] Based on feedback tried a mini version that eliminated the inner classes completely:
Ok, so did a local mini-class based on what you said:</p>
<pre><code>class testClass:
def __init__(self):
self.testVar = 2
def incrementVar(self):
self.testVar += 1
myClass = testClass()
</code></pre>
<p>Set it up via <strong>init</strong>.py</p>
<pre><code>__all__ = [myClass]
from .logHelpers import myClass
</code></pre>
<p>Went to other module and </p>
<pre><code>from helpers import myClass
class Test_LogHelpers(unittest.TestCase):
def test_mini(self):
myClass.incrementVar()
</code></pre>
<p>Ran it directly instead of looking at PyCharm, no Global anything.. <code>NameError: name 'myClass is not defined</code></p>
<p>So still at square one :( (and still need to store state)</p>
<p>[EDIT] Adding Traceback:</p>
<pre><code>Traceback (most recent call last):
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 3.4.1\helpers\pycharm\utrunner.py", line 124, in <module> module = loadSource(a[0])
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 3.4.1\helpers\pycharm\utrunner.py", line 40, in loadSource module = imp.load_source(moduleName, fileName)
File "C:\[...mylocation...]\py\src\ULTs\LogHelpers_ULT.py", line 3, in <module> from helpers import myClass
File "C:\[...mylocation...]\py\src\helpers\__init__.py", line 7, in <module>
__all__ = [myClass]
NameError: name 'myClass' is not defined
</code></pre>
<p>============================================================================</p>
<p>kk, I got it working with the miniclass. I don't know why the other approach / approaches was not working, but this seemed to fix things.
(Resources: <a href="http://docs.python-guide.org/en/latest/writing/structure/" rel="noreferrer">http://docs.python-guide.org/en/latest/writing/structure/</a> , <a href="http://mikegrouchy.com/blog/2012/05/be-pythonic-__init__py.html" rel="noreferrer">http://mikegrouchy.com/blog/2012/05/be-pythonic-__init__py.html</a> )</p>
<pre><code>**logHelpers.py**
[... some static logging functionality ...]
class testClass:
def __init__(self):
self.testVar = 2
def incrementVar(self, source):
self.testVar += 1
mylogger.myLog.info(source + " called, new val: " + str(self.testVar))
myClass = testClass()
**test_LogHelpers_ULT.py**
import unittest
from helpers.logHelpers import myClass
class Test_LogHelpers(unittest.TestCase):
def test_mini(self):
myClass.incrementVar("LogHelpers")
</code></pre>
<p>For some reason skipping the
<strong>init</strong>.py
(and leaving it blank) and going for the explicit importation worked. It also maintained state - I created a duplicate of the test file and my log output correctly had '3' for the first file to call the helper, and '4' for the second file to call the helper.</p>
<p>Thanks Daniel Roseman for the help and suggestions, they had me look a bit more in the right direction. If you can spot why the previous stuff wasn't working it would be much appreciate just to add to my understanding of this language, but I'm gonna go ahead and mark your answer as 'Answered' since it had some very useful feedback.</p> | 26,775,843 | 1 | 0 | null | 2014-11-06 07:28:18.033 UTC | 5 | 2018-09-24 22:37:25.333 UTC | 2018-09-24 22:37:25.333 UTC | null | 6,862,601 | null | 2,076,617 | null | 1 | 12 | python|module|scope|global-variables | 82,284 | <p>Before I start, note that the PyCharm warnings are not actual Python errors: if you ran your code, you would probably get more useful feedback (remember static analysis of a dynamic language like Python can only get you so far, many things can't be resolved until you actually run the code).</p>
<p>Firstly, it's really not clear why you have nested classes here. The outer class seems completely useless; you should remove it. </p>
<p>The reason for the error message about "self" is that you have defined an instance method, which can only be called on an instance of <code>log</code>. You could make <code>mylogger</code> (absolutely no need for the double-underscore prefix) an instance: <code>mylogger = log()</code> - and then import that, or import the class and instantiate it where it is used.</p>
<p>So in your first snippet, the error message is quite clear: you have not defined <code>mylogger</code>. Using my recommendation above, you can do <code>from helpers import mylogger</code> and then directly call <code>mylogger.classEnter()</code>.</p>
<p>Finally, I can't see what that <code>global</code> statement is doing in <code>someFunction</code>. There's no need to declare a name as global unless you plan to reassign it within your scope and have that reassignment reflected in the global scope. You're not doing that here, so no need for <code>global</code>.</p>
<p>By the way, you should also question whether you even need the inner <code>log</code> class. Generally speaking, classes are only useful when you need to store some kind of state in the object. Here, as your docstring says, you have a collection of utility methods. So why put them in a class? Just make them top-level functions inside the <code>logHelpers</code> module (incidentally, Python style prefers <code>lower_case_with_underscore</code> for module names, so it should be "log_helpers.py").</p> |
271,238 | How do I detect when a removable disk is inserted using C#? | <p>I'm just concerned about Windows, so there's no need to go into esoterica about Mono compatibility or anything like that.</p>
<p>I should also add that the app that I'm writing is WPF, and I'd prefer to avoid taking a dependency on <code>System.Windows.Forms</code> if at all possible.</p> | 271,251 | 3 | 2 | null | 2008-11-07 04:24:05.117 UTC | 9 | 2014-08-14 15:35:21.88 UTC | 2014-08-14 15:35:21.88 UTC | David Mitchell | 655,973 | David Mitchell | 26,628 | null | 1 | 16 | c#|wpf|windows | 17,326 | <p>Give this a shot...</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
namespace WMITestConsolApplication
{
class Program
{
static void Main(string[] args)
{
AddInsertUSBHandler();
AddRemoveUSBHandler();
while (true) {
}
}
static ManagementEventWatcher w = null;
static void AddRemoveUSBHandler()
{
WqlEventQuery q;
ManagementScope scope = new ManagementScope("root\\CIMV2");
scope.Options.EnablePrivileges = true;
try {
q = new WqlEventQuery();
q.EventClassName = "__InstanceDeletionEvent";
q.WithinInterval = new TimeSpan(0, 0, 3);
q.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'";
w = new ManagementEventWatcher(scope, q);
w.EventArrived += USBRemoved;
w.Start();
}
catch (Exception e) {
Console.WriteLine(e.Message);
if (w != null)
{
w.Stop();
}
}
}
static void AddInsertUSBHandler()
{
WqlEventQuery q;
ManagementScope scope = new ManagementScope("root\\CIMV2");
scope.Options.EnablePrivileges = true;
try {
q = new WqlEventQuery();
q.EventClassName = "__InstanceCreationEvent";
q.WithinInterval = new TimeSpan(0, 0, 3);
q.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'";
w = new ManagementEventWatcher(scope, q);
w.EventArrived += USBInserted;
w.Start();
}
catch (Exception e) {
Console.WriteLine(e.Message);
if (w != null)
{
w.Stop();
}
}
}
static void USBInserted(object sender, EventArgs e)
{
Console.WriteLine("A USB device inserted");
}
static void USBRemoved(object sender, EventArgs e)
{
Console.WriteLine("A USB device removed");
}
}
}
</code></pre> |
614,728 | Best practice for rate limiting users of a REST API? | <p>I am putting together a REST API and as I'm unsure how it will scale or what the demand for it will be, I'd like to be able to rate limit uses of it as well as to be able to temporarily refuse requests when the box is over capacity or if there is some kind of slashdotted scenario.</p>
<p>I'd also like to be able to gracefully bring the service down temporarily (while giving clients results that indicate the main service is offline for a bit) when/if I need to scale the service by adding more capacity.</p>
<p>Are there any best practices for this kind of thing? Implementation is Rails with mysql.</p> | 614,786 | 3 | 0 | null | 2009-03-05 13:22:27.617 UTC | 19 | 2014-05-31 21:33:13.293 UTC | null | null | null | frankodwyer | 42,404 | null | 1 | 30 | ruby-on-rails|rest|scaling|capacity | 10,650 | <p>This is all done with outer webserver, which listens to the world (i recommend nginx or lighttpd).</p>
<p>Regarding rate limits, nginx is able to limit, i.e. 50 req/minute per each IP, all over get 503 page, which you can customize.</p>
<p>Regarding expected temporary down, in rails world this is done via special maintainance.html page. There is some kind of automation that creates or symlinks that file when rails app servers go down. I'd recommend relying not on file presence, but on actual availability of app server.</p>
<p>But really you are able to start/stop services without losing any connections at all. I.e. you can run separate instance of app server on different UNIX socket/IP port and have balancer (nginx/lighty/haproxy) use that new instance too. Then you shut down old instance and all clients are served with only new one. No connection lost. Of course this scenario is not always possible, depends on type of change you introduced in new version.</p>
<p>haproxy is a balancer-only solution. It can extremely efficiently balance requests to app servers in your farm.</p>
<p>For quite big service you end-up with something like:</p>
<ul>
<li>api.domain resolving to round-robin N balancers</li>
<li>each balancer proxies requests to M webservers for static and P app servers for dynamic content. Oh well your REST API don't have static files, does it?</li>
</ul>
<p>For quite small service (under 2K rps) all balancing is done inside one-two webservers.</p> |
1,107,996 | Creating an NSDictionary | <p>In the following code, the first log statement shows a decimal as expected, but the second logs NULL. What am I doing wrong?</p>
<pre><code>NSDictionary *entry = [[NSDictionary alloc] initWithObjectsAndKeys:
@"x", [NSNumber numberWithDouble:acceleration.x],
@"y", [NSNumber numberWithDouble:acceleration.y],
@"z", [NSNumber numberWithDouble:acceleration.z],
@"date", [NSDate date],
nil];
NSLog([NSString stringWithFormat:@"%@", [NSNumber numberWithDouble:acceleration.x]]);
NSLog([NSString stringWithFormat:@"%@", [entry objectForKey:@"x"]]);
</code></pre> | 1,108,015 | 3 | 1 | null | 2009-07-10 06:28:37.737 UTC | 3 | 2015-06-03 10:43:36.343 UTC | null | null | null | null | 108,512 | null | 1 | 37 | iphone|cocoa-touch | 65,769 | <p>You are exchanging the order in which you insert objects and key: you need to insert first the object, then the key as shown in the following example.</p>
<pre><code>NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil];
</code></pre> |
39,610,294 | Import two exported classes with the same name | <p>In typescript, using Angular 2, I need to import two classes with the same name, but lying in different paths.</p>
<p>The project is quite too big that I find it hard to change the exported class names.</p>
<p>Is there any way to alias the imported classes,</p>
<pre><code>import {Class1} from '../location1/class1'
import {Class1} from '../location2/class1'
</code></pre> | 39,610,348 | 1 | 0 | null | 2016-09-21 07:38:56.767 UTC | 7 | 2019-07-21 15:33:46.267 UTC | null | null | null | null | 4,294,275 | null | 1 | 187 | angular|typescript|ionic2 | 76,198 | <p>You can use <code>as</code> like this:</p>
<pre class="lang-js prettyprint-override"><code>import {Class1} from '../location1/class1'
import {Class1 as Alias} from '../location2/class1'
</code></pre>
<p>You can find more about the ES6 import statement <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import" rel="noreferrer">here</a>.</p> |
21,961,839 | Simulation background-size: cover in canvas | <p>I'm drawing images on a canvas like this:</p>
<pre class="lang-js prettyprint-override"><code>ctx.drawImage(data[i].image, data[i].pos.x, data[i].pos.y, data[i].pos.w, data[i].pos.h);
</code></pre>
<p>The picture is getting stretched and I don't want this. How can I simulate the CSS property?</p>
<pre class="lang-css prettyprint-override"><code>background-size: cover
</code></pre>
<p>when drawing images on the canvas?</p>
<p><a href="http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size&preval=cover" rel="noreferrer">http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size&preval=cover</a></p>
<p>see the difference between <code>100% 100%</code> (what I currently have) and <code>cover</code> (my goal).</p> | 21,961,894 | 6 | 0 | null | 2014-02-22 23:04:52.053 UTC | 22 | 2022-06-12 11:24:39.163 UTC | 2020-10-04 08:48:45.17 UTC | null | 9,449,426 | null | 2,183,827 | null | 1 | 52 | javascript|css|html|canvas | 53,900 | <p>It's a bit more complicated to get a cover functionality, though here is one solution for this:</p>
<p><strong>Updated 2016-04-03</strong> to address special cases. Also see @Yousef's comment below.</p>
<pre><code>/**
* By Ken Fyrstenberg Nilsen
*
* drawImageProp(context, image [, x, y, width, height [,offsetX, offsetY]])
*
* If image and context are only arguments rectangle will equal canvas
*/
function drawImageProp(ctx, img, x, y, w, h, offsetX, offsetY) {
if (arguments.length === 2) {
x = y = 0;
w = ctx.canvas.width;
h = ctx.canvas.height;
}
// default offset is center
offsetX = typeof offsetX === "number" ? offsetX : 0.5;
offsetY = typeof offsetY === "number" ? offsetY : 0.5;
// keep bounds [0.0, 1.0]
if (offsetX < 0) offsetX = 0;
if (offsetY < 0) offsetY = 0;
if (offsetX > 1) offsetX = 1;
if (offsetY > 1) offsetY = 1;
var iw = img.width,
ih = img.height,
r = Math.min(w / iw, h / ih),
nw = iw * r, // new prop. width
nh = ih * r, // new prop. height
cx, cy, cw, ch, ar = 1;
// decide which gap to fill
if (nw < w) ar = w / nw;
if (Math.abs(ar - 1) < 1e-14 && nh < h) ar = h / nh; // updated
nw *= ar;
nh *= ar;
// calc source rectangle
cw = iw / (nw / w);
ch = ih / (nh / h);
cx = (iw - cw) * offsetX;
cy = (ih - ch) * offsetY;
// make sure source rectangle is valid
if (cx < 0) cx = 0;
if (cy < 0) cy = 0;
if (cw > iw) cw = iw;
if (ch > ih) ch = ih;
// fill image in dest. rectangle
ctx.drawImage(img, cx, cy, cw, ch, x, y, w, h);
}
</code></pre>
<p>Now you can call it like this:</p>
<pre><code>drawImageProp(ctx, image, 0, 0, width, height);
</code></pre>
<p>and it will scale the image proportionally to fit inside in that container.</p>
<p>Use the two last parameters to offset the image:</p>
<pre><code>var offsetX = 0.5; // center x
var offsetY = 0.5; // center y
drawImageProp(ctx, image, 0, 0, width, height, offsetX, offsetY);
</code></pre>
<p>Hope this helps!</p> |
6,699,330 | How to save photo with EXIF(GPS) AND orientation on iPhone? | <p>I'm using <a href="http://developer.apple.com/library/ios/documentation/AssetsLibrary/Reference/ALAssetsLibrary_Class/Reference/Reference.html#//apple_ref/occ/instm/ALAssetsLibrary/writeImageToSavedPhotosAlbum:metadata:completionBlock:" rel="noreferrer">writeImageToSavedPhotosAlbum:metadata:completionBlock:</a> to save images to the camera roll (GPS data is in dictionary passed to metadata). However pictures are misoriented (as I flip the device while taking the pictures). </p>
<p>There's another function writeImageToSavedPhotosAlbum:orientation:completionBlock: but I won't be able to pass EXIF data.</p>
<p>According to the documentation, there's <a href="http://developer.apple.com/library/mac/documentation/GraphicsImaging/Reference/CGImageProperties_Reference/Reference/reference.html#//apple_ref/doc/c_ref/kCGImagePropertyOrientation" rel="noreferrer">kCGImagePropertyOrientation</a> property to set orientation manually but I'm having problems with detecting current orientation of the device while taking the picture and saving it.</p>
<p>Has anyone achieved saving picture with EXIF data and proper orientation? Any help would be very appreciated.</p>
<p>Here's my code:</p>
<pre><code>- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
[self dismissModalViewControllerAnimated:YES];
[imageView setImage:image];
if(sourceCamera) {
//EXIF and GPS metadata dictionary
(...)
//saving image
ALAssetsLibrary *al = [[ALAssetsLibrary alloc] init];
[al writeImageToSavedPhotosAlbum:[image CGImage]
metadata:dict
completionBlock:^(NSURL *assetURL, NSError *error) {
if (error == nil) {
NSLog(@"saved");
} else {
NSLog(@"error");
}
}];
[al release];
}
}
</code></pre>
<p>Best wishes,</p>
<p>a.</p> | 6,699,649 | 1 | 0 | null | 2011-07-14 20:08:55.173 UTC | 9 | 2011-07-14 20:41:44.083 UTC | null | null | null | null | 845,273 | null | 1 | 13 | iphone|gps|orientation|exif | 6,671 | <p>You need to map the UIImageOrientation values to the corresponding EXIF orientation values when setting <code>kCGImagePropertyOrientation</code>. That mapping is:</p>
<pre><code>UIImageOrientationUp: 1
UIImageOrientationDown: 3
UIImageOrientationLeft: 8
UIImageOrientationRight: 6
UIImageOrientationUpMirrored: 2
UIImageOrientationDownMirrored: 4
UIImageOrientationLeftMirrored: 5
UIImageOrientationRightMirrored: 7
</code></pre>
<p>Note that UIImageOrientationLeft and UIImageOrientationRight are the opposite of what you might expect from <a href="http://developer.apple.com/library/ios/documentation/uikit/reference/UIImage_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40006890-CH3-SW1">the documentation</a>; the little sample images are what you get if you apply the orientation to an upright image, rather than the orientation of the raw image data that will give an upright image when the orientation is applied.</p> |
20,864,406 | Remove package and module name from sphinx function | <p>it's any way to remove the package and or module name from sphinx doc?</p>
<p>Example: if exist a function called waa inside the module foo.bar, the rst code</p>
<pre><code>.. automodule:: foo.bar
:members:
</code></pre>
<p>will generate</p>
<pre><code>foo.bar.waa()
</code></pre>
<p>and i want to output</p>
<pre><code>waa()
</code></pre> | 23,686,917 | 2 | 0 | null | 2013-12-31 23:59:42.57 UTC | 3 | 2022-06-17 11:07:51.477 UTC | 2014-01-01 00:18:13.117 UTC | null | 65,548 | null | 2,489,206 | null | 1 | 31 | python-sphinx | 7,147 | <p>You can change <code>add_module_names</code> to <code>False</code> in the file <code>conf.py</code>:</p>
<pre><code># If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
add_module_names = False
</code></pre>
<p>Then <code>foo.bar.my_function()</code> will display as <code>my_function()</code>.</p> |
24,201,120 | MongoDB - The argument to $size must be an Array, but was of type: EOO / missing | <p>Trying to create a MongoDB data source with <a href="http://www.iccube.com" rel="noreferrer">icCube</a>. The idea is to return the size of an array as a new field. Something like :</p>
<pre><code>$project:
{
"people": 1,
"Count myFieldArray" : {$size : "$myFieldArray" }
}
</code></pre>
<p>But I'm getting for some records the following error :</p>
<pre><code>The argument to $size must be an Array, but was of type: EOO
</code></pre>
<p>Is there a way that size is 0 if the field is empty or not an array (getting rid of the error) ?</p> | 24,201,302 | 3 | 0 | null | 2014-06-13 08:41:21.367 UTC | 11 | 2019-08-23 08:07:22.497 UTC | 2019-04-02 05:57:28.397 UTC | null | 2,313,887 | null | 763,790 | null | 1 | 75 | mongodb|mongodb-query|aggregation-framework|iccube | 29,580 | <p>You can use the <a href="http://docs.mongodb.org/manual/reference/operator/aggregation/ifNull/"><strong><code>$ifNull</code></strong></a> operator here. It seems the field is either not an array or not present by the given error:</p>
<pre class="lang-js prettyprint-override"><code>{ "$project": {
"people": 1,
"Count": {
"$size": { "$ifNull": [ "$myFieldArray", [] ] }
}
}}
</code></pre>
<p>Also you might want to check for the <a href="http://docs.mongodb.org/manual/reference/operator/query/type/"><strong><code>$type</code></strong></a> in your <a href="http://docs.mongodb.org/manual/reference/operator/aggregation/match/"><strong><code>$match</code></strong></a> in case these do exist but are not an array.</p> |
24,062,989 | clang fails replacing a statement if it contains a macro | <p>I'm using clang to try and parse (with the C++ API) some C++ files and make all the case - break pairs use a specific style.</p>
<p><strong>Example</strong>:</p>
<pre><code>**Original**
switch(...)
{
case 1:
{
<code>
}break;
case 2:
{
<code>
break;
}
}
**After replacement**
switch(...)
{
case 1:
{
<code>
break;
}
case 2:
{
<code>
break;
}
}
</code></pre>
<p>What I have so far does exactly what I want if the code parts don't contain any macros.
My question is: does clang treat expanded ( if I do a dump of a problematic statement it will show the expanded version ) macros differently? if so how can I get this to work?</p>
<p>Additional info that may help:</p>
<p>I'm using <a href="http://clang.llvm.org/doxygen/classclang_1_1Rewriter.html#afe268d736bda618e176fc754bb4657a8" rel="noreferrer"><strong>Rewriter::ReplaceStmt</strong></a> to replace the sub-statements of each case with a newly created <strong>CompoundStmt</strong> and I noticed <strong>ReplaceStmt</strong> returns true if the "from" parameter contains a macro and the only way that method returns <strong>true</strong> is if</p>
<blockquote>
<p><a href="http://clang.llvm.org/doxygen/classclang_1_1Rewriter.html#a73a1da56ec0a9d2a720f087ddd94870c" rel="noreferrer">Rewriter::getRangeSize</a>(from-><a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html#a6844392ee6148b5fe821f211b95e5d1b" rel="noreferrer">getSourceRange</a>())</p>
</blockquote>
<p>returns -1</p> | 24,223,347 | 2 | 0 | null | 2014-06-05 14:33:10.487 UTC | 9 | 2015-08-20 12:23:11.323 UTC | 2014-06-05 17:52:41.9 UTC | null | 1,233,963 | null | 1,233,963 | null | 1 | 23 | c++|clang|clang++ | 3,474 | <p>Your problem is caused by the design of <a href="http://clang.llvm.org/doxygen/classclang_1_1SourceLocation.html">SourceLocation</a>.</p>
<p>An article follows:</p>
<hr>
<h1>Macro expansion with clang's SourceLocation</h1>
<p><a href="http://clang.llvm.org/doxygen/classclang_1_1SourceLocation.html"><code>SourceLocation</code></a> is designed to be flexible enough to handle <strong>both unexpanded locations and macro expanded locations at the same time</strong>. </p>
<p>If the token is the result of an expansion, then there are two different locations to be kept into account: the <em>spelling location</em> (the location of the characters corresponding to the token) and the <em>instantiation location</em> (the location where the token was used - the macro instantiation point).</p>
<p>Let's take the following simple source file as an example:</p>
<pre><code>#define MACROTEST bool
int main() {
int var = 2;
switch(var)
{
case 1:
{
MACROTEST newvar;
}break;
case 2:
{
MACROTEST newvar;
break;
}
}
return 0;
}
</code></pre>
<p>and suppose we want to replace the two declarations statements</p>
<pre><code>MACROTEST newvar;
</code></pre>
<p>with the declaration statement</p>
<pre><code>int var = 2;
</code></pre>
<p>in order to get something like this</p>
<pre><code>#define MACROTEST bool
int main() {
int var = 2;
switch(var)
{
case 1:
{
int var = 2;
}break;
case 2:
{
int var = 2;
break;
}
}
return 0;
}
</code></pre>
<p>if we output the AST (<em>-ast-dump</em>) we get the following (I'm including an image since it's more intuitive than just uncolored text):</p>
<p><img src="https://i.stack.imgur.com/bukgZ.png" alt="clang AST"></p>
<p>as you can see the location reported for the first <code>DeclStmt</code> we're interested in, spans from line 1 to 10: that means clang is reporting in the dump the interval spanning from the macro's line to the point where the macro is used:</p>
<pre><code>#define MACROTEST [from_here]bool
int main() {
int var = 2;
switch(var)
{
case 1:
{
MACROTEST newvar[to_here];
}break;
case 2:
{
MACROTEST newvar;
break;
}
}
return 0;
}
</code></pre>
<p><sub>(notice that the count of characters might not be the same with normal spaces since my text editor used tabs)</sub></p>
<p>Ultimately, this is triggering the <code>Rewriter::getRangeSize</code> failure (<code>-1</code>) and the subsequent <a href="http://clang.llvm.org/doxygen/classclang_1_1Rewriter.html#afe268d736bda618e176fc754bb4657a8"><code>Rewriter::ReplaceStmt</code></a> <code>true</code> return value (which means failure - see documentation).</p>
<p>What is happening is the following: you're receiving a couple of <a href="http://clang.llvm.org/doxygen/classclang_1_1SourceLocation.html"><code>SourceLocation</code></a> markers where the first is a macro ID (<a href="http://clang.llvm.org/doxygen/classclang_1_1SourceLocation.html#a83c660ad7c57096011c5f40c50b52c7d"><code>isMacroID()</code></a> would return true) while the latter isn't.</p>
<p>In order to successfully get the extent of the macro-expanded statement we need to take a step back and communicate with the <a href="http://clang.llvm.org/doxygen/classclang_1_1SourceManager.html"><code>SourceManager</code></a> which is the query-gateway for all your <em>spelling locations</em> and <em>instantiation locations</em> (take a step back if you don't remember these terms) needs. I can't be more clear than the detailed description provided <a href="http://clang.llvm.org/doxygen/classclang_1_1SourceManager.html#details">in the documentation</a>:</p>
<blockquote>
<p>The SourceManager can be queried for information about SourceLocation
objects, turning them into either spelling or expansion locations.
Spelling locations represent where the bytes corresponding to a token
came from and expansion locations represent where the location is in
the user's view. In the case of a macro expansion, for example, the
spelling location indicates where the expanded token came from and the
expansion location specifies where it was expanded.</p>
</blockquote>
<p>At this point you should be getting why I explained all this stuff in the first place: <strong>if you intend to use source ranges for your substitution, you need to use the appropriate expansion interval</strong>.</p>
<p>Back to the sample I proposed, this is the code to achieve it:</p>
<pre><code>SourceLocation startLoc = declaration_statement->getLocStart();
SourceLocation endLoc = declaration_statement->getLocEnd();
if( startLoc.isMacroID() ) {
// Get the start/end expansion locations
std::pair< SourceLocation, SourceLocation > expansionRange =
rewriter.getSourceMgr().getImmediateExpansionRange( startLoc );
// We're just interested in the start location
startLoc = expansionRange.first;
}
if( endLoc.isMacroID() ) {
// will not be executed
}
SourceRange expandedLoc( startLoc, endLoc );
bool failure = rewriter.ReplaceText( expandedLoc,
replacer_statement->getSourceRange() );
if( !failure )
std::cout << "This will get printed if you did it correctly!";
</code></pre>
<p>The <code>declaration_statement</code> is either one of the two</p>
<pre><code>MACROTEST newvar;
</code></pre>
<p>while <code>replacer_statement</code> is the statement used for the replacement</p>
<pre><code>int var = 2;
</code></pre>
<p>The above code will get you this:</p>
<pre><code>#define MACROTEST bool
int main() {
int var = 2;
switch(var)
{
case 1:
{
int var = 2;
}break;
case 2:
{
int var = 2;
break;
}
}
return 0;
}
</code></pre>
<p>i.e. a complete and successful substitution of the macro-expanded statement.</p>
<hr>
<p>References:</p>
<ul>
<li><a href="http://clang.llvm.org/docs/InternalsManual.html#the-sourcelocation-and-sourcemanager-classes">clang documentation</a></li>
<li>clang doxygen API</li>
<li>clang source code</li>
</ul> |
5,953,759 | Using a class' __new__ method as a Factory: __init__ gets called twice | <p>I encountered a strange bug in python where using the <code>__new__</code> method of a class as a factory would lead to the <code>__init__</code> method of the instantiated class to be called twice.</p>
<p>The idea was originally to use the <code>__new__</code> method of the mother class to return a specific instance of one of her children depending on the parameters that are passed, without having to declare a factory function outside of the class.</p>
<p>I know that using a factory function would be the best design-pattern to use here, but changing the design pattern at this point of the project would be costly. My question hence is: is there a way to avoid the double call to <code>__init__</code> and get only a single call to <code>__init__</code> in such a schema ?</p>
<pre><code>class Shape(object):
def __new__(cls, desc):
if cls is Shape:
if desc == 'big': return Rectangle(desc)
if desc == 'small': return Triangle(desc)
else:
return super(Shape, cls).__new__(cls, desc)
def __init__(self, desc):
print "init called"
self.desc = desc
class Triangle(Shape):
@property
def number_of_edges(self): return 3
class Rectangle(Shape):
@property
def number_of_edges(self): return 4
instance = Shape('small')
print instance.number_of_edges
>>> init called
>>> init called
>>> 3
</code></pre>
<p>Any help greatly appreciated.</p> | 5,953,974 | 3 | 0 | null | 2011-05-10 17:11:00.177 UTC | 13 | 2016-08-02 09:05:16.847 UTC | null | null | null | null | 287,297 | null | 1 | 41 | python|design-patterns|inheritance|class-design | 17,593 | <p>When you construct an object Python calls its <code>__new__</code> method to create the object then calls <code>__init__</code> on the object that is returned. When you create the object from inside <code>__new__</code> by calling <code>Triangle()</code> that will result in further calls to <code>__new__</code> and <code>__init__</code>.</p>
<p>What you should do is:</p>
<pre><code>class Shape(object):
def __new__(cls, desc):
if cls is Shape:
if desc == 'big': return super(Shape, cls).__new__(Rectangle)
if desc == 'small': return super(Shape, cls).__new__(Triangle)
else:
return super(Shape, cls).__new__(cls, desc)
</code></pre>
<p>which will create a <code>Rectangle</code> or <code>Triangle</code> without triggering a call to <code>__init__</code> and then <code>__init__</code> is called only once.</p>
<p>Edit to answer @Adrian's question about how super works:</p>
<p><code>super(Shape,cls)</code> searches <code>cls.__mro__</code> to find <code>Shape</code> and then searches down the remainder of the sequence to find the attribute.</p>
<p><code>Triangle.__mro__</code> is <code>(Triangle, Shape, object)</code> and
<code>Rectangle.__mro__</code> is <code>(Rectangle, Shape, object)</code> while <code>Shape.__mro__</code> is just <code>(Shape, object)</code>.
For any of those cases when you call <code>super(Shape, cls)</code> it ignores everything in the mro squence up to and including <code>Shape</code> so the only thing left is the single element tuple <code>(object,)</code> and that is used to find the desired attribute.</p>
<p>This would get more complicated if you had a diamond inheritance:</p>
<pre><code>class A(object): pass
class B(A): pass
class C(A): pass
class D(B,C): pass
</code></pre>
<p>now a method in B might use <code>super(B, cls)</code> and if it were a B instance would search <code>(A, object)</code> but if you had a <code>D</code> instance the same call in <code>B</code> would search <code>(C, A, object)</code> because the <code>D.__mro__</code> is <code>(B, C, A, object)</code>.</p>
<p>So in this particular case you could define a new mixin class that modifies the construction behaviour of the shapes and you could have specialised triangles and rectangles inheriting from the existing ones but constructed differently.</p> |
6,065,609 | document.getElementById(...).setAttribute('style',... not working in Internet Explorer | <p>document.getElementById(...).setAttribute('style',... is not working in Internet Explorer 7.0. How can I make this work in Internet Explorer?</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var myarray=new Array(3);
for (i=0; i <1000; i++){
myarray[i]=new Array(3);
}
myarray[0][0]="new"; myarray[0][1]="old";
function swapText(id){
document.getElementById('id' + id).setAttribute('style', 'font-weight: bold; color: red; font-size:150%;');
document.getElementById('id'+ id).innerHTML = myarray[id][0];
}
function originalText(id){
document.getElementById('id' + id).setAttribute('style', 'color:' + 'black' + ';');
document.getElementById('id' + id).innerHTML = myarray[id][1];
}
</script>
</head>
<body>
<div id="scoreboard" border='1'> </div>
<div id="qa">
<div id="col1" class="column">
<div id="id0" onmouseover="swapText(0)"; onmouseout="originalText(0)">old</div>
</div>
</div>
</body>
</html>
</code></pre> | 6,065,647 | 4 | 3 | null | 2011-05-19 22:37:26.893 UTC | 3 | 2013-12-30 10:28:05.88 UTC | null | null | null | null | 647,405 | null | 1 | 6 | javascript | 96,062 | <p>Using <code>setAttribute</code> is unreliable if you want the change to be reflected in the document. Use <a href="http://msdn.microsoft.com/en-us/library/ms536498%28v=VS.85%29.aspx"><code>Element.style</code></a> instead:</p>
<pre><code>var el = document.getElementById('id' + id);
el.style.fontWeight = 'bold';
el.style.color = 'red';
el.style.fontSize = '150%';
</code></pre>
<p>and suchlike.</p> |
1,778,221 | Understanding ASP.NET Eval() and Bind() | <p>Can anyone show me some absolutely minimal ASP.NET code to understand <code>Eval()</code> and <code>Bind()</code>?</p>
<p>It is best if you provide me with two separate code-snippets or may be web-links.</p> | 1,778,236 | 2 | 0 | null | 2009-11-22 08:57:12.69 UTC | 29 | 2017-11-21 06:16:01.573 UTC | 2011-12-19 17:46:07.43 UTC | null | 681,785 | null | 159,072 | null | 1 | 61 | asp.net|eval|bind | 149,401 | <p>For read-only controls they are the same. For 2 way databinding, using a datasource in which you want to update, insert, etc with declarative databinding, you'll need to use <code>Bind</code>.</p>
<p>Imagine for example a GridView with a <code>ItemTemplate</code> and <code>EditItemTemplate</code>. If you use <code>Bind</code> or <code>Eval</code> in the <code>ItemTemplate</code>, there will be no difference. If you use <code>Eval</code> in the <code>EditItemTemplate</code>, the value will not be able to be passed to the <code>Update</code> method of the <code>DataSource</code> that the grid is bound to.</p>
<hr>
<p>UPDATE: I've come up with this example:</p>
<pre><code><%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Data binding demo</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView
ID="grdTest"
runat="server"
AutoGenerateEditButton="true"
AutoGenerateColumns="false"
DataSourceID="mySource">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# Eval("Name") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox
ID="edtName"
runat="server"
Text='<%# Bind("Name") %>'
/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
<asp:ObjectDataSource
ID="mySource"
runat="server"
SelectMethod="Select"
UpdateMethod="Update"
TypeName="MyCompany.CustomDataSource" />
</body>
</html>
</code></pre>
<p>And here's the definition of a custom class that serves as object data source:</p>
<pre><code>public class CustomDataSource
{
public class Model
{
public string Name { get; set; }
}
public IEnumerable<Model> Select()
{
return new[]
{
new Model { Name = "some value" }
};
}
public void Update(string Name)
{
// This method will be called if you used Bind for the TextBox
// and you will be able to get the new name and update the
// data source accordingly
}
public void Update()
{
// This method will be called if you used Eval for the TextBox
// and you will not be able to get the new name that the user
// entered
}
}
</code></pre> |
29,665,534 | Type a String using java.awt.Robot | <p>I already know how to use <code>java.awt.Robot</code> to type a single character using <code>keyPress</code>, as seen below. How can I simply enter a <strong>whole</strong> pre-defined <code>String</code> value <strong>at once</strong> into a textbox? </p>
<pre><code>robot.keyPress(KeyEvent.VK_1);
robot.keyPress(KeyEvent.VK_1);
robot.keyPress(KeyEvent.VK_1);
// instead, enter String x = "111"
</code></pre> | 29,665,705 | 7 | 0 | null | 2015-04-16 04:47:13.163 UTC | 3 | 2018-11-13 15:06:49.747 UTC | 2015-04-16 05:05:35.433 UTC | null | 2,891,664 | user1196937 | null | null | 1 | 32 | java|swing|awtrobot | 36,549 | <p>Common solution is to use the clipboard:</p>
<pre><code>String text = "Hello World";
StringSelection stringSelection = new StringSelection(text);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, stringSelection);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
</code></pre> |
50,452,359 | Navigation Architecture Component - Activities | <p>I've been following the docs from <a href="https://developer.android.com/topic/libraries/architecture/navigation/navigation-implementing" rel="noreferrer">Navigation Architecture Component</a> to understand how this new navigation system works. </p>
<p>To go/back from one screen to another you need a component which implements <code>NavHost</code> interface.</p>
<blockquote>
<p>The NavHost is an empty view whereupon destinations are swapped in and
out as a user navigates through your app.</p>
</blockquote>
<p>But, it seems that currently only Fragments implement <code>NavHost</code> </p>
<blockquote>
<p>The Navigation Architecture Component’s default NavHost implementation is NavHostFragment.</p>
</blockquote>
<p>So, my questions are:</p>
<ul>
<li><p>Even if I have a very simple screen which can be implemented with an <code>Activity</code>, in order to work with this new navigation system, a <code>Fragment</code> needs to be hosted containing the actual view?</p></li>
<li><p>Will <code>Activity</code> implement <code>NavHost</code> interface in a near future?</p></li>
</ul>
<p><strong>--UPDATED--</strong> </p>
<p>Based on ianhanniballake's answer, I understand that every activity contains its own navigation graph. But if I want to go from one activity to another using the nav component (replacing "old" <code>startActivity</code> call), I can use <code>activity destinations</code>. What is <code>activity destinations</code> is not clear to me because the <a href="https://developer.android.com/topic/libraries/architecture/navigation/navigation-migrate" rel="noreferrer">docs for migration</a> don't go into any detail:</p>
<blockquote>
<p>Separate Activities can then be linked by adding activity destinations to the navigation graph, replacing existing usages of startActivity() throughout the code base.</p>
</blockquote>
<ul>
<li>Is there any benefit on using <code>ActivityNavigator</code> instead of <code>startActivity</code>? </li>
<li>What is the proper way to go from activities when using the nav component? </li>
</ul> | 53,432,167 | 3 | 2 | null | 2018-05-21 15:47:10.133 UTC | 13 | 2020-04-22 01:04:29.03 UTC | 2018-11-22 13:34:53.137 UTC | null | 1,525,990 | null | 1,525,990 | null | 1 | 53 | android|android-architecture-navigation | 40,070 | <p>I managed to navigate from one activity to another without hosting a Fragment by using <code>ActivityNavigator</code>.</p>
<pre><code>ActivityNavigator(this)
.createDestination()
.setIntent(Intent(this, SecondActivity::class.java))
.navigate(null, null)
</code></pre> |
5,804,844 | Implementing Depth First Search into C# using List and Stack | <p>I want to create a depth first search which I have been somewhat successful in.</p>
<p>Here is my code so far (Except my constructor, note the Vertex and Edge classes only contain properties, nothing important to post here):</p>
<pre><code>private Stack<Vertex> workerStack = new Stack<Vertex>();
private List<Vertex> vertices = new List<Vertex>();
private List<Edge> edges = new List<Edge>();
private int numberOfVertices;
private int numberOfClosedVertices;
private int visitNumber = 1;
private void StartSearch()
{
// Make sure to visit all vertices
while (numberOfClosedVertices < numberOfVertices && workerStack.Count > 0)
{
// Get top element in stack and mark it as visited
Vertex workingVertex = workerStack.Pop();
workingVertex.State = State.Visited;
workingVertex.VisitNumber = visitNumber;
visitNumber++;
numberOfClosedVertices++;
// Get all edges connected to the working vertex
foreach (Vertex vertex in GetConnectedVertices(workingVertex))
{
vertex.Parent = workingVertex;
workerStack.Push(vertex);
}
}
}
private List<Vertex> GetConnectedVertices(Vertex vertex)
{
List<Vertex> vertices = new List<Vertex>();
// Get all vertices connected to vertex and is unvisited, then add them to the vertices list
edges.FindAll(edge => edge.VertexSource == vertex && edge.VertexTarget.State == State.Unvisited).ForEach(edge => vertices.Add(edge.VertexTarget));
return vertices;
}
</code></pre>
<p>Its working in the way that all vertices get visited, but not in the right order.</p>
<p>Here is a comparison of how mine gets visited compared to wikipedia:
<img src="https://i.stack.imgur.com/GhT5V.jpg" alt="Comparison"></p>
<p>Its seems mine is turned around and is beginning from right to left.</p>
<p>Do you know what causes it? (Also any advice on my implementation would be greatly appreciated)</p>
<p>EDIT: I got my answer, but still wanted to show the end result for the GetConnectedVertices method:</p>
<pre><code>private List<Vertex> GetConnectedVertices(Vertex vertex)
{
List<Vertex> connectingVertices = new List<Vertex>();
(from edge in edges
where edge.VertexSource == vertex && edge.VertexTarget.State == State.Unvisited
select edge).
Reverse().
ToList().
ForEach(edge => connectingVertices.Add(edge.VertexTarget));
return connectingVertices;
}
</code></pre> | 5,806,795 | 6 | 0 | null | 2011-04-27 13:25:37.51 UTC | 20 | 2019-09-20 19:26:49.54 UTC | 2019-09-20 19:26:49.54 UTC | null | 2,756,409 | null | 668,521 | null | 1 | 32 | c#|search|vertex|depth|edges | 49,112 | <blockquote>
<p>It seems mine is turned around and is beginning from right to left. Do you know what causes it? </p>
</blockquote>
<p>As others have noted, you are pushing the nodes-to-visit-next on the stack in order from left to right. That means they get popped off right-to-left, since a stack reverses the order. Stacks are last-in-first-out.</p>
<p>You can fix the problem by making GetConnectedVertices build a stack, not a list. That way the connected vertices are reversed <em>twice</em>, once when they go on the returned stack and once when they go on the real stack.</p>
<blockquote>
<p>Also any advice on my implementation would be greatly appreciated</p>
</blockquote>
<p>The implementation works, I suppose, but it has a great many fundamental problems. If I were presented that code for review, here's what I'd say:</p>
<p>First off, suppose you wanted to do two depth-first searches of this data structure at the same time. Either because you were doing it on multiple threads, or because you have a nested loop in which the inner loop does a DFS for a different element than the outer loop. What happens? They interfere with each other because both try to mutate the "State" and "VisitNumber" fields. It is a really bad idea to have what should be a "clean" operation like searching actually make your data structure "dirty".</p>
<p>Doing so also makes it impossible for you to use <em>persistent immutable data</em> to represent redundant portions of your graph.</p>
<p>Also, I notice that you omit the code that cleans up. When is "State" ever set back to its original value? What if you did a <em>second</em> DFS? It would immediately fail since the root is already visited.</p>
<p>A better choice for all these reasons is to keep the "visited" state in its own object, not in each vertex.</p>
<p>Next, why are all the state objects private variables of a class? This is a simple algorithm; there's no need to build an entire class for it. A depth first search algorithm should take the graph to search as a formal parameter, not as object state, and it should maintain its own local state as necessary in local variables, not fields.</p>
<p>Next, the abstraction of the graph is... well, its not an abstraction. It's two lists, one of vertices and one of edges. How do we know that those two lists are even consistent? Suppose there are vertices that are not in the vertex list but are on the edge list. How do you prevent that? What you want is a graph abstraction. Let the graph abstraction implementation worry about how to represent edges and find neighbours.</p>
<p>Next, your use of ForEach is both legal and common, but it makes my head hurt. It is hard to read your code and reason about it with all the lambdas. We have a perfectly good "foreach" statement. Use it.</p>
<p>Next, you are mutating a "parent" property but it is not at all clear what this property is for or why it is being mutated during a traversal. Vertices in an arbitrary graph do not have "parents" unless the graph is a tree, and if the graph is a tree then there is no need to keep track of the "visited" state; there are no loops in a tree. What is going on here? This code is just bizarre, and it is not necessary to perform a DFS.</p>
<p>Next, your helper method named GetConnectedVertices is a lie. It does not get connected vertices, it gets connected not-already-visited vertices. Methods whose names lie are very confusing.</p>
<p>Finally, this claims to be a depth first search but <em>it doesn't search for anything!</em> Where is the thing being searched for? Where is the result returned? This isn't a search at all, it's a traversal.</p>
<p>Start over. What do you want? <strong>A depth-first traversal of a graph given a starting vertex</strong>. Then implement that. Start by defining what you are traversing. A graph. What service do you need from a graph? A way of getting the set of neighbouring vertices:</p>
<pre><code>interface IGraph
{
IEnumerable<Vertex> GetNeighbours(Vertex v);
}
</code></pre>
<p>What is your method returning? A sequence of Vertices in depth-first order. What does it take? A starting vertex. OK:</p>
<pre><code>static class Extensions
{
public static IEnumerable<Vertex> DepthFirstTraversal(
this IGraph graph,
Vertex start)
{ ... }
}
</code></pre>
<p>We now have a trivial implementation of depth first search; you can now use the Where clause:</p>
<pre><code>IGraph myGraph = whatever;
Vertex start = whatever;
Vertex result = myGraph.DepthFirstTraversal(start)
.Where(v=>something)
.FirstOrDefault();
</code></pre>
<p>OK, so how are we going to implement that method so it does a traversal without wrecking the graph's state? Maintain your own external state:</p>
<pre><code>public static IEnumerable<Vertex> DepthFirstTraversal(
this IGraph graph,
Vertex start)
{
var visited = new HashSet<Vertex>();
var stack = new Stack<Vertex>();
stack.Push(start);
while(stack.Count != 0)
{
var current = stack.Pop();
if(!visited.Add(current))
continue;
yield return current;
var neighbours = graph.GetNeighbours(current)
.Where(n=>!visited.Contains(n));
// If you don't care about the left-to-right order, remove the Reverse
foreach(var neighbour in neighbours.Reverse())
stack.Push(neighbour);
}
}
</code></pre>
<p>See how much cleaner and shorter that is? No mutation of state. No mucking around with edge lists. No badly-named helper functions. And the code actually does what it says it does: traverses a graph. </p>
<p>We also get the benefits of iterator blocks; namely, if someone is using this for a DF search, then the iteration is abandoned when the search criteria are met. We don't have to do a full traversal if we find the result early.</p> |
6,141,710 | Running rsync in background | <p>I use this to run rsync in background</p>
<pre><code>rsync -avh /home/abc/abac /backups/ddd &
</code></pre>
<p>When i do that i see line saying 1 process stopped. </p>
<p>Now does that mean my process is still running ot it is stopped</p> | 6,141,758 | 7 | 2 | null | 2011-05-26 16:15:00.46 UTC | 4 | 2018-08-23 21:27:54.247 UTC | null | null | null | null | 767,244 | null | 1 | 11 | linux|background|rsync | 83,743 | <p>It is probably trying to read from the terminal (to ask you for a password, perhaps). When a background process tries to read from the terminal, it gets stopped.</p>
<p>You can make the error go away by redirecting stdin from /dev/null:</p>
<pre><code>rsync -avh /home/abc/abac /backups/ddd < /dev/null &
</code></pre>
<p>...but then it will probably fail because it will not be able to read whatever it was trying to read.</p> |
6,138,042 | Javascript selecbox.options to array? | <p>From what I understand a <code>option</code> elements that popuate <code>select</code> elements in HTML are an array.<br>
So basically what i want to do is return an array string that is separated by commas.</p>
<p>Tried to do <code>selecbox.options.join(',');</code>, but got an error that its not supported; anyone have an idea why?</p> | 6,138,067 | 8 | 1 | null | 2011-05-26 11:53:47.91 UTC | 6 | 2022-06-04 10:04:02.737 UTC | 2017-04-05 16:59:05.98 UTC | null | 401,672 | null | 572,771 | null | 1 | 31 | javascript|html|html-select | 45,640 | <p>It is not an array. It is an HTMLCollection. It is "array-like"</p>
<p>In 2022, a week before EOL of Internet Explorer 11, the simplest vanilla JavaScript solution is using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax" rel="nofollow noreferrer">spread</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map" rel="nofollow noreferrer">Array map</a></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>const opts = document.querySelectorAll("select option");
// we can use forEach on the resulting HTMLCollection
// but map needs to be spread to array
const vals = [...opts]
.map(el => el.value);
console.log(vals);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><select>
<option value="Please select">Text 0</option>
<option value="one">Text 1</option>
<option value="two">Text 2</option>
<option value="three">Text 3</option>
</select><br/>
The above select has the following option values:<br/>
<span id="result"></span></code></pre>
</div>
</div>
</p>
<hr />
<p><strong>Older answer that is compatible with IE11</strong></p>
<p>from <a href="http://api.jquery.com/jQuery.each/" rel="nofollow noreferrer">http://api.jquery.com/jQuery.each/</a> which CAN iterate over either:</p>
<blockquote>
<p>Iterate over both objects and arrays.
Arrays and array-like objects with a
length property (such as a function's
arguments object) are iterated by
numeric index, from 0 to length-1.
Other objects are iterated via their
named properties.</p>
</blockquote>
<p>Each <a href="https://developer.mozilla.org/en/DOM/HTMLOptionElement" rel="nofollow noreferrer">HTML Option element</a> has a value and a text and some more attributes.</p>
<p>A simple for loop can be used</p>
<pre><code>vals = []
var sel = document.querySelector("select");
for (var i=0, n=sel.options.length;i<n;i++) { // looping over the options
if (sel.options[i].value) vals.push(sel.options[i].value);
}
</code></pre>
<p>the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply" rel="nofollow noreferrer">Array.apply</a> posted by typeracer will return an array of HTMLOptionElements which still needs to be looped over or mapped to get at the values and texts</p>
<p>Here are a few versions that will return the same.</p>
<p><a href="http://jsfiddle.net/mplungjan/nwmzsghc/show" rel="nofollow noreferrer">This fiddle will run in IE11 too</a></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var vals, sel = document.querySelector("select"), show=function(vals) {$("#result").append("[" + vals.join("][") + "]<hr/>");}
var supportsES6 = function() {try{new Function("(a = 0) => a");return true;}catch (err) {return false; }}();
// jQuery mapping jQuery objects - note the "this" and the .get()
vals = $('select > option').map(function() {return this.value;}).get();
show(vals);
// plain JS using loop over select options
vals = [];
for (var i = 0, n = sel.options.length; i < n; i++) { // looping over the options
if (sel.options[i].value) vals.push(sel.options[i].value); // a bit of testing never hurts
}
show(vals);
// Plain JS using map of HTMLOptionElements - note the el
vals = Array.apply(null, sel.options).map(function(el) { return el.value; });
show(vals);
// ES6 JS using spread and map of HTMLOptionElements - note the fat arrow and el
if (supportsES6)
document.write(`<script>
vals = [...sel.options].map(el => el.value);
show(vals);
<\/script>`
);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<select>
<option value="Please select">Text 0</option>
<option value="one">Text 1</option>
<option value="two">Text 2</option>
<option value="three">Text 3</option>
</select><br/>
The above select has the following option values:<br/>
<span id="result"></span></code></pre>
</div>
</div>
</p> |
5,903,323 | Can't get value of input type="file"? | <p>I have a <code><input type="file" id="uploadPicture" value="123"></code></p>
<p>When I'm using: <code>alert($("#uploadPicture").val());</code></p>
<p>It alerts an empty dialog.</p> | 5,903,347 | 8 | 2 | null | 2011-05-05 19:51:06.367 UTC | 12 | 2021-04-24 21:56:00.7 UTC | 2017-04-16 04:15:00.293 UTC | null | 1,033,581 | null | 717,559 | null | 1 | 61 | javascript|jquery|file|input | 286,605 | <p>You can read it, but you can't <strong>set</strong> it. <code>value="123"</code> will be ignored, so it won't have a value until you click on it and pick a file.</p>
<p>Even then, the value will likely be mangled with something like <code>c:\fakepath\</code> to keep the details of the user's filesystem private.</p> |
38,976,582 | Reading text-file until EOF using fgets in C | <p>what is the correct way to read a text file until EOF using fgets in C? Now I have this (simplified):</p>
<pre><code>char line[100 + 1];
while (fgets(line, sizeof(line), tsin) != NULL) { // tsin is FILE* input
... //doing stuff with line
}
</code></pre>
<p>Specifically I'm wondering if there should be something else as the while-condition? Does the parsing from the text-file to "line" have to be carried out in the while-condition? </p> | 38,976,686 | 3 | 3 | null | 2016-08-16 13:42:40.35 UTC | 6 | 2017-02-10 16:38:07.853 UTC | null | null | null | null | 6,544,207 | null | 1 | 9 | c|while-loop|fgets | 51,722 | <p>According to the <a href="http://www.cplusplus.com/reference/cstdio/fgets/" rel="noreferrer">reference</a></p>
<blockquote>
<p><strong>On success, the function returns str</strong>.
If the end-of-file is encountered while attempting to read a character, the eof indicator is
set (feof). <strong>If this happens before any characters could be read, the
pointer returned is a null pointer</strong> (and the contents of str remain
unchanged). If a read error occurs, the error indicator (ferror) is
set and a null pointer is also returned (but the contents pointed by
str may have changed).</p>
</blockquote>
<p>So checking the returned value whether it is <code>NULL</code> is enough. Also the parsing goes into the while-body.</p> |
829,952 | How do I host WPF content in MFC Applications? | <p>I'm going to answer my own question here because I spent a few hours piecing this together and wanted to share what I found in the hope that I will save someone else the digging.</p>
<p>There is an <a href="http://msdn.microsoft.com/en-us/library/ms744829.aspx" rel="noreferrer">MSDN Walkthrough</a> that gets you most of the way there, but there are a couple of key pieces that I found elsewhere. For example, the walkthrough tells you to place the line [System::STAThreadAttribute] before the _tWinMain() definition but if you're implementing a standard MFC application then you don't have _tWinMain() in your source code.</p>
<p>If anything here is unclear, feel free to ask questions and I will edit the answer to make things more clear.</p> | 829,955 | 1 | 0 | null | 2009-05-06 14:43:20.243 UTC | 14 | 2009-05-06 14:50:10.943 UTC | 2009-05-06 14:50:10.943 UTC | null | 2,284 | null | 2,284 | null | 1 | 18 | wpf|mfc|wpf-controls | 11,484 | <p><strong>Step 1: Configure the MFC application to compile with CLR support</strong></p>
<p>The best way to achieve interoperability between native C++ and managed .NET code is to compile the application as managed C++ rather than native C++. This is done by going to the Configuration Properties of the project. Under General there is an option "Common Language Runtime support". Set this to "Common Language Runtime Support /clr".</p>
<p><strong>Step 2: Add the WPF assemblies to the project</strong></p>
<p>Right-click on the project in the Solution Explorer and choose "References". Click "Add New Reference". Under the .NET tab, add WindowsBase, PresentationCore, PresentationFramework, and System. Make sure you Rebuild All after adding any references in order for them to get picked up.</p>
<p><strong>Step 3: Set STAThreadAttribute on the MFC application</strong></p>
<p>WPF requires that STAThreadAttribute be set on the main UI thread. Set this by going to Configuration Properties of the project. Under Linker->Advanced there is an option called "CLR Thread Attribute". Set this to "STA threading attribute".</p>
<p><strong>Step 4: Create an instance of HwndSource to wrap the WPF component</strong></p>
<p>System::Windows::Interop::HwndSource is a .NET class that handles the interaction between MFC and .NET components. Create one using the following syntax:</p>
<pre><code>System::Windows::Interop::HwndSourceParameters^ sourceParams = gcnew System::Windows::Interop::HwndSourceParameters("MyWindowName");
sourceParams->PositionX = x;
sourceParams->PositionY = y;
sourceParams->ParentWindow = System::IntPtr(hWndParent);
sourceParams->WindowStyle = WS_VISIBLE | WS_CHILD;
System::Windows::Interop::HwndSource^ source = gcnew System::Windows::Interop::HwndSource(*sourceParams);
source->SizeToContent = System::Windows::SizeToContent::WidthAndHeight;
</code></pre>
<p>Add an HWND member variable to the dialog class and then assign it like this:
m_hWnd = (HWND) source->Handle.ToPointer();</p>
<p>The source object and the associated WPF content will remain in existence until you call ::DestroyWindow(m_hWnd).</p>
<p><strong>Step 5: Add the WPF control to the HwndSource wrapper</strong></p>
<pre><code>System::Windows::Controls::WebBrowser^ browser = gcnew System::Windows::Controls::WebBrowser();
browser->Height = height;
browser->Width = width;
source->RootVisual = browser;
</code></pre>
<p><strong>Step 6: Keep a reference to the WPF object</strong></p>
<p>Since the browser variable will go out of scope after we exit the function doing the creation, we need to somehow hold a reference to it. Managed objects cannot be members of unmanaged objects but you can use a wrapper template called gcroot to get the job done.</p>
<p>Add a member variable to the dialog class: </p>
<pre><code>#include <vcclr.h>
gcroot<System::Windows::Controls::WebBrowser^> m_webBrowser;
</code></pre>
<p>Then add the following line to the code in Step 5:</p>
<pre><code>m_webBrowser = browser;
</code></pre>
<p>Now we can access properties and methods on the WPF component through m_webBrowser. </p> |
48,757,816 | Catch all exceptions in django rest framework | <p>I guess this is more of a code quality question but it does involve handling unhandled exceptions is Django rest framework.</p>
<p>Deleting a protected record just return <code><h1>500 internal server error<h1></code>
So I added the example custom exception handler. The first line returns a response that is none. </p>
<p><code>response = exception_handler(exc, context)</code></p>
<pre><code>from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status
def custom_exception_handler(exc, context):
response = exception_handler(exc, context)
if response is None:
#DRF could not process the exception so we will treat it as a 500 and try to get the user as much info as possible.
response = Response({'error': str(exc)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
return response
</code></pre>
<p>So in this case I am treating it as a 500 because the DRF couldn't handle the <code>exc</code>.</p>
<p>I guess my question is is this an appropriate way to handle it and does anyone have experience with this have a better solution?</p>
<p>Update:</p>
<pre><code>Traceback:
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/viewsets.py" in view
116. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
495. response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
455. self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
492. response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/mixins.py" in create
21. self.perform_create(serializer)
File "/device_mgmt/selection/views.py" in perform_create
84. serializer.save(realm=utils.get_realm_from_request(self.request))
File "/usr/local/lib/python3.6/site-packages/rest_framework/serializers.py" in save
214. self.instance = self.create(validated_data)
File "/usr/local/lib/python3.6/site-packages/rest_framework/serializers.py" in create
943. instance = ModelClass._default_manager.create(**validated_data)
File "/usr/local/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py" in create
422. obj.save(force_insert=True, using=self.db)
File "/device_mgmt/selection/models.py" in save
123. self.full_clean()
File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py" in full_clean
1203. raise ValidationError(errors)
Exception Type: ValidationError at /company/api/company/
Exception Value: {'id': ['Company with this Id already exists.']}
</code></pre>
<p>Django models are throwing validation error but rest framework view it calling it uncaught.</p> | 56,349,560 | 2 | 0 | null | 2018-02-13 00:40:55.83 UTC | 10 | 2019-05-28 20:21:09.193 UTC | 2019-04-03 13:39:15.827 UTC | null | 4,610,896 | null | 4,610,896 | null | 1 | 8 | django|exception|django-rest-framework | 8,883 | <p>This seems to be the thing I was looking for...</p>
<p><a href="https://gist.github.com/twidi/9d55486c36b6a51bdcb05ce3a763e79f" rel="noreferrer">https://gist.github.com/twidi/9d55486c36b6a51bdcb05ce3a763e79f</a></p>
<p>Basically convert the django exception into a drf exception with the same details.</p>
<pre><code>"""
Sometimes in your Django model you want to raise a ``ValidationError``
in the ``save`` method, for
some reason.
This exception is not managed by Django Rest Framework because it
occurs after its validation
process. So at the end, you'll have a 500.
Correcting this is as simple as overriding the exception handler, by
converting the Django
``ValidationError`` to a DRF one.
"""
from django.core.exceptions import ValidationError as
DjangoValidationError
from rest_framework.exceptions import ValidationError as
DRFValidationError
from rest_framework.views import exception_handler as
drf_exception_handler
def exception_handler(exc, context):
"""Handle Django ValidationError as an accepted exception
Must be set in settings:
>>> REST_FRAMEWORK = {
... # ...
... 'EXCEPTION_HANDLER': 'mtp.apps.common.drf.exception_handler',
... # ...
... }
For the parameters, see ``exception_handler``
"""
if isinstance(exc, DjangoValidationError):
if hasattr(exc, 'message_dict'):
exc = DRFValidationError(detail={'error': exc.message_dict})
elif hasattr(exc, 'message'):
exc = DRFValidationError(detail={'error': exc.message})
elif hasattr(exc, 'messages'):
exc = DRFValidationError(detail={'error': exc.messages})
return drf_exception_handler(exc, context)
</code></pre>
<p>This worked for me and now instead of a generic 500 response I get a 500 response with the relevant details.</p> |
42,582,633 | How to show index creation time with _cat/indices API in Elasticsearch | <p>I am using Elasticsearch 5.2, and cannot see <code>index creation time</code> with <code>http://localhost:9200/_cat/indices?v</code>.</p>
<p>Just wonder what options will show <code>index creation time</code> for each of the indices. </p> | 42,583,024 | 1 | 0 | null | 2017-03-03 15:23:40.047 UTC | 14 | 2020-05-03 14:47:58.51 UTC | null | null | null | null | 1,914,002 | null | 1 | 52 | elasticsearch | 43,275 | <p>Have a look at the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/cat.html" rel="noreferrer">cat API</a> : you can get the list of available parameters via <code>http://localhost:9200/_cat/indices?help</code></p>
<p>To get the creation date of your indexes, you would use <code>creation.date</code> (or <code>creation.date.string</code>). For example, use</p>
<pre><code>http://localhost:9200/_cat/indices?h=h,s,i,id,p,r,dc,dd,ss,creation.date.string
</code></pre>
<p>For full header names:</p>
<pre><code>http://localhost:9200/_cat/indices?h=health,status,index,id,pri,rep,docs.count,docs.deleted,store.size,creation.date.string&v=
</code></pre> |
20,040,745 | Call to a member function getClientOriginalName() on a non-object | <p>I'm trying to make an image uploader, but it always give me this error</p>
<pre><code>Call to a member function getClientOriginalName() on a non-object
</code></pre>
<p>here is my code controller code</p>
<pre><code>public function uploadImageProcess(){
$destinatonPath = '';
$filename = '';
$file = Input::file('image');
$destinationPath = public_path().'/assets/images/';
$filename = str_random(6).'_'.$file->getClientOriginalName();
$uploadSuccess = $file->move($destinationPath, $filename);
if(Input::hasFile('image')){
$images = new Images;
$images->title = Input::get('title');
$images->path = '/assets/images/' . $filename;
$image->user_id = Auth::user()->id;
Session::flash('success_insert','<strong>Upload success</strong>');
return Redirect::to('user/dashboard');
}
}
</code></pre>
<p>and here is the upload form</p>
<pre><code><form role="form" action="{{URL::to('user/poster/upload_process')}}" method="post">
<label>Judul Poster</label>
<input class="form-control" type="text" name="title">
<label>Poster</label>
<input class="" type="file" name="image"><br/>
<input class="btn btn-primary" type="submit" >
</form>
</code></pre>
<p>what's wrong with my code?</p> | 20,045,366 | 6 | 0 | null | 2013-11-18 05:30:49.44 UTC | 2 | 2020-03-31 07:03:05.953 UTC | null | null | null | null | 3,003,423 | null | 1 | 9 | php|object|upload|laravel|laravel-4 | 52,490 | <p>You miss <code>enctype</code> attribute in your form markup.</p>
<p>Either do this</p>
<pre><code><form role="form" action="{{URL::to('user/poster/upload_process')}}" method="post" enctype="multipart/form-data">
...
</form>
</code></pre>
<p>or this...</p>
<pre><code>{{ Form::open(array('url' => 'user/poster/upload_process', 'files' => true, 'method' => 'post')) }}
// ...
{{ Form::close() }}
</code></pre> |
35,055,088 | Get current value when change select option - Angular2 | <p>I'm writing an angular2 component and am facing this problem.</p>
<p><strong>Description:</strong> I want to push an option value in select selector to its handler when the <code>(change)</code> event is triggered.</p>
<p>Such as the below template:</p>
<pre><code><select (change)="onItemChange(<!--something to push-->)">
<option *ngFor="#value of values" value="{{value.key}}">{{value.value}}</option>
</select>
</code></pre>
<p>Component Class:</p>
<pre class="lang-typescript prettyprint-override"><code>export Class Demo{
private values = [
{
key:"key1",
value:"value1"
},
{
key:"key2",
value:"value2"
}
]
constructor(){}
onItemChange(anyThing:any){
console.log(anyThing); //Here I want the changed value
}
}
</code></pre>
<p>How can I get the value(without using jquery) ?</p> | 35,055,235 | 7 | 0 | null | 2016-01-28 07:18:17.57 UTC | 11 | 2021-07-21 07:54:09.553 UTC | 2021-02-02 15:26:16.653 UTC | user10747134 | 31,532 | null | 4,407,950 | null | 1 | 50 | html|angular | 179,843 | <p>There is a way to get the value from different options. check this <a href="http://plnkr.co/edit/tD3UeHLVK9nKYoDJa68d?p=preview" rel="noreferrer">plunker</a></p>
<p>component.html</p>
<pre><code><select class="form-control" #t (change)="callType(t.value)">
<option *ngFor="#type of types" [value]="type">{{type}}</option>
</select>
</code></pre>
<p>component.ts</p>
<pre class="lang-typescript prettyprint-override"><code>this.types = [ 'type1', 'type2', 'type3' ];
callType(value) {
console.log(value);
this.order.type = value;
}
</code></pre> |
61,154,795 | Revert IntelliJ IDEA font to pre-2020.1 default font | <p>I upgraded to IntelliJ 2020.1, which uses the new JetBrains Mono font by default. However, I would like to switch back to using the previous default, but I don't remember the name. What was the name of the default font on pre-2020.1 versions of IntelliJ IDEA?</p> | 61,154,796 | 2 | 0 | null | 2020-04-11 09:46:57.757 UTC | 4 | 2021-10-05 11:58:48.733 UTC | 2020-04-13 16:42:43.773 UTC | null | 1,225,617 | null | 1,225,617 | null | 1 | 47 | intellij-idea|fonts|default | 8,197 | <p>There is an <a href="https://intellij-support.jetbrains.com/hc/en-us/community/posts/360007965440-How-to-put-the-editor-appearance-back-to-the-previous-version-?page=1#community_comment_360001564299" rel="noreferrer">official comment</a> on the IntelliJ support site, stating the pre-2020.1 defaults per operating system are as follows:</p>
<ul>
<li>Mac OS: <code>Menlo</code></li>
<li>Linux: <code>DejaVu Sans Mono</code></li>
<li>Windows: <code>Consolas</code></li>
<li>Fallback: <code>Monospaced</code></li>
</ul>
<p>I checked the default settings on IDEA version 2019.3 on OSX, and the default font is indeed <code>Menlo</code>, Size <code>12</code>, Line spacing <code>1.2</code>.</p>
<p>You can configure it by going to <kbd>Preferences</kbd> → <kbd>Editor</kbd> → <kbd>Font</kbd></p> |
42,728,140 | Is it possible to export * as foo in typescript | <p>I can:</p>
<pre><code>import * as foo from './foo'
</code></pre>
<p>But can't seem to export the same:</p>
<pre><code>export * as foo from './foo'
</code></pre>
<p>This doesn't seem to work either...:</p>
<pre><code>import * as fooImport from './foo';
export const foo = fooImport;
</code></pre>
<p>Any ideas?</p>
<p>--- UPDATE ---</p>
<blockquote>
<p>What are you trying to achieve?</p>
</blockquote>
<p>Basically, I am working on implementing an <code>ngrx/store</code> backend for my app. I want to organize my code like this:</p>
<pre><code>app/core/
index.ts
viewer/
index.ts
viewer-actions.ts
viewer-reducer.ts
view-data/
index.ts
view-data-actions.ts
view-data-reducer.ts
</code></pre>
<p>And I want to use my <code>index.ts</code> files to chain up all the exports from each subset (common paradigm). </p>
<p>However, I want to keep things <em>namespaced</em>. Each of my <code>xxx-reducer.ts</code> and <code>xxx-actions.ts</code> files have exports of the same name (<code>reducer</code>, <code>ActionTypes</code>, <code>Actions</code>, ...) so normal chaining would result in a name collision. What I am trying to do is allow for all of the exports from <code>xxx-actions</code> and <code>xxx-reducer</code> to be <em>re-exported</em> as <code>xxx</code>. This would allow me to:</p>
<pre><code>import { viewer, viewerData } from './core';
...
private viewer: Observable<viewer.Viewer>;
private viewData: Observable<viewData.ViewData>;
ngOnInit() {
this.viewer = this.store.let(viewer.getViewer());
this.viewData = this.store.let(viewData.getViewData());
}
</code></pre>
<p>Instead of the more verbose:</p>
<pre><code>import * as viewer from './core/viewer';
import * as viewerData from './core/viewer-data';
...
</code></pre>
<p>Thats the gist anyway...</p> | 42,731,800 | 2 | 0 | null | 2017-03-10 21:38:56.153 UTC | 1 | 2020-10-20 03:11:50.15 UTC | 2017-03-11 15:57:51.63 UTC | null | 516,433 | null | 516,433 | null | 1 | 52 | typescript|module|export | 29,323 | <h1>TypeScript 3.8 or Later</h1>
<p>See <a href="https://stackoverflow.com/a/59712387/1108891">https://stackoverflow.com/a/59712387/1108891</a> for details.</p>
<h1>Before TypeScript 3.7 or Earlier</h1>
<blockquote>
<p>Is it possible to export * as foo in typescript</p>
</blockquote>
<p>Nope. You can, however, use a two step process:</p>
<p>src/core/index.ts</p>
<pre><code>import * as Foo from "./foo";
import * as Bar from "./bar";
export {
Foo,
Bar,
}
</code></pre>
<p>src/index.ts</p>
<pre><code>import { Foo, Bar } from "./core";
function FooBarBazBop() {
Foo.Baz;
Foo.Bop;
Bar.Baz;
Bar.Bop;
}
</code></pre>
<p>src/core/foo/index.ts <strong>and</strong> src/core/bar/index.ts</p>
<pre><code>export * from "./baz";
export * from "./bop";
</code></pre>
<p>src/core/foo/baz.ts <strong>and</strong> src/core/bar/baz.ts</p>
<pre><code>export class Baz {
}
</code></pre>
<p>src/core/foo/bop.ts <strong>and</strong> src/core/bar/bop.ts</p>
<pre><code>export class Bop {
}
</code></pre>
<p>See also: <a href="https://www.typescriptlang.org/docs/handbook/modules.html" rel="noreferrer">https://www.typescriptlang.org/docs/handbook/modules.html</a></p> |
21,709,305 | How to directly execute SQL query in C#? | <p>Ok, I have an old batch file that does exactly what I need. However, with out new administration we can't run the batch file anymore so I need to start up with C#.</p>
<p>I'm using Visual Studio C# and already have the forms set up for the application I need to build. (I'm learning as I go)</p>
<p>Here is what I need to accomplish in C# (This is the batch guts)</p>
<pre><code>sqlcmd.exe -S .\PDATA_SQLEXPRESS -U sa -P 2BeChanged! -d PDATA_SQLEXPRESS -s ; -W -w 100 -Q "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday FROM [dbo].[TPatientRaw] WHERE tPatSName = '%name%' "
</code></pre>
<p>Basically it uses <code>SQLCMD.exe</code> with the already existing datasource called <code>PDATA_SQLExpress</code>.<br>
I've searched and gotten close but I'm still at a loss on where to start. </p> | 21,709,663 | 3 | 1 | null | 2014-02-11 17:50:22.943 UTC | 21 | 2019-01-18 14:59:18.777 UTC | 2019-01-18 14:59:18.777 UTC | null | 542,251 | null | 3,191,919 | null | 1 | 83 | c#|.net|sql-server|batch-file | 374,826 | <p>To execute your command directly from within C#, you would use the <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand%28v=vs.110%29.aspx">SqlCommand</a> class.</p>
<p>Quick sample code using paramaterized SQL (to avoid injection attacks) might look like this:</p>
<pre><code>string queryString = "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday FROM [dbo].[TPatientRaw] WHERE tPatSName = @tPatSName";
string connectionString = "Server=.\PDATA_SQLEXPRESS;Database=;User Id=sa;Password=2BeChanged!;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("@tPatSName", "Your-Parm-Value");
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader["tPatCulIntPatIDPk"], reader["tPatSFirstname"]));// etc
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
</code></pre> |
42,335,754 | Python Asynchronous Comprehensions - how do they work? | <p>I'm having trouble understanding the use of asynchronous comprehensions introduced in Python 3.6. As a disclaimer, I don't have a lot of experience dealing with asynchronous code in general in Python.</p>
<p>The example given in the <a href="https://docs.python.org/3/whatsnew/3.6.html" rel="noreferrer">what's new for Python 3.6</a> document is:</p>
<pre><code>result = [i async for i in aiter() if i % 2]
</code></pre>
<p>In the <a href="https://www.python.org/dev/peps/pep-0530/" rel="noreferrer">PEP</a>, this is expanded to:</p>
<pre><code>result = []
async for i in aiter():
if i % 2:
result.append(i)
</code></pre>
<p>I <em>think</em> I understand that the <code>aiter()</code> function gets called asynchronously, so that each iteration of <code>aiter</code> can proceed without the previous one necessarily returning yet (or is this understanding wrong?).</p>
<p>What I'm not sure about is how that then translates to the list comprehension here. Do results get placed into the list in the order that they are returned? Or are there effective 'placeholders' in the final list so that each result is placed in the list in the right order? Or am I thinking about this the wrong way?</p>
<p>Additionally, is someone able to provide a real-world example that would illustrate both an applicable use case and the basic mechanics of <code>async</code> in comprehensions like this?</p> | 42,415,821 | 2 | 1 | null | 2017-02-20 02:56:44.487 UTC | 9 | 2017-02-23 12:29:52.427 UTC | null | null | null | null | 4,497,519 | null | 1 | 35 | python|asynchronous|list-comprehension|python-3.6 | 13,963 | <p>You are basically asking how an <code>async for</code> loop works over a regular loop. That you can now use such a loop in a list comprehension doesn't make any difference here; that's just an optimisation that avoids repeated <code>list.append()</code> calls, exactly like a normal list comprehension does.</p>
<p>An <code>async for</code> loop then, simply awaits each next step of the iteration protocol, where a regular <code>for</code> loop would block.</p>
<p>To illustrate, imagine a normal <code>for</code> loop:</p>
<pre><code>for foo in bar:
...
</code></pre>
<p>For this loop, Python essentially does this:</p>
<pre><code>bar_iter = iter(bar)
while True:
try:
foo = next(bar_iter)
except StopIteration:
break
...
</code></pre>
<p>The <code>next(bar_iter)</code> call is not asynchronous; it blocks.</p>
<p>Now replace <code>for</code> with <code>async for</code>, and what Python does changes to:</p>
<pre><code>bar_iter = aiter(bar) # aiter doesn't exist, but see below
while True:
try:
foo = await anext(bar_iter) # anext doesn't exist, but see below
except StopIteration:
break
...
</code></pre>
<p>In the above example <code>aiter()</code> and <code>anext()</code> are fictional functions; these are functionally exact equivalents of their <code>iter()</code> and <code>next()</code> brethren but instead of <code>__iter__</code> and <code>__next__</code> these use <code>__aiter__</code> and <code>__anext__</code>. That is to say, asynchronous hooks exist for the same functionality but are distinguished from their non-async variants by the prefix <code>a</code>.</p>
<p>The <code>await</code> keyword there is the crucial difference, so for each iteration an <code>async for</code> loop yields control so other coroutines can run instead.</p>
<p>Again, to re-iterate, all this already was added in Python 3.5 (see <a href="https://www.python.org/dev/peps/pep-0492/#asynchronous-iterators-and-async-for" rel="noreferrer">PEP 492</a>), all that is new in Python 3.6 is that you can use such a loop in a list comprehension too. And in generator expressions and set and dict comprehensions, for that matter.</p>
<p>Last but not least, the same set of changes also made it possible to use <code>await <expression></code> in the expression section of a comprehension, so:</p>
<pre><code>[await func(i) for i in someiterable]
</code></pre>
<p>is now possible.</p> |
51,203,570 | Is it well-defined to hold a misaligned pointer, as long as you don't ever dereference it? | <p>I have some C code that parses packed/unpadded binary data that comes in from the network.</p>
<p>This code was/is working fine under Intel/x86, but when I compiled it under ARM it would often crash. </p>
<p>The culprit, as you might have guessed, was unaligned pointers -- in particular, the parsing code would do questionable things like this:</p>
<pre><code>uint8_t buf[2048];
[... code to read some data into buf...]
int32_t nextWord = *((int32_t *) &buf[5]); // misaligned access -- can crash under ARM!
</code></pre>
<p>... that's obviously not going to fly in ARM-land, so I modified it to look more like this:</p>
<pre><code>uint8_t buf[2048];
[... code to read some data into buf...]
int32_t * pNextWord = (int32_t *) &buf[5];
int32 nextWord;
memcpy(&nextWord, pNextWord, sizeof(nextWord)); // slower but ARM-safe
</code></pre>
<p>My question (from a language-lawyer perspective) is: is my "ARM-fixed" approach well-defined under the C language rules?</p>
<p>My worry is that maybe even just having a misaligned-int32_t-pointer might be enough to invoke undefined behavior, even if I never actually dereference it directly. (If my concern is valid, I think I could fix the problem by changing <code>pNextWord</code>'s type from <code>(const int32_t *)</code> to <code>(const char *)</code>, but I'd rather not do that unless it's actually necessary to do so, since it would mean doing some pointer-stride arithmetic by hand)</p> | 51,203,895 | 4 | 2 | null | 2018-07-06 05:31:33.87 UTC | 4 | 2019-08-05 00:29:33.613 UTC | null | null | null | null | 131,930 | null | 1 | 38 | c|pointers|alignment|language-lawyer | 2,706 | <p>No, the new code still has undefined behaviour. <a href="http://port70.net/~nsz/c/c11/n1570.html#6.3.2.3p7" rel="nofollow noreferrer">C11 6.3.2.3p7</a>:</p>
<blockquote>
<ol start="7">
<li>A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned <a href="http://port70.net/~nsz/c/c11/n1570.html#note68" rel="nofollow noreferrer">68)</a> for the referenced type, the behavior is undefined. [...]</li>
</ol>
</blockquote>
<p>It doesn't say anything about dereferencing the pointer - even the conversion has undefined behaviour.</p>
<hr>
<p>Indeed, the modified code that you assume is <em>ARM</em>-safe might not be even <em>Intel</em>-safe. Compilers are known to generate code for <a href="https://stackoverflow.com/a/46790815/918959">Intel that can crash on unaligned access</a>. While not in the linked case, it might just be that a clever compiler can take the conversion as a <strong>proof</strong> that the address is indeed aligned and use a specialized code for <code>memcpy</code>.</p>
<hr>
<p>Alignment aside, your first excerpt also suffers from strict aliasing violation. <a href="http://port70.net/~nsz/c/c11/n1570.html#6.5p7" rel="nofollow noreferrer">C11 6.5p7</a>:</p>
<blockquote>
<ol start="7">
<li>An object shall have its stored value accessed only by an lvalue expression that has one of the following types:88)
<ul>
<li>a type compatible with the effective type of the object,</li>
<li>a qualified version of a type compatible with the effective type of
the object, </li>
<li>a type that is the signed or unsigned type
corresponding to the effective type of the object, </li>
<li>a type that
is the signed or unsigned type corresponding to a qualified version of
the effective type of the object, </li>
<li>an aggregate or union type
that includes one of the aforementioned types among its members
(including, recursively, a member of a subaggregate or contained
union), or</li>
<li>a character type.</li>
</ul></li>
</ol>
</blockquote>
<p>Since the array <code>buf[2048]</code> is statically <em>typed</em>, each element being <code>char</code>, and therefore the effective types of the elements are <code>char</code>; you may access the contents of the array <strong>only</strong> as characters, not as <code>int32_t</code>s. </p>
<p>I.e., even</p>
<pre><code>int32_t nextWord = *((int32_t *) &buf[_Alignof(int32_t)]);
</code></pre>
<p>has undefined behaviour.</p> |
9,364,807 | JavaScript - Reference Browser Window by name? | <p>When you create a new browser window, you pass it a name like this:</p>
<pre><code>myWindow = window.open('http://www.google.com', "googleWindow");
</code></pre>
<p>Later you can access the window from the variable you saved it as:</p>
<pre><code>myWindow.close();
</code></pre>
<p>Is it possible to access and manipulate a window by it's name (<code>googleWindow</code>) instead of the variable?</p>
<p>If it is not possible, what is the point giving windows names?</p> | 9,364,899 | 5 | 0 | null | 2012-02-20 16:40:56.957 UTC | 5 | 2018-02-09 20:50:12.97 UTC | 2012-02-20 16:45:57.613 UTC | null | 172,350 | null | 172,350 | null | 1 | 9 | javascript | 42,519 | <p>No. Without a reference to the window, you can't find it again, by name or otherwise. There is no collection of windows.</p>
<p><strong>UPDATE:</strong> Here's how you could do it yourself:</p>
<pre><code>var windows = {};
function openWindow(url, name, features) {
windows[name] = window.open(url, name, features);
return windows[name];
}
</code></pre>
<p>Now, <code>openWindow</code> will always open the window, and if the window already exists, it will load the given URL in that window and return a reference to that window. Now you can also implement <code>findWindow</code>:</p>
<pre><code>function findWindow(name) {
return windows[name];
}
</code></pre>
<p>Which will return the window if it exists, or <code>undefined</code>.</p>
<p>You should also have <code>closeWindow</code>, so you don't keep references to windows that you opened yourself:</p>
<pre><code>function closeWindow(name) {
var window = windows[name];
if(window) {
window.close();
delete windows[name];
}
}
</code></pre>
<blockquote>
<p>If it is not possible, what is the point giving windows names?</p>
</blockquote>
<p>The name is used internally by the browser to manage windows. If you call <code>window.open</code> with the same name, it won't open a new window but instead load the URL into the previously opened window. There are a few more things, from <a href="https://developer.mozilla.org/en/DOM/window.open">MDN window.open()</a>:</p>
<blockquote>
<p>If a window with the name strWindowName already exists, then strUrl is loaded into the existing window. In this case the return value of the method is the existing window and strWindowFeatures is ignored. Providing an empty string for strUrl is a way to get a reference to an open window by its name without changing the window's location. To open a new window on every call of window.open(), use the special value _blank for strWindowName.</p>
</blockquote> |
9,162,926 | iOS property declaration clarification | <p>This is a two part question in hopes that I can <em>understand</em> more about the topic.</p>
<p><strong>1)</strong> It seems to me that you have two <em>popular</em> options for declaring a property for a <em>class</em> in <code>objective c</code>. One is to add the property to the header's class body eg.</p>
<pre><code>@interface MyClass : NSObject {
NSArray *myArray;
}
</code></pre>
<p>Or you can add it after the <code>@interface</code> body and before the <code>@end</code> statement <em>like so</em>.</p>
<pre><code>@interface MyClass : NSObject {
//
}
@property (nonatomic, retain) NSArray *myArray;
</code></pre>
<p>What is the difference between these two "styles" and when do you <em>choose</em> one over the other?</p>
<p>2) after the <code>@property</code> you find options such as <code>(nonatomic, retain)</code>. What are those for and <em>why/when</em> do you use different options?</p> | 9,163,058 | 5 | 0 | null | 2012-02-06 15:54:40.903 UTC | 31 | 2016-04-19 01:37:54.943 UTC | 2012-08-30 11:22:22.18 UTC | null | 74,118 | null | 332,578 | null | 1 | 22 | ios|class|properties | 16,678 | <p>Here are the only property modifiers that Xcode recognizes:</p>
<ul>
<li><code>nonatomic</code> (does not enforce thread safety on the property, mainly for use when only one thread shall be used throughout a program)</li>
<li><code>atomic</code> (enforces thread safety on the property, mainly for use when multiple threads shall be used throughout a program) (default)</li>
<li><code>retain</code> / <code>strong</code> (automatically retains / releases values on set, makes sure values do not deallocate unexpectedly) (default if ARC and object type)</li>
<li><code>readonly</code> (cannot set property)</li>
<li><code>readwrite</code> (can both set and get property) (default)</li>
<li><code>assign</code> / <code>unsafe_unretained</code> (no memory management shall be done with this property, it is handled manually by the person assigning the value) (default if not ARC or object type)</li>
<li><code>copy</code> (copies the object before setting it, in cases where the value set must not change due to external factors (strings, arrays, etc).</li>
<li><code>weak</code> (automatically zeroes the reference should the object be deallocated, and does not retain the value passed in)</li>
<li><code>getter=method</code> (sets the selector used for getting the value of this property)</li>
<li><code>setter= method</code> (set the selector used for setting the value of this property)</li>
</ul> |
22,803,607 | How do I debug CMakeLists.txt files? | <p>Is there a possibility to debug <code>CMakeLists.txt</code> files (at least listing of variables) except for the <a href="http://www.cmake.org/cmake/help/v2.8.12/cmake.html#command:message" rel="noreferrer">message</a> statement?</p> | 22,803,821 | 5 | 1 | null | 2014-04-02 06:51:55.92 UTC | 31 | 2020-01-30 17:28:28.277 UTC | 2019-02-16 15:57:57.153 UTC | null | 63,550 | null | 2,838,364 | null | 1 | 102 | cmake | 75,334 | <p>There is no interactive debugger for CMake, however there are also the flags <code>-Wdev</code>, <code>--debug-output</code> and <code>--trace</code> which might help. Also remember to check the log files <code>CMakeFiles\CMakeOutput.log</code> and <code>CMakeFiles\CMakeError.log</code> which mainly collect outputs of processes called by CMake (for example while checking for presence of a type or header).</p>
<p><a href="https://blog.kitware.com/cmake-e-server-improves-visual-studio-and-qt-creator-ides/" rel="noreferrer">Since version 3.7</a>, CMake now officially supports a "server mode" so integration in IDEs is likely to improve in the near future. Initial support exists both in <a href="https://blog.qt.io/blog/2016/11/15/cmake-support-in-qt-creator-and-elsewhere/" rel="noreferrer">Qt Creator</a> and <a href="https://blogs.msdn.microsoft.com/vcblog/2016/11/16/cmake-support-in-visual-studio-the-visual-studio-2017-rc-update/" rel="noreferrer">Visual Studio 2017 RC</a></p> |
22,781,788 | How could I pass a dynamic set of arguments to Go's command exec.Command? | <p>I came across a question on here relating to arguments being passed to Go's <code>exec.Command</code> function, and I was wondering if there was a way do pass these arguments dynamically? Here's some sample code from sed question:</p>
<pre><code>package main
import "os/exec"
func main() {
app := "echo"
//app := "buah"
arg0 := "-e"
arg1 := "Hello world"
arg2 := "\n\tfrom"
arg3 := "golang"
cmd := exec.Command(app, arg0, arg1, arg2, arg3)
out, err := cmd.Output()
if err != nil {
println(err.Error())
return
}
print(string(out))
}
</code></pre>
<p>So as you can see each arg is defined above as <code>arg0</code>, <code>arg1</code>, <code>arg2</code> and <code>arg3</code>. They are passed into the <code>Command</code> function along with the actual command to run, in this case, the <code>app</code> var.</p>
<p>What if I had an array of arguments that always perhaps had an indeterministic count that I wanted to pass through. Is this possible?</p> | 22,781,927 | 3 | 1 | null | 2014-04-01 09:30:05.933 UTC | 4 | 2021-10-21 02:20:03.643 UTC | null | null | null | null | 1,898,062 | null | 1 | 32 | go|command|exec | 34,192 | <p>Like this:</p>
<pre><code>args := []string{"what", "ever", "you", "like"}
cmd := exec.Command(app, args...)
</code></pre>
<p>Have a look at the language and tutorial on golang.org.</p> |
7,455,893 | change the position of image on click | <pre><code> <html>
<head>
<script type="text/javascript">
function changepic()
{
document.getElementById("demo").style.top=2000;
}
</script>
</head>
<body>
<h1>My First Web Page</h1>
<div id="demo">
<img src="./omna.jpg" style="position:absolute; left: 400; top: 100; width: 200; height: 200;"/>
</div>
<button type="button" onclick="changepic()">change pic</button>
</body>
</html>
</code></pre>
<p>Why im unable to change the position of picture whats going wrong ?</p>
<pre><code><img id="demo"> ' google says it works
</code></pre>
<p>I dont know but the above html page isnt working I wanted to change the position of an image when I click the button, please help me with these. Im using google chrome</p>
<pre><code><img onclick="somefunc()"> can I set function onclick to image also? right?
</code></pre>
<p>But its not working please help me with the html Code!</p> | 7,455,921 | 2 | 0 | null | 2011-09-17 15:37:22.02 UTC | 1 | 2020-06-25 14:31:37.143 UTC | null | null | null | null | 834,032 | null | 1 | 4 | javascript|html | 57,477 | <p>You're trying to set the <code>top</code> of an element with the id <code>demo</code>, which is a <code><div></code>. I assume that div doesn't have <code>position:absolute</code> set on it so won't move anywhere, and I guess you want the <code><img></code> to move and and not the <code><div></code> anyway. If you remove the id from the <code><div></code> and add it to the <code><img></code> (like in your second piece of code above) you shouldn't have any problems. This code should work:</p>
<pre><code><html>
<head>
<script type="text/javascript">
function changepic()
{
document.getElementById("demo").style.top=2000 + "px";
}
</script>
</head>
<body>
<h1>My First Web Page</h1>
<div>
<img id="demp" src="./omna.jpg" style="position:absolute; left: 400; top: 100; width: 200; height: 200;"/>
</div>
<button type="button" onclick="changepic()">change pic</button>
</body>
</html>
</code></pre> |
21,105,315 | Git: Move head one commit ahead | <p>I did a <code>git reset HEAD~1</code> to go back one commit. I did this a number of times.</p>
<p>I now want to go back to where <code>HEAD</code> was originally but am not sure how to move my <code>HEAD</code> forward. </p>
<p>Does anyone know what command I need to use?</p>
<p>1-2-3-4-5-6</p>
<p>Originally I was at 6 and I reset back to 3. I now want to go back to 5. My understanding is that since I did not do <code>git reset --hard</code> my original files from commit 6 is still available. Theoretically I should be able to un-reset and move back up correct?</p> | 21,105,355 | 1 | 2 | null | 2014-01-14 02:59:28.417 UTC | 10 | 2014-09-24 05:46:38.35 UTC | 2014-09-24 05:46:38.35 UTC | null | 31,671 | null | 2,020,869 | null | 1 | 37 | git | 31,218 | <p>use <code>git reflog</code> to see SHA-1 of last operations and then do <code>git reset --hard <sha1></code>.</p>
<p>Git keeps objects (and their SHA-1 respectively) even they go "out of scope" until next <code>git gc</code> invocation. So if you think, you've lost something in the project history, use <code>git reflog</code> to see if that smth is there.</p> |
Subsets and Splits