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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
255,852 | Parallel Programming and C++ | <p>I've been writing a lot recently about Parallel computing and programming and I do notice that there are a lot of patterns that come up when it comes to parallel computing. Noting that Microsoft already has released a library along with the Microsoft Visual C++ 2010 Community Technical Preview (named Parallel Patterns Library) I'm wondering what are the common parallel programming patterns you have been using and encountering that may be worth remembering? Do you have any idioms you follow and patterns that you seem to keep popping up as you write parallel programs with C++?</p> | 255,937 | 4 | 2 | null | 2008-11-01 17:51:12.793 UTC | 13 | 2017-10-12 02:48:28.397 UTC | null | null | null | Dean Michael | 11,274 | null | 1 | 8 | c++|design-patterns|parallel-processing|idioms | 6,217 | <p>Patterns:</p>
<ul>
<li><p>Produce/Consumer</p>
<ul>
<li>One Thread produces data</li>
<li>One Thread consumes the data</li>
</ul></li>
<li><p>Loop parallelism</p>
<ul>
<li>If you can show that each loop is independent<br>
each iteration can be done in a sperate thread</li>
</ul></li>
<li><p>Re-Draw Thread</p>
<ul>
<li>Other threads do work and update data structures but one thread re-draws screen.</li>
</ul></li>
<li><p>Main-Event Thread</p>
<ul>
<li>Multiple threads can be generating events</li>
<li>One thread has to processes the events (as order is important)</li>
<li>Should try separate the Event Thread/Re-Draw Thread<br>
This (helps) prevents the UI from freezing<br>
But may cause excessive re-draws if not done carefully.</li>
</ul></li>
<li><p>Work Group</p>
<ul>
<li>A set of threads waits for jobs on a que.</li>
<li>Thread extract one work item from queue (waiting if none is available).<br>
Thread works on one work item until complete<br>
Once completed thread returns to queue.</li>
</ul></li>
</ul> |
1,204,553 | Are there any good libraries for solving cubic splines in C++? | <p>I'm looking for a good C++ library to give me functions to solve for large cubic splines (on the order of 1000 points) anyone know one?</p> | 1,204,576 | 4 | 1 | null | 2009-07-30 05:07:22.88 UTC | 14 | 2019-11-01 07:00:12.277 UTC | 2012-01-24 05:38:39.907 UTC | null | 44,729 | null | 134,046 | null | 1 | 22 | c++|spline | 50,457 | <p>Try the Cubic B-Spline library:</p>
<ul>
<li><a href="https://github.com/NCAR/bspline" rel="noreferrer">https://github.com/NCAR/bspline</a></li>
</ul>
<p>and ALGLIB:</p>
<ul>
<li><a href="http://www.alglib.net/interpolation/spline3.php" rel="noreferrer">http://www.alglib.net/interpolation/spline3.php</a></li>
</ul> |
878,348 | Where do I configure log4j in a JUnit test class? | <p>Looking at the last JUnit test case I wrote, I called log4j's BasicConfigurator.configure() method inside the class constructor. That worked fine for running just that single class from Eclipse's "run as JUnit test case" command. But I realize it's incorrect: I'm pretty sure our main test suite runs all of these classes from one process, and therefore log4j configuration should be happening higher up somewhere.</p>
<p>But I still need to run a test case by itself some times, in which case I want log4j configured. Where should I put the configuration call so that it gets run when the test case runs standalone, but not when the test case is run as part of a larger suite?</p> | 878,362 | 4 | 1 | null | 2009-05-18 15:37:09.807 UTC | 17 | 2018-05-16 15:12:15.643 UTC | 2009-05-18 16:21:26.77 UTC | null | 20,774 | null | 18,103 | null | 1 | 91 | java|logging|junit|log4j | 109,433 | <p>The <code>LogManager</code> class determines which log4j config to use in a <a href="https://github.com/apache/log4j/blob/trunk/src/main/java/org/apache/log4j/LogManager.java#L81" rel="noreferrer">static block</a> which runs when the class is loaded. There are three options intended for end-users:</p>
<ol>
<li>If you specify <code>log4j.defaultInitOverride</code> to false, it will not configure log4j at all.</li>
<li><p>Specify the path to the configuration file manually yourself and override the classpath search. You can specify the location of the configuration file directly by using the following argument to <code>java</code>: </p>
<p><code>-Dlog4j.configuration=<path to properties file></code></p>
<p>in your test runner configuration. </p></li>
<li><p>Allow log4j to scan the classpath for a log4j config file during your test. (the default) </p></li>
</ol>
<p>See also the <a href="http://logging.apache.org/log4j/1.2/manual.html#Default_Initialization_Procedure" rel="noreferrer">online documentation</a>.</p> |
20,738,953 | Remove Blank option from Select Option with AngularJS | <p>I am new to AngularJS. I searched a lot, but it does not solve my problem.</p>
<p>I am getting a blank option for the first time in select box.</p>
<p>Here is my HTML code</p>
<pre><code><div ng-app="MyApp1">
<div ng-controller="MyController">
<input type="text" ng-model="feed.name" placeholder="Name" />
<select ng-model="feed.config">
<option ng-repeat="template in configs">{{template.name}}</option>
</select>
</div>
</div>
</code></pre>
<p><strong>JS</strong></p>
<pre><code>var MyApp=angular.module('MyApp1',[])
MyApp.controller('MyController', function($scope) {
$scope.feed = {};
//Configuration
$scope.configs = [
{'name': 'Config 1',
'value': 'config1'},
{'name': 'Config 2',
'value': 'config2'},
{'name': 'Config 3',
'value': 'config3'}
];
//Setting first option as selected in configuration select
$scope.feed.config = $scope.configs[0].value;
});
</code></pre>
<p>But it doesn't seem to work.
How can I get this solved? Here is <a href="http://jsfiddle.net/ugkPr/1/" rel="noreferrer">JSFiddle Demo</a></p> | 20,738,971 | 12 | 0 | null | 2013-12-23 07:33:04.547 UTC | 13 | 2019-10-24 21:56:41.903 UTC | 2018-07-22 17:33:01.54 UTC | null | 5,535,245 | null | 2,189,617 | null | 1 | 81 | angularjs|angularjs-select | 145,404 | <p>For reference : <a href="https://stackoverflow.com/a/12654812/2353403">Why does angularjs include an empty option in select</a>?</p>
<blockquote>
<p>The empty <code>option</code> is generated when a value referenced by <code>ng-model</code> doesn't exist in a set of options passed to <code>ng-options</code>. This happens to prevent accidental model selection: AngularJS can see that the initial model is either undefined or not in the set of options and don't want to decide model value on its own.</p>
<p>In short: the empty option means that no valid model is selected (by valid I mean: from the set of options). You need to select a valid model value to get rid of this empty option.</p>
</blockquote>
<p>Change your code like this</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var MyApp=angular.module('MyApp1',[])
MyApp.controller('MyController', function($scope) {
$scope.feed = {};
//Configuration
$scope.feed.configs = [
{'name': 'Config 1',
'value': 'config1'},
{'name': 'Config 2',
'value': 'config2'},
{'name': 'Config 3',
'value': 'config3'}
];
//Setting first option as selected in configuration select
$scope.feed.config = $scope.feed.configs[0].value;
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="MyApp1">
<div ng-controller="MyController">
<input type="text" ng-model="feed.name" placeholder="Name" />
<!-- <select ng-model="feed.config">
<option ng-repeat="template in configs">{{template.name}}</option>
</select> -->
<select ng-model="feed.config" ng-options="template.value as template.name for template in feed.configs">
</select>
</div>
</div></code></pre>
</div>
</div>
</p>
<p><a href="http://jsfiddle.net/ugkPr/2/" rel="noreferrer">Working JSFiddle Demo</a></p>
<p><strong>UPDATE (Dec 31, 2015)</strong></p>
<p>If You don't want to set a default value and want to remove blank option,</p>
<pre><code><select ng-model="feed.config" ng-options="template.value as template.name for template in feed.configs">
<option value="" selected="selected">Choose</option>
</select>
</code></pre>
<p>And in JS no need to initialize value.</p>
<p><s><code>$scope.feed.config = $scope.feed.configs[0].value;</code></s></p> |
20,470,626 | python script for RaspberryPi to connect wifi automatically | <p>I want to operate a WiFi dongle with RaspberryPi, (it's like a CPU without built-in WiFi). I need to write a python script which automatically scan for WiFi networks and a connection need to be automatically established with known SSID and password.</p>
<p>This mean that I need to provide the password for the WiFi network from a file, and the
remaining thing is to do the scanning and connecting automatically.</p>
<p>I read a file from the Web which contains WiFi SSID name and password.</p>
<p>I need to write a script which scan and list current networds and match it to the SSID from the file and further to automatically create the connection to this known network.</p>
<p>RaspberryPi OS: Rasbian</p> | 54,320,536 | 4 | 2 | null | 2013-12-09 12:24:53.733 UTC | 8 | 2022-08-22 17:52:09.65 UTC | 2013-12-09 13:01:20.26 UTC | null | 1,134,742 | null | 3,077,250 | null | 1 | 10 | python|wifi|raspberry-pi | 46,612 | <p>Thank you all for your answers i made simple solution like below </p>
<pre><code>def wifiscan():
allSSID = Cell.all('wlan0')
print allSSID # prints all available WIFI SSIDs
myssid= 'Cell(ssid=vivekHome)' # vivekHome is my wifi name
for i in range(len(allSSID )):
if str(allSSID [i]) == myssid:
a = i
myssidA = allSSID [a]
print b
break
else:
print "getout"
# Creating Scheme with my SSID.
myssid= Scheme.for_cell('wlan0', 'home', myssidA, 'vivek1234') # vive1234 is the password to my wifi myssidA is the wifi name
print myssid
myssid.save()
myssid.activate()
wifiscan()
</code></pre> |
32,534,602 | JavaScript - Built in Function to Delete Multiple Keys in an Object? | <p>In JavaScript, I can delete an object's key with</p>
<p><code>delete myObject[myKey];</code></p>
<p>Is there an efficient way to delete multiple keys using one line? Something that looks like:</p>
<p><code>multiDelete myObject[keyOne, keyTwo, keyThree];</code></p> | 32,535,117 | 9 | 2 | null | 2015-09-12 02:34:57.647 UTC | 8 | 2022-09-23 20:13:59.983 UTC | 2022-09-23 20:13:59.983 UTC | null | 1,016,004 | user4596113 | null | null | 1 | 42 | javascript | 46,582 | <p>Here's a one-liner similar to what you're requesting.</p>
<pre><code>var obj = {a: 1, b: 2, c: 3, d: 4, e: 5 };
['c', 'e'].forEach(e => delete obj[e]);
// obj is now {a:1, b:2, d:4}
</code></pre> |
32,423,348 | Angular - POST uploaded file | <p>I'm using <a href="https://angular.io/" rel="noreferrer">Angular</a>, <a href="https://www.typescriptlang.org/" rel="noreferrer">TypeScript</a> to send a file, along with JSON Data to a server.</p>
<p>Below is my code:</p>
<pre><code>import {Component, View, NgFor, FORM_DIRECTIVES, FormBuilder, ControlGroup} from 'angular2/angular2';
import {Http, Response, Headers} from 'http/http';
@Component({ selector: 'file-upload' })
@View({
directives: [FORM_DIRECTIVES],
template: `
<h3>File Upload</h3>
<div>
Select file:
<input type="file" (change)="changeListener($event)">
</div>
`
})
export class FileUploadCmp {
public file: File;
public url: string;
headers: Headers;
constructor(public http: Http) {
console.log('file upload Initialized');
//set the header as multipart
this.headers = new Headers();
this.headers.set('Content-Type', 'multipart/form-data');
this.url = 'http://localhost:8080/test';
}
//onChange file listener
changeListener($event): void {
this.postFile($event.target);
}
//send post file to server
postFile(inputValue: any): void {
var formData = new FormData();
formData.append("name", "Name");
formData.append("file", inputValue.files[0]);
this.http.post(this.url +,
formData ,
{
headers: this.headers
});
}
}
</code></pre>
<p>How can I transform the <code>formData</code> to String and send it to the server? I remember in <a href="https://angularjs.org/" rel="noreferrer">AngularJS</a> (v1) you would use <code>transformRequest</code>.</p> | 35,519,607 | 5 | 4 | null | 2015-09-06 12:04:44.437 UTC | 37 | 2018-02-25 08:21:24.413 UTC | 2018-02-25 08:16:09.043 UTC | null | 1,429,387 | null | 2,971,571 | null | 1 | 64 | angular|typescript|file-upload|angular2-http | 132,125 | <p>Look at my code, but be aware. I use async/await, because latest Chrome beta can read any es6 code, which gets by TypeScript with compilation. So, you must replace asyns/await by <code>.then()</code>.</p>
<p>Input change handler:</p>
<pre><code>/**
* @param fileInput
*/
public psdTemplateSelectionHandler (fileInput: any){
let FileList: FileList = fileInput.target.files;
for (let i = 0, length = FileList.length; i < length; i++) {
this.psdTemplates.push(FileList.item(i));
}
this.progressBarVisibility = true;
}
</code></pre>
<p>Submit handler: </p>
<pre><code>public async psdTemplateUploadHandler (): Promise<any> {
let result: any;
if (!this.psdTemplates.length) {
return;
}
this.isSubmitted = true;
this.fileUploadService.getObserver()
.subscribe(progress => {
this.uploadProgress = progress;
});
try {
result = await this.fileUploadService.upload(this.uploadRoute, this.psdTemplates);
} catch (error) {
document.write(error)
}
if (!result['images']) {
return;
}
this.saveUploadedTemplatesData(result['images']);
this.redirectService.redirect(this.redirectRoute);
}
</code></pre>
<p>FileUploadService. That service also stored uploading progress in progress$ property, and in other places, you can subscribe on it and get new value every 500ms.</p>
<pre><code>import { Component } from 'angular2/core';
import { Injectable } from 'angular2/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/share';
@Injectable()
export class FileUploadService {
/**
* @param Observable<number>
*/
private progress$: Observable<number>;
/**
* @type {number}
*/
private progress: number = 0;
private progressObserver: any;
constructor () {
this.progress$ = new Observable(observer => {
this.progressObserver = observer
});
}
/**
* @returns {Observable<number>}
*/
public getObserver (): Observable<number> {
return this.progress$;
}
/**
* Upload files through XMLHttpRequest
*
* @param url
* @param files
* @returns {Promise<T>}
*/
public upload (url: string, files: File[]): Promise<any> {
return new Promise((resolve, reject) => {
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
for (let i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
};
FileUploadService.setUploadUpdateInterval(500);
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
this.progressObserver.next(this.progress);
};
xhr.open('POST', url, true);
xhr.send(formData);
});
}
/**
* Set interval for frequency with which Observable inside Promise will share data with subscribers.
*
* @param interval
*/
private static setUploadUpdateInterval (interval: number): void {
setInterval(() => {}, interval);
}
}
</code></pre> |
54,734,538 | OpenCV Assertion failed: (-215:Assertion failed) npoints >= 0 && (depth == CV_32F || depth == CV_32S) | <p>I have found the following code on <a href="https://medium.com/@ageitgey/how-to-break-a-captcha-system-in-15-minutes-with-machine-learning-dbebb035a710" rel="noreferrer">this website</a>:</p>
<pre><code>import os
import os.path
import cv2
import glob
import imutils
CAPTCHA_IMAGE_FOLDER = "generated_captcha_images"
OUTPUT_FOLDER = "extracted_letter_images"
# Get a list of all the captcha images we need to process
captcha_image_files = glob.glob(os.path.join(CAPTCHA_IMAGE_FOLDER, "*"))
counts = {}
# loop over the image paths
for (i, captcha_image_file) in enumerate(captcha_image_files):
print("[INFO] processing image {}/{}".format(i + 1, len(captcha_image_files)))
# Since the filename contains the captcha text (i.e. "2A2X.png" has the text "2A2X"),
# grab the base filename as the text
filename = os.path.basename(captcha_image_file)
captcha_correct_text = os.path.splitext(filename)[0]
# Load the image and convert it to grayscale
image = cv2.imread(captcha_image_file)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Add some extra padding around the image
gray = cv2.copyMakeBorder(gray, 8, 8, 8, 8, cv2.BORDER_REPLICATE)
# threshold the image (convert it to pure black and white)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
# find the contours (continuous blobs of pixels) the image
contours = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Hack for compatibility with different OpenCV versions
contours = contours[0] if imutils.is_cv2() else contours[1]
letter_image_regions = []
# Now we can loop through each of the four contours and extract the letter
# inside of each one
for contour in contours:
# Get the rectangle that contains the contour
(x, y, w, h) = cv2.boundingRect(contour)
# Compare the width and height of the contour to detect letters that
# are conjoined into one chunk
if w / h > 1.25:
# This contour is too wide to be a single letter!
# Split it in half into two letter regions!
half_width = int(w / 2)
letter_image_regions.append((x, y, half_width, h))
letter_image_regions.append((x + half_width, y, half_width, h))
else:
# This is a normal letter by itself
letter_image_regions.append((x, y, w, h))
# If we found more or less than 4 letters in the captcha, our letter extraction
# didn't work correcly. Skip the image instead of saving bad training data!
if len(letter_image_regions) != 4:
continue
# Sort the detected letter images based on the x coordinate to make sure
# we are processing them from left-to-right so we match the right image
# with the right letter
letter_image_regions = sorted(letter_image_regions, key=lambda x: x[0])
# Save out each letter as a single image
for letter_bounding_box, letter_text in zip(letter_image_regions, captcha_correct_text):
# Grab the coordinates of the letter in the image
x, y, w, h = letter_bounding_box
# Extract the letter from the original image with a 2-pixel margin around the edge
letter_image = gray[y - 2:y + h + 2, x - 2:x + w + 2]
# Get the folder to save the image in
save_path = os.path.join(OUTPUT_FOLDER, letter_text)
# if the output directory does not exist, create it
if not os.path.exists(save_path):
os.makedirs(save_path)
# write the letter image to a file
count = counts.get(letter_text, 1)
p = os.path.join(save_path, "{}.png".format(str(count).zfill(6)))
cv2.imwrite(p, letter_image)
# increment the count for the current key
counts[letter_text] = count + 1
</code></pre>
<p>When I try to run the code I get the following error:</p>
<pre><code>[INFO] processing image 1/9955
Traceback (most recent call last):
File "extract_single_letters_from_captchas.py", line 47, in <module>
(x, y, w, h) = cv2.boundingRect(contour)
cv2.error: OpenCV(4.0.0) /Users/travis/build/skvark/opencv-python/opencv/modules/imgproc/src/shapedescr.cpp:741: error: (-215:Assertion failed) npoints >= 0 && (depth == CV_32F || depth == CV_32S) in function 'pointSetBoundingRect'
</code></pre>
<p>I've tried searching for a solution on StackOverflow, but I didn't find anything remotely similar.</p>
<hr>
<p>EDIT (see comments):</p>
<ul>
<li><p><code>type(contour[0])</code> = <code><class 'numpy.ndarray'></code></p></li>
<li><p><code>len(contour)</code> = <code>4</code></p></li>
</ul> | 54,734,716 | 7 | 5 | null | 2019-02-17 15:06:29.313 UTC | 3 | 2022-08-23 07:49:32.603 UTC | 2022-08-23 07:49:32.603 UTC | null | 6,885,902 | null | 8,306,666 | null | 1 | 17 | python|opencv|contour | 47,660 | <p>This is doing the wrong thing:</p>
<pre class="lang-py prettyprint-override"><code>contours = contours[0] if imutils.is_cv2() else contours[1]
</code></pre>
<p><code>imutils.is_cv2()</code> is returning <code>False</code> even though it should return <code>True</code>. If you don't mind to remove this dependency, change to:</p>
<pre class="lang-py prettyprint-override"><code>contours = contours[0]
</code></pre>
<hr>
<p>I found out the reason. Probably, the tutorial you are following was published before OpenCV 4 was released. OpenCV 3 changed <a href="https://docs.opencv.org/3.0-beta/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=find%20contours#cv2.findContours" rel="noreferrer"><code>cv2.findContours(...)</code></a> to return <code>image, contours, hierarchy</code>, while <a href="https://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=findcontours#cv2.findContours" rel="noreferrer">OpenCV 2's <code>cv2.findContours(...)</code></a> and <a href="https://docs.opencv.org/4.0.1/d3/dc0/group__imgproc__shape.html#gadf1ad6a0b82947fa1fe3c3d497f260e0" rel="noreferrer">OpenCV 4's <code>cv2.findContours(...)</code></a> return <code>contours, hierarchy</code>. Therefore, before OpenCV 4, it was correct to say that if you use OpenCV 2 it should be <code>contours[0]</code> else <code>contours[1]</code>. If you still want to have this "compatibility", you can change to:</p>
<pre class="lang-py prettyprint-override"><code>contours = contours[1] if imutils.is_cv3() else contours[0]
</code></pre> |
39,327,028 | Can a C++ function be declared such that the return value cannot be ignored? | <p>I'm trying to determine whether a C++ function can be declared in such a way that the return value cannot be ignored (ideally detected at compile time). I tried to declare a class with a <code>private</code> (or in C++11, <code>delete</code>d) <code>operator void()</code> to try to catch the implicit conversion to void when a return value is unused.</p>
<p>Here's an example program:</p>
<pre><code>class Unignorable {
operator void();
};
Unignorable foo()
{
return Unignorable();
}
int main()
{
foo();
return 0;
}
</code></pre>
<p>Unfortunately, my compiler (clang-703.0.31) says:</p>
<pre><code>test.cpp:2:5: warning: conversion function converting 'Unignorable' to 'void' will never be used
operator void();
^
</code></pre>
<p>and doesn't raise any error or warning on the call to <code>foo()</code>. So, that won't work. Is there any other way to do this? Answers specific to C++11 or C++14 or later would be fine.</p> | 39,341,050 | 4 | 5 | null | 2016-09-05 08:58:05.783 UTC | 5 | 2020-08-23 12:32:35.353 UTC | 2016-09-05 17:59:38.1 UTC | null | 893 | null | 893 | null | 1 | 32 | c++|return-value|void | 4,264 | <p>To summarize from other answers & comments, basically you have 3 choices:</p>
<ol>
<li>Get C++17 to be able to use <code>[[nodiscard]]</code></li>
<li>In g++ (also clang++), use compiler extensions like <code>__wur</code> (defined
as <code>__attribute__ ((__warn_unused_result__))</code>), or the more portable (C++11 and up only) <code>[[gnu::warn_unused_result]]</code> attribute.</li>
<li>Use runtime checks to catch the problem during unit testing</li>
</ol>
<hr>
<p>If all of these 3 are not possible, then there is one more way, which is kind of <strong>"Negative compiling"</strong>. Define your <code>Unignorable</code> as below:</p>
<pre><code>struct Unignorable {
Unignorable () = default;
#ifdef NEGATIVE_COMPILE
Unignorable (const Unignorable&) = delete; // C++11
Unignorable& operator= (const Unignorable&) = delete;
//private: Unignorable (const Unignorable&); public: // C++03
//private: Unignorable& operator= (const Unignorable&); public: // C++03
/* similar thing for move-constructor if needed */
#endif
};
</code></pre>
<p>Now compile with <code>-DNEGATIVE_COMPILE</code> or equivalent in other compilers like MSVC. It will give errors at wherever the result <em>is Not ignored</em>:</p>
<pre><code>auto x = foo(); // error
</code></pre>
<p>However, it will not give any error wherever the result <em>is ignored</em>:</p>
<pre><code>foo(); // no error
</code></pre>
<p>Using any modern code browser (like eclipse-cdt), you may find all the occurrences of <code>foo()</code> and fix those places which didn't give error. In the new compilation, simply remove the pre-defined macro for "NEGATIVE_COMPILE". </p>
<p>This might be bit better compared to simply finding <code>foo()</code> and checking for its return, because there might be many functions like <code>foo()</code> where you may not want to ignore the return value.</p>
<p>This is bit tedious, but will work for all the versions of C++ with all the compilers.</p> |
20,142,002 | java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US | <p>I am trying to create a utility class <code>ReadPropertyUtil.java</code> for reading data from property file. While my class is located under a util directory , my <code>skyscrapper.properties</code> file is placed in some other directory.</p>
<p>But , when i try to access the properties using <code>[ResourceBundle][1]</code>, i get exceptions, that bundle can't be loaded.</p>
<p>Below is the code on how I am reading the properties and also an image which shows my directory structure.</p>
<p><strong>ReadPropertiesUtil.java</strong></p>
<pre><code>/**
* Properties file name.
*/
private static final String FILENAME = "skyscrapper";
/**
* Resource bundle.
*/
private static ResourceBundle resourceBundle = ResourceBundle.getBundle(FILENAME);
/**
* Method to read the property value.
*
* @param key
* @return
*/
public static String getProperty(final String key) {
String str = null;
if (resourceBundle != null) {
str = resourceBundle.getString(key);
LOGGER.debug("Value found: " + str + " for key: " + key);
} else {
LOGGER.debug("Properties file was not loaded correctly!!");
}
return str;
}
</code></pre>
<p><strong>Directory Structure</strong></p>
<p><img src="https://i.stack.imgur.com/ACdp4.png" alt="enter image description here"></p>
<p>This line is giving the error <code>private static ResourceBundle resourceBundle = ResourceBundle.getBundle(FILENAME);</code></p>
<p>I am unable to understand why isn't this working and what is the solution. The <code>src</code> folder is already added in build path completely.</p> | 20,142,626 | 12 | 0 | null | 2013-11-22 10:01:21.94 UTC | 5 | 2022-08-11 05:11:10.043 UTC | null | null | null | null | 1,471,314 | null | 1 | 44 | java|properties|resourcebundle | 225,786 | <p>Try with the <strong>fully qualified name</strong> for the resource:<br/></p>
<pre><code>private static final String FILENAME = "resources/skyscrapper";
</code></pre> |
20,052,769 | get first and last element in array | <p>hey there i have this array:</p>
<pre><code>array(1) {
["dump"]=>
string(38) "["24.0",24.1,24.2,24.3,24.4,24.5,24.6]"
}
</code></pre>
<p>my question:</p>
<p>how to get the first and the last element out from this array, so i will have:</p>
<pre><code>$firstEle = "24.0";
</code></pre>
<p>and</p>
<pre><code>$lastEle = "24.6";
</code></pre>
<p>anybody knows how to get those elements from the array?</p>
<p>i already tried this:</p>
<pre><code>$arr = json_decode($_POST["dump"], true);
$col0 = $arr[0];
$col1 = $arr[1];
$col2 = $arr[2];
$col3 = $arr[3];
$col4 = $arr[4];
$col5 = $arr[5];
$col6 = $arr[6];
</code></pre>
<p>i could chose $col0 and $col6, but the array could be much longer, so need a way to filter the first("24.0") and the last("24.6") element.
greetings</p> | 20,052,835 | 6 | 1 | null | 2013-11-18 16:29:12.587 UTC | 11 | 2019-08-06 19:10:22.49 UTC | null | null | null | null | 2,999,787 | null | 1 | 49 | php|arrays|indexing | 96,224 | <p><a href="http://us1.php.net/reset" rel="noreferrer"><code>reset()</code></a> and <a href="http://us2.php.net/end" rel="noreferrer"><code>end()</code></a> does exactly this.</p>
<p>From the manual:</p>
<blockquote>
<p><a href="http://us1.php.net/reset" rel="noreferrer"><strong><code>reset()</code></strong></a>: Returns the value of the first array element, or FALSE if the array is empty.</p>
<p><a href="http://us2.php.net/end" rel="noreferrer"><strong><code>end()</code></strong></a>: Returns the value of the last element or FALSE for empty array.</p>
</blockquote>
<p>Example:</p>
<pre><code><?php
$array = array(24.0,24.1,24.2,24.3,24.4,24.5,24.6);
$first = reset($array);
$last = end($array);
var_dump($first, $last);
?>
</code></pre>
<p>Which outputs:</p>
<blockquote>
<p>float(24)<br />
float(24.6)</p>
</blockquote>
<p><a href="http://codepad.org/9G3QPc72" rel="noreferrer"><strong>DEMO</strong></a></p>
<hr />
<p><strong>NOTE</strong>: This will reset your array pointer meaning if you use <a href="http://us1.php.net/reset" rel="noreferrer"><code>current()</code></a> to get the current element or you've seeked into the middle of the array, <a href="http://us1.php.net/reset" rel="noreferrer"><code>reset()</code></a> and <a href="http://us1.php.net/reset" rel="noreferrer"><code>end()</code></a> will reset the array pointer (to the beginning and to the end):</p>
<pre><code><?php
$array = array(30.0, 24.0, 24.1, 24.2, 24.3, 24.4, 24.5, 24.6, 12.0);
// reset — Set the internal pointer of an array to its first element
$first = reset($array);
var_dump($first); // float(30)
var_dump(current($array)); // float(30)
// end — Set the internal pointer of an array to its last element
$last = end($array);
var_dump($last); // float(12)
var_dump(current($array)); // float(12) - this is no longer 30 - now it's 12
</code></pre> |
7,032,965 | How do I figure out and change which version of Java Maven is using to execute? | <p>When running our Maven build, a member of my team gets a NoSuchMethodError in one of the dependant plug-ins when executing. However, when we run <code>java -version</code> from her command line, it indicates Java 1.6.0_26. The error obviously seems to be screaming that Maven is using Java 5.</p>
<p>How do I figure out and change what version of Java is being used by Maven?</p>
<p>3 potentially important notes:</p>
<ol>
<li>This is executed at the command line, not using Eclipse plugin</li>
<li>JAVA_HOME is set to a Java 1.6 JDK</li>
<li>Using Maven 2.2.1</li>
</ol> | 7,033,062 | 3 | 2 | null | 2011-08-11 21:17:33.91 UTC | 8 | 2022-02-26 13:25:01.437 UTC | 2022-02-26 13:25:01.437 UTC | null | 6,083,675 | null | 292 | null | 1 | 95 | java|maven | 89,082 | <p><code>mvn -version</code> will output which java it's using. If JAVA_HOME is set to a valid JDK directory and Maven is using something else, then most likely someone has tampered with the way that Maven starts up.</p> |
24,310,696 | UIColor not working with RGBA values | <p>I am trying to change the text colour in a UITextField using the following code (RGBA value) however it just appears white, or clear, I'm not too sure as the background is white itself. </p>
<pre><code>passwordTextField.textColor = UIColor(red: CGFloat(202.0), green: CGFloat(228.0), blue: CGFloat(230.0), alpha: CGFloat(100.0))
passwordTextField.returnKeyType = UIReturnKeyType.Done
passwordTextField.placeholder = "Password"
passwordTextField.backgroundColor = UIColor.clearColor()
passwordTextField.borderStyle = UITextBorderStyle.RoundedRect
passwordTextField.font = UIFont(name: "Avenir Next", size: 14)
passwordTextField.textAlignment = NSTextAlignment.Center
passwordTextField.secureTextEntry = true
</code></pre> | 24,310,767 | 6 | 1 | null | 2014-06-19 15:40:29.96 UTC | 3 | 2019-11-29 07:51:16.007 UTC | 2017-05-22 07:36:43.027 UTC | null | 6,214,222 | null | 2,875,074 | null | 1 | 30 | ios|swift|uicolor | 20,757 | <p>RGB values for UIColor are between 0 and 1 (see <a href="https://developer.apple.com/library/ios/documentation/uikit/reference/UIColor_Class/Reference/Reference.html#//apple_ref/occ/clm/UIColor/colorWithRed%3agreen%3ablue%3aalpha%3a">the documentation</a> "specified as a value from 0.0 to 1.0")</p>
<p>You need to divide your numbers by 255:</p>
<pre><code>passwordTextField.textColor = UIColor(red: CGFloat(202.0/255.0), green: CGFloat(228.0/255.0), blue: CGFloat(230.0/255.0), alpha: CGFloat(1.0))
</code></pre>
<p>Another thing, you don't need to create CGFloats:</p>
<pre><code>passwordTextField.textColor = UIColor(red:202.0/255.0, green:228.0/255.0, blue:230.0/255.0, alpha:1.0)
</code></pre> |
1,957,290 | calculate the number of html checkbox checked using jquery | <p>how can i calculate the number of checkboxes that a user has checked using jquery?</p>
<p>what i want to do is limiting the number of checking for checkboxes in a form to 10 for example and when a user exceeds this range display a warning message.</p> | 1,957,296 | 4 | 1 | null | 2009-12-24 08:00:05.073 UTC | 5 | 2015-05-05 08:33:15.607 UTC | null | null | null | null | 107,887 | null | 1 | 25 | jquery|html|forms|checkbox | 56,954 | <p>There are multiple methods to do that:</p>
<p><strong>Method 1:</strong></p>
<pre><code>alert($('.checkbox_class_here:checked').size());
</code></pre>
<p><strong>Method 2:</strong></p>
<pre><code>alert($('input[name=checkbox_name]').attr('checked'));
</code></pre>
<p><strong>Method: 3</strong></p>
<pre><code>alert($(":checkbox:checked").length);
</code></pre> |
49,522,619 | The result of subscribe is not used | <p>I've upgraded to Android Studio 3.1 today, which seems to have added a few more lint checks. One of these lint checks is for one-shot RxJava2 <code>subscribe()</code> calls that are not stored in a variable. For example, getting a list of all players from my Room database:</p>
<pre><code>Single.just(db)
.subscribeOn(Schedulers.io())
.subscribe(db -> db.playerDao().getAll());
</code></pre>
<p>Results in a big yellow block and this tooltip:</p>
<blockquote>
<p>The result of <code>subscribe</code> is not used</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/UThmL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UThmL.png" alt="Screenshot of Android Studio. Code is highlighted in Yellow with a tooltip. Tooltip text: The result of subscribe is not used."></a></p>
<p>What is the best practice for one-shot Rx calls like this? Should I keep hold of the <code>Disposable</code> and <code>dispose()</code> on complete? Or should I just <code>@SuppressLint</code> and move on?</p>
<p>This only seems to affect RxJava2 (<code>io.reactivex</code>), RxJava (<code>rx</code>) does not have this lint.</p> | 49,523,600 | 8 | 4 | null | 2018-03-27 21:22:34.037 UTC | 31 | 2020-05-18 20:36:20.803 UTC | 2019-05-08 07:59:30.173 UTC | null | 469,080 | null | 469,080 | null | 1 | 153 | android|android-studio|rx-java2|lint|android-studio-3.1 | 57,538 | <p>The IDE does not know what potential effects your subscription can have when it's not disposed, so it treats it as potentially unsafe. For example, your <code>Single</code> may contain a network call, which could cause a memory leak if your <code>Activity</code> is abandoned during its execution. </p>
<p>A convenient way to manage a large amount of <code>Disposable</code>s is to use a <a href="http://reactivex.io/RxJava/javadoc/io/reactivex/disposables/CompositeDisposable.html" rel="noreferrer">CompositeDisposable</a>; just create a new <code>CompositeDisposable</code> instance variable in your enclosing class, then add all your Disposables to the CompositeDisposable (with RxKotlin you can just append <code>addTo(compositeDisposable)</code> to all of your Disposables). Finally, when you're done with your instance, call <code>compositeDisposable.dispose()</code>. </p>
<p>This will get rid of the lint warnings, and ensure your <code>Disposables</code> are managed properly. </p>
<p>In this case, the code would look like: </p>
<pre><code>CompositeDisposable compositeDisposable = new CompositeDisposable();
Disposable disposable = Single.just(db)
.subscribeOn(Schedulers.io())
.subscribe(db -> db.get(1)));
compositeDisposable.add(disposable); //IDE is satisfied that the Disposable is being managed.
disposable.addTo(compositeDisposable); //Alternatively, use this RxKotlin extension function.
compositeDisposable.dispose(); //Placed wherever we'd like to dispose our Disposables (i.e. in onDestroy()).
</code></pre> |
26,023,886 | Unknown type name 'UIImage' | <p>I've upgraded XCode from 5.1.1 to XCode 6.0.1 recently. Now everytime I want to define a new UIImage object I get this error:</p>
<pre>Unknown type name 'UIImage'</pre>
<p>Code:<br>
1. Create a new project<br>
2. Add <code>Image View</code> control to the storyboard<br>
3. Reference the <code>Image View</code> by adding IBOutlet<br>
4. Add new class file<br>
5. Add the following line of code to the header file of the new class:<br></p>
<p><pre>@property (strong, nonatomic) UIImage *background;</pre></p>
<p>Header file (.h) content:</p>
<p><pre>
#import <Foundation/Foundation.h>
@interface CCTile : NSObject
@property (strong, nonatomic) NSString *story;
@property (strong, nonatomic) UIImage *background; // Error: Unknown type name 'UIImage'
@end
</pre></p>
<p>However, if I add <code>#import <UIKit/UIKit.h></code> to the header file (above) everything seems OK!
Any ideas what am I missing here, please? Is this a change in XCode header files!</p> | 26,690,066 | 3 | 2 | null | 2014-09-24 18:26:00.707 UTC | 12 | 2014-11-01 14:10:18.62 UTC | 2014-09-26 11:11:21.07 UTC | null | 2,198,253 | null | 2,198,253 | null | 1 | 38 | xcode5|xcode6 | 26,706 | <p>I also had the same problem and fixed it using</p>
<pre><code>#import <UIKit/UIKit.h>
</code></pre>
<p>However, I dug around some more and compared a project made in XCode 6 compared to Xcode 5, and I noticed that Xcode 6 did not create a prefix header file. The prefix header file is implicitly imported into every class, and the prefix header file (.pch) includes UIKit as well as Foundation.</p>
<p>To create a pch file, go to File -> New -> File -> Other -> PCH file. Edit the name to "YourProject-prefix.pch". Add the following:</p>
<pre><code>#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#endif
</code></pre>
<p>Then you need to set the build settings. Go to your project -> build settings -> search at the top: prefix header. </p>
<p>You will see Precompile Prefix Header -> change to yes.
Also, right below is Prefix Header. Add the path of your prefix header. Should be like: "YourProject/YourProject-prefix.pch".</p> |
7,051,743 | Extending or including - what is better in Twig? | <p>Why Twig documentation recommends to use extending rather than including? Symfony 2 documentation says because "In Symfony2, we like to think about this problem differently: a template can be decorated by another one." but nothing more. It's just author's whim or something more? Thanks for help.</p> | 7,162,701 | 5 | 0 | null | 2011-08-13 16:25:13.117 UTC | 14 | 2016-01-20 18:10:51.107 UTC | 2012-08-05 09:09:31.133 UTC | null | 569,101 | null | 893,222 | null | 1 | 31 | php|symfony|twig|template-engine | 18,734 | <p><strong>When to use inheritance:</strong></p>
<p>You have 50 pages sharing the same layout - you create a layout.twig as a parent, and each page extends that layout.twig. So the parent is the generic and the child is the specific.</p>
<p><strong>When to use include:</strong></p>
<p>Out of the 50 pages, there are 6 pages that share a chunk of HTML - you create a shared-chunk.twig and include it in those 6 pages.</p>
<p>Another usage:</p>
<p>You notice that your layout.twig is bit cluttered and you would like to modularize it, so you split sidebar.twig into a separate file and include it in layout.twig.</p>
<p><strong>Can you use include for the inheritance use-case:</strong></p>
<p>Sure, create chunks for header, footer and what have you, and use includes in each of the 50 pages. But that's wrong design as explained above.</p>
<p><strong>Can you use inheritance for the include use-case:</strong></p>
<p>Sure, create an empty block for the shared chunk in the parent layout.twig, and create a second level child layout-with-chunk.twig that extends layout.twig and fills in the chunk block, and the 6 pages in the above example that share the chunk can then extend layout-with-chunk.twig instead of layout.twig. But this again is wrong design because the chunk block is not shared by all children and shouldn't go into the base parent. Plus you have cluttered the inheritance tree.</p>
<p>So:</p>
<p>As explained above - it's a matter of design not programmability. It's not about: I can achieve this same result using a different programming technique, its about which usage is better design.</p> |
7,373,853 | Warning: session_start() [function.session-start]: Cannot send session cache limiter | <p>I have a problem with Session_start() here :</p>
<p><strong>Warning</strong>: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\pages\home.php:4) in <strong>C:\xampp\htdocs\charts\home-chart.php</strong> on line <strong>2</strong></p>
<p>and in home-chart.php in line 2 I wrote codes like this : </p>
<pre><code>session_start();
.
.
.
echo ' username: '.$_SESSION['user_name'];
</code></pre>
<hr>
<p>although with this warning i can get result of <code>$_SESSION['user_name']</code> but when I try to clear this part of the code :</p>
<pre><code>session_start();
</code></pre>
<p>I can't see any result in screen.
so, what's your solution?</p>
<pre><code><?php
@session_start();
require_once '../class/chart.class.php';
$chart = new chart();
?>
<html>
<head>
<link href='../css/home-chart.css' rel='stylesheet' type='text/css' />
</head>
<body>
<div class='float_left' style="margin-bottom:20px;">
<div class='float_left' style='line-height: 9.41px; font-size: x-small;'>0<br /></div> <div class='float_left' style="background-image: url('../image/web/chart.png'); width: 367px; height: 226px; " >
<!-- 1 --><div class='float_left float_left column' style='margin-left:2px;'>
<?php echo $chart->mysql_fetch($chart->daycal(-3)); ?>
</div>
<!-- 2 --><div class='float_left float_left column'>
<?php echo $chart->mysql_fetch($chart->daycal(-2)); ?>
</div>
<!-- 3 --><div class='float_left column' >
<?php echo $chart->mysql_fetch($chart->daycal(-1)); ?>
</div>
<!-- 4 --><div class='float_left column' >
<?php echo $chart->mysql_fetch($chart->daycal(0)); ?>
</div>
<!-- 5 --><div class='float_left column' >
<?php echo $chart->mysql_fetch($chart->daycal(1)); ?>
</div>
<!-- 6 --><div class='float_left column' >
<?php echo $chart->mysql_fetch($chart->daycal(2)); ?>
</div>
<!-- 7 --><div class='float_left column' >
<?php echo $chart->mysql_fetch($chart->daycal(3)); ?>
</div>
</div>
<div class='float_single_full' ></div>
<div class='float_left bottom_chart' style="margin-left:10px;"><?php echo $chart->dayofweek(-3); ?></div>
<div class='float_left bottom_chart'><?php echo $chart->dayofweek(-2); ?></div>
<div class='float_left bottom_chart'><?php echo $chart->dayofweek(-1); ?></div>
<div class='float_left bottom_chart' style='font-weight:bold'><?php echo $chart->dayofweek(0); ?></div>
<div class='float_left bottom_chart'><?php echo $chart->dayofweek(1); ?></div>
<div class='float_left bottom_chart'><?php echo $chart->dayofweek(2); ?></div>
<div class='float_left bottom_chart'><?php echo $chart->dayofweek(3);
echo ' username: ' . $_SESSION['user_name'];
?></div>
</div>
</body>
</html>
</code></pre> | 7,373,904 | 9 | 5 | null | 2011-09-10 18:49:26.813 UTC | 1 | 2018-05-07 23:52:16.2 UTC | 2014-01-12 17:35:27.07 UTC | null | 2,153,274 | null | 723,066 | null | 1 | 7 | php|session | 54,770 | <p>If you even have blank lines before the <code><?php</code> tag, then you can't set headers. Your start of file, with line numbers, should look like this:</p>
<pre><code>1. <?php
2. session_start();
3. header('Cache-control: private');
</code></pre>
<p>The message says "headers sent at line 2", so you're outputting something (a space, a blank line, whatever) on line 4 of home.php</p>
<p>If this file is an include, you should put your <code>session_start();</code> at the top of home.php instead, and then you don't need it in this file.</p> |
13,847,963 | Akka Kill vs. Stop vs. Poison Pill? | <p>Newbie question of Akka - I'm reading over Akka Essentials, could someone please explain the difference between Akka Stop/Poison Pill vs. Kill ? The book offers just a small explaination "Kill is synchronous vs. Poison pill is asynchronous." But in what way? Does the calling actor thread lock during this time? Are the children actors notified during kill, post-stop envoked, etc? Example uses of one concept vs. the other?</p>
<p>Many thanks!</p> | 13,848,350 | 4 | 3 | null | 2012-12-12 20:22:11.24 UTC | 76 | 2020-04-30 00:32:21.373 UTC | null | null | null | null | 1,243,034 | null | 1 | 223 | scala|akka | 58,938 | <p>Both <code>stop</code> and <code>PoisonPill</code> will terminate the actor and stop the message queue. They will cause the actor to cease processing messages, send a stop call to all its children, wait for them to terminate, then call its <code>postStop</code> hook. All further messages are sent to the dead letters mailbox.</p>
<p>The difference is in which messages get processed before this sequence starts. In the case of the <code>stop</code> call, the message currently being processed is completed first, with all others discarded. When sending a <code>PoisonPill</code>, this is simply another message in the queue, so the sequence will start when the <code>PoisonPill</code> is received. All messages that are ahead of it in the queue will be processed first.</p>
<p>By contrast, the <code>Kill</code> message causes the actor to throw an <code>ActorKilledException</code> which gets handled using the normal supervisor mechanism. So the behaviour here depends on what you've defined in your supervisor strategy. The default is to stop the actor. But the mailbox persists, so when the actor restarts it will still have the old messages except for the one that caused the failure.</p>
<p>Also see the 'Stopping an Actor', 'Killing an Actor' section in the docs:</p>
<p><a href="http://doc.akka.io/docs/akka/snapshot/scala/actors.html">http://doc.akka.io/docs/akka/snapshot/scala/actors.html</a></p>
<p>And more on supervision strategies:</p>
<p><a href="http://doc.akka.io/docs/akka/snapshot/scala/fault-tolerance.html">http://doc.akka.io/docs/akka/snapshot/scala/fault-tolerance.html</a></p> |
30,172,605 | How do I get into a Docker container's shell? | <p>I'm getting started working with Docker. I'm using the WordPress base image and docker-compose.</p>
<p>I'm trying to ssh into one of the containers to inspect the files/directories that were created during the initial build. I tried to run <code>docker-compose run containername ls -la</code>, but that didn't do anything. Even if it did, I'd rather have a console where I can traverse the directory structure, rather than run a single command. What is the right way to do this with Docker?</p> | 30,173,220 | 30 | 6 | null | 2015-05-11 16:12:30.83 UTC | 491 | 2022-09-11 10:08:44.06 UTC | 2019-02-03 16:25:40.59 UTC | null | 1,663,462 | null | 48,523 | null | 1 | 1,781 | docker|docker-container | 1,720,975 | <p><code>docker attach</code> will let you connect to your Docker container, but this isn't really the same thing as <code>ssh</code>. If your container is running a webserver, for example, <code>docker attach</code> will probably connect you to the <em>stdout</em> of the web server process. It won't necessarily give you a shell.</p>
<p>The <code>docker exec</code> command is probably what you are looking for; this will let you run arbitrary commands inside an existing container. For example:</p>
<pre><code>docker exec -it <mycontainer> bash
</code></pre>
<p>Of course, whatever command you are running must exist in the container filesystem.</p>
<p>In the above command <code><mycontainer></code> is the name or ID of the target container. It doesn't matter whether or not you're using <code>docker compose</code>; just run <code>docker ps</code> and use either the ID (a hexadecimal string displayed in the first column) or the name (displayed in the final column). E.g., given:</p>
<pre><code>$ docker ps
d2d4a89aaee9 larsks/mini-httpd "mini_httpd -d /cont 7 days ago Up 7 days web
</code></pre>
<p>I can run:</p>
<pre><code>$ docker exec -it web ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
18: eth0: <BROADCAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
link/ether 02:42:ac:11:00:03 brd ff:ff:ff:ff:ff:ff
inet 172.17.0.3/16 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::42:acff:fe11:3/64 scope link
valid_lft forever preferred_lft forever
</code></pre>
<p>I could accomplish the same thing by running:</p>
<pre><code>$ docker exec -it d2d4a89aaee9 ip addr
</code></pre>
<p>Similarly, I could start a shell in the container;</p>
<pre><code>$ docker exec -it web sh
/ # echo This is inside the container.
This is inside the container.
/ # exit
$
</code></pre> |
9,390,134 | Rsync cronjob that will only run if rsync isn't already running | <p>I have checked for a solution here but cannot seem to find one. I am dealing with a very slow wan connection about 300kb/sec. For my downloads I am using a remote box, and then I am downloading them to my house. I am trying to run a cronjob that will rsync two directories on my remote and local server every hour. I got everything working but if there is a lot of data to transfer the rsyncs overlap and end up creating two instances of the same file thus duplicate data sent.</p>
<p>I want to instead call a script that would run my rsync command but only if rsync isn't running?</p> | 9,390,183 | 5 | 1 | null | 2012-02-22 06:30:42.56 UTC | 9 | 2020-10-14 17:02:43.537 UTC | null | null | null | null | 1,225,088 | null | 1 | 22 | cron|rsync | 21,747 | <p>Via the script you can create a "lock" file. If the file exists, the cronjob should skip the run ; else it should proceed. Once the script completes, it should delete the lock file.</p>
<pre>
if [ -e /home/myhomedir/rsyncjob.lock ]
then
echo "Rsync job already running...exiting"
exit
fi
touch /home/myhomedir/rsyncjob.lock
#your code in here
#delete lock file at end of your job
rm /home/myhomedir/rsyncjob.lock
</pre> |
9,170,670 | How do I set textarea scroll bar to bottom as a default? | <p>I have a textarea that is being dynamically reloaded as user input is being sent in. It refreshes itself every couple seconds. When the amount of text in this textarea exceeds the size of the textarea, a scroll bar appears. However the scroll bar isn't really usable because if you start scrolling down, a couple seconds later the textarea refreshes and brings the scroll bar right back up to the top. I want to set the scroll bar to by default show the bottom most text. Anyone have an idea of how to do so?</p> | 9,170,709 | 5 | 1 | null | 2012-02-07 03:37:25.493 UTC | 25 | 2022-07-21 12:25:37.21 UTC | null | null | null | null | 1,190,419 | null | 1 | 114 | javascript|css|scroll|textarea | 114,758 | <p>pretty simple, in vanilla javascript:</p>
<pre><code>var textarea = document.getElementById('textarea_id');
textarea.scrollTop = textarea.scrollHeight;
</code></pre> |
19,719,397 | Qt Slots and C++11 lambda | <p>I have a QAction item that I initialize like follows:</p>
<pre><code>QAction* action = foo->addAction(tr("Some Action"));
connect(action, SIGNAL(triggered()), this, SLOT(onSomeAction()));
</code></pre>
<p>And then onSomeAction looks something like:</p>
<pre><code>void MyClass::onSomeAction()
{
QAction* caller = qobject_cast<QAction*>(sender());
Q_ASSERT(caller != nullptr);
// do some stuff with caller
}
</code></pre>
<p>This works fine, I get the <code>caller</code> object back and I'm able to use it as expected. Then I try the C++11 way to connect the object like such:</p>
<pre><code>connect(action, &QAction::triggered, [this]()
{
QAction* caller = qobject_cast<QAction*>(sender());
Q_ASSERT(caller != nullptr);
// do some stuff with caller
});
</code></pre>
<p>But <code>caller</code> is always null and thus the <code>Q_ASSERT</code> triggers. How can I use lambdas to get the sender?</p> | 19,721,153 | 3 | 2 | null | 2013-11-01 01:21:49.583 UTC | 26 | 2019-09-24 11:49:49.47 UTC | 2013-11-01 20:55:38.067 UTC | null | 1,329,652 | null | 552,613 | null | 1 | 60 | c++|qt|c++11 | 48,009 | <p>The simple answer is: you can't. Or, rather, you don't want (or need!) to use <code>sender()</code>. Simply capture and use <code>action</code>.</p>
<pre><code>// Important!
// vvvv
connect(action, &QAction::triggered, this, [action, this]() {
// use action as you wish
...
});
</code></pre>
<p>The specification of <code>this</code> as the object context for the functor ensures that the functor will not get invoked if either the action or <code>this</code> (a <code>QObject</code>) cease to exist. Otherwise, the functor would try to reference dangling pointers.</p>
<p>In general, the following must hold when capturing context variables for a functor passed to <code>connect</code>, in order to avoid the use of dangling pointers/references:</p>
<ol>
<li><p>The pointers to the source and target objects of <code>connect</code> can be captured by value, as above. It is guaranteed that if the functor is invoked, both ends of the connection exist. </p>
<pre><code>connect(a, &A::foo, b, [a, b]{});
</code></pre>
<p>Scenarios where <code>a</code> and <code>b</code> are in different threads require special attention. It can not be guaranteed that once the functor is entered, some thread will not delete either object.</p>
<p>It is idiomatic that an object is only destructed in its <code>thread()</code>, or in any thread if <code>thread() == nullptr</code>. Since a thread's event loop invokes the functor, the null thread is never a problem for <code>b</code> - without a thread the functor won't be invoked. Alas, there's no guarantee about the lifetime of <code>a</code> in <code>b</code>'s thread. It is thus safer to capture the necessary state of the action by value instead, so that <code>a</code>'s lifetime is not a concern.</p>
<pre><code>// SAFE
auto aName = a->objectName();
connect(a, &A::foo, b, [aName, b]{ qDebug() << aName; });
// UNSAFE
connect(a, &A::foo, b, [a,b]{ qDebug() << a->objectName(); });
</code></pre></li>
<li><p>Raw pointers to other objects can be captured by value if you're absolutely sure that the lifetime of the objects they point to overlaps the lifetime of the connection.</p>
<pre><code>static C c;
auto p = &c;
connect(..., [p]{});
</code></pre></li>
<li><p>Ditto for references to objects:</p>
<pre><code>static D d;
connect(..., [&d]{});
</code></pre></li>
<li><p>Non-copyable objects that don't derive from <code>QObject</code> should be captured through their shared pointers by value.</p>
<pre><code>std::shared_ptr<E> e { new E };
QSharedPointer<F> f { new F; }
connect(..., [e,f]{});
</code></pre></li>
<li><p><code>QObject</code>s living in the same thread can be captured by a <code>QPointer</code>; its value must be checked prior to use in the functor.</p>
<pre><code>QPointer<QObject> g { this->parent(); }
connect(..., [g]{ if (g) ... });
</code></pre></li>
<li><p><code>QObject</code>s living in other threads must be captured by a shared pointer or a weak pointer. Their parent must be unset prior to their destruction, otherwise you'll have double deletes:</p>
<pre><code>class I : public QObject {
...
~I() { setParent(nullptr); }
};
std::shared_ptr<I> i { new I };
connect(..., [i]{ ... });
std::weak_ptr<I> j { i };
connect(..., [j]{
auto jp = j.lock();
if (jp) { ... }
});
</code></pre></li>
</ol> |
19,432,913 | Select info from table where row has max date | <p>My table looks something like this:</p>
<pre><code>group date cash checks
1 1/1/2013 0 0
2 1/1/2013 0 800
1 1/3/2013 0 700
3 1/1/2013 0 600
1 1/2/2013 0 400
3 1/5/2013 0 200
</code></pre>
<p>-- Do not need cash just demonstrating that table has more information in it</p>
<p>I want to get the each unique group where date is max and checks is greater than 0. So the return would look something like:</p>
<pre><code>group date checks
2 1/1/2013 800
1 1/3/2013 700
3 1/5/2013 200
</code></pre>
<p>attempted code:</p>
<pre><code>SELECT group,MAX(date),checks
FROM table
WHERE checks>0
GROUP BY group
ORDER BY group DESC
</code></pre>
<p>problem with that though is it gives me all the dates and checks rather than just the max date row.</p>
<p>using ms sql server 2005</p> | 19,433,107 | 4 | 3 | null | 2013-10-17 17:01:34.013 UTC | 29 | 2020-01-28 23:51:14.97 UTC | 2013-10-17 17:10:34.42 UTC | null | 255,562 | null | 714,254 | null | 1 | 86 | sql|sql-server-2005|greatest-n-per-group | 510,799 | <pre><code>SELECT group,MAX(date) as max_date
FROM table
WHERE checks>0
GROUP BY group
</code></pre>
<p>That works to get the max date..join it back to your data to get the other columns:</p>
<pre><code>Select group,max_date,checks
from table t
inner join
(SELECT group,MAX(date) as max_date
FROM table
WHERE checks>0
GROUP BY group)a
on a.group = t.group and a.max_date = date
</code></pre>
<p>Inner join functions as the filter to get the max record only.</p>
<p>FYI, your column names are horrid, don't use reserved words for columns (group, date, table).</p> |
34,078,354 | How to disable landscape mode in React Native Android dev mode? | <p>I am new to android environment. I know iOS can be done in Xcode to disable device orientation. How can I disable landscape mode or any orientation mode in React Native Android?</p>
<p>Thanks.</p> | 34,086,828 | 9 | 3 | null | 2015-12-03 23:37:41.24 UTC | 12 | 2021-05-14 13:19:01.513 UTC | 2017-04-02 16:14:59.297 UTC | null | 1,206,613 | null | 108,524 | null | 1 | 87 | android|react-native | 56,197 | <p>Add <code>android:screenOrientation="portrait"</code> to the <code>activity</code> section in <code>android/app/src/main/AndroidManifest.xml</code> file, so that it end up looking like this:</p>
<pre><code><activity
android:name=".Activity"
android:label="Activity"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation|screenSize">
</activity>
</code></pre>
<p>There are several different values for the <code>android:screenOrientation</code> property; for a comprehensive list take a look at the following: <a href="https://developer.android.com/guide/topics/manifest/activity-element.html" rel="noreferrer">https://developer.android.com/guide/topics/manifest/activity-element.html</a></p> |
24,868,226 | How do you mute an embedded Youtube player? | <p>I'm experimenting with the Youtube player but I can't get it to mute by default.</p>
<pre><code>function onPlayerReady() {
player.playVideo();
// Mute?!
player.mute();
player.setVolume(0);
}
</code></pre>
<p>How do I mute it from the start?</p>
<p><strong><a href="http://jsfiddle.net/Jonathan_Ironman/BFDKS/">Fiddle</a></strong></p>
<hr>
<p><strong>Update:</strong></p>
<p><a href="https://developers.google.com/youtube/js_api_reference">JavaScript Player API is deprecated</a>.<br>
Use <a href="https://developers.google.com/youtube/iframe_api_reference">iframe Embeds</a> instead.</p> | 24,869,361 | 4 | 4 | null | 2014-07-21 14:54:26.187 UTC | 6 | 2016-08-16 09:40:33.9 UTC | 2015-09-07 12:24:43.473 UTC | null | 2,407,212 | null | 2,407,212 | null | 1 | 22 | javascript|youtube|youtube-api | 82,486 | <p>Turns out <code>player.mute()</code> works fine. It only needed the parameter <code>enablejsapi=1</code>. Initial test in the fiddle didn't work because the player initiation had an error. The following works.</p>
<p>HTML:</p>
<pre><code><iframe id="ytplayer" type="text/html" src="https://www.youtube-nocookie.com/embed/zJ7hUvU-d2Q?rel=0&enablejsapi=1&autoplay=1&controls=0&showinfo=0&loop=1&iv_load_policy=3" frameborder="0" allowfullscreen></iframe>
</code></pre>
<p>JS:</p>
<pre><code>var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('ytplayer', {
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
player.mute();
player.playVideo();
}
</code></pre>
<p><strong><a href="http://jsfiddle.net/Jonathan_Ironman/BFDKS/9/" rel="noreferrer">Fiddle</a></strong></p>
<p><sup>Credit to Gagandeep Singh and Anton King for pointing to <code>enablejsapi=1</code></sup></p> |
44,998,051 | Cannot create an instance of class ViewModel | <p>I am trying to write a sample app using Android architecture components and but even after trying for days I could not get it to work. It gives me the above exception.</p>
<p>Lifecycle owner:-</p>
<pre><code>public class MainActivity extends LifecycleActivity {
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.tv_user);
PostViewModel viewModel = ViewModelProviders.of(this).get(PostViewModel.class);
viewModel.loadPosts();
viewModel.getPost().observe(this, new Observer<Post>() {
@Override
public void onChanged(@Nullable Post post) {
if(post != null) {
textView.setText(post.toString());
}
}
});
}
}
</code></pre>
<p>ViewModel:-</p>
<pre><code>public class PostViewModel extends ViewModel {
private MediatorLiveData<Post> post;
private PostRepository postRepo;
PostViewModel() {
post = new MediatorLiveData<>();
postRepo = new PostRepository();
}
public LiveData<Post> loadPosts() {
post.addSource(postRepo.getPost(),
post -> this.post.setValue(post)
);
return post;
}
@NonNull
public LiveData<Post> getPost() {
return post;
}
}
</code></pre> | 44,998,087 | 34 | 1 | null | 2017-07-09 15:30:39.017 UTC | 13 | 2022-08-20 17:27:30.717 UTC | null | null | null | null | 4,581,287 | null | 1 | 122 | android|mvvm|android-architecture-components | 116,932 | <p>Make your constructor <code>public</code>.</p> |
279,729 | How to wait until all child processes called by fork() complete? | <p>I am forking a number of processes and I want to measure how long it takes to complete the whole task, that is when all processes forked are completed. Please advise how to make the parent process wait until all child processes are terminated? I want to make sure that I stop the timer at the right moment.</p>
<p>Here is as a code I use:</p>
<pre><code>#include <iostream>
#include <string>
#include <fstream>
#include <sys/time.h>
#include <sys/wait.h>
using namespace std;
struct timeval first, second, lapsed;
struct timezone tzp;
int main(int argc, char* argv[])// query, file, num. of processes.
{
int pCount = 5; // process count
gettimeofday (&first, &tzp); //start time
pid_t* pID = new pid_t[pCount];
for(int indexOfProcess=0; indexOfProcess<pCount; indexOfProcess++)
{
pID[indexOfProcess]= fork();
if (pID[indexOfProcess] == 0) // child
{
// code only executed by child process
// magic here
// The End
exit(0);
}
else if (pID[indexOfProcess] < 0) // failed to fork
{
cerr << "Failed to fork" << endl;
exit(1);
}
else // parent
{
// if(indexOfProcess==pCount-1) and a loop with waitpid??
gettimeofday (&second, &tzp); //stop time
if (first.tv_usec > second.tv_usec)
{
second.tv_usec += 1000000;
second.tv_sec--;
}
lapsed.tv_usec = second.tv_usec - first.tv_usec;
lapsed.tv_sec = second.tv_sec - first.tv_sec;
cout << "Job performed in " <<lapsed.tv_sec << " sec and " << lapsed.tv_usec << " usec"<< endl << endl;
}
}//for
}//main
</code></pre> | 279,761 | 5 | 1 | null | 2008-11-11 01:11:39.53 UTC | 12 | 2017-04-30 03:45:18.307 UTC | 2017-04-30 03:26:49.43 UTC | null | 1,033,581 | Kamil Zadora | 3,515 | null | 1 | 19 | c++|linux|gcc|parallel-processing | 72,755 | <p>I'd move everything after the line "else //parent" down, outside the for loop. After the loop of forks, do another for loop with waitpid, then stop the clock and do the rest:</p>
<pre><code>for (int i = 0; i < pidCount; ++i) {
int status;
while (-1 == waitpid(pids[i], &status, 0));
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
cerr << "Process " << i << " (pid " << pids[i] << ") failed" << endl;
exit(1);
}
}
gettimeofday (&second, &tzp); //stop time
</code></pre>
<p>I've assumed that if the child process fails to exit normally with a status of 0, then it didn't complete its work, and therefore the test has failed to produce valid timing data. Obviously if the child processes are <em>supposed</em> to be killed by signals, or exit non-0 return statuses, then you'll have to change the error check accordingly.</p>
<p>An alternative using wait:</p>
<pre><code>while (true) {
int status;
pid_t done = wait(&status);
if (done == -1) {
if (errno == ECHILD) break; // no more child processes
} else {
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
cerr << "pid " << done << " failed" << endl;
exit(1);
}
}
}
</code></pre>
<p>This one doesn't tell you which process in sequence failed, but if you care then you can add code to look it up in the pids array and get back the index.</p> |
474,316 | HashTables in Cocoa | <p>HashTables/HashMaps are one of the most (if not <em>the</em> most) useful of data-structures in existence. As such, one of the first things I investigated when starting to learn programming in Cocoa was how to create, populate, and read data from a hashtable.</p>
<p>To my surprise: all the documentation I've been reading on Cocoa/Objective-C programming doesn't seem to explain this much at all. As a Java developer that uses "java.util" as if it were a bodily function: I am utterly baffled by this.</p>
<p>So, if someone could provide me with a primer for creating, populating, and reading the contents of a hashtable: I would greatly appreciate it.</p> | 474,366 | 5 | 4 | null | 2009-01-23 20:09:25.353 UTC | 9 | 2019-10-17 10:07:16.167 UTC | 2009-01-23 21:14:08.953 UTC | Ryan Delucchi | 9,931 | Ryan Delucchi | 9,931 | null | 1 | 28 | objective-c|cocoa|macos|hashtable | 34,199 | <p><a href="https://developer.apple.com/documentation/foundation/nsdictionary?language=objc" rel="nofollow noreferrer">NSDictionary</a> and <a href="https://developer.apple.com/documentation/foundation/nsmutabledictionary?language=objc" rel="nofollow noreferrer">NSMutableDictionary</a>?</p>
<p>And here's a simple example:</p>
<pre><code>NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setObject:anObj forKey:@"foo"];
[dictionary objectForKey:@"foo"];
[dictionary removeObjectForKey:@"foo"];
[dictionary release];
</code></pre> |
280,658 | Can I detect animated gifs using php and gd? | <p>I'm currently running into some issues resizing images using GD.</p>
<p>Everything works fine until i want to resize an animated gif, which delivers the first frame on a black background.</p>
<p>I've tried using <code>getimagesize</code> but that only gives me dimensions and nothing to distinguish between just any gif and an animated one.</p>
<p>Actual resizing is not required for animated gifs, just being able to skip them would be enough for our purposes.</p>
<p>Any clues?</p>
<p>PS. I don't have access to imagemagick.</p>
<p>Kind regards,</p>
<p>Kris</p> | 280,705 | 6 | 1 | null | 2008-11-11 11:32:33.757 UTC | 15 | 2018-03-13 18:45:36.04 UTC | 2008-11-11 11:56:50.54 UTC | Mitch Wheat | 16,076 | Kris | 18,565 | null | 1 | 47 | php|gd | 23,246 | <p>There is a brief snippet of code in the PHP manual page of the <code>imagecreatefromgif()</code> function that should be what you need:</p>
<p><a href="https://php.net/manual/en/function.imagecreatefromgif.php#59787" rel="nofollow noreferrer"><code>imagecreatefromgif</code> comment #59787 by ZeBadger</a></p> |
752,373 | Is it safe to rely on condition evaluation order in if statements? | <p>Is it bad practice to use the following format when <code>my_var</code> can be None?</p>
<pre><code>if my_var and 'something' in my_var:
#do something
</code></pre>
<p><em>The issue is that <code>'something' in my_var</code> will throw a TypeError if my_var is None.</em></p>
<p>Or should I use:</p>
<pre><code>if my_var:
if 'something' in my_var:
#do something
</code></pre>
<p>or </p>
<pre><code>try:
if 'something' in my_var:
#do something
except TypeError:
pass
</code></pre>
<p>To rephrase the question, which of the above is the best practice in Python (if any)?</p>
<p>Alternatives are welcome!</p> | 752,390 | 6 | 0 | null | 2009-04-15 15:57:19.04 UTC | 15 | 2011-11-21 13:08:45.143 UTC | null | null | null | null | 64,206 | null | 1 | 87 | python|if-statement | 34,231 | <p>It's safe to depend on the order of conditionals (<a href="http://docs.python.org/library/stdtypes.html#boolean-operations-and-or-not" rel="noreferrer">Python reference here</a>), specifically because of the problem you point out - it's very useful to be able to short-circuit evaluation that could cause problems in a string of conditionals.</p>
<p>This sort of code pops up in most languages:</p>
<pre><code>IF exists(variable) AND variable.doSomething()
THEN ...
</code></pre> |
473,478 | How to do JSLint in Vim | <p>I spend my days in vim, currently writing a lot of JavaScript. I've been trying to find a way to integrate JSLint or something similar into vim to improve my coding. Has anyone managed to do something like this?</p>
<p>I tried this: <a href="http://mikecantelon.com/story/javascript-syntax-checking-vim" rel="nofollow noreferrer">Javascript Syntax Checking From Vim</a>, unfortunately the output is very crude.</p> | 496,086 | 6 | 0 | null | 2009-01-23 16:10:29.47 UTC | 110 | 2022-04-06 09:19:01.71 UTC | 2022-04-06 09:19:01.71 UTC | uidzer0 | 5,446,749 | uidzer0 | 40,843 | null | 1 | 121 | javascript|vim|lint | 40,943 | <p>You can follow the intructions from <a href="http://wiki.whatwg.org/wiki/IDE" rel="noreferrer">JSLint web-service + VIM integration</a> or do what I did:</p>
<p>Download <a href="http://jslint.webvm.net/mylintrun.js" rel="noreferrer">http://jslint.webvm.net/mylintrun.js</a> and <a href="http://www.jslint.com/fulljslint.js" rel="noreferrer">http://www.jslint.com/fulljslint.js
</a> and put them in a directory of your choice.</p>
<p>Then add the following line to the beginning of mylintrun.js:</p>
<pre><code>var filename= arguments[0];
</code></pre>
<p>and change last line of code in mylintrun.js ("print( ...)") to:</p>
<pre><code> print ( filename + ":" + (obj["line"] + 1) + ":" + (obj["character"] + 1) + ":" + obj["reason"] );
</code></pre>
<p>This makes in mylintrun.js output a error list that can be used with the VIM quickfix window (:copen).</p>
<p>Now set the following in VIM:</p>
<pre><code>set makeprg=cat\ %\ \\\|\ /my/path/to/js\ /my/path/to/mylintrun.js\ %
set errorformat=%f:%l:%c:%m
</code></pre>
<p>where you have to change <em>/my/path/to/js</em> to the path to SpiderMonkey and <em>/my/path/to/mylintrun.js</em> to the path where you put the JS files.</p>
<p>Now, you can use <strong>:make</strong> in VIM and use the <em>quickfix</em> window (:he quickfix-window) to jump from error to error.</p> |
30,972,252 | How do I delete my Google Cloud Platform Account? | <p>I have 2 cloud accounts and only need one, how do I delete or cancel my account so I do not have to pay for the one?</p> | 30,992,122 | 8 | 4 | null | 2015-06-22 04:45:35.673 UTC | 9 | 2022-04-18 16:25:26.993 UTC | null | null | null | null | 4,855,065 | null | 1 | 31 | google-cloud-platform | 73,670 | <p>By "account", I assume that you mean "Google Cloud Platform project", because a "Google Cloud Platform Account" is the same as a Google account, assuming you're referring to user credentials. You don't pay for such an account; you only pay for the resources you use, which are attached to a project.</p>
<p>You can easily delete a project from <a href="https://console.cloud.google.com" rel="noreferrer">Google Cloud Console</a> — once you delete it, it will delete any contained resources and you won't be charged for them.</p>
<hr>
<p>Note that a project will not cost you anything if it is not consuming any resources.</p>
<p>Thus, there's no need to delete or cancel either your email accounts or projects. As soon as you stop using resources within a particular project, you will stop being charged for those resources.</p> |
39,298,474 | Java thread executing remainder operation in a loop blocks all other threads | <p>The following code snippet executes two threads, one is a simple timer logging every second, the second is an infinite loop that executes a remainder operation:</p>
<pre><code>public class TestBlockingThread {
private static final Logger LOGGER = LoggerFactory.getLogger(TestBlockingThread.class);
public static final void main(String[] args) throws InterruptedException {
Runnable task = () -> {
int i = 0;
while (true) {
i++;
if (i != 0) {
boolean b = 1 % i == 0;
}
}
};
new Thread(new LogTimer()).start();
Thread.sleep(2000);
new Thread(task).start();
}
public static class LogTimer implements Runnable {
@Override
public void run() {
while (true) {
long start = System.currentTimeMillis();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// do nothing
}
LOGGER.info("timeElapsed={}", System.currentTimeMillis() - start);
}
}
}
}
</code></pre>
<p>This gives the following result:</p>
<pre><code>[Thread-0] INFO c.m.c.concurrent.TestBlockingThread - timeElapsed=1004
[Thread-0] INFO c.m.c.concurrent.TestBlockingThread - timeElapsed=1003
[Thread-0] INFO c.m.c.concurrent.TestBlockingThread - timeElapsed=13331
[Thread-0] INFO c.m.c.concurrent.TestBlockingThread - timeElapsed=1006
[Thread-0] INFO c.m.c.concurrent.TestBlockingThread - timeElapsed=1003
[Thread-0] INFO c.m.c.concurrent.TestBlockingThread - timeElapsed=1004
[Thread-0] INFO c.m.c.concurrent.TestBlockingThread - timeElapsed=1004
</code></pre>
<p>I don't understand why the infinite task blocks all other threads for 13.3 seconds. I tried to change thread priorities and other settings, nothing worked.</p>
<p>If you have any suggestions to fix this (including tweaking OS context switching settings) please let me know. </p> | 39,298,768 | 4 | 27 | null | 2016-09-02 18:10:27.753 UTC | 47 | 2016-09-08 15:55:57.963 UTC | 2016-09-07 07:07:07.507 UTC | null | 545,127 | null | 492,936 | null | 1 | 126 | java|multithreading | 8,688 | <p>After all the explanations here (thanks to <a href="https://stackoverflow.com/users/57695/peter-lawrey">Peter Lawrey</a>) we found that the main source of this pause is that safepoint inside the loop is reached rather rarely so it takes a long time to stop all threads for JIT-compiled code replacement. </p>
<p>But I decided to go deeper and find <strong><em>why</em></strong> safepoint is reached rarely. I found it a bit confusing why the back jump of <code>while</code> loop is not "safe" in this case.</p>
<p>So I summon <code>-XX:+PrintAssembly</code> in all its glory to help</p>
<pre><code>-XX:+UnlockDiagnosticVMOptions \
-XX:+TraceClassLoading \
-XX:+DebugNonSafepoints \
-XX:+PrintCompilation \
-XX:+PrintGCDetails \
-XX:+PrintStubCode \
-XX:+PrintAssembly \
-XX:PrintAssemblyOptions=-Mintel
</code></pre>
<p>After some investigation I found that after third recompilation of lambda <code>C2</code> compiler threw away safepoint polls inside loop completely.</p>
<p><strong>UPDATE</strong></p>
<p>During the profiling stage variable <code>i</code> was never seen equal to 0. That's why <code>C2</code> speculatively optimized this branch away, so that the loop was transformed to something like</p>
<pre><code>for (int i = OSR_value; i != 0; i++) {
if (1 % i == 0) {
uncommon_trap();
}
}
uncommon_trap();
</code></pre>
<p>Note that originally infinite loop was reshaped to a regular finite loop with a counter! Due to JIT optimization to eliminate safepoint polls in finite counted loops, there was no safepoint poll in this loop either.</p>
<p>After some time, <code>i</code> wrapped back to <code>0</code>, and the uncommon trap was taken. The method was deoptimized and continued execution in the interpreter. During recompilation with a new knowledge <code>C2</code> recognized the infinite loop and gave up compilation. The rest of the method proceeded in the interpreter with proper safepoints.</p>
<p>There is a great must-read blog post <a href="http://psy-lob-saw.blogspot.ru/2015/12/safepoints.html" rel="nofollow noreferrer">"Safepoints: Meaning, Side Effects and Overheads"</a> by <a href="https://stackoverflow.com/users/1047667/nitsan-wakart">Nitsan Wakart</a> covering safepoints and this particular issue.</p>
<p>Safepoint elimination in very long counted loops is known to be a problem. The bug <a href="https://bugs.openjdk.java.net/browse/JDK-5014723" rel="nofollow noreferrer"><code>JDK-5014723</code></a> (thanks to <a href="https://twitter.com/iwan0www" rel="nofollow noreferrer">Vladimir Ivanov</a>) addresses this problem.</p>
<p>The workaround is available until the bug is finally fixed.</p>
<ol>
<li>You can try using <a href="https://bugs.openjdk.java.net/browse/JDK-6869327" rel="nofollow noreferrer"><code>-XX:+UseCountedLoopSafepoints</code></a> (it <em>will</em> cause overall performance penalty and <strong>may lead to JVM crash</strong> <a href="https://bugs.openjdk.java.net/browse/JDK-8161147" rel="nofollow noreferrer"><code>JDK-8161147</code></a>). After using it <code>C2</code> compiler continue keeping safepoints at the back jumps and original pause disappears completely.</li>
<li><p>You can explicitly disable compilation of problematic method by using<br/>
<code>-XX:CompileCommand='exclude,binary/class/Name,methodName'</code></p></li>
<li><p>Or you can rewrite your code by adding safepoint manually. For example <code>Thread.yield()</code> call at the end of cycle or even changing <code>int i</code> to <code>long i</code> (thanks, <a href="https://stackoverflow.com/users/1047667/nitsan-wakart">Nitsan Wakart</a>) will also fix pause.</p></li>
</ol> |
17,887,265 | how to #include third party libraries | <p>I have built and installed a library called <a href="http://wiki.openhome.org/wiki/OhNet" rel="noreferrer">OhNet</a>. After <code>make install</code> the corresponding header files of the framework have been installed under <code>usr/local/include/ohNet</code>. Now I want to use the Library in my C++ project (i am using eclipse) but when i try to include some header files, eclipse is not able to find the files.
As far as i know eclipse should search for header files in these directories (/usr/include , /usr/local/include ,...) by default.... What do i have to do to use the library?
I am pretty new to C++ and haven't used third party sources before.</p>
<p>Thank you.</p>
<p>--EDIT--
I simply want to write an easy "helloworld" programm to verify that i have included the framework correctly. In order to do that i want to instatiate the class <code>OpenHome::Net::DvDeviceStdStandard</code>. see: <a href="http://www.openhome.org/build/nightly/docs/CppStd/" rel="noreferrer">ohNet C++ reference</a></p>
<p>I can now include the header file using:
<code>#include <ohNet/OpenHome/Net/Core/DvDevice.h></code> That works fine. But how can i create an object of type <code>OpenHome::Net::DvDeviceStdStandard</code> ? now? Eclipse says that this type cannot be resolved. :( </p>
<pre><code>#include <iostream>
#include <ohNet/OpenHome/Net/Core/DvDevice.h>
using namespace std;
int main() {
OpenHome::Net::DvDeviceStdStandard device; //type cannot be resolved
cout << "!!!Hello World!!!" << endl;
return 0;
}
</code></pre> | 17,887,552 | 2 | 4 | null | 2013-07-26 17:15:38.36 UTC | 10 | 2017-02-27 21:49:17.59 UTC | 2017-02-27 21:49:17.59 UTC | null | 311,966 | null | 1,291,235 | null | 1 | 10 | c++|build|include|libraries|include-path | 24,277 | <ol>
<li>Use the <code>-I</code> compiler option to point to the 3rd party libraries directory (<code>-I/usr/local/include/ohNet</code>)</li>
<li>Use <code>#include "[whatever you need from oHNet].h"</code> in your header files and compilation units as needed (<strong>Note:</strong> you might need to put relative prefix pathes for subdirecories in the 3rd party include paths tree here!)</li>
<li>Use the <code>-L</code> linker option to specify a path to the 3rd party libs you need (<code>-L/usr/local/lib</code> probably)</li>
<li>Use the <code>-l</code> linker option to specify any concrete 3rd libs you need (<code>-l[oHNet]</code> probably)</li>
</ol>
<p>Look in the directories what actually was installed there to figure what to place for <code>[whatever you need from oHNet].h</code> and <code>[oHNet]</code>, s.th. like <code>liboHNet.a</code> for the latter.</p>
<p>You didn't tag [tag:Eclipse CDT] explicitly here, but go to the Project->Properties->C++ Builder->Settings Dialog and look for C/C++ Includes and Linker Options.</p> |
17,807,929 | JavaScript get href onclick | <p>I am trying to return the <code>href</code> attribute of a link using JavaScript when the user clicks on it. I want the URL the link is linking to displayed in an alert instead of loading the page.</p>
<p>I have the following code so far:</p>
<pre><code>function doalert(){
alert(document.getElementById("link").getAttribute("href"));
return false;
}
</code></pre>
<p>With the following markup:</p>
<pre><code><a href="http://www.example.com/" id="link" onclick="return doalert()">Link</a>
</code></pre>
<p>For some reason, <strong>no alert is ever displayed and the page loads instead.</strong> Does anyone know why this is?</p>
<p>Using jQuery is not an option in this case.</p> | 17,808,032 | 2 | 0 | null | 2013-07-23 10:43:36.55 UTC | 4 | 2013-07-23 10:51:21.653 UTC | null | null | null | null | 506,399 | null | 1 | 15 | javascript|html | 100,822 | <p>Seems to be the order of your code, try this</p>
<pre><code><script>
function doalert(obj) {
alert(obj.getAttribute("href"));
return false;
}
</script>
<a href="http://www.example.com/" id="link" onclick="doalert(this); return false;">Link</a>
</code></pre>
<p><a href="http://jsfiddle.net/YZ8yV/" rel="noreferrer">http://jsfiddle.net/YZ8yV/</a></p>
<p><a href="http://jsfiddle.net/YZ8yV/2/" rel="noreferrer">http://jsfiddle.net/YZ8yV/2/</a></p> |
46,658,847 | Crypto Currency MySQL Datatypes ? | <h2>The infamous question about datatypes when storing money values in an SQL database.</h2>
<p>However in these trying times, we now have currencies that have worth up to 18 decimal places (thank you ETH).</p>
<p>This now reraises the classic argument.</p>
<p><strong>IDEAS</strong></p>
<p><strong>Option 1</strong> <code>BIGINT</code> Use a big integer to save the real value, then store how many decimal places the currency has (simply dividing <code>A</code> by <code>10^B</code> in translation)?</p>
<p><strong>Option 2</strong> <code>Decimal(60,30)</code> Store the datatype in a large decimal, which inevitibly will cost a large amount of space.</p>
<p><strong>Option 3</strong> <code>VARCHAR(64)</code> Store in a string. Which would have a performance impact.</p>
<hr />
<p>I want to know peoples thoughts and what they are using if they are dealing with cryptocurrency values. As I am stumped with the best method for proceeding.</p> | 48,555,882 | 1 | 3 | null | 2017-10-10 04:55:08.397 UTC | 6 | 2018-02-01 05:24:48.67 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 1,849,429 | null | 1 | 28 | mysql|sql|currency|sqldatatypes | 7,923 | <p>There's a clear best option out of the three you suggested (plus one from the comments).</p>
<p><strong>BIGINT</strong> — uses just 8 bytes, but the largest <code>BIGINT</code> only has 19 decimal digits; if you divide by 10<sup>18</sup>, the largest value you can represent is 9.22, which isn't enough range.</p>
<p><strong>DOUBLE</strong> — only has 15–17 decimal digits of precision; has all the known drawbacks of floating-point arithmetic.</p>
<p><strong>VARCHAR</strong> — will use 20+ bytes if you're dealing with 18 decimal places; will require constant string↔int conversions; can't be sorted; can't be compared; can't be added in DB; many downsides.</p>
<p><strong>DECIMAL(27,18)</strong> – if using MySQL, this will take 12 bytes (<a href="https://dev.mysql.com/doc/refman/5.7/en/precision-math-decimal-characteristics.html" rel="noreferrer">4 for each group of 9 digits</a>). This is quite a reasonable storage size, and has enough range to support amounts as large as one billion or as small as one Wei. It can be sorted, compared, added, subtracted, etc. in the database without loss of precision.</p>
<p>I would use <code>DECIMAL(27,18)</code> (or <code>DECIMAL(36,18)</code> if you need to store truly huge values) to store cryptocurrency money values.</p> |
2,105,979 | For interfaces with one implementation how can I just directly go to that implementation? | <p>I often have to debug Java code which was written so that there is an interface and exactly one implementation of that interface.</p>
<p>For instance there would be an interface Foo with exactly one implementation called <code>FooImpl</code>. In the following code if I Ctrl-click on <code>doThings</code> it'll jump to <code>Foo.java</code> when I actually want to go to <code>FooImpl.java</code> to see the implementation.</p>
<pre><code>public void doStuff(Foo foo) {
foo.doThings();
}
</code></pre>
<p>When I end up at the interface I have to use Ctrl-Shift-R to open up <code>FooImpl</code>. It'd be really nice if I could do something lick Ctrl-Alt-click on <code>doThings</code> and end up inside <code>FooImpl.java</code>. If there are multiple implementations in the workspace then perhaps it would just pop up a box telling me what they are.</p>
<p>Is there a plugin or existing function in eclipse that does this? I know that I could go to <code>Foo.java</code> and then get the hierarchy and go to the implementation, but that's more clicks than are necessary when there is exactly one implementation of an interface.</p> | 2,106,233 | 5 | 3 | null | 2010-01-20 23:59:16.217 UTC | 13 | 2022-09-09 09:18:57.91 UTC | 2022-09-09 09:18:57.91 UTC | null | 452,775 | null | 124,696 | null | 1 | 41 | java|eclipse|keyboard-shortcuts | 35,276 | <p>The <a href="http://eclipse-tools.sourceforge.net/implementors/" rel="noreferrer">Implementors</a> plugin does pretty much exactly what you ask for. If there is only one implementation it will open it directly, otherwise it will let you choose.</p> |
1,438,141 | how to get list of port which are in use on the server | <p>How to get list of ports which are in use on the server?</p> | 1,438,160 | 5 | 0 | null | 2009-09-17 11:03:31.02 UTC | 10 | 2018-07-13 09:00:09.31 UTC | 2017-06-14 09:58:55.293 UTC | null | 1,285,055 | null | 136,161 | null | 1 | 47 | networking|port|windows-server-2003 | 201,647 | <p>Open up a command prompt then type...</p>
<pre><code>netstat -a
</code></pre> |
1,470,939 | string encryption/decryption | <p>I am interested if it's possible to do string encryption/decryption using Excel Visual Basic and some cryptographic service provider.</p>
<p>I have found a walk-through <a href="http://msdn.microsoft.com/en-us/library/ms172831.aspx" rel="nofollow noreferrer">Encrypting and Decrypting Strings in Visual Basic</a>, but it seems it's valid for standalone Visual Basic only.</p>
<p>So would you suggest me another encryption method or show how the walk-through could be adopted for Excel Visual Basic?</p> | 1,471,093 | 6 | 0 | null | 2009-09-24 10:53:47.657 UTC | 8 | 2020-07-05 16:45:16.677 UTC | 2020-07-05 16:45:16.677 UTC | null | 8,422,953 | null | 11,256 | null | 1 | 14 | excel|vba|string|encryption | 93,050 | <p>The link you provide shows how to perform string encryption and decryption using VB.NET, and thus, using the .NET Framework.</p>
<p>Currently, Microsoft Office products cannot yet use the <a href="http://en.wikipedia.org/wiki/Visual_Studio_Tools_for_Applications" rel="nofollow noreferrer">Visual Studio Tools for Applications</a> component which will enable Office products to access the .NET framework's BCL (base class libraries) which, in turn, access the underlying Windows CSP (cryptographic server provider) and provide a nice wrapper around those encryption/decryption functions.</p>
<p>For the time being, Office products are stuck with the old VBA (<a href="http://en.wikipedia.org/wiki/Visual_Basic_for_Applications" rel="nofollow noreferrer">Visual Basic for Applications</a>) which is based on the old VB6 (and earlier) versions of visual Basic which are based upon COM, rather than the .NET Framework.</p>
<p>Because of all of this, you will either need to call out to the Win32 API to access the CSP functions, or you will have to "roll-your-own" encryption method in pure VB6/VBA code, although this is likely to be less secure. It all depends upon how "secure" you'd like your encryption to be.</p>
<p>If you want to "roll-your-own" basic string encryption/decryption routine, take a look at these link to get you started:</p>
<p><a href="http://www.devx.com/tips/Tip/5676" rel="nofollow noreferrer">Encrypt a String Easily</a><br>
<strike><a href="http://www.codetoad.com/visual_basic_better_xor.asp" rel="nofollow noreferrer">Better XOR Encryption with a readable string</a></strike></p>
<p><a href="http://www.vbforums.com/showthread.php?t=334313" rel="nofollow noreferrer">vb6 - encryption function</a><br>
<strike><a href="http://paste2.org/p/435362" rel="nofollow noreferrer">Visual Basic 6 / VBA String Encryption/Decryption Function</a></strike></p>
<p>If you want to access the Win32 API and use the underlying Windows CSP (a much more secure option), see these links for detailed information on how to achieve this:</p>
<p><strike><a href="http://support.microsoft.com/kb/821762" rel="nofollow noreferrer">How to encrypt a string in Visual Basic 6.0</a></strike></p>
<p><a href="http://social.msdn.microsoft.com/Forums/en-US/isvvba/thread/84d49593-2d8e-4e7c-af3a-61882af9557d" rel="nofollow noreferrer">Access to CryptEncrypt (CryptoAPI/WinAPI) functions in VBA</a></p>
<p>That last link is likely the one you'll want and includes a complete VBA Class module to "wrap" the Windows CSP functions.</p> |
1,411,089 | How to stop GHC from generating intermediate files? | <p>When compiling a haskell source file via <code>ghc --make foo.hs</code> GHC always leaves behind a variety of intermediate files other than <code>foo.exe</code>. These are <code>foo.hi</code> and <code>foo.o</code>.</p>
<p>I often end up having to delete the .hi and .o files to avoid cluttering up the folders.</p>
<p>Is there a command line option for GHC not to leave behind its intermediate files? (When asked on #haskell, the best answer I got was <code>ghc --make foo.hs && rm foo.hi foo.o</code>.</p> | 1,411,994 | 6 | 0 | null | 2009-09-11 14:08:07.64 UTC | 3 | 2021-09-13 17:19:54.827 UTC | null | null | null | unknown | null | null | 1 | 40 | haskell|ghc | 7,675 | <p>I've gone through the GHC docs a bit, and there doesn't seem to be a built-in way to remove the temporary files automatically -- after all, GHC needs those intermediate files to build the final executable, and their presence speeds up overall compilation when GHC knows it doesn't have to recompile a module.</p>
<p>However, you might find that <a href="http://haskell.org/ghc/docs/latest/html/users_guide/separate-compilation.html" rel="noreferrer">setting the <code>-outputdir</code> option</a> will help you out; that will place all of your object files (<code>.o</code>), interface files (<code>.hi</code>), and FFI stub files in the specified directory. It's still "clutter," but at least it's not in your working directory anymore.</p> |
1,984,464 | Make private methods final? | <p>Is it beneficial to make private methods final? Would that improve performance?</p>
<p>I think "private final" doesn't make much sense, because a private method cannot be overridden. So the method lookup should be efficient as when using final.</p>
<p>And would it be better to make a private helper method static (when possible)?</p>
<p>What's best to use?</p>
<pre><code> private Result doSomething()
private final Result doSomething()
private static Result doSomething()
private static final Result doSomething()
</code></pre> | 1,985,183 | 6 | 1 | null | 2009-12-31 08:01:20.22 UTC | 8 | 2012-11-29 11:15:24.537 UTC | null | null | null | null | 238,134 | null | 1 | 51 | java|final | 18,238 | <p>Adding <code>final</code> to methods does not improve performance with Sun HotSpot. Where <code>final</code> could be added, HotSpot will notice that the method is never overridden and so treat it the same.</p>
<p>In Java <code>private</code> methods are non-virtual. You can't override them, even using nested classes where they may be accessible to subclasses. For instance methods the instructoin to call privates is different from that used for non-privates. Adding <code>final</code> to private methods makes no odds.</p>
<p>As ever, these sort of micro-optimisations are not worth spending time on.</p> |
1,468,007 | AtomicInteger lazySet vs. set | <p>What is the difference between the <code>lazySet</code> and <code>set</code> methods of <code>AtomicInteger</code>? The <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html#lazySet-int-" rel="noreferrer">documentation</a> doesn't have much to say about <code>lazySet</code>:</p>
<blockquote>
<p>Eventually sets to the given value.</p>
</blockquote>
<p>It seems that the stored value will not be immediately set to the desired value but will instead be scheduled to be set some time in the future. But, what is the practical use of this method? Any example?</p> | 1,468,020 | 6 | 1 | null | 2009-09-23 19:07:23.407 UTC | 49 | 2020-06-13 18:52:28.457 UTC | 2014-09-03 17:34:25.1 UTC | null | 285,873 | null | 72,437 | null | 1 | 127 | java|concurrency|atomic | 33,011 | <p>Cited straight from <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6275329" rel="noreferrer">"JDK-6275329: Add lazySet methods to atomic classes"</a>:</p>
<blockquote>
<p>As probably the last little JSR166 follow-up for Mustang,
we added a "lazySet" method to the Atomic classes
(AtomicInteger, AtomicReference, etc). This is a niche
method that is sometimes useful when fine-tuning code using
non-blocking data structures. The semantics are
that the write is guaranteed not to be re-ordered with any
previous write, but may be reordered with subsequent operations
(or equivalently, might not be visible to other threads) until
some other volatile write or synchronizing action occurs).</p>
<p>The main use case is for nulling out fields of nodes in
non-blocking data structures solely for the sake of avoiding
long-term garbage retention; it applies when it is harmless
if other threads see non-null values for a while, but you'd
like to ensure that structures are eventually GCable. In such
cases, you can get better performance by avoiding
the costs of the null volatile-write. There are a few
other use cases along these lines for non-reference-based
atomics as well, so the method is supported across all of the
AtomicX classes.</p>
<p>For people who like to think of these operations in terms of
machine-level barriers on common multiprocessors, lazySet
provides a preceeding store-store barrier (which is either
a no-op or very cheap on current platforms), but no
store-load barrier (which is usually the expensive part
of a volatile-write).</p>
</blockquote> |
1,966,010 | What does this mean? "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM" | <p>T_PAAMAYIM_NEKUDOTAYIM sounds really exotic, but most certainly absolutely nonsense to me. I traced it all down to this lines of code:</p>
<pre><code><?php
Class Context {
protected $config;
public function getConfig($key) { // Here's the problem somewhere...
$cnf = $this->config;
return $cnf::getConfig($key);
}
function __construct() {
$this->config = new Config();
}
}
?>
</code></pre>
<p>In the constructor I create a Config object. Here's the class:</p>
<pre><code>final class Config {
private static $instance = NULL;
private static $config;
public static function getConfig($key) {
return self::$config[$key];
}
public static function getInstance() {
if (!self::$instance) {
self::$instance = new Config();
}
return self::$instance;
}
private function __construct() {
// include configuration file
include __ROOT_INCLUDE_PATH . '/sys/config/config.php'; // defines a $config array
$this->config = $config;
}
}
</code></pre>
<p>No idea why this doesnt work / what the error means...</p> | 1,966,020 | 8 | 1 | null | 2009-12-27 14:02:50.36 UTC | 11 | 2020-09-29 11:58:31.843 UTC | null | null | null | null | 221,023 | null | 1 | 65 | php | 112,808 | <p>T_PAAMAYIM_NEKUDOTAYIM is the double colon scope resolution thingy PHP uses - ::</p>
<p>Quick glance at your code, I think this line:</p>
<pre><code>return $cnf::getConfig($key);
</code></pre>
<p>should be</p>
<pre><code>return $cnf->getConfig($key);
</code></pre>
<p>The first is the way to call a method statically - this code would be valid if $cnf contained a string that was also a valid class. The -> syntax is for calling a method on an instance of a class/object.</p> |
2,067,472 | What is JSONP, and why was it created? | <p>I understand JSON, but not JSONP. <a href="http://en.wikipedia.org/wiki/JSON" rel="noreferrer">Wikipedia's document on JSON</a> is (was) the top search result for JSONP. It says this:</p>
<blockquote>
<p>JSONP or "JSON with padding" is a JSON extension wherein a prefix is specified as an input argument of the call itself.</p>
</blockquote>
<p>Huh? What call? That doesn't make any sense to me. JSON is a data format. There's no call.</p>
<p>The <a href="http://remysharp.com/2007/10/08/what-is-jsonp/" rel="noreferrer">2nd search result</a> is from some guy named <a href="https://stackoverflow.com/users/22617/remy-sharp">Remy</a>, who writes this about JSONP:</p>
<blockquote>
<p>JSONP is script tag injection, passing the response from the server in to a user specified function.</p>
</blockquote>
<p>I can sort of understand that, but it's still not making any sense.</p>
<hr>
<p>So what is JSONP? Why was it created (what problem does it solve)? And why would I use it? </p>
<hr>
<p><strong>Addendum</strong>: I've just created <a href="http://en.wikipedia.org/wiki/JSONP" rel="noreferrer">a new page for JSONP</a> on Wikipedia; it now has a clear and thorough description of JSONP, based on <a href="https://stackoverflow.com/users/25330/jvenema">jvenema</a>'s answer.</p> | 2,067,584 | 10 | 4 | null | 2010-01-14 20:53:48.287 UTC | 925 | 2022-09-21 10:49:49.997 UTC | 2019-02-27 14:26:58.997 UTC | null | 123,671 | null | 48,082 | null | 1 | 2,376 | javascript|json|jsonp|terminology | 572,221 | <p>It's actually not too complicated...</p>
<p>Say you're on domain <strong><code>example.com</code></strong>, and you want to make a request to domain <strong><code>example.net</code></strong>. To do so, you need to <strong>cross domain</strong> boundaries, a <strong>no-no</strong> in most of browserland. </p>
<p>The one item that bypasses this limitation is <code><script></code> tags. When you use a script tag, the domain limitation is ignored, but under normal circumstances, you can't really <strong>do</strong> anything with the results, the script just gets evaluated.</p>
<p>Enter <strong><code>JSONP</code></strong>. When you make your request to a server that is JSONP enabled, you pass a special parameter that tells the server a little bit about your page. That way, the server is able to nicely wrap up its response in a way that your page can handle. </p>
<p>For example, say the server expects a parameter called <strong><code>callback</code></strong> to enable its JSONP capabilities. Then your request would look like:</p>
<pre class="lang-none prettyprint-override"><code>http://www.example.net/sample.aspx?callback=mycallback
</code></pre>
<p>Without JSONP, this might return some basic JavaScript object, like so:</p>
<pre><code>{ foo: 'bar' }
</code></pre>
<p>However, with JSONP, when the server receives the "callback" parameter, it wraps up the result a little differently, returning something like this:</p>
<pre><code>mycallback({ foo: 'bar' });
</code></pre>
<p>As you can see, it will now invoke the method you specified. So, in your page, you define the callback function:</p>
<pre><code>mycallback = function(data){
alert(data.foo);
};
</code></pre>
<p>And now, when the script is loaded, it'll be evaluated, and your function will be executed. Voila, cross-domain requests!</p>
<p>It's also worth noting the one major issue with JSONP: you lose a lot of control of the request. For example, there is no "nice" way to get proper failure codes back. As a result, you end up using timers to monitor the request, etc, which is always a bit suspect. The proposition for <a href="http://www.json.org/JSONRequest.html" rel="noreferrer">JSONRequest</a> is a great solution to allowing cross domain scripting, maintaining security, and allowing proper control of the request.</p>
<p>These days (2015), <a href="http://en.wikipedia.org/wiki/Cross-origin_resource_sharing" rel="noreferrer">CORS</a> is the recommended approach vs. JSONRequest. JSONP is still useful for older browser support, but given the security implications, unless you have no choice CORS is the better choice.</p> |
1,586,882 | How do I convert a byte array to a long in Java? | <p>I am reading 8 bytes of data in from a hardware device. I need to convert them into a numeric value. I think I want to convert them to a long as that should fit 8 bytes. I am not very familiar with Java and low level data type operations. I seem to have two problems (apart from the fact there is almost no documentation for the hardware in question), The bytes are expecting to be unsigned, so I can't do a straight integer conversion. I am not sure what endianness they are.</p>
<p>Any advice would be appreciated.</p>
<hr>
<p>Ended up with this (taken from some source code I probably should have read a week ago):</p>
<pre><code>public static final long toLong (byte[] byteArray, int offset, int len)
{
long val = 0;
len = Math.min(len, 8);
for (int i = (len - 1); i >= 0; i--)
{
val <<= 8;
val |= (byteArray [offset + i] & 0x00FF);
}
return val;
}
</code></pre> | 1,586,894 | 11 | 4 | null | 2009-10-19 03:55:30.55 UTC | 3 | 2021-10-16 08:11:21.87 UTC | 2021-05-04 21:29:33.23 UTC | null | 423,105 | null | 78,428 | null | 1 | 7 | java | 41,563 | <p>For the endianness, test with some numbers you know, and then you will be using a byte shifting to move them into the long.</p>
<p>You may find this to be a starting point.
<a href="http://www.janeg.ca/scjp/oper/shift.html" rel="nofollow noreferrer">http://www.janeg.ca/scjp/oper/shift.html</a></p>
<p>The difficulty is that depending on the endianess will change how you do it, but you will shift by 24, 16, 8 then add the last one, basically, if doing 32 bits, but you are going longer, so just do extra shifting.</p> |
2,177,116 | Absolute DIV height 100% | <p>I have been working on this for the past couple of hours, and searching the web and stackoverflow hasn't been much support. How do I make <code>#gradient</code> and <code>#holes</code> fill the entire page?</p>
<p>I have used the Inspect Element feature in Safari, and when I highlight the body element it does not fill the entire window.<br>
<a href="https://i.stack.imgur.com/C1cNw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C1cNw.png" alt="alt text"></a>
</p>
<p>HTML:</p>
<pre><code><body>
<div id="gradient"></div>
<div id="holes"></div>
<div id="header">Header Text</div>
</body>
</code></pre>
<p>CSS:</p>
<pre class="lang-css prettyprint-override"><code>html, body {
height:100%;
margin:0;
padding:0;
}
body {
background-image:url(../Images/Tile.png);
background-color:#7D7D7D;
background-repeat:repeat;
}
#gradient {
background-image:url(../Images/Background.png);
background-repeat:repeat-x;
position:absolute;
top:0px;
left:0px;
height:100%;
right:0px;
}
#holes {
background-image:url(../Images/Holes.png);
background-repeat:repeat;
position:absolute;
top:2px;
left:2px;
height:100%;
right:0px;
}
#header {
background-image:url(../Images/Header.png);
background-repeat:repeat-x;
position:absolute;
top:0px;
left:0px;
width:100%;
padding-top:24px;
height:49px; /* 73 - padding */
color:rgb(113, 120, 128);
font-family:Helvetica, Arial;
font-weight:bold;
font-size:24px;
text-align:center;
text-shadow:#FFF 0px 1px 0px;
}
</code></pre> | 2,177,518 | 11 | 5 | null | 2010-02-01 13:59:01.887 UTC | 7 | 2019-06-11 13:06:19.693 UTC | 2019-06-11 13:06:19.693 UTC | null | 4,751,173 | null | 147,091 | null | 1 | 24 | css|html|height|absolute | 58,557 | <p>Well it looks to me that your element with all the content is floated. If it is then its not going to expand the body unless it is cleared. </p> |
1,735,550 | Find the minimum number in an array with recursion? | <pre><code>int i = 0;
int min = x[i];
while ( i < n ){
if ( x[i] < min ){
min = x[i];
}
i++;
}
return min;
</code></pre>
<p>I've written the iterative form to find the min number of an array. But I'd like to write a function that with recursion. Please help!</p> | 1,735,557 | 12 | 4 | null | 2009-11-14 20:49:09.267 UTC | null | 2022-06-07 07:18:12.9 UTC | 2009-11-14 20:55:36.43 UTC | null | 8,976 | null | 133,466 | null | 1 | 3 | c|recursion | 47,326 | <p>Because this sounds like homework, here's a hint: The minimum value in an array is either the first element, or the minimum number in the <em>rest</em> of the array, whichever is smaller.</p> |
33,940,015 | How to choose the Redux state shape for an app with list/detail views and pagination? | <p>Imagine I have a number of entries(say, users) in my database. I also have two routes, one for list, other for detail(where you can edit the entry). Now I'm struggling with how to approach the data structure. </p>
<p>I'm thinking of two approaches and a kinda combination of both.</p>
<h2>Shared data set</h2>
<ul>
<li>I navigate to <code>/list</code>, all of my users are downloaded from api a stored in redux store, under the key <code>users</code>, I also add some sort of <code>users_offset</code> and <code>users_limit</code> to render only part of the of the list</li>
<li>I then navigate to <code>/detail/<id></code>, and store <code>currently_selected_user</code> with <code><id></code> as the val... which means I will be able to get my user's data with something like this <code>users.find(res => res.id === currently_selected_user)</code></li>
<li>updating will be nice and easy as well, since I'm working with just one data set and detail pointing to it</li>
<li>adding a new user also easy, again just working with the same list of users</li>
</ul>
<p>Now the problem I have with this approach is that, when the list of users gets huge(say millions), it might take a while to download. And also, when I navigate directly to <code>/detail/<id></code>, I won't yet have all of my users downloaded, so to get data for just the one I need, I'm gonna have to first download the whole thing. Millions of users just to edit one.</p>
<h2>Separated data set</h2>
<ul>
<li>I navigate to <code>/list</code>, and instead of downloading all of my users from api, I only download a couple of them, depending on what my <code>users_per_page</code> and <code>users_current_page</code> would be set to, and I'd probably store the data as <code>users_currently_visible</code></li>
<li>I then navigate to <code>/detail/<id></code>, store <code>currently_selected_user</code> with <code><id></code> as the val...and instead of searching through <code>users_currently_visible</code> I simply download user's data from api.. </li>
<li>on update, I'm not gonna update <code>users_currently_visible</code> in any way</li>
<li>nor will I on add</li>
</ul>
<p>What I see as possible problem here is that I'm gonna have to, upon visiting <code>/list</code>, download data from api again, because it might not be in sync with what's in the database, I also might be unnecessarily downloading users data in detail, because they might be incidentally already inside my <code>users_currently_visible</code></p>
<h2>some sort of frankenstein-y shenanigans</h2>
<ul>
<li>I detail, I do the same as in <em>Separated data set</em> but instead of directly downloading user's data from api, I first check:
<ul>
<li>do I have any <code>users_currently_visible</code></li>
<li>if so, is there a user with my id between them?
if both are true, I then use it as my user data, otherwise I make the api call</li>
</ul></li>
<li>same happens on update, I check if my user exists between <code>users_currently_visible</code> if so, I also update that list, if not I do nothing</li>
</ul>
<p>This would probably work, but doesn't really feel like it's the proper way. I would also probably still need to download fresh list of <code>users_currently_visible</code> upon visiting <code>/list</code>, because I might have added a new one..</p>
<p>Is there any fan favorite way of doing this?... I'm sure every single one redux user must have encountered the same things.</p>
<p>Thanks!</p> | 33,946,576 | 2 | 3 | null | 2015-11-26 13:31:37.18 UTC | 40 | 2020-08-14 12:27:07.003 UTC | 2016-05-15 11:05:19.143 UTC | null | 301,596 | null | 301,596 | null | 1 | 66 | javascript|redux|ngrx | 14,474 | <p>Please consult <a href="https://github.com/reactjs/redux/tree/master/examples/real-world" rel="noreferrer">“real world” example</a> from Redux repo.<br>
It shows the solution to exactly this problem.</p>
<p>Your state shape should look like this:</p>
<pre><code>{
entities: {
users: {
1: { id: 1, name: 'Dan' },
42: { id: 42, name: 'Mary' }
}
},
visibleUsers: {
ids: [1, 42],
isFetching: false,
offset: 0
}
}
</code></pre>
<p>Note I’m storing <code>entities</code> (ID -> Object maps) and <code>visibleUsers</code> (description of currently visible users with pagination state and IDs) separately.</p>
<p>This seems similar to your “Shared data set” approach. However I don’t think the drawbacks you list are real problems inherent to this approach. Let’s take a look at them.</p>
<blockquote>
<p>Now the problem I have with this approach is that when then list of users gets huge(say millions), it might take a while to download</p>
</blockquote>
<p>You don’t need to download all of them! Merging all downloaded entities to <code>entities</code> doesn’t mean you should query all of them. The <code>entities</code> should contain all entities that have been downloaded <strong>so far</strong>—not all entities in the world. Instead, you’d only download those you’re currently showing according to the pagination information.</p>
<blockquote>
<p>when I navigate directly to /detail/, I wouldn't yet have all of my users downloaded, so to get data for just the one, I'm gonna have to download them all. Millions of users just to edit one.</p>
</blockquote>
<p>No, you’d request just one of them. The response action would fire, and reducer responsible for <code>entities</code> would merge <strong>this single entity</strong> into the existing state. Just because <code>state.entities.users</code> may contain more than one user doesn’t mean you need to download all of them. Think of <code>entities</code> as of a cache that doesn’t <em>have</em> to be filled.</p>
<hr>
<p>Finally, I will direct you again to the <a href="https://github.com/reactjs/redux/tree/master/examples/real-world" rel="noreferrer">“real world” example</a> from Redux repo. It shows exactly how to write a reducer for pagination information and entity cache, and <a href="https://github.com/gaearon/normalizr" rel="noreferrer">how to normalize JSON in your API responses with <code>normalizr</code></a> so that it’s easy for reducers to extract information from server actions in a uniform way.</p> |
17,684,921 | sort json object in javascript | <p>For example with have this code:</p>
<pre><code>var json = {
"user1" : {
"id" : 3
},
"user2" : {
"id" : 6
},
"user3" : {
"id" : 1
}
}
</code></pre>
<p>How can I sort this json to be like this -</p>
<pre><code>var json = {
"user3" : {
"id" : 1
},
"user1" : {
"id" : 3
},
"user2" : {
"id" : 6
}
}
</code></pre>
<p>I sorted the users with the IDs..
<br />
I don't know how to do this in javascript..</p> | 17,685,499 | 4 | 5 | null | 2013-07-16 19:03:47.613 UTC | 23 | 2018-10-13 09:59:20.863 UTC | 2014-09-25 23:32:38.437 UTC | null | 749,725 | null | 1,703,140 | null | 1 | 56 | javascript|json|sorting | 169,702 | <p>First off, that's <strong>not</strong> JSON. It's a JavaScript object literal. JSON is a <em>string representation</em> of data, that just so happens to very closely resemble JavaScript syntax.</p>
<p>Second, you have an object. They are unsorted. The order of the elements cannot be guaranteed. If you want guaranteed order, you <em>need</em> to use an array. This will require you to change your data structure.</p>
<p>One option might be to make your data look like this:</p>
<pre><code>var json = [{
"name": "user1",
"id": 3
}, {
"name": "user2",
"id": 6
}, {
"name": "user3",
"id": 1
}];
</code></pre>
<p>Now you have an array of objects, and we can sort it.</p>
<pre><code>json.sort(function(a, b){
return a.id - b.id;
});
</code></pre>
<p>The resulting array will look like:</p>
<pre><code>[{
"name": "user3",
"id" : 1
}, {
"name": "user1",
"id" : 3
}, {
"name": "user2",
"id" : 6
}];
</code></pre> |
17,685,674 | Nginx proxy_pass with $remote_addr | <p>I'm trying to include $remote_addr or $http_remote_addr on my proxy_pass without success.</p>
<p>The rewrite rule works</p>
<pre><code>location ^~ /freegeoip/ {
rewrite ^ http://freegeoip.net/json/$remote_addr last;
}
</code></pre>
<p>The proxy_pass without the $remote_addr works, but freegeoip does not read the x-Real-IP</p>
<pre><code>location ^~ /freegeoip/ {
proxy_pass http://freegeoip.net/json/;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
}
</code></pre>
<p>Then, I'm adding the ip to the end of the request, like this: </p>
<pre><code>location ^~ /freegeoip/ {
proxy_pass http://freegeoip.net/json/$remote_addr;
}
</code></pre>
<p>but nginx report this error: no resolver defined to resolve freegeoip.net</p> | 22,259,088 | 7 | 2 | null | 2013-07-16 19:48:30.137 UTC | 14 | 2022-04-26 13:15:37.27 UTC | null | null | null | null | 1,052,498 | null | 1 | 62 | nginx|proxypass | 91,859 | <p>If the proxy_pass statement has no variables in it, then it will use the "gethostbyaddr" system call during start-up or reload and will cache that value permanently.</p>
<p>if there are any variables, such as using either of the following:</p>
<pre><code>set $originaddr http://origin.example.com;
proxy_pass $originaddr;
# or even
proxy_pass http://origin.example.com$request_uri;
</code></pre>
<p>Then nginx will use a built-in resolver, and the "resolver" directive <em>must</em> be present. "resolver" is probably a misnomer; think of it as "what DNS server will the built-in resolver use". Since nginx 1.1.9 the built-in resolver will honour DNS TTL values. Before then it used a fixed value of 5 minutes.</p> |
17,853,898 | The name 'InitializeComponent' does not exist in the current context. Cannot get any help on net searches | <p>Hi I am getting an error of <code>InitializeComponent</code> in my <code>app.xaml.cs</code> page I have checked the net and everything but no solution works. Please help.</p>
<p><a href="https://stackoverflow.com/questions/6925584/the-name-initializecomponent-does-not-exist-in-the-current-context">InitializeComponent does not exist</a></p>
<p>C# file:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;
namespace Miser_sApp
{
public partial class App : Application
{
/// <summary>
/// Provides easy access to the root frame of the Phone Application.
/// </summary>
/// <returns>The root frame of the Phone Application.</returns>
public PhoneApplicationFrame RootFrame { get; private set; }
/// <summary>
/// Constructor for the Application object.
/// </summary>
public App()
{
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Standard Silverlight initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
// Show graphics profiling information while debugging.
if (System.Diagnostics.Debugger.IsAttached)
{
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are handed off to GPU with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
// Disable the application idle detection by setting the UserIdleDetectionMode property of the
// application's PhoneApplicationService object to Disabled.
// Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
// and consume battery power when the user is not using the phone.
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
}
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}
// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
}
// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}
// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
}
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
#region Phone application initialization
// Avoid double-initialization
private bool phoneApplicationInitialized = false;
// Do not add any additional code to this method
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Ensure we don't initialize again
phoneApplicationInitialized = true;
}
// Do not add any additional code to this method
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// Set the root visual to allow the application to render
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// Remove this handler since it is no longer needed
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
#endregion
}
}
</code></pre>
<p>XAML file:</p>
<pre><code><Application
x:Class="Miser_sApp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone">
<!--Application Resources-->
<Application.Resources>
</Application.Resources>
<Application.ApplicationLifetimeObjects>
<!--Required object that handles lifetime events for the application-->
<shell:PhoneApplicationService
Launching="Application_Launching" Closing="Application_Closing"
Activated="Application_Activated" Deactivated="Application_Deactivated"/>
</Application.ApplicationLifetimeObjects>
</Application>
</code></pre>
<p>I have uploaded the <code>app.xaml</code> contents.
I have not made any changes in it.</p> | 19,873,833 | 10 | 0 | null | 2013-07-25 09:19:41.08 UTC | 6 | 2018-11-22 18:10:49.367 UTC | 2017-09-07 13:17:32.257 UTC | null | 6,113,711 | null | 2,598,085 | null | 1 | 38 | c#|.net|windows-phone-7|windows-phone-8 | 94,510 | <p><strong>There are two potential causes of this</strong>.</p>
<ol>
<li><p>The most common is the <strong>x:Class</strong> doesn't match up with the MainPage.xaml namespace. Make sure that x:Class in MainPage.xaml has the correct namespace.</p></li>
<li><p>The second most common cause of this problem is that the "Build Action" is not set to "Page" for MainPage.xaml!</p></li>
</ol> |
17,707,961 | No connection could be made because the target machine actively refused it (PHP / WAMP) | <p>Note: <strong>I realise this could be seen as a duplicate but i have looked at the other responses and they didn't fix the problem for me.</strong></p>
<hr>
<p>I have recently installed Zend Studio and Zend Server with the mysql plugin on Windows 7.</p>
<p>I am not a qualified server administrator but neither am i completely incompetent; i have dedicated my day trying to get a local development 'server' up to cut down on upload/download times.</p>
<p>When I say server/machine i mean my home computer</p>
<p>I have come to a grinding halt trying to get mysql to work with Zend Server.</p>
<p>The error I keep receiving is (or verbose):</p>
<pre><code>#2002 Cannot log in to the MySQL server
or (if i change to 'config' authentication type)
#2002 - No connection could be made because the target machine actively refused it.
The server is not responding (or the local server's socket is not correctly configured).
</code></pre>
<p>I have tried:</p>
<ul>
<li>Change $cfg['Servers'][$i]['host'] from 'localhost' to '127.0.0.1'</li>
<li>Add/Remove $cfg['Servers'][$i]['socket'] = '';</li>
<li>Change from cookie to config auth type</li>
<li>reinstall server and mysql</li>
<li>Disable firewalls</li>
<li>Restarting machine</li>
</ul>
<p>Zend's approach was to 'configure the phpmyadmin setup screen'... done that i don't know how many times.</p>
<p>Can anyone on here lend a hand, or point me in a direction that I haven't tried yet?</p> | 33,981,831 | 11 | 3 | null | 2013-07-17 18:54:17.553 UTC | 4 | 2021-06-04 18:14:07.497 UTC | 2019-12-23 12:05:40.897 UTC | null | 2,377,343 | null | 2,144,796 | null | 1 | 21 | mysql|zend-server | 130,366 | <ol>
<li>Go to C:\wamp\bin\mysql\mysql[your-version]\data </li>
<li>Copy and save "ib_logfile0" and "ib_logfile1" anywhere else. </li>
<li>delete "ib_logfile0" and ib_logfile1</li>
</ol>
<p>Did the trick for me. hope it works for you too.</p>
<p>Its working fine.
But we will have to stop apache and mysql, We need to quit xampp and then delete file. when deleted successfully. now start xampp it will work properly..</p> |
6,496,433 | Multiple Sinatra apps using rack-mount | <p>I have a question regarding using rack-mount with Sinatra. I've got two classic-style Sinatra apps. Let's call one App defined in app.rb and the other API defined in api.rb.</p>
<p>I would like it so that api.rb handles all routes beginning with '/api' and app.rb handles all other requests including the root ('/').</p>
<p>How would I set this up with rack-mount? Or is there a better solution than that?</p> | 6,496,677 | 4 | 0 | null | 2011-06-27 17:13:52.1 UTC | 9 | 2013-04-11 21:26:09.977 UTC | 2011-06-28 13:01:04.103 UTC | null | 613,444 | null | 613,444 | null | 1 | 17 | ruby|sinatra | 11,344 | <p>I think you'll prefer Rack::URLMap - it will probably look something like this:</p>
<pre><code>run Rack::URLMap.new("/" => App.new,
"/api" => Api.new)
</code></pre>
<p>That should go in your <code>config.ru</code> file.</p> |
18,577,860 | Creating app which opens a custom file extension | <p>Want to create an android application, which opens a custom-build file extension (for example, I want to open .abcd files)</p>
<p>It is something like Adobe Reader that opens .pdf files, or Photo Viewer that opens .jpg files</p>
<p><em>Specific conditions:</em><br>
1. The .abcd file should be outside / external from the application itself. (as .pdf is to Adobe Reader)<br>
2. The .abcd file would be a zipped file, which contains few folders and .xml, .txt, and .jpg files. I think I want to extract it - maybe temporarily - to somewhere in the storage (definitely need a zipper/unzipper library), then read the individual .xml, .txt, and .jpg files.</p>
<p><strong>Looking for insights and answers for this problem.</strong></p>
<p><em>Additional information:</em><br>
I am relatively new to Android programming.</p> | 18,578,704 | 2 | 6 | null | 2013-09-02 16:59:10.62 UTC | 9 | 2019-05-03 20:51:12.16 UTC | 2013-09-02 16:59:54.04 UTC | null | 620,444 | null | 2,695,256 | null | 1 | 19 | android|file | 13,394 | <p>I think you need to do that type of customization via <code>intent-filter</code> something like:</p>
<pre><code><intent-filter android:icon="your_drawable-resource"
android:label="your_string_resource"
android:priority="integer">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="file" />
<data android:host="*" />
<data android:pathPattern=".*\\.YOUR_CUSTOM_FILE_EXTENSION" />
</intent-filter>
</code></pre>
<p>Also you should look:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/4675257/custom-filetype-in-android-not-working">Custom Filetype in Android not working</a></li>
<li><a href="https://stackoverflow.com/questions/1733195/android-intent-filter-for-a-particular-file-extension">Android intent filter for a particular file extension?</a></li>
<li><a href="https://stackoverflow.com/questions/14256537/android-intent-filter-for-custom-file-extension">android intent filter for custom file extension</a></li>
</ul> |
34,958,886 | Gradle Could not find method compile() for arguments | <p>i have a hello world full screen android studio 1.5.1 app that i added a gradle/eclipse-mars subproject to. no other files were modified except for adding include ':javalib' to settings.gradle. adding a <a href="https://docs.gradle.org/current/userguide/multi_project_builds.html#sec:project_jar_dependencies" rel="noreferrer">project lib dependency</a>:</p>
<pre><code>project(':app') {
dependencies {
compile project(':javalib') // line 23
}
}
</code></pre>
<p>to the root build build file and running gradle from the command line , gets:</p>
<ul>
<li><p>Where:
Build file 'D:\AndroidStudioProjects\AndroidMain\build.gradle' line: 23</p></li>
<li><p>What went wrong:
A problem occurred evaluating root project 'AndroidMain'.</p>
<blockquote>
<p>Could not find method compile() for arguments [project ':javalib'] on org.grad
le.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler_Decorated@46
3ca82f.</p>
</blockquote></li>
</ul>
<p><a href="https://stackoverflow.com/a/23800903/51292">adding the java plugin</a> to the root build file did not help.</p>
<p>i don't think it's in the <a href="https://stackoverflow.com/a/23627293/51292">wrong place</a>.</p>
<p>both the root project and the added subproject have the gradle wrapper.</p>
<p>any pointers will be appreciated.</p>
<p>thanks</p>
<p>edit: for clarification, the root build file is:</p>
<pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.5.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
task hello << { task -> println "I'm $task.project.name" }
}
project(':app') {
dependencies {
//compile project(':javalib') // causes problems
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
</code></pre>
<p>and the app build file is:</p>
<pre><code>apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
applicationId "acme.androidmain"
minSdkVersion 22
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 project(':javalib') // use :javalib:jar?
//testCompile project(':javalib')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:support-v4:23.1.1'
}
</code></pre>
<p>edit: the whole purpose of this exercise is to get core java code into an android project. currently the core code is a standalone gradle/eclispe project. i have a batch in the android project that does a gradle -p standaloneprojectdir/ jar and copied the jar into libs/.</p>
<p>i just though there would be an easier way other than to publish the jar and get it from a repository since this all done on my pc.</p>
<p>it would be nice to have all the code live and just do a build :(</p>
<p>edit: as per <a href="https://stackoverflow.com/users/745574/rage">RaGe</a>'s suggestion, here is a <a href="https://github.com/rtayek/Virginandroidstudioproject" rel="noreferrer">virgin android studio project</a> and a <a href="https://github.com/rtayek/virginjavaproject.git" rel="noreferrer">virgin gradle/eclipse project</a>. no editing has been done to these files. you mission should you choose to accept it is to get the android app to easily access the java project classes (i.e. new Library(); in MainActivity.onCreate() will compile and run). i don't care where the java project lives. ideally, both sources would be <em>live</em> in both ide's.</p>
<p>atempting <a href="https://stackoverflow.com/a/17490233/51292">this</a> fails also. says: > Could not find :virginjavaproject, but directory does exist.</p>
<p>edit: what actually worked was RaGe's pull request to the <a href="https://github.com/rtayek/Virginandroidstudioproject" rel="noreferrer">virgin android project</a>.</p> | 34,965,185 | 5 | 8 | null | 2016-01-23 02:16:37.333 UTC | 4 | 2021-07-17 14:26:13.987 UTC | 2017-05-23 10:31:31.273 UTC | null | -1 | null | 51,292 | null | 1 | 14 | android|gradle|android-gradle-plugin|subproject | 82,011 | <p>You already have </p>
<pre><code>compile project(':javalib')
</code></pre>
<p>in your <code>:app</code> project, you don't have to also inject the dependency from your root build.gradle. If you still want to do it from the root <code>build.gradle</code>, the correct way to do it is:</p>
<pre><code>configure(':app') {
dependencies {
compile project(':javalib') // causes problems - NOT ANYMORE!
}
}
</code></pre>
<p>the <a href="https://github.com/rtayek/Virginandroidstudioproject" rel="nofollow">virgin android studio</a> head is what worked.</p> |
57,673,026 | 'require' and 'process' is not defined in ESlint. problem with node? | <p>I had an error in my pipeline in <code>GitLab</code>. I changed the settings in <code>.eslint.json</code> using information from StackOverflow. But I still have problem.</p>
<p>My <code>.eslint.json</code> looks like:</p>
<pre><code>{
"extends": "eslint:recommended",
"rules": {
"semi": ["warn", "never"],
"quotes": ["warn", "single"],
"no-console": ["off"]
},
"parserOptions": {
"ecmaVersion": 9
},
"env": {
"es6": true,
"node": true,
"browser": true,
"amd": true
},
"globals": {
"$": true,
"require": true
"process": true
},
"root": true
}
</code></pre>
<p>In <code>env</code> I added <code>"adm": true</code> and in <code>globals</code> I added <code>"process": true</code> and <code>"require": true</code>. </p>
<p>The errors are: </p>
<p><strong>error 'require' is not defined no-undef</strong></p>
<p><strong>error 'process' is not defined no-undef</strong></p>
<p>The file where is the errors are looks like this:</p>
<pre class="lang-js prettyprint-override"><code>const qs = require("querystring");
const coEndpoint =
process.env.NODE_ENV == "production"
</code></pre>
<p>So where is the problem? Is this a problem with env node? How can I fixed this?</p> | 57,690,631 | 2 | 3 | null | 2019-08-27 10:46:24.79 UTC | 4 | 2020-09-30 06:53:19.31 UTC | 2020-05-22 16:25:15.623 UTC | null | 1,441,857 | null | 11,647,728 | null | 1 | 35 | node.js|eslint | 23,676 | <p>Rename <code>.eslint.json</code> to <code>.eslintrc.json</code> or make sure that <code>eslintConfig</code> is specified in your package.json</p>
<p><a href="https://eslint.org/docs/user-guide/configuring" rel="nofollow noreferrer">https://eslint.org/docs/user-guide/configuring</a></p>
<p>Also make sure that <code>eslint</code> is started in the directory where your .eslintrc.json is and is not started with <code>--no-eslintrc</code> option.</p> |
542,312 | ASP.NET Access to the temp directory is denied | <p>I'm experiencing this problem today on many different servers. </p>
<p><strong>System.UnauthorizedAccessException: Access to the temp directory is denied.</strong></p>
<p>The servers were not touched recently. The only thing that comes in my mind is a windows update breaking something.. Any idea? </p>
<p>This happens when trying to access a webservice from an asp.net page</p>
<pre><code>System.UnauthorizedAccessException: Access to the temp directory is denied. Identity 'NT AUTHORITY\NETWORK SERVICE' under which XmlSerializer is running does not have sufficient permission to access the temp directory. CodeDom will use the user account the process is using to do the compilation, so if the user doesnt have access to system temp directory, you will not be able to compile. Use Path.GetTempPath() API to find out the temp directory location.
at System.Xml.Serialization.Compiler.Compile(Assembly parent, String ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence)
at System.Xml.Serialization.TempAssembly.GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, Evidence evidence, XmlSerializerCompilerParameters parameters, Assembly assembly, Hashtable assemblies)
at System.Xml.Serialization.TempAssembly..ctor(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, String location, Evidence evidence)
at System.Xml.Serialization.XmlSerializer.FromMappings(XmlMapping[] mappings, Evidence evidence)
at System.Web.Services.Protocols.XmlReturn.GetInitializers(LogicalMethodInfo[] methodInfos)
at System.Web.Services.Protocols.HttpServerType..ctor(Type type)
at System.Web.Services.Protocols.HttpServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response)
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)
</code></pre> | 542,343 | 7 | 0 | null | 2009-02-12 17:02:22.813 UTC | 3 | 2017-02-16 13:34:35.44 UTC | null | null | null | Luca Martinetti | 2,250,286 | null | 1 | 15 | c#|asp.net|exception | 51,026 | <p>Have you checked the permissions on the temp folder? In these cases, the easiest and quickest solution is usually to re-run the <em>aspnet_regiis -i</em> command to re-install the asp.net framework which also resets the permissions on the required folders. Failing that, try using <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx" rel="noreferrer">Process Monitor</a> to check what's going on and modify the permissions accordingly.</p> |
498,343 | Putting a password to a user in PhpMyAdmin in Wamp | <p>How do you change the password for the root user in phpMyAdmin on WAMP server? because I'm locked out of phpMyAdmin, after changing the password incorrectly.</p> | 498,392 | 7 | 0 | null | 2009-01-31 05:35:12.76 UTC | 6 | 2015-01-23 11:51:57.127 UTC | 2009-10-15 08:00:04.607 UTC | Rogue | 44,386 | Rogue | 44,386 | null | 1 | 22 | phpmyadmin|wampserver | 144,727 | <p>my config.inc.php file in the phpmyadmin folder.
Change username and password to the one you have set for your database.</p>
<pre><code> <?php
/*
* This is needed for cookie based authentication to encrypt password in
* cookie
*/
$cfg['blowfish_secret'] = 'xampp'; /* YOU SHOULD CHANGE THIS FOR A MORE SECURE COOKIE AUTH! */
/*
* Servers configuration
*/
$i = 0;
/*
* First server
*/
$i++;
/* Authentication type and info */
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'enter_username_here';
$cfg['Servers'][$i]['password'] = 'enter_password_here';
$cfg['Servers'][$i]['AllowNoPasswordRoot'] = true;
/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = '';
/* Advanced phpMyAdmin features */
$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
$cfg['Servers'][$i]['relation'] = 'pma_relation';
$cfg['Servers'][$i]['table_info'] = 'pma_table_info';
$cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
$cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
$cfg['Servers'][$i]['column_info'] = 'pma_column_info';
$cfg['Servers'][$i]['history'] = 'pma_history';
$cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';
/*
* End of servers configuration
*/
?>
</code></pre> |
739,682 | How to add percent sign to NSString | <p>I want to have a percentage sign in my string after a digit. Something like this: 75%.</p>
<p>How can I have this done? I tried:</p>
<pre><code>[NSString stringWithFormat:@"%d\%", someDigit];
</code></pre>
<p>But it didn't work for me.</p> | 739,707 | 7 | 0 | null | 2009-04-11 07:33:57.037 UTC | 58 | 2017-06-07 16:41:36.067 UTC | 2016-04-22 19:55:59.727 UTC | null | 10,468 | null | 77,449 | null | 1 | 464 | objective-c|nsstring|string-literals | 135,735 | <p>The code for percent sign in <code>NSString</code> format is <code>%%</code>. This is also true for <code>NSLog()</code> and <code>printf()</code> formats.</p> |
171,785 | How do you organize Python modules? | <p>When it comes to organizing python modules, my Mac OS X system is a mess. I've packages lying around everywhere on my hdd and no particular system to organize them.</p>
<p>How do you keep everything manageable?</p> | 173,715 | 8 | 0 | null | 2008-10-05 10:09:28.113 UTC | 19 | 2013-04-11 06:28:56.453 UTC | 2013-04-11 06:28:56.453 UTC | user1131435 | null | ak | 20,672 | null | 1 | 14 | python|module | 6,862 | <p>My advice:</p>
<ul>
<li>Read <a href="http://docs.python.org/install/index.html" rel="noreferrer">Installing Python Modules</a>.</li>
<li>Read <a href="http://docs.python.org/distutils/index.html" rel="noreferrer">Distributing Python Modules</a>.</li>
<li>Start using easy_install from <a href="http://peak.telecommunity.com/DevCenter/setuptools" rel="noreferrer">setuptools</a>. Read the documentation for setuptools.</li>
<li>Always use <a href="http://pypi.python.org/pypi/virtualenv" rel="noreferrer">virtualenv</a>. My site-packages directory contains <strong>setuptools and virtualenv only</strong>.</li>
<li>Check out Ian Bicking's new project <a href="http://www.openplans.org/projects/topp-engineering/blog/2008/09/24/pyinstall-a-new-hope/" rel="noreferrer">pyinstall</a>. </li>
<li>Follow everything <a href="http://blog.ianbicking.org" rel="noreferrer">Ian Bicking</a> is working on. It is always goodness.</li>
<li>When creating your own packages, use distutils/setuptools. Consider using <code>paster create</code> (see <a href="http://pythonpaste.org" rel="noreferrer">http://pythonpaste.org</a>) to create your initial directory layout.</li>
</ul> |
754,512 | MySQL: How do I find out which tables reference a specific table? | <p>I want to drop a table but it is referenced by one or more other tables. How can I find out which tables are referencing this table without having to look at each of the tables in the database one by one?</p> | 754,582 | 8 | 1 | null | 2009-04-16 02:19:58.17 UTC | 11 | 2022-01-11 19:08:10.213 UTC | null | null | null | seppy | null | null | 1 | 44 | mysql|foreign-keys | 34,639 | <pre class="lang-sql prettyprint-override"><code>SELECT TABLE_NAME
FROM information_schema.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = 'your_schema_name'
AND REFERENCED_TABLE_NAME = 'your_table_name';
</code></pre>
<p>This works.</p> |
728,205 | WPF ListView: Attaching a double-click (on an item) event | <p>I have the following <code>ListView</code>:</p>
<pre><code><ListView Name="TrackListView">
<ListView.View>
<GridView>
<GridViewColumn Header="Title" Width="100"
HeaderTemplate="{StaticResource BlueHeader}"
DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Header="Artist" Width="100"
HeaderTemplate="{StaticResource BlueHeader}"
DisplayMemberBinding="{Binding Album.Artist.Name}" />
</GridView>
</ListView.View>
</ListView>
</code></pre>
<p>How can I attach an event to every bound item that will fire on double-clicking the item?</p> | 728,248 | 8 | 0 | null | 2009-04-08 01:40:55.05 UTC | 24 | 2022-06-24 18:06:25.33 UTC | 2018-01-23 07:44:01.447 UTC | null | 336,648 | null | 44,084 | null | 1 | 87 | c#|wpf|xaml | 103,015 | <p>Found the solution from here: <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/3d0eaa54-09a9-4c51-8677-8e90577e7bac/" rel="noreferrer">http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/3d0eaa54-09a9-4c51-8677-8e90577e7bac/</a></p>
<hr>
<p>XAML:</p>
<pre><code><UserControl.Resources>
<Style x:Key="itemstyle" TargetType="{x:Type ListViewItem}">
<EventSetter Event="MouseDoubleClick" Handler="HandleDoubleClick" />
</Style>
</UserControl.Resources>
<ListView Name="TrackListView" ItemContainerStyle="{StaticResource itemstyle}">
<ListView.View>
<GridView>
<GridViewColumn Header="Title" Width="100" HeaderTemplate="{StaticResource BlueHeader}" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Header="Artist" Width="100" HeaderTemplate="{StaticResource BlueHeader}" DisplayMemberBinding="{Binding Album.Artist.Name}" />
</GridView>
</ListView.View>
</ListView>
</code></pre>
<p>C#:</p>
<pre class="lang-cs prettyprint-override"><code>protected void HandleDoubleClick(object sender, MouseButtonEventArgs e)
{
var track = ((ListViewItem) sender).Content as Track; //Casting back to the binded Track
}
</code></pre> |
604,484 | Linker errors between multiple projects in Visual C++ | <p>I have a solution with multiple projects. I have a "main" project, which acts as a menu and from there, the user can access any of the other projects. On this main project, I get linker errors for every function called. How do I avoid these linker errors? I set the project dependencies already in the "Project Dependencies..." dialog.</p>
<p>Thanks</p>
<p><strong>EDIT -- I did as suggested and added the output folder to the linker's additional directories. Now, however, I get a million errors as follows:</strong></p>
<pre><code>3>msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: void __thiscall std::basic_ios >::setstate(int,bool)" (?setstate@?$basic_ios@DU?$char_traits@D@std@@@std@@QAEXH_N@Z) already defined in panels.lib(panel_main.obj)
3>msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: int __thiscall std::ios_base::width(int)" (?width@ios_base@std@@QAEHH@Z) already defined in panels.lib(panel_main.obj)
3>msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: int __thiscall std::basic_streambuf >::sputn(char const *,int)" (?sputn@?$basic_streambuf@DU?$char_traits@D@std@@@std@@QAEHPBDH@Z) already defined in panels.lib(panel_main.obj)
3>msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: static bool __cdecl std::char_traits::eq_int_type(int const &,int const &)" (?eq_int_type@?$char_traits@D@std@@SA_NABH0@Z) already defined in panels.lib(panel_main.obj)
3>msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: static int __cdecl std::char_traits::eof(void)" (?eof@?$char_traits@D@std@@SAHXZ) already defined in panels.lib(panel_main.obj)
3>msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: int __thiscall std::basic_streambuf >::sputc(char)" (?sputc@?$basic_streambuf@DU?$char_traits@D@std@@@std@@QAEHD@Z) already defined in panels.lib(panel_main.obj)
3>msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: class std::basic_streambuf > * __thiscall std::basic_ios >::rdbuf(void)const " (?rdbuf@?$basic_ios@DU?$char_traits@D@std@@@std@@QBEPAV?$basic_streambuf@DU?$char_traits@D@std@@@2@XZ) already defined in panels.lib(panel_main.obj)
3>msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: char __thiscall std::basic_ios >::fill(void)const " (?fill@?$basic_ios@DU?$char_traits@D@std@@@std@@QBEDXZ) already defined in panels.lib(panel_main.obj)
3>msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: int __thiscall std::ios_base::flags(void)const " (?flags@ios_base@std@@QBEHXZ) already defined in panels.lib(panel_main.obj)
3>msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: int __thiscall std::ios_base::width(void)const " (?width@ios_base@std@@QBEHXZ) already defined in panels.lib(panel_main.obj)
3>msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: static unsigned int __cdecl std::char_traits::length(char const *)" (?length@?$char_traits@D@std@@SAIPBD@Z) already defined in panels.lib(panel_main.obj)
3>msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: class std::basic_ostream > & __thiscall std::basic_ostream >::flush(void)" (?flush@?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV12@XZ) already defined in panels.lib(panel_main.obj)
3>msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: class std::basic_ostream > * __thiscall std::basic_ios >::tie(void)const " (?tie@?$basic_ios@DU?$char_traits@D@std@@@std@@QBEPAV?$basic_ostream@DU?$char_traits@D@std@@@2@XZ) already defined in panels.lib(panel_main.obj)
3>msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: bool __thiscall std::ios_base::good(void)const " (?good@ios_base@std@@QBE_NXZ) already defined in panels.lib(panel_main.obj)
3>msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: void __thiscall std::basic_ostream >::_Osfx(void)" (?_Osfx@?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEXXZ) already defined in panels.lib(panel_main.obj)
3>msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: void __thiscall std::basic_streambuf >::_Lock(void)" (?_Lock@?$basic_streambuf@DU?$char_traits@D@std@@@std@@QAEXXZ) already defined in panels.lib(panel_main.obj)
3>msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: void __thiscall std::basic_streambuf >::_Unlock(void)" (?_Unlock@?$basic_streambuf@DU?$char_traits@D@std@@@std@@QAEXXZ) already defined in panels.lib(panel_main.obj)
3>msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: class std::locale::facet * __thiscall std::locale::facet::_Decref(void)" (?_Decref@facet@locale@std@@QAEPAV123@XZ) already defined in panels.lib(panel_main.obj)
3>libcpmtd.lib(ios.obj) : error LNK2005: "private: static void __cdecl std::ios_base::_Ios_base_dtor(class std::ios_base *)" (?_Ios_base_dtor@ios_base@std@@CAXPAV12@@Z) already defined in msvcprtd.lib(MSVCP90D.dll)
3>libcpmtd.lib(ios.obj) : error LNK2005: "public: static void __cdecl std::ios_base::_Addstd(class std::ios_base *)" (?_Addstd@ios_base@std@@SAXPAV12@@Z) already defined in msvcprtd.lib(MSVCP90D.dll)
3>libcpmtd.lib(locale0.obj) : error LNK2005: "void __cdecl _AtModuleExit(void (__cdecl*)(void))" (?_AtModuleExit@@YAXP6AXXZ@Z) already defined in msvcprtd.lib(locale0_implib.obj)
3>libcpmtd.lib(locale0.obj) : error LNK2005: __Fac_tidy already defined in msvcprtd.lib(locale0_implib.obj)
3>libcpmtd.lib(locale0.obj) : error LNK2005: "private: static void __cdecl std::locale::facet::facet_Register(class std::locale::facet *)" (?facet_Register@facet@locale@std@@CAXPAV123@@Z) already defined in msvcprtd.lib(locale0_implib.obj)
3>libcpmtd.lib(locale0.obj) : error LNK2005: "private: static class std::locale::_Locimp * __cdecl std::locale::_Getgloballocale(void)" (?_Getgloballocale@locale@std@@CAPAV_Locimp@12@XZ) already defined in msvcprtd.lib(MSVCP90D.dll)
3>libcpmtd.lib(locale0.obj) : error LNK2005: "private: static class std::locale::_Locimp * __cdecl std::locale::_Init(void)" (?_Init@locale@std@@CAPAV_Locimp@12@XZ) already defined in msvcprtd.lib(MSVCP90D.dll)
3>libcpmtd.lib(locale0.obj) : error LNK2005: "public: static void __cdecl std::_Locinfo::_Locinfo_ctor(class std::_Locinfo *,class std::basic_string,class std::allocator > const &)" (?_Locinfo_ctor@_Locinfo@std@@SAXPAV12@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@2@@Z) already defined in msvcprtd.lib(MSVCP90D.dll)
3>libcpmtd.lib(locale0.obj) : error LNK2005: "public: static void __cdecl std::_Locinfo::_Locinfo_dtor(class std::_Locinfo *)" (?_Locinfo_dtor@_Locinfo@std@@SAXPAV12@@Z) already defined in msvcprtd.lib(MSVCP90D.dll)
3>libcpmtd.lib(xlock.obj) : error LNK2005: "public: __thiscall std::_Lockit::_Lockit(int)" (??0_Lockit@std@@QAE@H@Z) already defined in msvcprtd.lib(MSVCP90D.dll)
3>libcpmtd.lib(xlock.obj) : error LNK2005: "public: __thiscall std::_Lockit::~_Lockit(void)" (??1_Lockit@std@@QAE@XZ) already defined in msvcprtd.lib(MSVCP90D.dll)
</code></pre> | 604,506 | 9 | 0 | null | 2009-03-02 23:25:28.177 UTC | 1 | 2018-11-09 02:30:55.863 UTC | 2009-03-03 00:13:41.68 UTC | rlbond | 72,631 | rlbond | 72,631 | null | 1 | 11 | visual-studio|visual-c++|projects-and-solutions | 46,152 | <p>Without knowing any other detail about your solution it is hard to tell, however Rebuild All, might be helpful. This situation can sometimes occur when there are mixed object files for different architectures.</p>
<p>You might also want to consider using "References" instead of "Dependencies"</p>
<p><strong>EDIT:</strong></p>
<p>After what you have posted it seems that your linkage to standard libraries is inconsistent. Could it be that one of the project links standard libraries statically while others dynamically? (See project properties->linker) Or one to the release runtime, while others to debug? (though the last one should be possible, with caveats)</p> |
547,542 | How can I manipulate MySQL fulltext search relevance to make one field more 'valuable' than another? | <p>Suppose I have two columns, keywords and content. I have a fulltext index across both. I want a row with foo in the keywords to have more relevance than a row with foo in the content. What do I need to do to cause MySQL to weight the matches in keywords higher than those in content? </p>
<p>I'm using the "match against" syntax. </p>
<p>SOLUTION:</p>
<p>Was able to make this work in the following manner: </p>
<pre><code>SELECT *,
CASE when Keywords like '%watermelon%' then 1 else 0 END as keywordmatch,
CASE when Content like '%watermelon%' then 1 else 0 END as contentmatch,
MATCH (Title, Keywords, Content) AGAINST ('watermelon') AS relevance
FROM about_data
WHERE MATCH(Title, Keywords, Content) AGAINST ('watermelon' IN BOOLEAN MODE)
HAVING relevance > 0
ORDER by keywordmatch desc, contentmatch desc, relevance desc
</code></pre> | 547,840 | 9 | 0 | null | 2009-02-13 20:26:32.86 UTC | 36 | 2019-02-26 15:06:46.147 UTC | 2009-02-17 12:16:34.927 UTC | Buzz | 13,113 | Buzz | 13,113 | null | 1 | 45 | mysql|search|indexing|full-text-search|relevance | 27,032 | <p>Actually, using a case statement to make a pair of flags might be a better solution:</p>
<pre><code>select
...
, case when keyword like '%' + @input + '%' then 1 else 0 end as keywordmatch
, case when content like '%' + @input + '%' then 1 else 0 end as contentmatch
-- or whatever check you use for the matching
from
...
and here the rest of your usual matching query
...
order by keywordmatch desc, contentmatch desc
</code></pre>
<p>Again, this is only if all keyword matches rank higher than all the content-only matches. I also made the assumption that a match in both keyword and content is the highest rank.</p> |
800,368 | Declaring an object before initializing it in c++ | <p>Is it possible to declare a variable in c++ without instantiating it? I want to do something like this:</p>
<pre><code>Animal a;
if( happyDay() )
a( "puppies" ); //constructor call
else
a( "toads" );
</code></pre>
<p>Basially, I just want to declare a outside of the conditional so it gets the right scope.</p>
<p>Is there any way to do this without using pointers and allocating <code>a</code> on the heap? Maybe something clever with references?</p> | 800,384 | 10 | 3 | null | 2009-04-29 00:16:51.633 UTC | 13 | 2021-01-25 00:59:11.897 UTC | 2013-03-13 11:48:24.107 UTC | null | 1,488,917 | null | 81,658 | null | 1 | 82 | c++|scope|declaration|instantiation | 59,058 | <p>You can't do this directly in C++ since the object is constructed when you define it with the default constructor.</p>
<p>You could, however, run a parameterized constructor to begin with:</p>
<pre><code>Animal a(getAppropriateString());
</code></pre>
<p>Or you could actually use something like the <code>?: operator</code> to determine the correct string.
(Update: @Greg gave the syntax for this. See that answer)</p> |
794,663 | .NET convert number to string representation (1 to one, 2 to two, etc...) | <p>Is there a built in method in .NET to convert a number to the string representation of the number? For example, 1 becomes one, 2 becomes two, etc.</p> | 794,831 | 11 | 1 | null | 2009-04-27 18:24:26.98 UTC | 7 | 2015-05-08 19:04:49.77 UTC | null | null | null | null | 86,191 | null | 1 | 31 | .net | 25,924 | <p>I've always been a fan of the recursive method</p>
<pre><code> public static string NumberToText( int n)
{
if ( n < 0 )
return "Minus " + NumberToText(-n);
else if ( n == 0 )
return "";
else if ( n <= 19 )
return new string[] {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
"Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
"Seventeen", "Eighteen", "Nineteen"}[n-1] + " ";
else if ( n <= 99 )
return new string[] {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy",
"Eighty", "Ninety"}[n / 10 - 2] + " " + NumberToText(n % 10);
else if ( n <= 199 )
return "One Hundred " + NumberToText(n % 100);
else if ( n <= 999 )
return NumberToText(n / 100) + "Hundreds " + NumberToText(n % 100);
else if ( n <= 1999 )
return "One Thousand " + NumberToText(n % 1000);
else if ( n <= 999999 )
return NumberToText(n / 1000) + "Thousands " + NumberToText(n % 1000);
else if ( n <= 1999999 )
return "One Million " + NumberToText(n % 1000000);
else if ( n <= 999999999)
return NumberToText(n / 1000000) + "Millions " + NumberToText(n % 1000000);
else if ( n <= 1999999999 )
return "One Billion " + NumberToText(n % 1000000000);
else
return NumberToText(n / 1000000000) + "Billions " + NumberToText(n % 1000000000);
}
</code></pre>
<p><a href="http://www.dotnet2themax.com/blogs/fbalena/PermaLink,guid,cdceca73-08cd-4c15-aef7-0f9c8096e20a.aspx" rel="noreferrer">Source</a></p> |
710,957 | How might I get the script filename from within that script? | <p>I'm pretty sure the answer is no, but thought I'd ask anyway.</p>
<p>If my site references a scripted named "whatever.js", is it possible to get "whatever.js" from within that script? Like:</p>
<pre><code>var scriptName = ???
if (typeof jQuery !== "function") {
throw new Error(
"jQuery's script needs to be loaded before " +
scriptName + ". Check the <script> tag order.");
}
</code></pre>
<p>Probably more trouble than it's worth for dependency checking, but what the hell.</p> | 710,996 | 12 | 7 | null | 2009-04-02 18:16:58.293 UTC | 10 | 2020-12-22 16:24:43.98 UTC | 2009-04-02 18:35:15.27 UTC | Shog9 | 811 | Chris | 11,574 | null | 1 | 59 | javascript|html | 51,047 | <pre><code>var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
var scriptName = lastScript.src;
alert("loading: " + scriptName);
</code></pre>
<p>Tested in: FF 3.0.8, Chrome 1.0.154.53, IE6</p>
<hr />
<h3>See also: <a href="https://stackoverflow.com/questions/403967/how-may-i-reference-the-script-tag-that-loaded-the-currently-executing-script">How may I reference the script tag that loaded the currently-executing script?</a></h3> |
56,692 | Random weighted choice | <p>Consider the class below that represents a Broker:</p>
<pre><code>public class Broker
{
public string Name = string.Empty;
public int Weight = 0;
public Broker(string n, int w)
{
this.Name = n;
this.Weight = w;
}
}
</code></pre>
<p>I'd like to randomly select a Broker from an array, taking into account their weights.</p>
<p>What do you think of the code below?</p>
<pre><code>class Program
{
private static Random _rnd = new Random();
public static Broker GetBroker(List<Broker> brokers, int totalWeight)
{
// totalWeight is the sum of all brokers' weight
int randomNumber = _rnd.Next(0, totalWeight);
Broker selectedBroker = null;
foreach (Broker broker in brokers)
{
if (randomNumber <= broker.Weight)
{
selectedBroker = broker;
break;
}
randomNumber = randomNumber - broker.Weight;
}
return selectedBroker;
}
static void Main(string[] args)
{
List<Broker> brokers = new List<Broker>();
brokers.Add(new Broker("A", 10));
brokers.Add(new Broker("B", 20));
brokers.Add(new Broker("C", 20));
brokers.Add(new Broker("D", 10));
// total the weigth
int totalWeight = 0;
foreach (Broker broker in brokers)
{
totalWeight += broker.Weight;
}
while (true)
{
Dictionary<string, int> result = new Dictionary<string, int>();
Broker selectedBroker = null;
for (int i = 0; i < 1000; i++)
{
selectedBroker = GetBroker(brokers, totalWeight);
if (selectedBroker != null)
{
if (result.ContainsKey(selectedBroker.Name))
{
result[selectedBroker.Name] = result[selectedBroker.Name] + 1;
}
else
{
result.Add(selectedBroker.Name, 1);
}
}
}
Console.WriteLine("A\t\t" + result["A"]);
Console.WriteLine("B\t\t" + result["B"]);
Console.WriteLine("C\t\t" + result["C"]);
Console.WriteLine("D\t\t" + result["D"]);
result.Clear();
Console.WriteLine();
Console.ReadLine();
}
}
}
</code></pre>
<p>I'm not so confident. When I run this, Broker A always gets more hits than Broker D, and they have the same weight.</p>
<p>Is there a more accurate algorithm?</p>
<p>Thanks!</p> | 56,735 | 12 | 3 | null | 2008-09-11 14:34:11.053 UTC | 28 | 2022-06-10 03:30:10.577 UTC | null | null | null | LD2008 | 2,868 | null | 1 | 65 | c#|algorithm|random | 48,069 | <p>Your algorithm is nearly correct. However, the test should be <code><</code> instead of <code><=</code>:</p>
<pre><code>if (randomNumber < broker.Weight)
</code></pre>
<p>This is because 0 is inclusive in the random number while <code>totalWeight</code> is exclusive. In other words, a broker with weight 0 would still have a small chance of being selected – not at all what you want. This accounts for broker A having more hits than broker D.</p>
<p>Other than that, your algorithm is fine and in fact the canonical way of solving this problem.</p> |
30,058 | How can I launch the Google Maps iPhone application from within my own native application? | <p>The <a href="http://developer.apple.com/documentation/AppleApplications/Reference/SafariWebContent/UsingiPhoneApplications/chapter_6_section_4.html" rel="nofollow noreferrer">Apple Developer Documentation</a> (link is dead now) explains that if you place a link in a web page and then click it whilst using Mobile Safari on the iPhone, the Google Maps application that is provided as standard with the iPhone will launch.</p>
<p>How can I launch the same Google Maps application with a specific address from within my own native iPhone application (i.e. not a web page through Mobile Safari) in the same way that tapping an address in Contacts launches the map?</p>
<p><strong>NOTE: THIS ONLY WORKS ON THE DEVICE ITSELF. NOT IN THE SIMULATOR.</strong></p> | 30,079 | 16 | 1 | null | 2008-08-27 13:15:40.493 UTC | 50 | 2019-04-07 12:07:38.073 UTC | 2017-09-18 11:18:24.107 UTC | Paul | 1,000,551 | DavidM | 2,183 | null | 1 | 70 | ios|objective-c|google-maps | 98,718 | <p>For iOS 5.1.1 and lower, use the <code>openURL</code> method of <code>UIApplication</code>. It will perform the normal iPhone magical URL reinterpretation. so</p>
<pre><code>[someUIApplication openURL:[NSURL URLWithString:@"http://maps.google.com/maps?q=London"]]
</code></pre>
<p>should invoke the Google maps app.</p>
<p>From iOS 6, you'll be invoking Apple's own Maps app. For this, configure an <code>MKMapItem</code> object with the location you want to display, and then send it the <code>openInMapsWithLaunchOptions</code> message. To start at the current location, try:</p>
<pre><code>[[MKMapItem mapItemForCurrentLocation] openInMapsWithLaunchOptions:nil];
</code></pre>
<p>You'll need to be linked against MapKit for this (and it will prompt for location access, I believe).</p> |
29,104 | Requirements Gathering | <p>How do you go about the requirements gathering phase? Does anyone have a good set of guidelines or tips to follow? What are some good questions to ask the stakeholders? </p>
<p>I am currently working on a new project and there are a lot of unknowns. I am in the process of coming up with a list of questions to ask the stakeholders. However I cant help but to feel that I am missing something or forgetting to ask a critical question. </p> | 29,118 | 20 | 0 | null | 2008-08-26 22:31:13.007 UTC | 35 | 2017-03-10 17:28:12.23 UTC | 2017-03-10 17:28:12.23 UTC | gary | 4,099,593 | Aros | 1,375 | null | 1 | 29 | requirements-management | 22,762 | <p>You're almost certainly missing something. A lot of things, probably. Don't worry, it's ok. Even if you remembered everything and covered all the bases stakeholders aren't going to be able to give you very good, clear requirements without any point of reference. The best way to do this sort of thing is to get what you can from them now, then take that and give them something to react to. It can be a paper prototype, a mockup, version 0.1 of the software, whatever. Then they can start telling you what they really want. </p> |
425,044 | How to estimate a programming task if you have no experience in it | <p>I am having a difficult time with management asking for estimates on programming tasks that are using third-party controls that I have no prior experience with.</p>
<p>I definitely understand why they would want the estimates, but I feel as though any estimate I give will either be a) too short and make me look bad or b) too long and make me look bad.</p>
<p>What estimate or reply could I give management to get them off of my back so that I can continue doing my work!</p> | 425,063 | 22 | 1 | null | 2009-01-08 17:02:05.82 UTC | 62 | 2014-02-02 15:18:16.12 UTC | 2014-02-02 14:54:33.803 UTC | eJames | 63,550 | Jon Erickson | 1,950 | null | 1 | 105 | estimation | 19,826 | <p>The best answer you can give is to ask for time to knock up a quick prototype to allow you to give a more accurate estimate. Without <em>some</em> experience with a tool or a problem, any estimate you give is essentially meaningless.</p>
<p>As an aside, there is very rarely a problem with giving too long an estimate. Unanticipated problems occur, priorities change, and requirements are "updated". Even if you don't use all the time you asked for, you will have more testing time, or can release "early".</p>
<p>I've always been far too optimistic in my estimates, and it can put a lot of stress into your life, especially when you are a young programmer without the experience and self-confidence to tell bosses uncomfortable truths.</p> |
198,431 | How do you compare two version Strings in Java? | <p>Is there a standard idiom for comparing version numbers? I can't just use a straight String compareTo because I don't know yet what the maximum number of point releases there will be. I need to compare the versions and have the following hold true:</p>
<pre><code>1.0 < 1.1
1.0.1 < 1.1
1.9 < 1.10
</code></pre> | 198,442 | 32 | 4 | null | 2008-10-13 17:54:41.37 UTC | 62 | 2022-03-02 09:07:46.483 UTC | 2008-10-13 21:16:59.933 UTC | Andrew | 826 | Bill the Lizard | 1,288 | null | 1 | 199 | java|comparison|versioning | 144,806 | <p>Tokenize the strings with the dot as delimiter and then compare the integer translation side by side, beginning from the left.</p> |
6,535,405 | What is the attribute property="og:title" inside meta tag? | <p>I have this extract of website source code:</p>
<pre><code><meta content="This is a basic text" property="og:title" />
</code></pre>
<p>What does this <strong>property attribute</strong> stand for, and what is its purpose?</p> | 6,535,427 | 4 | 0 | null | 2011-06-30 13:21:39.443 UTC | 36 | 2017-02-24 04:25:34.79 UTC | 2017-02-24 04:25:34.79 UTC | null | 402,884 | null | 505,762 | null | 1 | 176 | html|facebook|properties|meta-tags | 222,750 | <p><code>og:title</code> is one of the open graph meta tags. <code>og:...</code> properties define objects in a social graph. They are used for example by Facebook.</p>
<p><code>og:title</code> stands for the title of your object as it should appear within the graph (see here for more <a href="http://ogp.me/" rel="noreferrer">http://ogp.me/</a> )</p> |
6,388,812 | How to validate uploaded file in ASP.NET MVC? | <p>I have a Create action that takes an entity object and a HttpPostedFileBase image. The image does not belong to the entity model.</p>
<p>I can save the entity object in the database and the file in disk, but I am not sure how to validate these business rules:</p>
<ul>
<li>Image is required</li>
<li>Content type must be "image/png"</li>
<li>Must not exceed 1MB</li>
</ul> | 6,388,927 | 5 | 0 | null | 2011-06-17 16:29:47.33 UTC | 48 | 2018-10-25 18:00:49.49 UTC | 2013-02-11 20:23:37.643 UTC | null | 638,990 | user386167 | null | null | 1 | 70 | asp.net-mvc|security | 75,246 | <p>A custom validation attribute is one way to go:</p>
<pre><code>public class ValidateFileAttribute : RequiredAttribute
{
public override bool IsValid(object value)
{
var file = value as HttpPostedFileBase;
if (file == null)
{
return false;
}
if (file.ContentLength > 1 * 1024 * 1024)
{
return false;
}
try
{
using (var img = Image.FromStream(file.InputStream))
{
return img.RawFormat.Equals(ImageFormat.Png);
}
}
catch { }
return false;
}
}
</code></pre>
<p>and then apply on your model:</p>
<pre><code>public class MyViewModel
{
[ValidateFile(ErrorMessage = "Please select a PNG image smaller than 1MB")]
public HttpPostedFileBase File { get; set; }
}
</code></pre>
<p>The controller might look like this:</p>
<pre><code>public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The uploaded image corresponds to our business rules => process it
var fileName = Path.GetFileName(model.File.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
model.File.SaveAs(path);
return Content("Thanks for uploading", "text/plain");
}
}
</code></pre>
<p>and the view:</p>
<pre><code>@model MyViewModel
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.LabelFor(x => x.File)
<input type="file" name="@Html.NameFor(x => x.File)" id="@Html.IdFor(x => x.File)" />
@Html.ValidationMessageFor(x => x.File)
<input type="submit" value="upload" />
}
</code></pre> |
6,588,856 | Conversion from null to int possible? | <p>I know that when I read the answer to this I will see that I have overlooked something
that was under my eyes. But I have spent the last 30 minutes trying to figure it out myself
with no result.</p>
<p>So, I was writing a program in Java 6 and discovered some (for me) strange feature.
In order to try and isolate it, I have made two small examples.
I first tried the following method:</p>
<pre><code>private static int foo()
{
return null;
}
</code></pre>
<p>and the compiler refused it: Type mismatch: cannot convert from null to int.</p>
<p>This is fine with me and it respects the Java semantics I am familiar with.
Then I tried the following:</p>
<pre><code>private static Integer foo(int x)
{
if (x < 0)
{
return null;
}
else
{
return new Integer(x);
}
}
private static int bar(int x)
{
Integer y = foo(x);
return y == null ? null : y.intValue();
}
private static void runTest()
{
for (int index = 2; index > -2; index--)
{
System.out.println("bar(" + index + ") = " + bar(index));
}
}
</code></pre>
<p>This compiles with no errors! But, in my opinion, there should be a type conversion error
in the line</p>
<pre><code> return y == null ? null : y.intValue();
</code></pre>
<p>If I run the program I get the following output:</p>
<pre><code>bar(2) = 2
bar(1) = 1
bar(0) = 0
Exception in thread "main" java.lang.NullPointerException
at Test.bar(Test.java:23)
at Test.runTest(Test.java:30)
at Test.main(Test.java:36)
</code></pre>
<p>Can you explain this behaviour?</p>
<p><strong>Update</strong></p>
<p>Thank you very much for the many clarifying answers. I was a bit worried because
this example did not correspond to my intuition. One thing that disturbed me was
that a null was being converted to an int and I was wondering what the result would
be: 0 like in C++? That would hae been very strange.
Good that the conversion is not possible at runtime (null pointer exception).</p> | 6,588,993 | 6 | 0 | null | 2011-07-05 21:05:08.793 UTC | 14 | 2017-04-16 18:46:20.78 UTC | 2011-07-05 21:43:39.273 UTC | null | 815,409 | null | 815,409 | null | 1 | 60 | java | 94,744 | <p>Let's look at the line:</p>
<pre><code>return y == null ? null : y.intValue();
</code></pre>
<p>In a <code>? :</code> statement, both sides of the <code>:</code> must have the same type. In this case, Java is going to make it have the type <code>Integer</code>. An <code>Integer</code> can be <code>null</code>, so the left side is ok. The expression <code>y.intValue()</code> is of type <code>int</code>, but Java is going to auto-box this to <code>Integer</code> (note, you could just as well have written <code>y</code> which would have saved you this autobox).</p>
<p>Now, the result has to be unboxed again to <code>int</code>, because the return type of the method is <code>int</code>. If you unbox an <code>Integer</code> that is <code>null</code>, you get a <code>NullPointerException</code>.</p>
<p>Note: <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25" rel="noreferrer">Paragraph 15.25</a> of the Java Language Specification explains the exact rules for type conversions with regard to the <code>? :</code> conditional operator.</p> |
41,336,301 | Typescript cannot find name window or document | <p>For either case:</p>
<pre><code>document.getElementById('body');
// or
window.document.getElementById('body');
</code></pre>
<p>I get <code>error TS2304: Cannot find name 'window'.</code></p>
<p>Am I missing something in <code>tsconfig.json</code> for a definition file I should install?</p>
<p>I get the message when running <code>tsc</code> and in <code>vscode</code></p>
<p>tsconfig.json:</p>
<pre><code>{
"compilerOptions": {
"allowJs": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"jsx": "react",
"module": "commonjs",
"moduleResolution": "node",
"noEmitOnError": true,
"noImplicitAny": false,
"sourceMap": true,
"suppressImplicitAnyIndexErrors": true,
"target": "ES2016",
"typeRoots": [
"node_modules/@types/",
"typings/index.d.ts"
]
},
"exclude": [
"node_modules",
"**/*-aot.ts"
]
}
</code></pre>
<p>My Answer:
For use with <code>tsconfig.json</code> I target <code>es5</code> and use <code>lib: ["es2015", "dom"]</code></p> | 41,336,998 | 3 | 2 | null | 2016-12-26 21:09:38.197 UTC | 4 | 2022-02-22 18:15:00.86 UTC | 2017-03-29 16:33:38.913 UTC | null | 3,989,609 | null | 3,989,609 | null | 1 | 101 | javascript|typescript|typescript2.0 | 69,557 | <p>It seems that the problem is caused by targeting <code>ES2016</code>.<br>
Are you targeting that for a reason? If you target <code>es6</code> the error will probably go away.</p>
<p>Another option is to specify the libraries for the compiler to use:</p>
<pre><code>tsc -t ES2016 --lib "ES2016","DOM" ./your_file.ts
</code></pre>
<p>Which should also make the error go away.</p>
<p>I'm not sure why the libs aren't used by default, in the <a href="https://www.typescriptlang.org/docs/handbook/compiler-options.html" rel="noreferrer">docs for compiler options</a> it states for the <code>--lib</code> option:</p>
<blockquote>
<p>Note: If --lib is not specified a default library is injected. The
default library injected is:<br>
► For --target ES5: DOM,ES5,ScriptHost<br>
► For --target ES6: DOM,ES6,DOM.Iterable,ScriptHost</p>
</blockquote>
<p>But it doesn't state what are the default libraries when targeting <code>ES2016</code>.<br>
It might be a bug, try to open an issue, if you do please share the link here.</p> |
15,911,014 | Watching a values in a service from a controller | <p>I have created a service to isolate the business logic and am injecting it in to the controllers that need the information. What I want to ultimately do is have the controllers be able to watch the values in the service so that I don't have to do broadcast/on notification or a complex message passing solution to have all controllers be notified of changes to the data in the service.</p>
<p>I've created a plnkr demonstrating the basic idea of what I'm trying to do.</p>
<p><a href="http://plnkr.co/edit/oL6AhHq2BBeGCLhAHX0K?p=preview">http://plnkr.co/edit/oL6AhHq2BBeGCLhAHX0K?p=preview</a></p>
<p>Is it possible to have a controller watch the values of a service?</p> | 15,911,810 | 1 | 1 | null | 2013-04-09 19:40:09.287 UTC | 8 | 2014-07-08 08:49:00.223 UTC | null | null | null | null | 1,392,862 | null | 1 | 18 | angularjs | 32,963 | <p>You were already doing it right. i.e pushing the service into a scope variable and then observing the service as part of the scope variable.</p>
<p>Here is the working solution for you :</p>
<p><a href="http://plnkr.co/edit/SgA0ztPVPxTkA0wfS1HU?p=preview">http://plnkr.co/edit/SgA0ztPVPxTkA0wfS1HU?p=preview</a></p>
<p>HTML</p>
<pre><code><!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css">
<script src="http://code.angularjs.org/1.1.3/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="start()">Start Count</button>
<button ng-click="stop()">Stop Count</button>
ControllerData: {{controllerData}}
</body>
</html>
</code></pre>
<p>Javascript : </p>
<pre><code>var app = angular.module('plunker', []);
app.service('myService', function($rootScope) {
var data = 0;
var id = 0;
var increment = function() {
data = data + 1;
$rootScope.$apply();
console.log("Incrementing data", data);
};
this.start = function() {
id = setInterval(increment, 500) ;
};
this.stop = function() {
clearInterval(id);
};
this.getData = function() { return data; };
}).controller('MainCtrl', function($scope, myService) {
$scope.service = myService;
$scope.controllerData = 0;
$scope.start = function() {
myService.start();
};
$scope.stop = function() {
myService.stop();
};
$scope.$watch('service.getData()', function(newVal) {
console.log("New Data", newVal);
$scope.controllerData = newVal;
});
});
</code></pre>
<p>Here are some of the things you missed : </p>
<ol>
<li>The order of variables in $scope.$watch were wrong. Its (newVal,oldVal) and not the other way around.</li>
<li>Since you were working with setInterval , which is an async operation you will have to let angular know that things changed. That is why you need the $rootScope.$apply.</li>
<li>You cant $watch a function, but you can watch what the function return's. </li>
</ol> |
15,737,974 | How do I compare two variables containing strings in JavaScript? | <p>I want compare two variables, that are strings, but I am getting an error.</p>
<pre class="lang-js prettyprint-override"><code><script>
var to_check=$(this).val();
var cur_string=$("#0").text();
var to_chk = "that";
var cur_str= "that";
if(to_chk==cur_str){
alert("both are equal");
$("#0").attr("class","correct");
} else {
alert("both are not equal");
$("#0").attr("class","incorrect");
}
</script>
</code></pre>
<p>Is something wrong with my if statement?</p> | 15,741,261 | 4 | 10 | null | 2013-04-01 05:15:19.693 UTC | 5 | 2019-03-03 18:11:31.233 UTC | 2017-05-31 06:50:28.937 UTC | null | 5,076,266 | null | 2,229,448 | null | 1 | 19 | javascript | 200,701 | <p><code>===</code> is not necessary. You know both values are strings so you dont need to compare types.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function do_check()
{
var str1 = $("#textbox1").val();
var str2 = $("#textbox2").val();
if (str1 == str2)
{
$(":text").removeClass("incorrect");
alert("equal");
}
else
{
$(":text").addClass("incorrect");
alert("not equal");
}
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.incorrect
{
background: #ff8888;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="textbox1" type="text">
<input id="textbox2" type="text">
<button onclick="do_check()">check</button></code></pre>
</div>
</div>
</p> |
15,697,830 | margin: auto is not centering | <p>In the following style from the website: <a href="http://6.470.scripts.mit.edu/css_exercises/exercise4.html" rel="noreferrer">http://6.470.scripts.mit.edu/css_exercises/exercise4.html</a></p>
<pre><code><style type="text/css">
#sponsors {
margin:auto;
margin-top:50px;
overflow: hidden;
width: auto;
display: inline-block;
}
div.image img {
margin: 3px;
border: 1px solid #ffffff;
}
div.image a:hover img {
border: 1px solid;
}
</style>
</head>
<body>
<h1>Sponsors of 6.470</h1>
<div id="sponsors">
<div class="image"><a href=""><img src="images/appian.png" width="150" height="85"></a></div>
<div class="image"><a href=""><img src="images/dropbox.png" width="150px" height="85px"></a></div>
<div class="image"><a href=""><img src="images/facebook.png" width="150px" height="85px"></a></div>
<div class="image"><a href=""><img src="images/nextjump.png" width="150px" height="85px"></a></div>
<div class="image"><a href=""><img src="images/palantir.png" width="150px" height="85px"></a></div>
<div class="image"><a href=""><img src="images/quora.png" width="150px" height="85px"></a></div>
<div class="image"><a href=""><img src="images/tripadvisor.png" width="150px" height="85px"></a></div>
<div class="image"><a href=""><img src="images/vecna.png" width="150px" height="85px"></a></div>
</div>
</body>
</code></pre>
<p>if the <code>width: auto</code> is removed from <code>#sponsors</code> then the <code>div#sponsors</code> is not center aligned even though <code>margin: auto</code> is used. </p>
<p>Similarly if instead of <code>text-align: center</code> is replaced by <code>margin: auto</code> in body style above, then the <code><h1></code> will not be center aligned which is preposterous; </p>
<p>because I have used <code>margin: auto</code> a lot of times and it was able to center the content without any issue. So hence help me and I will appreciate this a lot.</p>
<p>PS: I used firefox and besides use the <code>doctype</code> tag it is still not able to center with <code>margin: auto</code>.</p> | 15,697,890 | 10 | 2 | null | 2013-03-29 05:25:23.507 UTC | 2 | 2022-01-02 15:59:18.39 UTC | 2013-03-29 06:01:20.6 UTC | null | 184,842 | null | 1,851,931 | null | 1 | 22 | css | 73,769 | <p>Define <code>width</code> or <code>margin</code> on your <code>#sponsors</code> ID</p>
<p>as like this</p>
<pre><code>#sponsors{
margin:0 auto; // left margin is auto, right margin is auto , top and bottom margin is 0 set
width:1000px; // define your width according to your design
}
</code></pre>
<p>More about <strong><a href="http://css-tricks.com/snippets/css/centering-a-website/" rel="noreferrer">margin auto</a></strong></p> |
15,761,094 | DOM: why is this a memory leak? | <p>Consider this quote from <a href="https://developer.mozilla.org/en-US/docs/JavaScript/A_re-introduction_to_JavaScript#Memory_leaks" rel="noreferrer">the Mozilla Docs on JavaScript memory leaks</a>:</p>
<blockquote>
<pre><code>function addHandler() {
var el = document.getElementById('el');
el.onclick = function() {
this.style.backgroundColor = 'red';
}
}
</code></pre>
<p>The above code sets up the element to turn red when it is clicked. It
also creates a memory leak. Why? Because the reference to el is
inadvertently caught in the closure created for the anonymous inner
function. This creates a circular reference between a JavaScript
object (the function) and a native object (el).</p>
</blockquote>
<p>Please explain the above reasons of leakage in a simple and concise way, I'm not getting the exact point.</p>
<p>Does the site/page face a security problem because of the leakage? How do I avoid them? What other code can cause memory leaks? How can I tell when a memory leak has occurred?</p>
<p>I'm an absolute beginner to the topic of memory leaks. Could someone clarify this stuff for me, step by step?Also can someone help me clarify this statement <em>"This creates a circular reference between a JavaScript object (the function) and a native object (el)."</em></p> | 15,761,640 | 4 | 13 | 2013-05-08 05:00:49.743 UTC | 2013-04-02 09:53:13.6 UTC | 10 | 2018-05-17 01:01:25.987 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 2,096,191 | null | 1 | 30 | javascript|internet-explorer|memory-leaks|garbage-collection|circular-reference | 3,784 | <p>There are two concepts that will help you understand this example.</p>
<p><strong>1) Closures</strong></p>
<p>The definition of a closure is that <em><a href="http://crockford.com/javascript/private.html" rel="nofollow noreferrer">Every inner function enjoys access to its parent's function variables and parameters.</a></em></p>
<p>When the <code>addHandler()</code> function finishes, the anonymous function still has access to the parent's variable <code>el</code>.</p>
<p>2) <strong>Functions = memory</strong></p>
<p>Every time you define a <code>function</code> a new object is created.
What makes this example slightly confusing is that onclick is an event that can only be set to a DOM element once.</p>
<p>So surely <code>el.onclick = function(){};</code> will just overwrite the old function right?</p>
<p>Wrong! every time addHandler runs, a new function object is created.</p>
<p><strong>In conclusion:</strong> </p>
<p>Each time the function runs it will create a new object, with a closure containing <code>el</code>. Seeing as the anonymous function maintains access to <code>el</code>, the garbage collector cannot remove it from memory. </p>
<p>The anon function will maintain access to el, and el has access to the function, that is a circular reference, which causes a memory leak in IE.</p> |
50,258,960 | How to apply LabelEncoder for a specific column in Pandas dataframe | <p>I have a dataset loaded by dataframe where the class label needs to be encoded using <code>LabelEncoder</code> from scikit-learn. The column <code>label</code> is the class label column which has the following classes:</p>
<pre><code>[‘Standing’, ‘Walking’, ‘Running’, ‘null’]
</code></pre>
<p>To perform label encoding, I tried the following but it does not work. How can I fix it? </p>
<pre><code>from sklearn import preprocessing
import pandas as pd
df = pd.read_csv('dataset.csv', sep=',')
df.apply(preprocessing.LabelEncoder().fit_transform(df['label']))
</code></pre> | 50,259,157 | 3 | 3 | null | 2018-05-09 17:26:12.237 UTC | 4 | 2021-10-01 10:08:58.137 UTC | 2020-04-28 07:41:47.24 UTC | null | 5,840,973 | null | 6,810,148 | null | 1 | 30 | python|python-3.x|machine-learning|scikit-learn|label-encoding | 43,710 | <p>You can try as following:</p>
<pre><code>le = preprocessing.LabelEncoder()
df['label'] = le.fit_transform(df.label.values)
</code></pre>
<p>Or following would work too:</p>
<pre><code>df['label'] = le.fit_transform(df['label'])
</code></pre>
<p>It will replace original <code>label</code> values in dataframe with encoded labels.</p> |
40,018,111 | Magento 2 goes terribly slow (Developer mode) | <p>Recently I started developing magento 2 projects.</p>
<p>First I tried on Windows with xampp and it was a mess... every refresh page was a nightmare, about 30-40sec to load the page. I read about it, that Windows system files is so slow working with magento because the large structure it has, and the article almmost was forcing you to use linux for developing on magento projects.</p>
<p>The problem is I need Windows for another company apps that only works on Windows, I tried to install a virtual machine with Virtualbox, it improved a bit... but the fact I'm working on a virtual machine pissed me off...</p>
<p>The next solution and I'm working currently, is using vagrant. Okay, I feel good developing on this way but it keeps going slow... 15-20s... </p>
<p><b>My config on Vagrant is 5120MB (pc has 8GB) and use all my pc 4 cores. </b></p>
<p>I'm feeling so bad working like this... when I was working on my previous projects, with symfony/Laravel/Codeigniter, was like:</p>
<p>write some lines of code, tab to browser, F5, INSTANTLY see changes.</p>
<p>On M2: write some lines of code, tab to browser, F5, wait... wait... okay now it refreshes the page, but it's not loaded, wait... wait... hmmm almost... okay. No changes but I cleaned the cache... ohhh I guess I had to remove static files too. Go for it... wait again...</p>
<p>God... There's no way M2 goes faster? I'm only asking 5s or something like that... it's just I'm feeling so dumb looking the screen waiting all the time...</p>
<p><b> For aclarations, I'm only asking for development mode, I <strike>tried</strike> had to install another project of magento on production mode for testing things faster and then it's okay fluid as hell compared with developer mode... because... omg... just try to do an order workflow again and again... </b></p>
<p>Well that's all... The only thing I didn't try is using Linux environment on the computer... but it's just the same as using vagrant... I don't understand... how are you developing M2 developers? in special frontend developers... I don't believe they are working the same way as me... waiting 20sec for loading the pages + cleaning cache + removing static files, etc.</p>
<p>Details: I tried everything with vagrant but don't improve, I'm currently on Ubuntu 15.04, Apache 2.4, PHP 5.6 (I tried 7 but still the same) mysql 5.6</p>
<p>This is the network tab:
<a href="https://i.imgur.com/HG7mbeX.png" rel="noreferrer">http://i.imgur.com/HG7mbeX.png</a>
<img src="https://i.imgur.com/HG7mbeX.png" alt="http://i.imgur.com/HG7mbeX.png"></p> | 43,973,521 | 14 | 6 | null | 2016-10-13 10:10:08.243 UTC | 9 | 2020-04-03 19:28:37.227 UTC | 2016-10-17 14:29:16.063 UTC | null | 3,936,931 | null | 3,936,931 | null | 1 | 21 | php|magento|vagrant|e-commerce|magento2 | 17,321 | <p>I tried everything and the only thing it works is the virtual machine that provides bitnami. <a href="https://bitnami.com/stack/magento/virtual-machine" rel="nofollow noreferrer">https://bitnami.com/stack/magento/virtual-machine</a></p>
<p>Seriously, I don't know what has this vm, but goes really fast. I tried creating my VM using a fresh installation of Ubuntu, CentOS, etc. But doesn't work so fine like this VM.</p> |
56,624,895 | Android jetpack navigation component result from dialog | <p>So far I'm successfully able to navigate to dialogs and back using only navigation component. The problem is that, I have to do some stuff in dialog and return result to the fragment where dialog was called from.</p>
<p>One way is to use shared viewmodel. But for that I have to use .of(activity) which leaves my app with a singleton taking up memory, even when I no longer need it.</p>
<p>Another way is to override show(fragmentManager, id) method, get access to fragment manager and from it, access to previous fragment, which could then be set as targetfragment. I've used targetFragment approach before where I would implement a callback interface, so my dialog could notify targetFragment about result. But in navigation component approach it feels hacky and might stop working at one point or another.</p>
<p>Any other ways to do what I want? Maybe there's a way to fix issue on first approach?</p> | 60,430,485 | 3 | 8 | null | 2019-06-17 04:52:13.85 UTC | 11 | 2020-07-28 14:47:30.73 UTC | 2019-11-05 13:38:58.713 UTC | null | 1,000,551 | null | 1,218,970 | null | 1 | 21 | android|android-jetpack|android-architecture-navigation | 11,050 | <p>In Navigation 2.3.0-alpha02 and higher, NavBackStackEntry gives access to a SavedStateHandle. A SavedStateHandle is a key-value map that can be used to store and retrieve data. These values persist through process death, including configuration changes, and remain available through the same object. By using the given SavedStateHandle, you can access and pass data between destinations. This is especially useful as a mechanism to get data back from a destination after it is popped off the stack.</p>
<p>To pass data back to Destination A from Destination B, first set up Destination A to listen for a result on its SavedStateHandle. To do so, retrieve the NavBackStackEntry by using the getCurrentBackStackEntry() API and then observe the LiveData provided by SavedStateHandle.</p>
<pre><code>override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val navController = findNavController();
// We use a String here, but any type that can be put in a Bundle is supported
navController.currentBackStackEntry?.savedStateHandle?.getLiveData("key")?.observe(
viewLifecycleOwner) { result ->
// Do something with the result.
}
</code></pre>
<p>}</p>
<p>In Destination B, you must set the result on the SavedStateHandle of Destination A by using the getPreviousBackStackEntry() API.</p>
<pre><code>navController.previousBackStackEntry?.savedStateHandle?.set("key", result)
</code></pre> |
22,447,651 | Copying mysql databases from one computer to another | <p>I want to copy my mysql database from my computer to another computer. How can I do this?</p> | 22,447,694 | 7 | 3 | null | 2014-03-17 05:39:23.383 UTC | 13 | 2022-08-25 01:06:17.25 UTC | 2016-04-26 14:19:33.527 UTC | null | 2,959 | null | 3,427,626 | null | 1 | 23 | mysql|copy | 96,110 | <p><strong>How to copy Mysql database from one Computer to another / backup database using mysqldump</strong></p>
<ol>
<li><p>We can transfer a MySQL database from one PC to another PC using
mysqldump command.</p>
</li>
<li><p>We have to create dump file of database to transfer database from
one PC to another PC.</p>
</li>
<li><p>MySQL database is not portable database i.e. we cannot transfer it
from one PC to another PC by copying and pasting it.</p>
</li>
<li><p>We can use following method to transfer database.</p>
</li>
<li><p>Creating a dumpfile from database/ Taking backup of MySQL database:</p>
</li>
<li><p>Open command prompt.</p>
</li>
<li><p>Execute following commands to change directory</p>
</li>
</ol>
<pre><code>>c: “press enter”
>cd program files/MySQL/MySQL Server 5.1/ bin “press enter”
>mysqldump -u root -p database_name > database_name.sql “press enter”
Enter password: password of MySQL
</code></pre>
<p>Copy sql file and paste it in PC where you want to transfer database.</p>
<pre><code> 2. Dumping sql file into database:-
- Open MySQL command line client command prompt.
- Execute following command to create database.
</code></pre>
<blockquote>
<p>create database database_name;</p>
</blockquote>
<p>“press enter” Database name is must as that of your database_name.</p>
<p>Copy that sql file into location “c:/program files/MySQL/MySQL Server 5.1/bin”</p>
<pre><code> *- Now open command prompt and execute following commands.*
>C: “press enter”
>cd program files/MySQL/MySQL Server5.1/bin “press enter”
>mysql –u root –p database_name < database_name.sql “press enter”
Your database is created on PC.
Now in MySQL command prompt check your database.
</code></pre>
<p><em><strong>Another one:1</strong></em></p>
<p>This best and the easy way is to use a db tools(SQLyog)</p>
<p><a href="http://www.webyog.com/product/downloads" rel="noreferrer">http://www.webyog.com/product/downloads</a></p>
<p>With this tools you can connect the 2 databases servers and just copy one database on server a to server b.</p>
<p>For more info</p>
<p><a href="http://faq.webyog.com/content/12/32/en/mysql-5-objects-are-greyed-out-in-copy-db-to-other-host-dialogue.html" rel="noreferrer">http://faq.webyog.com/content/12/32/en/mysql-5-objects-are-greyed-out-in-copy-db-to-other-host-dialogue.html</a></p>
<p><img src="https://i.stack.imgur.com/YypfE.png" alt="look here" /></p>
<p><em><strong>Another one:2</strong></em></p>
<p><em>For a database named "lbry", try this:</em></p>
<pre><code>mysqldump -u root -p lbry > dump-lbry.sql
</code></pre>
<p><em>Create a database of the same name ("lbry" in this example) on the computer to which you wish to copy the database contents</em></p>
<p><em>Then import it:</em></p>
<pre><code>mysql -u root -p lbry < dump-lbry.sql
</code></pre> |
13,254,189 | Writing debuggers | <p>I am very dissatisfied at how little info is available on writing Windows debuggers.</p>
<p>Most of the code I have was made by a long process of trial and error, the documentation obviously "thinks" most of the topics are too trivial while explaining in much detail obvious and useless things.</p>
<p>I found 2 articles or so on it but not much stuff I didn't already know came out of it.</p>
<p>Is there any documentation at all, and I mean complete documentation, or some GOOD article (not how to change a byte to 0xCC in vb.NET but real world stuff) about debuggers? Advanced debuggers with memory breakpoints.</p>
<p>For now I didn't find a way for example how to find out how many bytes were being written in a GUARD_PAGE_VIOLATION. I just make a buffer before and after the code executes and compare.</p>
<p>Also where to find info what lies in <code>debug_event.u.Exception.ExceptionRecord.ExceptionInformation</code>? (among other things that lay in debug_event)</p>
<p>Do I really have to reverse the reversing environment myself?</p> | 14,585,096 | 2 | 3 | null | 2012-11-06 15:27:50.473 UTC | 9 | 2013-01-30 08:39:00.727 UTC | 2013-01-30 08:39:00.727 UTC | null | 815,724 | null | 78,054 | null | 1 | 10 | c++|windows|debugging | 2,862 | <p>This is indeed some information available.</p>
<p>DEBUG_EVENT (and the rest of the Debug API) is officially described in MSDN here: <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms679308%28v=vs.85%29.aspx">http://msdn.microsoft.com/en-us/library/windows/desktop/ms679308(v=vs.85).aspx</a></p>
<p>There is a nice CodeProject article: <a href="http://www.codeproject.com/Articles/43682/Writing-a-basic-Windows-debugger">Writing a basic Windows debugger</a> and its sequel: <a href="http://www.codeproject.com/Articles/132742/Writing-Windows-Debugger-Part-2">Writing Windows Debugger - Part 2</a></p>
<p>And finally, a complete list of references from Devon Strawn: <a href="http://devonstrawntech.tumblr.com/post/15878429193/how-to-write-a-windows-debugger-references">How to write a (Windows) debugger - References</a></p> |
13,721,758 | How to search replace with regex and keep case as original in javascript | <p>Here is my problem. I have a string with mixed case in it. I want to search regardless of case and then replace the matches with some characters either side of the matches.</p>
<p>For example:</p>
<pre><code>var s1 = "abC...ABc..aBC....abc...ABC";
var s2 = s.replace(/some clever regex for abc/g, "#"+original abc match+"#");
</code></pre>
<p>The result in s2 should end up like:</p>
<pre><code>"#abC#...#ABc#..#aBC#....#abc#...#ABC#"
</code></pre>
<p>Can this be done with regex? If so, how?</p> | 13,721,786 | 3 | 0 | null | 2012-12-05 11:01:36.217 UTC | 10 | 2022-04-11 17:12:28.34 UTC | null | null | null | null | 1,180,438 | null | 1 | 23 | javascript|regex | 14,578 | <p>This can be done using a callback function for regex replace.</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>var s1 = "abC...ABc..aBC....abc...ABC";
var s2 = s1.replace(/abc/ig, function(match) {
return "#" + match + "#";
});
console.log(s2);</code></pre>
</div>
</div>
</p> |
13,261,602 | RadioGroup.setEnabled(false) doesn't work as expected | <p>I have used <code>setEnabled(false)</code> to set it unable, but it doesn't work and after this method, the value of <code>RadioGroup.isEnabled()</code> is false. The value was changed.</p>
<p>The code is from Android Programming Guide.</p>
<p>PS: The <code>Spinner</code> component use the <code>setEnabled(false)</code> as well.</p>
<p>Code is as follows:</p>
<pre><code>import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioGroup;
public class TestRadioGroup extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.radiogroup);
final RadioGroup testRadioGroup = (RadioGroup) findViewById(R.id.testRadioGroup);
final Button changeEnabledButton = (Button) findViewById(R.id.changeEnabledButton);
changeEnabledButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
changeEnabled(testRadioGroup);
}
});
final Button changeBgColorButton = (Button) findViewById(R.id.changeBackgroundColorButton);
changeBgColorButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
changeBgColor(testRadioGroup);
}
});
}
protected void changeBgColor(RadioGroup testRadioGroup) {
// TODO Auto-generated method stub
testRadioGroup.setBackgroundColor(Color.BLUE);
}
protected void changeEnabled(RadioGroup testRadioGroup) {
// TODO Auto-generated method stub
if (testRadioGroup.isEnabled()) {
testRadioGroup.setEnabled(false);
} else {
testRadioGroup.setEnabled(true);
}
}
</code></pre>
<p>}</p> | 13,262,317 | 3 | 0 | null | 2012-11-07 00:34:15.967 UTC | 6 | 2021-05-26 20:22:37.853 UTC | 2020-04-22 09:21:10.163 UTC | null | 3,641,812 | null | 1,803,669 | null | 1 | 36 | android|android-widget | 21,758 | <p>Iterate and disable each button belonging to the radio group via a loop, for example:</p>
<pre><code>for (int i = 0; i < testRadioGroup.getChildCount(); i++) {
testRadioGroup.getChildAt(i).setEnabled(false);
}
</code></pre> |
13,422,743 | Convert a time span in seconds to formatted time in shell | <p>I have a variable of $i which is seconds in a shell script, and I am trying to convert it to 24 HOUR HH:MM:SS. Is this possible in shell?</p> | 13,422,982 | 7 | 0 | null | 2012-11-16 18:59:53.25 UTC | 8 | 2018-02-13 15:02:25.187 UTC | 2017-05-04 03:26:20.69 UTC | null | 45,375 | null | 377,269 | null | 1 | 39 | linux|shell|timespan|date-formatting | 54,634 | <p>Here's a fun hacky way to do exactly what you are looking for =)</p>
<pre><code>date -u -d @${i} +"%T"
</code></pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>The <code>date</code> utility allows you to specify a time, from string, in seconds since 1970-01-01 00:00:00 UTC, and output it in whatever format you specify.</li>
<li>The <code>-u</code> option is to display UTC time, so it doesn't factor in timezone offsets (since start time from 1970 is in UTC)</li>
<li>The following parts are GNU <code>date</code>-specific (Linux):
<ul>
<li>The <code>-d</code> part tells <code>date</code> to accept the time information from string instead of using <code>now</code></li>
<li>The <code>@${i}</code> part is how you tell <code>date</code> that <code>$i</code> is in seconds</li>
</ul></li>
<li>The <code>+"%T"</code> is for formatting your output. From the <code>man date</code> page: <code>%T time; same as %H:%M:%S</code>. Since we only care about the <code>HH:MM:SS</code> part, this fits!</li>
</ul> |
13,568,337 | No warning or error (or runtime failure) when contravariance leads to ambiguity | <p>First, remember that a .NET <code>String</code> is both <code>IConvertible</code> and <code>ICloneable</code>.</p>
<p>Now, consider the following quite simple code:</p>
<pre><code>//contravariance "in"
interface ICanEat<in T> where T : class
{
void Eat(T food);
}
class HungryWolf : ICanEat<ICloneable>, ICanEat<IConvertible>
{
public void Eat(IConvertible convertibleFood)
{
Console.WriteLine("This wolf ate your CONVERTIBLE object!");
}
public void Eat(ICloneable cloneableFood)
{
Console.WriteLine("This wolf ate your CLONEABLE object!");
}
}
</code></pre>
<p>Then try the following (inside some method):</p>
<pre><code>ICanEat<string> wolf = new HungryWolf();
wolf.Eat("sheep");
</code></pre>
<p>When one compiles this, one gets <em>no</em> compiler error or warning. When running it, it looks like the method called depends on the order of the interface list in my <code>class</code> declaration for <code>HungryWolf</code>. (Try swapping the two interfaces in the comma (<code>,</code>) separated list.)</p>
<p>The question is simple: <strong>Shouldn't this give a compile-time warning (or throw at run-time)?</strong></p>
<p>I'm probably not the first one to come up with code like this. I used <em>contravariance</em> of the interface, but you can make an entirely analogous example with <em>covarainace</em> of the interface. And in fact <a href="http://blogs.msdn.com/b/ericlippert/archive/2007/11/09/covariance-and-contravariance-in-c-part-ten-dealing-with-ambiguity.aspx" rel="noreferrer">Mr Lippert did just that</a> a long time ago. In the comments in his blog, almost everyone agrees that it should be an error. Yet they allow this silently. <strong>Why?</strong></p>
<p><strong>---</strong></p>
<p><strong>Extended question:</strong></p>
<p>Above we exploited that a <code>String</code> is both <code>Iconvertible</code> (interface) and <code>ICloneable</code> (interface). Neither of these two interfaces derives from the other.</p>
<p>Now here's an example with base classes that is, in a sense, a bit worse.</p>
<p>Remember that a <code>StackOverflowException</code> is both a <code>SystemException</code> (direct base class) and an <code>Exception</code> (base class of base class). Then (if <code>ICanEat<></code> is like before):</p>
<pre><code>class Wolf2 : ICanEat<Exception>, ICanEat<SystemException> // also try reversing the interface order here
{
public void Eat(SystemException systemExceptionFood)
{
Console.WriteLine("This wolf ate your SYSTEM EXCEPTION object!");
}
public void Eat(Exception exceptionFood)
{
Console.WriteLine("This wolf ate your EXCEPTION object!");
}
}
</code></pre>
<p>Test it with:</p>
<pre><code>static void Main()
{
var w2 = new Wolf2();
w2.Eat(new StackOverflowException()); // OK, one overload is more "specific" than the other
ICanEat<StackOverflowException> w2Soe = w2; // Contravariance
w2Soe.Eat(new StackOverflowException()); // Depends on interface order in Wolf2
}
</code></pre>
<p>Still no warning, error or exception. Still depends on interface list order in <code>class</code> declaration. But the reason why I think it's worse is that this time someone might think that overload resolution would always pick <code>SystemException</code> because it's more specific than just <code>Exception</code>.</p>
<hr>
<p>Status before the bounty was opened: Three answers from two users.</p>
<p>Status on the last day of the bounty: Still no new answers received. If no answers show up, I shall have to award the bounty to Moslem Ben Dhaou.</p> | 14,184,540 | 4 | 13 | null | 2012-11-26 15:51:34.567 UTC | 16 | 2013-02-18 05:31:07.46 UTC | 2012-12-05 08:53:29.62 UTC | null | 1,336,654 | null | 1,336,654 | null | 1 | 43 | c#|.net|undefined-behavior|contravariance|ambiguity | 1,077 | <p>I believe the compiler does the better thing in VB.NET with the warning, but I still don't think that is going far enough. Unfortunately, the "right thing" probably either requires disallowing something that is potentially useful(implementing the same interface with two covariant or contravariant generic type parameters) or introducing something new to the language.</p>
<p>As it stands, there is no place the compiler could assign an error right now other than the <code>HungryWolf</code> class. That is the point at which a class is claiming to know how to do something that could potentially be ambiguous. It is stating </p>
<blockquote>
<p>I know how to eat an <code>ICloneable</code>, or anything implementing or inheriting from it, in a certain way. </p>
<p>And, I also know how to eat an <code>IConvertible</code>, or anything implementing or inheriting from it, in a certain way. </p>
</blockquote>
<p>However, <strong>it never states what it should do</strong> if it receives on its plate something that is <strong>both an <code>ICloneable</code> and an <code>IConvertible</code></strong>. This doesn't cause the compiler any grief if it is given an instance of <code>HungryWolf</code>, since it can say with certainty <em>"Hey, I don't know what to do here!"</em>. But it will give the compiler grief when it is given the <code>ICanEat<string></code> instance. <strong>The compiler has no idea what the actual type of the object in the variable is, only that it definitely does implement <code>ICanEat<string></code></strong>. </p>
<p>Unfortunately, when a <code>HungryWolf</code> is stored in that variable, it ambiguously implements that exact same interface twice. So surely, we cannot throw an error trying to call <code>ICanEat<string>.Eat(string)</code>, as that method exists and would be perfectly valid for many other objects which could be placed into the <code>ICanEat<string></code> variable (<a href="https://stackoverflow.com/users/183217/batwad">batwad</a> already mentioned this in one of his answers). </p>
<p>Further, although the compiler could complain that the assignment of a <code>HungryWolf</code> object to an <code>ICanEat<string></code> variable is ambiguous, it cannot prevent it from happening in two steps. A <code>HungryWolf</code> can be assigned to an <code>ICanEat<IConvertible></code> variable, which could be passed around into other methods and eventually assigned into an <code>ICanEat<string></code> variable. <strong>Both of these are perfectly legal assignments</strong> and it would be impossible for the compiler to complain about either one.</p>
<p>Thus, <strong>option one</strong> is to disallow the <code>HungryWolf</code> class from implementing both <code>ICanEat<IConvertible></code> and <code>ICanEat<ICloneable></code> when <code>ICanEat</code>'s generic type parameter is contravariant, since these two interfaces could unify. However, this <strong>removes the ability to code something useful</strong> with no alternative workaround.</p>
<p><strong>Option two</strong>, unfortunately, would <strong>require a change to the compiler</strong>, both the IL and the CLR. It would allow the <code>HungryWolf</code> class to implement both interfaces, but it would also require the implementation of the interface <code>ICanEat<IConvertible & ICloneable></code> interface, where the generic type parameter implements both interfaces. This likely is not the best syntax(what does the signature of this <code>Eat(T)</code> method look like, <code>Eat(IConvertible & ICloneable food)</code>?). Likely, a better solution would be to an auto-generated generic type upon the implementing class so that the class definition would be something like:</p>
<pre><code>class HungryWolf:
ICanEat<ICloneable>,
ICanEat<IConvertible>,
ICanEat<TGenerated_ICloneable_IConvertible>
where TGenerated_ICloneable_IConvertible: IConvertible, ICloneable {
// implementation
}
</code></pre>
<p>The IL would then have to changed, to be able to allow interface implementation types to be constructed just like generic classes for a <code>callvirt</code> instruction:</p>
<pre><code>.class auto ansi nested private beforefieldinit HungryWolf
extends
[mscorlib]System.Object
implements
class NamespaceOfApp.Program/ICanEat`1<class [mscorlib]System.ICloneable>,
class NamespaceOfApp.Program/ICanEat`1<class [mscorlib]System.IConvertible>,
class NamespaceOfApp.Program/ICanEat`1<class ([mscorlib]System.IConvertible, [mscorlib]System.ICloneable>)!TGenerated_ICloneable_IConvertible>
</code></pre>
<p>The CLR would then have to process <code>callvirt</code> instructions by constructing an interface implementation for <code>HungryWolf</code> with <code>string</code> as the generic type parameter for <code>TGenerated_ICloneable_IConvertible</code>, and checking to see if it matches better than the other interface implementations.</p>
<p>For covariance, all of this would be simpler, since the extra interfaces required to be implemented wouldn't have to be generic type parameters with constraints <strong>but simply the most derivative base type between the two other types</strong>, which is known at compile time.</p>
<p>If the same interface is implemented more than twice, then the number of extra interfaces required to be implemented grows exponentially, but this would be the cost of the flexibility and type-safety of implementing multiple contravariant(or covariant) on a single class.</p>
<p>I doubt this will make it into the framework, but it would be my preferred solution, especially since the new language complexity would always be self-contained to the class which wishes to do what is currently dangerous.</p>
<hr>
<p><strong>edit:</strong><br>
Thanks <a href="https://stackoverflow.com/users/1336654/jeppe-stig-nielsen">Jeppe</a> for reminding me that <strong>covariance is no simpler than contravariance</strong>, due to the fact that common interfaces must also be taken into account. In the case of <code>string</code> and <code>char[]</code>, the set of greatest commonalities would be {<code>object</code>, <code>ICloneable</code>, <code>IEnumerable<char></code>} (<code>IEnumerable</code> is <em>covered</em> by <code>IEnumerable<char></code>). </p>
<p>However, this would require a new syntax for the interface generic type parameter constraint, to indicate that the generic type parameter only needs to </p>
<ul>
<li>inherit from the specified class or a class implementing at least one of the specified interfaces</li>
<li>implement at least one of the specified interfaces</li>
</ul>
<p>Possibly something like:</p>
<pre><code>interface ICanReturn<out T> where T: class {
}
class ReturnStringsOrCharArrays:
ICanReturn<string>,
ICanReturn<char[]>,
ICanReturn<TGenerated_String_ArrayOfChar>
where TGenerated_String_ArrayOfChar: object|ICloneable|IEnumerable<char> {
}
</code></pre>
<p>The generic type parameter <code>TGenerated_String_ArrayOfChar</code> in this case(where one or more interfaces are common) always have to be treated as <code>object</code>, even though the common base class has already derived from <code>object</code>; because <strong>the common type may implement a common interface without inheriting from the common base class</strong>.</p> |
13,654,401 | Why transform normals with the transpose of the inverse of the modelview matrix? | <p>I am working on some shaders, and I need to transform normals. </p>
<p>I read in few tutorials the way you transform normals is you <em>multiply them with the transpose of the inverse of the modelview matrix</em>. But I can't find explanation of why is that so, and what is the logic behind that?</p> | 13,654,662 | 5 | 0 | null | 2012-11-30 22:59:08.893 UTC | 34 | 2021-11-30 08:20:44.543 UTC | 2021-11-30 08:20:44.543 UTC | null | 1,907,004 | null | 1,796,942 | null | 1 | 58 | opengl|glsl|game-engine|game-physics | 39,019 | <p>Take a look at this tutorial:</p>
<p><a href="https://paroj.github.io/gltut/Illumination/Tut09%20Normal%20Transformation.html" rel="noreferrer">https://paroj.github.io/gltut/Illumination/Tut09%20Normal%20Transformation.html</a></p>
<p>You can imagine that when the surface of a sphere stretches (so the sphere is scaled along one axis or something similar) the normals of that surface will all 'bend' towards each other. It turns out you need to invert the scale applied to the normals to achieve this. This is the same as transforming with the <strong>Inverse Transpose Matrix</strong>. The link above shows how to derive the inverse transpose matrix from this.</p>
<p>Also note that when the scale is uniform, you can simply pass the original matrix as normal matrix. Imagine the same sphere being scaled uniformly along all axes, the surface will not stretch or bend, nor will the normals.</p> |
13,511,203 | Why can't I assign a *Struct to an *Interface? | <p>I'm just working through the <a href="http://tour.golang.org/">Go tour</a>, and I'm confused about pointers and interfaces. Why doesn't this Go code compile?</p>
<pre><code>package main
type Interface interface {}
type Struct struct {}
func main() {
var ps *Struct
var pi *Interface
pi = ps
_, _ = pi, ps
}
</code></pre>
<p>i.e. if <code>Struct</code> is an <code>Interface</code>, why wouldn't a <code>*Struct</code> be a <code>*Interface</code>?</p>
<p>The error message I get is:</p>
<pre><code>prog.go:10: cannot use ps (type *Struct) as type *Interface in assignment:
*Interface is pointer to interface, not interface
</code></pre> | 13,511,853 | 4 | 3 | null | 2012-11-22 10:55:50.997 UTC | 50 | 2020-01-11 10:38:59.377 UTC | null | null | null | null | 4,728 | null | 1 | 160 | go | 72,073 | <p>When you have a struct implementing an interface, a pointer to that struct implements automatically that interface too. That's why you never have <code>*SomeInterface</code> in the prototype of functions, as this wouldn't add anything to <code>SomeInterface</code>, and you don't need such a type in variable declaration (see <a href="https://stackoverflow.com/questions/13255907/in-go-http-handlers-why-is-the-responsewriter-a-value-but-the-request-a-pointer">this related question</a>).</p>
<p>An interface value isn't the value of the concrete struct (as it has a variable size, this wouldn't be possible), but it's a kind of pointer (to be more precise a pointer to the struct and a pointer to the type). Russ Cox describes it exactly <a href="http://research.swtch.com/interfaces" rel="noreferrer">here</a> :</p>
<blockquote>
<p>Interface values are represented as a two-word pair giving a pointer
to information about the type stored in the interface and a pointer to
the associated data.</p>
</blockquote>
<p><img src="https://i.stack.imgur.com/H78Bz.png" alt="enter image description here"></p>
<p>This is why <code>Interface</code>, and not <code>*Interface</code> is the correct type to hold a pointer to a struct implementing <code>Interface</code>.</p>
<p>So you must simply use</p>
<pre><code>var pi Interface
</code></pre> |
39,802,164 | Asp.net MVC - How to hash password | <p>How do I hash an users input(password) to database and then later read the hashed password during login? </p>
<p>I believe the solution is to hash the password upon register, where the password is saved as hashed inside db. Later upon Login, it should un-hash and compare its password with users password-input.
But I don't know how to do it. </p>
<p>I allowed password to have <code>nvarchar(MAX)</code>in db since hashed password are usually long.</p>
<pre><code> [Required]
[StringLength(MAX, MinimumLength = 3, ErrorMessage = "min 3, max 50 letters")]
public string Password { get; set; }
</code></pre>
<p>Register:</p>
<pre><code> [HttpPost]
public ActionResult Register(User user) {
if (ModelState.IsValid) {
var u = new User {
UserName = user.UserName,
Password = user.Password
};
db.Users.Add(u);
db.SaveChanges();
return RedirectToAction("Login");
}
}return View();
}
</code></pre>
<p>Login: </p>
<pre><code> public ActionResult Login() {
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(User u) {
if (ModelState.IsValid)
{
using (UserEntities db = new UserEntities()) {
//un-hash password?
var v = db.Users.Where(a => a.UserName.Equals(u.UserName) && a.Password.Equals(u.Password)).FirstOrDefault();
if (v != null) {
return RedirectToAction("Index", "Home"); //after login
}
}
}return View(u);
}
</code></pre>
<p>I'm using database first.</p> | 39,802,195 | 3 | 5 | null | 2016-10-01 01:31:40.24 UTC | 4 | 2019-07-23 07:51:27.773 UTC | 2016-10-01 01:32:52.23 UTC | null | 6,026,036 | null | 6,026,036 | null | 1 | 7 | c#|asp.net-mvc|entity-framework|hash | 45,331 | <p>You should never need to unhash a password. A <a href="https://en.wikipedia.org/wiki/Cryptographic_hash_function" rel="noreferrer">cryptographic hash function</a> is supposed to be a one-way operation. </p>
<p>(And that's precisely why it is called <em>hashing</em> and not <em>encrypting</em>. If unhashing passwords was to be a normal procedure in your flow of operations, then it would not be hashing and unhashing, it would be encrypting and decrypting. So, hashing is a different thing from encryption, precisely because unhashing is not supposed to ever happen.)</p>
<p>Hashing provides security, because nobody can steal your user's passwords even if they manage to view the contents of your database.</p>
<ul>
<li><p>When the user registers, compute the hash of their password, store the hash in the database, and <em>forget the password forever.</em></p></li>
<li><p>When the user logs in, compute the hash of the password they entered, (forget that password too,) and see if the hash matches the hash stored in the database.</p></li>
</ul>
<p>This is the mechanism used by most websites out there, and that's precisely why if you successfully go through the "I forgot my password" procedure, they will <em>still not</em> show you your password: they don't have it; they cannot retrieve it even if they wanted to. Instead, they send you a password reset link.</p>
<p>As for how to compute a hash from a string, the interwebz abound with answers to that question, for example: <a href="https://msdn.microsoft.com/en-us/library/system.security.cryptography.md5(v=vs.110).aspx#Anchor_7" rel="noreferrer">MD5 (MSDN)</a>; <a href="https://msdn.microsoft.com/en-us/library/system.security.cryptography.sha256(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#Anchor_7" rel="noreferrer">SHA-256 (MSDN)</a>; <a href="https://msdn.microsoft.com/en-us/library/system.security.cryptography.sha512(v=vs.110).aspx#Anchor_7" rel="noreferrer">SHA-512 (MSDN)</a></p> |
39,621,880 | Is there an alternative for .bashrc for /bin/sh? | <p>I need a script which is run on startup of <code>/bin/sh</code>, similar to <code>.bashrc</code> for <code>/bin/bash</code>. Is there any way to do this?</p>
<p><strong>EDIT:</strong></p>
<p>I tried both <code>/etc/profile</code> and <code>~/.profile</code>, I wrote <code>echo 'hello world'</code> to both files. None of these are working. When I type <code>sh</code> into the console, nothing pops up.</p>
<p>I am using ArchLinux.</p> | 39,622,593 | 2 | 5 | null | 2016-09-21 16:27:36.95 UTC | 9 | 2016-09-21 17:24:41.287 UTC | 2016-09-21 16:46:29.187 UTC | null | 14,122 | null | 2,339,620 | null | 1 | 21 | linux|shell|sh | 17,874 | <p>In Arch, <code>/bin/sh</code> is a symlink to <code>/bin/bash</code>, which has quite a few rules about startup scripts, with special cases when called <code>sh</code> :</p>
<blockquote>
<p>If bash is invoked with the name sh, it tries to mimic the startup
behavior of historical versions of sh as closely as possible, ...</p>
</blockquote>
<p>If you start it from the console, without any command, i.e. as an interactive, non-login shell, you should use the <code>ENV</code> variable :</p>
<pre><code>export ENV=~/.profile
sh
</code></pre>
<p>or</p>
<pre><code>ENV=~/.profile sh
</code></pre>
<blockquote>
<p>When invoked as an <strong>interactive [non login] shell with the name sh</strong>, bash looks for the variable ENV, expands its value if it is defined, and uses the expanded value as the name of a file to read and execute. </p>
</blockquote>
<p>Alternatively you can use the <code>--login</code> option to make it behave like a login shell, and read the <code>.profile</code> file.</p>
<pre><code>sh --login
</code></pre>
<blockquote>
<p>When invoked <strong>as an interactive login shell [with the name sh]</strong>, or a
non-interactive shell with the --login option, it first attempts to
read and execute commands from /etc/profile and ~/.profile, in that
order</p>
</blockquote> |
20,529,234 | How to select/reduce a list of dictionaries in Flask/Jinja | <p>I have a Jinja template with a list of dictionaries. Order matters. I'd like to reduce the list or lookup values based on the keys/values of the dictionaries. Here's an example:</p>
<pre><code>{%
set ordered_dicts = [
{
'id': 'foo',
'name': 'My name is Foo'
},
{
'id': 'bar',
'name': 'My name is Bar'
}
]
%}
</code></pre>
<p>If I have a variable <code>some_id = 'foo'</code>, how do I get <code>'My name is Foo'</code> out of <code>ordered_dicts</code> in my Jinja template? </p>
<p>I tried <a href="http://jinja.pocoo.org/docs/templates/#select"><code>select()</code></a> and <a href="http://jinja.pocoo.org/docs/templates/#selectattr"><code>selectattr()</code></a> but couldn't figure them out based on the documentation. Here's what I tried:</p>
<pre><code>{{ ordered_dicts|selectattr("id", "foo") }}
</code></pre>
<p>That outputs: </p>
<pre><code><generator object _select_or_reject at 0x10748d870>
</code></pre>
<p>I don't think I'm understanding the use of <code>select()</code> and <code>selectattr()</code> properly. </p>
<p>Do I need to iterate over the list and do the lookup manually?</p>
<hr>
<p><strong>Update:</strong> </p>
<p>As codegeek and gipi pointed out, I need to do something like this with the generator:</p>
<pre><code>{{ ordered_dicts|selectattr("id", "foo")|list }}
</code></pre>
<p>The resulting error: <code>TemplateRuntimeError: no test named 'foo'</code>, which clarifies how <code>selectattr()</code> works. The second argument has to be one of <a href="http://jinja.pocoo.org/docs/templates/#list-of-builtin-tests">the builtin tests</a>. As far as I can tell, none of these tests will let me check whether the value associated with a key matches another value. Here's what I'd like to do:</p>
<pre><code>{{ ordered_dicts|selectattr("id", "sameas", "foo")|list }}
</code></pre>
<p>But that doesn't work, since the <code>sameas</code> test checks whether two objects are really the same object in memory, not whether two strings/numbers are equivalent. </p>
<p>So is it possible to pick an item based on a key/value comparison test?</p> | 24,187,114 | 6 | 2 | null | 2013-12-11 20:26:28.457 UTC | 6 | 2018-08-05 06:57:38.903 UTC | 2013-12-12 02:12:15.41 UTC | null | 174,676 | null | 174,676 | null | 1 | 21 | python|flask|jinja2 | 39,882 | <p>I've just backported <code>equalto</code> like this:</p>
<pre><code>app.jinja_env.tests['equalto'] = lambda value, other : value == other
</code></pre>
<p>After that <a href="http://jinja.pocoo.org/docs/templates/#equalto">this example from 2.8 docs</a> works:</p>
<pre><code>{{ users|selectattr("email", "equalto", "[email protected]") }}
</code></pre>
<p><em>Update</em>: Flask has a decorator for registering tests, slightly cleaner syntax: <a href="http://flask.pocoo.org/docs/api/#flask.Flask.template_test">http://flask.pocoo.org/docs/api/#flask.Flask.template_test</a></p> |
3,857,485 | iphone 4 sdk : detect return from background mode | <p>How can I detect that an app has just returned from "background mode"? I mean, I don't want my app to fetch data (each 60 sec) when the user press the "home button". But, I'd like to make some "special" update the first time the app is in foreground mode.</p>
<p>How can I detect these two events:</p>
<ol>
<li>app going to background mode </li>
<li>app going to foreground mode</li>
</ol>
<p>Thanks in advance.</p>
<p>François</p> | 3,857,559 | 2 | 0 | null | 2010-10-04 17:10:24.067 UTC | 13 | 2017-11-26 03:44:35.76 UTC | 2012-08-14 13:33:41.287 UTC | null | 1,487,063 | null | 446,576 | null | 1 | 26 | ios4|background-foreground | 19,051 | <p>Here's how to listen for such events:</p>
<pre><code>// Register for notification when the app shuts down
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFunc) name:UIApplicationWillTerminateNotification object:nil];
// On iOS 4.0+ only, listen for background notification
if(&UIApplicationDidEnterBackgroundNotification != nil)
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFunc) name:UIApplicationDidEnterBackgroundNotification object:nil];
}
// On iOS 4.0+ only, listen for foreground notification
if(&UIApplicationWillEnterForegroundNotification != nil)
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFunc) name:UIApplicationWillEnterForegroundNotification object:nil];
}
</code></pre>
<p>Note: The <code>if(&SomeSymbol)</code> checks ensure that your code will work on iOS 4.0+ and also on iOS 3.x - if you build against an iOS 4.x or 5.x SDK and set the deployment target to iOS 3.x your app can still run on 3.x devices but the address of relevant symbols will be nil, and therefore it won't try to ask for notifications that don't exist on 3.x devices (which would crash the app).</p>
<p><strong>Update:</strong> In this case, the <code>if(&Symbol)</code> checks are now redundant (unless you <em>really</em> need to support iOS 3 for some reason). However, it's useful to know this technique for checking if an API exists before using it. I prefer this technique than testing the OS version because you are checking if the specific API is present rather than using outside knowledge of what APIs are present in what OS versions.</p> |
3,888,569 | expected specifier-qualifier-list before | <p>I have this struct type definition:</p>
<pre><code>typedef struct {
char *key;
long canTag;
long canSet;
long allowMultiple;
confType *next;
} confType;
</code></pre>
<p>When compiling, gcc throws this error:</p>
<pre><code>conf.c:6: error: expected specifier-qualifier-list before ‘confType’
</code></pre>
<p>What does this mean? It doesn't seem related to other questions with this error.</p> | 3,888,583 | 2 | 4 | null | 2010-10-08 07:40:58.957 UTC | 4 | 2010-10-08 07:52:48.493 UTC | null | null | null | null | 330,644 | null | 1 | 27 | c | 84,599 | <p>You used confType before you declared it. (for next). Instead, try this:</p>
<pre><code>typedef struct confType {
char *key;
long canTag;
long canSet;
long allowMultiple;
struct confType *next;
} confType;
</code></pre> |
3,591,867 | How to get the last n items in a PHP array as another array? | <p>How to I get an array of the last n items of another array in PHP?</p> | 3,591,872 | 2 | 0 | null | 2010-08-28 18:10:21.793 UTC | 4 | 2016-03-14 12:31:07.367 UTC | null | null | null | null | 263,929 | null | 1 | 45 | php|arrays | 24,005 | <p><code>$n</code> is equal to the number of items you want off the end.</p>
<pre><code>$arr = array_slice($old_arr, -$n);
</code></pre> |
28,473,710 | How to scroll to element with Selenium WebDriver | <p>How do I get Selenium WebDriver to scroll to a particular element to get it on the screen. I have tried a lot of different options but have had no luck.
Does this not work in the C# bindings?</p>
<p>I can make it jump to a particular location ex</p>
<pre><code>((IJavaScriptExecutor)Driver).ExecuteScript("window.scrollTo(0, document.body.scrollHeight - 150)");
</code></pre>
<p>But I want to be able to send it to different elements without giving the exact location each time.</p>
<pre><code>public IWebElement Example { get { return Driver.FindElement(By.Id("123456")); } }
</code></pre>
<p>Ex 1)</p>
<pre><code>((IJavaScriptExecutor)Driver).ExecuteScript("arguments[0].scrollIntoView(true);", Example);
</code></pre>
<p>Ex 2)</p>
<pre><code>((IJavaScriptExecutor)Driver).ExecuteScript("window.scrollBy(Example.Location.X", "Example.Location.Y - 100)");
</code></pre>
<p>When I watch it, it does not jump down the page to the element, and the exception matches the element being off screen.</p>
<p>I added an <code>bool ex = Example.Exists();</code> after it and checked the results.
It does Exist (its true).
Its not Displayed (as its still offscreen as it has not moved to the element)
Its not Selected ??????</p>
<p>Someone is seeing success By.ClassName.
Does anyone know if there is a problem with doing this By.Id in the C# bindings?</p> | 31,241,093 | 11 | 5 | null | 2015-02-12 09:25:43.76 UTC | 5 | 2022-05-18 20:48:03.897 UTC | 2020-08-29 19:58:24.03 UTC | null | 5,231,607 | null | 2,583,014 | null | 1 | 29 | c#|selenium|selenium-webdriver|selenium-chromedriver | 116,631 | <p>Its little older question, but I believe that there is better solution than suggested above.</p>
<p>Here is original answer: <a href="https://stackoverflow.com/a/26461431/1221512">https://stackoverflow.com/a/26461431/1221512</a></p>
<p>You should use Actions class to perform scrolling to element.</p>
<pre><code>var element = driver.FindElement(By.id("element-id"));
Actions actions = new Actions(driver);
actions.MoveToElement(element);
actions.Perform();
</code></pre> |
9,469,264 | C++ "cin" only reads the first word | <pre><code>#include<iostream.h>
#include<conio.h>
class String
{
char str[100];
public:
void input()
{
cout<<"Enter string :";
cin>>str;
}
void display()
{
cout<<str;
}
};
int main()
{
String s;
s.input();
s.display();
return 0;
}
</code></pre>
<p>I am working in Turbo C++ 4.5. The code is running fine but its not giving the desired output
for e.g if i give input as "steve hawking" only "steve" is being displayed. Can anyone please help?</p> | 9,469,338 | 5 | 2 | null | 2012-02-27 17:21:13.077 UTC | 1 | 2020-03-02 15:31:20.933 UTC | 2020-03-02 15:31:20.933 UTC | null | 4,342,498 | null | 1,221,631 | null | 1 | 6 | c++|string | 44,910 | <p>Using <code>>></code> on a stream reads one word at a time. To read a whole line into a <code>char</code> array:</p>
<pre><code>cin.getline(str, sizeof str);
</code></pre>
<p>Of course, once you've learnt how to implement a string, you should use <code>std::string</code> and read it as</p>
<pre><code>getline(cin, str);
</code></pre>
<p>It would also be a very good idea to get a compiler from this century; yours is over 15 years old, and C++ has changed significantly since then. Visual Studio Express is a good choice if you want a free compiler for Windows; other compilers are available.</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.