qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
112,464 | I have SharePoint list with more than 1000 items(ID's).
I'm dumping list with *BASH* script to my server with *curl*:
`curl --ntlm -u $curl_account $SITE -o $output_file 2>/dev/null`
and I get only 1000 ID's to my *$output\_file*. Is there are some limits or smth to do, that I could get all items?
Thanks for any info :) | 2014/08/20 | [
"https://sharepoint.stackexchange.com/questions/112464",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/31504/"
] | add RowLimit=0
```
http://sharepoint/_vti_bin/owssvr.dll?Cmd=Display&XMLDATA=1&RowLimit=0&List=%7BID1%7D&View=%7BID2%7D
```
Setting the row limit will override the default limit | Try and do it in a loop, record the last id retrieved after each 1000, then add a filter to the call i.e. where ID > lastid. do this until the number of items retrieved is < 1000 |
328,103 | First of all, I don't know if this kind of question is allowed here, so sorry if it isn't.
I am looking for a 7400 series register which has common in and out pins (like for the RAM ou EEPROM: ) with a load signal and a store signal. I searched on Google but I didn't found anything (maybe my searches are wrong).
Does it exist and if yes, what is its name/reference? | 2017/09/07 | [
"https://electronics.stackexchange.com/questions/328103",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/139408/"
] | After deeper research on the Wikipedia list of the 7400 series (<https://en.wikipedia.org/wiki/List_of_7400_series_integrated_circuits>), I found out the 74299 which has common in/out pins.
I searched with the wrong keyword which should have been "bidirectionnal register". | There isn't a register that has common input and output pins, but you can certainly wire up a '373 or '374 (8-bit latch or register with tristate outputs) to achieve that functionality:

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2f5UBPj.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/) |
13,740,691 | I'm a little bit confused by the behavior of the multiplication operator `*` when scipy sparse matrices are involved. It seems the operator implements matrix multiplication, not component-wise multiplication as it would with numpy arrays.
Some code to check this:
```
from scipy.sparse import lil_matrix
A = lil_matrix(-numpy.eye(2))
b = lil_matrix(numpy.ones((2,2)))
print (A * B).toarray()
```
results in:
```
[[-1. -1.]
[-1. -1.]]
```
The [documentation](http://docs.scipy.org/doc/scipy/reference/sparse.html#module-scipy.sparse) of the `scipy.sparse` module does not really go into details on this, and I wonder whether there is a clear specification of the multiplication behavior somewhere?
Furthermore, are there some clearly defined rules for multiplication operator with scipy sparse matrices and numpy matrices or arrays? | 2012/12/06 | [
"https://Stackoverflow.com/questions/13740691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1050484/"
] | Documentation is indeed scarse. If you are looking for component-wise multiplication you can use `A.multiply(b)`, where b can be an element, vector or matrix:
<https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.sparse.csr_matrix.multiply.html> | Yes, it is matrix multiplication in all cases. |
25,255,329 | I have a query:
```
db.events.aggregate(
{ $match: { "camera._id": "1NJE48", "start_timestamp": { $lte: 1407803834.07 } } },
{ $sort: { "start_timestamp": -1 } },
{ $limit: 2 },
{ $project: { "_id": 0, "snapshots": 1 } }
)
```
It returns data like so:
```
/* 0 */
{
"result" : [
{
"snapshots" : {
"1401330834010" : {
"uploaded_timestamp" : 1401330895,
"filename_timestamp" : 1401330834.01,
"timestamp" : 1401330834.01
},
"1401330835010" : {
"uploaded_timestamp" : 1401330896,
"filename_timestamp" : 1401330835.01,
"timestamp" : 1401330835.01
},
"1401330837010" : {
"uploaded_timestamp" : 1401330899,
"filename_timestamp" : 1401330837.01,
"timestamp" : 1401330837.01
}
}
},
{
"snapshots" : {
"1401319837010" : {
"uploaded_timestamp" : 1401319848,
"filename_timestamp" : 1401319837.01,
"timestamp" : 1401319837.01
},
"1401319838010" : {
"uploaded_timestamp" : 1401319849,
"filename_timestamp" : 1401319838.01,
"timestamp" : 1401319838.01
},
"1401319839010" : {
"uploaded_timestamp" : 1401319850,
"filename_timestamp" : 1401319839.01,
"timestamp" : 1401319839.01
}
}
}
],
"ok" : 1
}
```
I would like an array of snapshots:
```
/* 0 */
{
"result" : [
{
"uploaded_timestamp" : 1401330895,
"filename_timestamp" : 1401330834.01,
"timestamp" : 1401330834.01
},
{
"uploaded_timestamp" : 1401330896,
"filename_timestamp" : 1401330835.01,
"timestamp" : 1401330835.01
},
{
"uploaded_timestamp" : 1401330899,
"filename_timestamp" : 1401330837.01,
"timestamp" : 1401330837.01
},
{
"uploaded_timestamp" : 1401319848,
"filename_timestamp" : 1401319837.01,
"timestamp" : 1401319837.01
},
{
"uploaded_timestamp" : 1401319849,
"filename_timestamp" : 1401319838.01,
"timestamp" : 1401319838.01
},
{
"uploaded_timestamp" : 1401319850,
"filename_timestamp" : 1401319839.01,
"timestamp" : 1401319839.01
}
],
"ok" : 1
}
```
I.e. no key names. I'm struggling to understand how to deal with the aggregation framework when the key names are unique like they are here. | 2014/08/12 | [
"https://Stackoverflow.com/questions/25255329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145567/"
] | I found out that it is a bug and you have to open Scene Builder from your desktop and:
* File>Preferences>Reset To BuiltIn Defaults
* File>Open recent>clear menu | I installed scene builder from a different maker (gluon)
Works wonderfully.
Associate the FXML files in your SO to that they are open by this application instead of the "normal" one and you can forget about this problem. |
62,668,365 | I want to get the value of a desired variable among several variables in a class
When i put string and class in Method, the method returns the value of the variable with the same name as the string received among all variables included in the class.
This method can get any type of class. So this method need to use generic.
Do anyone have a good idea for my problem?
```
public class A
{
public int valA_int;
public string valA_string;
public float valA_float;
public long valA_long;
}
public class B
{
public int valB_int;
public string valB_string;
public float valB_float;
public long valB_long;
}
public static class Method {
public static object GetvalueFromClass<T>(string varName, T classType) {
//Find val from class
return object;
}
}
public class Program {
public A aClass;
public B bClass;
public void MainProgram() {
object valA_int = Method.GetvalueFromClass("valA_int", aClass);
object valB_long = Method.GetvalueFromClass("valB_long", bClass);
}
}
```
The concept of method is like this.
please help me to figure out my problem. | 2020/07/01 | [
"https://Stackoverflow.com/questions/62668365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10086945/"
] | your task already defined.
if you use
```
#{Class}.GetType().GetProperty(#{VariableName}).GetValue(#{DefinedClass}, null);
```
you can easily get variable from your class with variable name.
it returns variable as object. so you need to convert it
**Example code**
```
CLASS YourClass = [A CLASS WHICH IS PRE DEFINED];
object Target = YourClass.GetType().GetProperty("YOUR VARIABLE").GetValue(YourClass , null);
``` | ok, use reflection to get all the variables in the object, then run through a loop checking them against the string of the property name. From there you should be able to return the value.
So something like
```
public object FindValByName(string PropName)
{
PropName = PropName.ToLower();
var props = this.GetType().GetProperties();
foreach(var item in props) {
if(item.Name.ToLower() == PropName) {
return item.GetValue(this);
}
}
}
``` |
181,108 | I'm having trouble implementing a concurrent login check.
The site needs to prevent more than 5 concurrent sessions for any particular user at one time.
**Example:**
User Matt can have 5 active sessions.
>
> If user Matt tries to login with a 6th session, it will remove the session which logged in first & had no activity older than 4 hours.
> If all 5 sessions have had activity in the past 4 hours, login fails and the user is presented an error/message to contact site admin.
>
>
>
I know Wordpress has WP\_Session\_Tokens but it seems they only store 'expiration' and 'login' with no 'last\_activity'. Is there any way to check for last activity either through Wordpress or PHP Sessions?
If not then a secondary question of mine is how best to compare 'last' login to current time and check if it's more than 4 hours.
Here is my current code:
```
// On login, check if there are already 5 sessions active for the user
function check_sessions($login) {
global $user_ID;
$user = get_user_by( 'slug', $login );
//If there are less than 5 sessions, let user login normally
if( count( wp_get_all_sessions() ) < 5 ) {
return true;
}
$sessions = WP_Session_Tokens::get_instance( $user->id );
$all_sessions = $sessions->get_all();
$first_login = $all_sessions[0]['login'];
if( $first_login->diff(time()) > 4hrs ) {
// log out first_login user & login new user
WP_Session_Tokens::destroy( $all_sessions[0] );
return true;
}
else {
// display message to user
}
}
add_action('wp_login','check_sessions');
``` | 2015/03/13 | [
"https://wordpress.stackexchange.com/questions/181108",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69034/"
] | This question made me really interested. Took about 5 hours of my Saturday to create the full solution :)
Plugin Limit Login Sessions
---------------------------
It doesn't provide a settings page yet, so all options are currently hard coded. The plugin implements the following (according to OP):
1. A user can have a maximum of 5 login sessions across various browsers and devices.
2. If more then 5 sessions are attempted it will show an error, unless the oldest activity session is more then 4 hours old.
3. If the oldest activity session is more then 4 hours old, that session will be closed and current attempt of the login is allowed.
I tried to add explanations in the code with comments. Most of the plugin code should be self explanatory. If some part of it is not clear, feel free to comment.
[The GitHub repository can be found here](https://github.com/prionkor/limit-login-sessions). Feel free to fork and improve it :) If anyone thinks it would be a useful addition to the WordPress plugin repository, let me know and I will upload to WordPress.org if required.
```
<?php
/*
Plugin Name: Limit Login Sessions
Version: 1.0.0
Author: Sisir Kanti Adhikari
Author URI: https://sisir.me/
Description: Limits users login sessions.
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Limit Login Sessions is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
any later version.
Limit Login Sessions is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License (http://www.gnu.org/licenses/gpl-2.0.html)
for more details.
*/
add_filter('authenticate', 'lls_authenticate', 1000, 2);
function lls_authenticate($user, $username){
if(!username_exists($username) || !$user = get_user_by('login', $username))
return null; // will trigger WP default no username/password matched error
// setup vars
$max_sessions = 5;
$max_oldest_allowed_session_hours = 4;
$error_code = 'max_session_reached';
$error_message = "Maximum $max_sessions login sessions are allowed. Please contact site administrator.";
// 1. Get all active session for this user
$manager = WP_Session_Tokens::get_instance( $user->ID );
$sessions = $manager->get_all();
// 2. Count all active session
$session_count = count($sessions);
// 3. Return okay if active session less then $max_sessions
if($session_count < $max_sessions)
return $user;
$oldest_activity_session = lls_get_oldest_activity_session($sessions);
// 4. If active sessions is equal to 5 then check if a session has no activity last 4 hours
// 5. if oldest session have activity return error
if(
( $session_count >= $max_sessions && !$oldest_activity_session ) // if no oldest is found do not allow
|| ( $session_count >= $max_sessions && $oldest_activity_session['last_activity'] + $max_oldest_allowed_session_hours * HOUR_IN_SECONDS > time())
){
return new WP_Error($error_code, $error_message);
}
// 5. Oldest activity session doesn't have activity is given recent hours
// destroy oldest active session and authenticate the user
$verifier = lls_get_verifier_by_session($oldest_activity_session, $user->ID);
lls_destroy_session($verifier, $user->ID);
return $user;
}
function lls_destroy_session($verifier, $user_id){
$sessions = get_user_meta( $user_id, 'session_tokens', true );
if(!isset($sessions[$verifier]))
return true;
unset($sessions[$verifier]);
if(!empty($sessions)){
update_user_meta( $user_id, 'session_tokens', $sessions );
return true;
}
delete_user_meta( $user_id, 'session_tokens');
return true;
}
function lls_get_verifier_by_session($session, $user_id = null){
if(!$user_id)
$user_id = get_current_user_id();
$session_string = implode(',', $session);
$sessions = get_user_meta( $user_id, 'session_tokens', true );
if(empty($sessions))
return false;
foreach($sessions as $verifier => $sess){
$sess_string = implode(',', $sess);
if($session_string == $sess_string)
return $verifier;
}
return false;
}
function lls_get_oldest_activity_session($sessions){
$sess = false;
foreach($sessions as $session){
if(!isset($session['last_activity']))
continue;
if(!$sess){
$sess = $session;
continue;
}
if($sess['last_activity'] > $session['last_activity'])
$sess = $session;
}
return $sess;
}
// add a new key to session token array
add_filter('attach_session_information', 'lls_attach_session_information');
function lls_attach_session_information($session){
$session['last_activity'] = time();
return $session;
}
add_action('template_redirect', 'lls_update_session_last_activity');
function lls_update_session_last_activity(){
if(!is_user_logged_in())
return;
// get the login cookie from browser
$logged_in_cookie = $_COOKIE[LOGGED_IN_COOKIE];
// check for valid auth cookie
if( !$cookie_element = wp_parse_auth_cookie($logged_in_cookie) )
return;
// get the current session
$manager = WP_Session_Tokens::get_instance( get_current_user_id() );
$current_session = $manager->get($cookie_element['token']);
if(
$current_session['expiration'] <= time() // only update if session is not expired
|| ( $current_session['last_activity'] + 5 * MINUTE_IN_SECONDS ) > time() // only update in every 5 min to reduce db load
){
return;
}
$current_session['last_activity'] = time();
$manager->update($cookie_element['token'], $current_session);
}
```
For some functionality, I had to directly interact with the database `user_meta` value. The class had some methods protected, so couldn't be accessed directly.
Plugin is tested locally with WP `v4.3.1`. | It is impossible to have an answer for the question as it is being asked because http protocol do not have any long term sessions. A session on http is one request and response.
Sessions as we know on the internet are just hacks designed to remove the need to provide login and pass info for every page load.
wordpress 4.1 done a small step in better associating a "session" with an end device, but it is just a better hack than before and it is not 100% reliable as you can still copy the cookies and/or use proxy to foul it into believing that two separate end devices belong to the same session. OTOH it will think that two browser on the same machine are on different devices.
You are just trying to make DRM work, and for the last 20 years there was one thing proven about DRM, 1. It does not prevent people from getting "illegal" access to content, it just takes a little longer. 2. It annoys the paying clients.
Your specific scheme depends on knowing which device is going to be used next, and your assumption that it is the one which was most recently active has no merit. OTOH 5 active session will probably be enough for my whole block, so you don't even "block content stealing"
It is not that the question has no merit at all. I can see something like that used to enhance security, but DRM depends very much on the small details and once you use a vogue but critical term like "active sessions" without defining the details of it first it means for me that you don't really know what you actually expect from the system, as finding out the "active sessions" is the most critical part of implementing your scheme. |
12,378,154 | Are there any aspects to the C++ programming language where the code is known to be slower than the equivalent C language? Obviously this would be excluding the OO features like virtual functions and vtable features etc.
I am wondering whether, when you are programming in a latency-critical area (and you aren't worried about OO features) whether you could stick with basic C++ or would C be better? | 2012/09/11 | [
"https://Stackoverflow.com/questions/12378154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/997112/"
] | That depends on what you mean by "equivalent". If you compare C's stdio.h with C++'s iostream, stdio.h operations are generally faster (quite a bit faster in some situations). But if you are talking about code written in the subset of C++ that also compiles as valid C, the generated machine code will likely be identical. | If you're using the language that's the intersection of C and C++, then any difference in performance when compiling that code with a C compiler versus a C++ compiler is purely a quality-of-implementation issue; there's no reason one should be faster than the other.
Of course in the real world, if you're using C++ you program using both the *additional features* that C++ has over the intersection of C and C++ and using *different idioms* than you would in C. And conversely, if you're using C, you at least use very different idioms from what you would use in C++, and you may also be using additional features of the modern C language which C++ does not have, like, as Steve mentioned, the `restrict` keyword, or VLAs or pointer-to-VLA types, or compound literals. These features *could* give major performance benefits in some situations, but in my experience they're not the reasons most people who choose C over C++ do so.
In my mind, the main difference really is idioms. In C, it's idiomatic to make a linked list by putting the next/prev pointers directly in the structure that's being kept in a list, rather than using a separate wrapper object for the list and list nodes. In C, it's idiomatic to iterate directly over the elements of a string as a character array. In C, it's idiomatic to work with objects that exist entirely in automatic storage whenever possible rather than allocating dynamic storage. And so on. These *idiomatic* differences are the main ways C code tends to be faster and lighter than C++.
Of course if you want, you can use the same idioms in C++, since most of the language constructs needed for most C idioms exist in the intersection of C and C++. And then you can also use the additional features of C++ when appropriate. But you'll be writing non-idiomatic C++ code, and you might receive a lot of criticism from other C++ programmers... |
12,378,154 | Are there any aspects to the C++ programming language where the code is known to be slower than the equivalent C language? Obviously this would be excluding the OO features like virtual functions and vtable features etc.
I am wondering whether, when you are programming in a latency-critical area (and you aren't worried about OO features) whether you could stick with basic C++ or would C be better? | 2012/09/11 | [
"https://Stackoverflow.com/questions/12378154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/997112/"
] | Does *Latency critical* mean *as fast as possible* or does it simply mean that *everything has to run in predictable time*?
If it is the second case, then the only things that don't run in predictable time are `new`, `delete` and `try/catch`. In embedded programming there are directives to avoid such calls. In other cases, especially in C++11 you might notice some things are faster (std::sort is faster than C's sort() ) and some are marginally slower.
But what you gain over C++ is higher abstraction levels and you don't get the C-style bugs (like the typical `malloc()` without a corresponding `free()` ) | There is no code in C++ whose direct equivalent in C is faster- or, indeed, more maintainable. |
12,378,154 | Are there any aspects to the C++ programming language where the code is known to be slower than the equivalent C language? Obviously this would be excluding the OO features like virtual functions and vtable features etc.
I am wondering whether, when you are programming in a latency-critical area (and you aren't worried about OO features) whether you could stick with basic C++ or would C be better? | 2012/09/11 | [
"https://Stackoverflow.com/questions/12378154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/997112/"
] | Nothing in the C or C++ language standards specifies the speed of any construct (C++ does specify the time complexity of some operations applied to containers, but that's outside the scope of your question). The speed of the code generated for a given construct depends on the compiler used to compile it, and on the system it runs on.
For a given code construct that's valid C and valid C++ with the same semantics, there's no *fundamental* reason why either should be faster than the other. But it's likely that one will be faster than the other if the developers of the compiler were a little more clever. | If you're using the language that's the intersection of C and C++, then any difference in performance when compiling that code with a C compiler versus a C++ compiler is purely a quality-of-implementation issue; there's no reason one should be faster than the other.
Of course in the real world, if you're using C++ you program using both the *additional features* that C++ has over the intersection of C and C++ and using *different idioms* than you would in C. And conversely, if you're using C, you at least use very different idioms from what you would use in C++, and you may also be using additional features of the modern C language which C++ does not have, like, as Steve mentioned, the `restrict` keyword, or VLAs or pointer-to-VLA types, or compound literals. These features *could* give major performance benefits in some situations, but in my experience they're not the reasons most people who choose C over C++ do so.
In my mind, the main difference really is idioms. In C, it's idiomatic to make a linked list by putting the next/prev pointers directly in the structure that's being kept in a list, rather than using a separate wrapper object for the list and list nodes. In C, it's idiomatic to iterate directly over the elements of a string as a character array. In C, it's idiomatic to work with objects that exist entirely in automatic storage whenever possible rather than allocating dynamic storage. And so on. These *idiomatic* differences are the main ways C code tends to be faster and lighter than C++.
Of course if you want, you can use the same idioms in C++, since most of the language constructs needed for most C idioms exist in the intersection of C and C++. And then you can also use the additional features of C++ when appropriate. But you'll be writing non-idiomatic C++ code, and you might receive a lot of criticism from other C++ programmers... |
12,378,154 | Are there any aspects to the C++ programming language where the code is known to be slower than the equivalent C language? Obviously this would be excluding the OO features like virtual functions and vtable features etc.
I am wondering whether, when you are programming in a latency-critical area (and you aren't worried about OO features) whether you could stick with basic C++ or would C be better? | 2012/09/11 | [
"https://Stackoverflow.com/questions/12378154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/997112/"
] | For one example, C++ lacks the keyword `restrict`. Used correctly that sometimes allows the compiler to produce faster code.
* it's fairly rare in practice to see benefits from `restrict`, but it happens,
* there are plenty of occasions when a C++ or C compiler can deduce (after inlining) that the necessary conditions for `restrict` apply, and act accordingly, even though the keyword isn't used,
* C++ compilers that are also C compilers might provide `restrict` or `__restrict` as an extension anyway.
But occasionally (or quite commonly in some domains), `restrict` is a *really* good optimization, which I'm told is one of the reasons for still using Fortran. It's certainly one of the reasons for the strict aliasing rules in both C and C++, which give the same optimization opportunity as `restrict` for a more limited set of circumstances.
Whether you "count" this depends to an extent what you consider "equivalent code". `restrict` never changes the meaning of a program that uses it validly -- compilers are free to ignore it. So it's not a stretch to describe the program that uses it (for the eyes of the C compiler) and the program that doesn't (for C++) as "equivalent". The version with `restrict` took more (perhaps only slightly more) programmer effort to create, since the programmer has to be sure that it's correct before using it.
If you mean, is there a program that is valid C and also valid C++, and has the same meaning in both, but implementations are somehow constrained by the C++ standard to run it slower than C implementations, then I'm pretty sure the answer is "no". If you mean, are there any potential performance tweaks available in standard C but not in standard C++, then the answer is "yes".
Whether you can get any benefit from the tweak is another matter, whether you'd have got more benefit for the same amount of effort with a different optimization available in both languages is another, and whether any benefit is big enough to base your choice of language on is still another. It's laughably easy to interoperate between C and C++ code, so if you have any reason at all to prefer C++, then like any optimization that alters your preferred way of coding, switching to C would normally be something you'd do when your profiler tells you your function is too slow, and not before.
Also, I'm trying to convince myself one way or the other whether the potential for exceptions costs performance, assuming that you never use any type that has a non-trivial destructor. I suspect that in practice it probably can (and that this is a contradiction to the "don't pay for what you don't use" principle), if only because otherwise there'd be no point gcc having `-fno-exceptions`. C++ implementations bring the cost down pretty low (and it's mostly in rodata, not code), but that doesn't mean it's zero. Latency-critical code may or may not also be binary-size-critical code.
Again it might depend what you mean by "equivalent" code -- if I have to compile my so-called "standard C++ program" using a non-standard compiler (such as `g++ -fno-exceptions`) in order to "prove" that the C++ code is as good as the C, then in some sense the C++ standard is costing me something.
Finally, the C++ runtime itself has a start-up cost, which is not necessarily identical to the C runtime start-up cost for the "same" program. You can generally hack about to reduce the cost of both by removing things you don't strictly need. But that is effort, implementations don't necessarily do it for you completely every time, so it's not *strictly* true that in C++ you don't pay for what you don't use. That's the general principle, but achieving it is a quality of implementation issue. | There is no code in C++ whose direct equivalent in C is faster- or, indeed, more maintainable. |
12,378,154 | Are there any aspects to the C++ programming language where the code is known to be slower than the equivalent C language? Obviously this would be excluding the OO features like virtual functions and vtable features etc.
I am wondering whether, when you are programming in a latency-critical area (and you aren't worried about OO features) whether you could stick with basic C++ or would C be better? | 2012/09/11 | [
"https://Stackoverflow.com/questions/12378154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/997112/"
] | Contrary to what many C programmers like to think, one can often write tighter and faster code in C++ all without having to sacrifice a great deal in design.
I can't think of anything in C++ that is slower than its counterpart in C. Virtual functions NOT excluded. | If you're using the language that's the intersection of C and C++, then any difference in performance when compiling that code with a C compiler versus a C++ compiler is purely a quality-of-implementation issue; there's no reason one should be faster than the other.
Of course in the real world, if you're using C++ you program using both the *additional features* that C++ has over the intersection of C and C++ and using *different idioms* than you would in C. And conversely, if you're using C, you at least use very different idioms from what you would use in C++, and you may also be using additional features of the modern C language which C++ does not have, like, as Steve mentioned, the `restrict` keyword, or VLAs or pointer-to-VLA types, or compound literals. These features *could* give major performance benefits in some situations, but in my experience they're not the reasons most people who choose C over C++ do so.
In my mind, the main difference really is idioms. In C, it's idiomatic to make a linked list by putting the next/prev pointers directly in the structure that's being kept in a list, rather than using a separate wrapper object for the list and list nodes. In C, it's idiomatic to iterate directly over the elements of a string as a character array. In C, it's idiomatic to work with objects that exist entirely in automatic storage whenever possible rather than allocating dynamic storage. And so on. These *idiomatic* differences are the main ways C code tends to be faster and lighter than C++.
Of course if you want, you can use the same idioms in C++, since most of the language constructs needed for most C idioms exist in the intersection of C and C++. And then you can also use the additional features of C++ when appropriate. But you'll be writing non-idiomatic C++ code, and you might receive a lot of criticism from other C++ programmers... |
12,378,154 | Are there any aspects to the C++ programming language where the code is known to be slower than the equivalent C language? Obviously this would be excluding the OO features like virtual functions and vtable features etc.
I am wondering whether, when you are programming in a latency-critical area (and you aren't worried about OO features) whether you could stick with basic C++ or would C be better? | 2012/09/11 | [
"https://Stackoverflow.com/questions/12378154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/997112/"
] | Nothing in the C or C++ language standards specifies the speed of any construct (C++ does specify the time complexity of some operations applied to containers, but that's outside the scope of your question). The speed of the code generated for a given construct depends on the compiler used to compile it, and on the system it runs on.
For a given code construct that's valid C and valid C++ with the same semantics, there's no *fundamental* reason why either should be faster than the other. But it's likely that one will be faster than the other if the developers of the compiler were a little more clever. | That depends on what you mean by "equivalent". If you compare C's stdio.h with C++'s iostream, stdio.h operations are generally faster (quite a bit faster in some situations). But if you are talking about code written in the subset of C++ that also compiles as valid C, the generated machine code will likely be identical. |
12,378,154 | Are there any aspects to the C++ programming language where the code is known to be slower than the equivalent C language? Obviously this would be excluding the OO features like virtual functions and vtable features etc.
I am wondering whether, when you are programming in a latency-critical area (and you aren't worried about OO features) whether you could stick with basic C++ or would C be better? | 2012/09/11 | [
"https://Stackoverflow.com/questions/12378154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/997112/"
] | Contrary to what many C programmers like to think, one can often write tighter and faster code in C++ all without having to sacrifice a great deal in design.
I can't think of anything in C++ that is slower than its counterpart in C. Virtual functions NOT excluded. | Does *Latency critical* mean *as fast as possible* or does it simply mean that *everything has to run in predictable time*?
If it is the second case, then the only things that don't run in predictable time are `new`, `delete` and `try/catch`. In embedded programming there are directives to avoid such calls. In other cases, especially in C++11 you might notice some things are faster (std::sort is faster than C's sort() ) and some are marginally slower.
But what you gain over C++ is higher abstraction levels and you don't get the C-style bugs (like the typical `malloc()` without a corresponding `free()` ) |
12,378,154 | Are there any aspects to the C++ programming language where the code is known to be slower than the equivalent C language? Obviously this would be excluding the OO features like virtual functions and vtable features etc.
I am wondering whether, when you are programming in a latency-critical area (and you aren't worried about OO features) whether you could stick with basic C++ or would C be better? | 2012/09/11 | [
"https://Stackoverflow.com/questions/12378154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/997112/"
] | Nothing in the C or C++ language standards specifies the speed of any construct (C++ does specify the time complexity of some operations applied to containers, but that's outside the scope of your question). The speed of the code generated for a given construct depends on the compiler used to compile it, and on the system it runs on.
For a given code construct that's valid C and valid C++ with the same semantics, there's no *fundamental* reason why either should be faster than the other. But it's likely that one will be faster than the other if the developers of the compiler were a little more clever. | Does *Latency critical* mean *as fast as possible* or does it simply mean that *everything has to run in predictable time*?
If it is the second case, then the only things that don't run in predictable time are `new`, `delete` and `try/catch`. In embedded programming there are directives to avoid such calls. In other cases, especially in C++11 you might notice some things are faster (std::sort is faster than C's sort() ) and some are marginally slower.
But what you gain over C++ is higher abstraction levels and you don't get the C-style bugs (like the typical `malloc()` without a corresponding `free()` ) |
12,378,154 | Are there any aspects to the C++ programming language where the code is known to be slower than the equivalent C language? Obviously this would be excluding the OO features like virtual functions and vtable features etc.
I am wondering whether, when you are programming in a latency-critical area (and you aren't worried about OO features) whether you could stick with basic C++ or would C be better? | 2012/09/11 | [
"https://Stackoverflow.com/questions/12378154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/997112/"
] | Contrary to what many C programmers like to think, one can often write tighter and faster code in C++ all without having to sacrifice a great deal in design.
I can't think of anything in C++ that is slower than its counterpart in C. Virtual functions NOT excluded. | There is no code in C++ whose direct equivalent in C is faster- or, indeed, more maintainable. |
12,378,154 | Are there any aspects to the C++ programming language where the code is known to be slower than the equivalent C language? Obviously this would be excluding the OO features like virtual functions and vtable features etc.
I am wondering whether, when you are programming in a latency-critical area (and you aren't worried about OO features) whether you could stick with basic C++ or would C be better? | 2012/09/11 | [
"https://Stackoverflow.com/questions/12378154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/997112/"
] | That depends on what you mean by "equivalent". If you compare C's stdio.h with C++'s iostream, stdio.h operations are generally faster (quite a bit faster in some situations). But if you are talking about code written in the subset of C++ that also compiles as valid C, the generated machine code will likely be identical. | Does *Latency critical* mean *as fast as possible* or does it simply mean that *everything has to run in predictable time*?
If it is the second case, then the only things that don't run in predictable time are `new`, `delete` and `try/catch`. In embedded programming there are directives to avoid such calls. In other cases, especially in C++11 you might notice some things are faster (std::sort is faster than C's sort() ) and some are marginally slower.
But what you gain over C++ is higher abstraction levels and you don't get the C-style bugs (like the typical `malloc()` without a corresponding `free()` ) |
714,344 | Yesterday, I noticed that <https://hkps.pool.sks-keyservers.net/> showed a different page on my laptop than it did on my desktop PC.
This URL redirects to one of the many servers listed here:
<https://sks-keyservers.net/status/>
Unlike a normal URL redirection, the URL does not change, while the contents of the page do.
How exactly does this work?
How can it be set up?
Does it have anything to do with a [round-robin DNS system](https://en.wikipedia.org/wiki/Round_robin_dns)?
It also seems that it always shows the same "server" on a given PC once it has been accessed once from there. How does it do that?
<http://www.pool.ntp.org/en/> appears to be a similar system. | 2014/02/09 | [
"https://superuser.com/questions/714344",
"https://superuser.com",
"https://superuser.com/users/41232/"
] | There are several ways to do this.
Here is a very superficial way describe this.
One common way is to have "<https://hkps.pool.sks-keyservers.net/>" point to a frontend with a webserver on it.
The frontend then proxies your request to one of it's backend servers. There are many ways for the frontend server to choose a backend server `round robin` is one of them, `number of connections` is another.
When you return to "<https://hkps.pool.sks-keyservers.net/>" the frontend either remembers your IP and send you to the same backend or the backend gives you a cookie that the frontend reads that tells it you want to go to a particular backend. | This probably has nothing special to do with the DNS part of the connection.
Web servers can key off information your browser sends with it's request headers, e.g., "referer" tags which indicate you clicked on a link on another site to get here, or what's most likely in this case is the User-Agent string sent by your browser. Here's a couple examples of User-Agent strings:
Chrome version 32 running on some 64-bit flavor of Linux:
>
> User-Agent: Mozilla/5.0 (X11; Linux x86\_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36
>
>
>
or
Safari version 7.0.1 running on OS X 10.9.1:
>
> User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10\_9\_1) AppleWebKit/537.73.11 (KHTML, like Gecko) Version/7.0.1 Safari/537.73.11
>
>
>
This is also how web servers figure out if you are on a mobile device.
Here's Safari version 7.0 running on an iPad running IOS 7.0.4:
>
> User-Agent: Mozilla/5.0 (iPad; CPU OS 7\_0\_4 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11B554a Safari/9537.53
>
>
>
The web server can use this information to display a different page if the designer made a conscious effort to do so. So you can get a different-looking page on Chrome versus Safari, as a simple example. But as you can see from the contents of the User-Agent strings, there's a lot of information there that a web designer can use to customize the resulting page you get back. |
714,344 | Yesterday, I noticed that <https://hkps.pool.sks-keyservers.net/> showed a different page on my laptop than it did on my desktop PC.
This URL redirects to one of the many servers listed here:
<https://sks-keyservers.net/status/>
Unlike a normal URL redirection, the URL does not change, while the contents of the page do.
How exactly does this work?
How can it be set up?
Does it have anything to do with a [round-robin DNS system](https://en.wikipedia.org/wiki/Round_robin_dns)?
It also seems that it always shows the same "server" on a given PC once it has been accessed once from there. How does it do that?
<http://www.pool.ntp.org/en/> appears to be a similar system. | 2014/02/09 | [
"https://superuser.com/questions/714344",
"https://superuser.com",
"https://superuser.com/users/41232/"
] | Yes, all the pools of sks-keyservers.net are set up using a DNS round-robin. In terms of reverse proxies, it require all servers to have one enabled, and if you look at the rprox column at <https://sks-keyservers.net/status/> some blue flags are specifying servers with multiple servers in the backend in a clustered setup.
The actual data for the round-robin is based on (i) hourly update run of the full pool (ii) authorative DNS server update the list of DNS records every 15 minutes. For the non-geographical pools a random selection is used in (ii), for the geographical pools (EU, NA, ... ) it is ranked by SRV record based on the description in <http://kfwebs.com/sks-keyservers-SRV.pdf> | There are several ways to do this.
Here is a very superficial way describe this.
One common way is to have "<https://hkps.pool.sks-keyservers.net/>" point to a frontend with a webserver on it.
The frontend then proxies your request to one of it's backend servers. There are many ways for the frontend server to choose a backend server `round robin` is one of them, `number of connections` is another.
When you return to "<https://hkps.pool.sks-keyservers.net/>" the frontend either remembers your IP and send you to the same backend or the backend gives you a cookie that the frontend reads that tells it you want to go to a particular backend. |
714,344 | Yesterday, I noticed that <https://hkps.pool.sks-keyservers.net/> showed a different page on my laptop than it did on my desktop PC.
This URL redirects to one of the many servers listed here:
<https://sks-keyservers.net/status/>
Unlike a normal URL redirection, the URL does not change, while the contents of the page do.
How exactly does this work?
How can it be set up?
Does it have anything to do with a [round-robin DNS system](https://en.wikipedia.org/wiki/Round_robin_dns)?
It also seems that it always shows the same "server" on a given PC once it has been accessed once from there. How does it do that?
<http://www.pool.ntp.org/en/> appears to be a similar system. | 2014/02/09 | [
"https://superuser.com/questions/714344",
"https://superuser.com",
"https://superuser.com/users/41232/"
] | Yes, all the pools of sks-keyservers.net are set up using a DNS round-robin. In terms of reverse proxies, it require all servers to have one enabled, and if you look at the rprox column at <https://sks-keyservers.net/status/> some blue flags are specifying servers with multiple servers in the backend in a clustered setup.
The actual data for the round-robin is based on (i) hourly update run of the full pool (ii) authorative DNS server update the list of DNS records every 15 minutes. For the non-geographical pools a random selection is used in (ii), for the geographical pools (EU, NA, ... ) it is ranked by SRV record based on the description in <http://kfwebs.com/sks-keyservers-SRV.pdf> | This probably has nothing special to do with the DNS part of the connection.
Web servers can key off information your browser sends with it's request headers, e.g., "referer" tags which indicate you clicked on a link on another site to get here, or what's most likely in this case is the User-Agent string sent by your browser. Here's a couple examples of User-Agent strings:
Chrome version 32 running on some 64-bit flavor of Linux:
>
> User-Agent: Mozilla/5.0 (X11; Linux x86\_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36
>
>
>
or
Safari version 7.0.1 running on OS X 10.9.1:
>
> User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10\_9\_1) AppleWebKit/537.73.11 (KHTML, like Gecko) Version/7.0.1 Safari/537.73.11
>
>
>
This is also how web servers figure out if you are on a mobile device.
Here's Safari version 7.0 running on an iPad running IOS 7.0.4:
>
> User-Agent: Mozilla/5.0 (iPad; CPU OS 7\_0\_4 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11B554a Safari/9537.53
>
>
>
The web server can use this information to display a different page if the designer made a conscious effort to do so. So you can get a different-looking page on Chrome versus Safari, as a simple example. But as you can see from the contents of the User-Agent strings, there's a lot of information there that a web designer can use to customize the resulting page you get back. |
3,632,331 | I am working through "Thinking Mathematically" by Mason, Burton and Stacey. One of the questions goes as follows:
*Three slices of bread are to be toasted under a grill. The grill can hold two slices at once but only one side is toasted at a time. It takes 30 seconds to toast one side of a piece of bread, 5 seconds to put a piece in or take a piece out and 3 seconds to turn a piece over. What is the shortest time in which the three slices can be toasted?*
I am wondering if I am overlooking something in my solution method, so I have come here. Some sources online say 130 seconds and others say 139. My solution, if non-fallacious, should be able to get it done in 118 seconds. The process goes as follows. Allow $T\_n$ to represent the first side of the $n$th piece of toast and $T\_n'$ to represent the opposite side of the $n$th piece of toast. Then, assuming a piece of toast is cooking as soon as it is placed, then the suggested sequence of events
[](https://i.stack.imgur.com/CL5aO.jpg)
Sorry for the convoluted timeline in the picture, but essentially I place the first piece of toast and then the second. $T\_1$ and $T\_2$'s cooking time will overlap, but there is necessarily a five-second window where they do not. You flip $T\_1 \to T\_1'$ where $T\_1'$ officially begins toasting at 38 seconds. This gives another thirty-second window (until $t = 68$) to get a lot of the time-wasting flipping and removing done. For example, $T\_2$ finished at $t=40$ and the most original part of this solution is to **remove** $T\_2$ rather than flip it over and begin cooking the other side immediately. As soon as we are done removing $T\_2$ the running total will be $t=45$ at which point we immediately begin placing $T\_3$ bringing us to a running total of $t=50$. Note, that $T\_3$ will be done at $t = 80$. At this point, we wait until $t=68$ to remove $T\_1'$ which brings us to a running total of $t = 73$, at which point we immediately begin placing $T\_2'$ which we put aside before. When we are done placing $T\_2'$ we will be at $t = 78$ and at $t = 80$ it will be time to flip $T\_3$, which brings us to $t = 83$ and which point $T\_3'$ will begin toasting. $T\_3'$ will thus be done at $t = 113$ and in that time we will have to remove $T\_2'$ which began cooking at $t = 78$. Finally, we remove $T\_3'$ at $t = 113$ and ending at $t = 118$.
Are there any problems with this solution that I am not detecting? I think it works well, indeed if it works at all, because it uses the long 30-second windows of cooking to do all the time-consuming activities of flipping etc. | 2020/04/18 | [
"https://math.stackexchange.com/questions/3632331",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/698855/"
] | Assuming that (a) flipping a slice does not require removing and replacing it (so that flipping is a total of 3 seconds and not 13 seconds) and (b) messing with one slice does not interrupt the cooking of the other slice, I see no flaw in your solution. | That is smart approach but I see 2 mistakes:
1. You do not add up the 5 seconds to add the Toast 2. You assume that since the "clock" is running once the toast 1 started to grill Toast 2 magically starts to cook at time 10 implying some parallelism there in the actions which does not seem to be justified from the problem.
2. You remove T2 at time 40 and place T3 at time 45 but you didn't add either the 5 secs to remove T2 or to add T3. I.e. you should be adding 10 hence T3 starts to cool at 55 and not 45. There is no mention of being able to remove slices/add slices at one movement. |
325,075 | I am using a RichTextBox in WPF, and am trying to set the default paragraph spacing to 0 (so that there is no paragraph spacing). While I could do this in XAML, I would like to achieve it programmatically if possible. Any ideas? | 2008/11/28 | [
"https://Stackoverflow.com/questions/325075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/691/"
] | I did it **with style** (pun indented)
```
<RichTextBox Margin="0,51,0,0" Name="mainTextBox" >
<RichTextBox.Resources>
<Style TargetType="{x:Type Paragraph}">
<Setter Property="Margin" Value="0"/>
</Style>
</RichTextBox.Resources>
</RichTextBox>
``` | Using Line Height
```
RichTextBox rtb = new RichTextBox();
Paragraph p = rtb.Document.Blocks.FirstBlock as Paragraph;
p.LineHeight = 10;
``` |
325,075 | I am using a RichTextBox in WPF, and am trying to set the default paragraph spacing to 0 (so that there is no paragraph spacing). While I could do this in XAML, I would like to achieve it programmatically if possible. Any ideas? | 2008/11/28 | [
"https://Stackoverflow.com/questions/325075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/691/"
] | ```
RichTextBox rtb = new RichTextBox();
rtb.SetValue(Paragraph.LineHeightProperty, 1.0);
``` | ```
<RichTextBox Height="250" Width="500" VerticalScrollBarVisibility="Auto" TextWrapping="Wrap" IsReadOnly="True" >
<Paragraph>
XYZ
<LineBreak />
</Paragraph>
</RichTextBox>
``` |
325,075 | I am using a RichTextBox in WPF, and am trying to set the default paragraph spacing to 0 (so that there is no paragraph spacing). While I could do this in XAML, I would like to achieve it programmatically if possible. Any ideas? | 2008/11/28 | [
"https://Stackoverflow.com/questions/325075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/691/"
] | I did it **with style** (pun indented)
```
<RichTextBox Margin="0,51,0,0" Name="mainTextBox" >
<RichTextBox.Resources>
<Style TargetType="{x:Type Paragraph}">
<Setter Property="Margin" Value="0"/>
</Style>
</RichTextBox.Resources>
</RichTextBox>
``` | For me on VS2017 in WPF works this:
```
<RichTextBox HorizontalAlignment="Left" Height="126" Margin="10,280,0,0" VerticalAlignment="Top" Width="343" FontSize="14" Block.LineHeight="2"/>
```
The key is **Block.LineHeight="2"**
You can found this also in Properties view but you can't change below 6px from there. |
325,075 | I am using a RichTextBox in WPF, and am trying to set the default paragraph spacing to 0 (so that there is no paragraph spacing). While I could do this in XAML, I would like to achieve it programmatically if possible. Any ideas? | 2008/11/28 | [
"https://Stackoverflow.com/questions/325075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/691/"
] | I did it **with style** (pun indented)
```
<RichTextBox Margin="0,51,0,0" Name="mainTextBox" >
<RichTextBox.Resources>
<Style TargetType="{x:Type Paragraph}">
<Setter Property="Margin" Value="0"/>
</Style>
</RichTextBox.Resources>
</RichTextBox>
``` | I know this question was posted before I even started coding but I found that simply setting `ShowSelectedMargin` to `true` did the trick |
325,075 | I am using a RichTextBox in WPF, and am trying to set the default paragraph spacing to 0 (so that there is no paragraph spacing). While I could do this in XAML, I would like to achieve it programmatically if possible. Any ideas? | 2008/11/28 | [
"https://Stackoverflow.com/questions/325075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/691/"
] | I did it **with style** (pun indented)
```
<RichTextBox Margin="0,51,0,0" Name="mainTextBox" >
<RichTextBox.Resources>
<Style TargetType="{x:Type Paragraph}">
<Setter Property="Margin" Value="0"/>
</Style>
</RichTextBox.Resources>
</RichTextBox>
``` | ```
RichTextBox rtb = new RichTextBox();
rtb.SetValue(Paragraph.LineHeightProperty, 1.0);
``` |
325,075 | I am using a RichTextBox in WPF, and am trying to set the default paragraph spacing to 0 (so that there is no paragraph spacing). While I could do this in XAML, I would like to achieve it programmatically if possible. Any ideas? | 2008/11/28 | [
"https://Stackoverflow.com/questions/325075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/691/"
] | For me on VS2017 in WPF works this:
```
<RichTextBox HorizontalAlignment="Left" Height="126" Margin="10,280,0,0" VerticalAlignment="Top" Width="343" FontSize="14" Block.LineHeight="2"/>
```
The key is **Block.LineHeight="2"**
You can found this also in Properties view but you can't change below 6px from there. | ```
<RichTextBox Height="250" Width="500" VerticalScrollBarVisibility="Auto" TextWrapping="Wrap" IsReadOnly="True" >
<Paragraph>
XYZ
<LineBreak />
</Paragraph>
</RichTextBox>
``` |
325,075 | I am using a RichTextBox in WPF, and am trying to set the default paragraph spacing to 0 (so that there is no paragraph spacing). While I could do this in XAML, I would like to achieve it programmatically if possible. Any ideas? | 2008/11/28 | [
"https://Stackoverflow.com/questions/325075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/691/"
] | For me on VS2017 in WPF works this:
```
<RichTextBox HorizontalAlignment="Left" Height="126" Margin="10,280,0,0" VerticalAlignment="Top" Width="343" FontSize="14" Block.LineHeight="2"/>
```
The key is **Block.LineHeight="2"**
You can found this also in Properties view but you can't change below 6px from there. | ```
RichTextBox rtb = new RichTextBox();
rtb.SetValue(Paragraph.LineHeightProperty, 1.0);
``` |
325,075 | I am using a RichTextBox in WPF, and am trying to set the default paragraph spacing to 0 (so that there is no paragraph spacing). While I could do this in XAML, I would like to achieve it programmatically if possible. Any ideas? | 2008/11/28 | [
"https://Stackoverflow.com/questions/325075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/691/"
] | ```
RichTextBox rtb = new RichTextBox();
rtb.SetValue(Paragraph.LineHeightProperty, 1.0);
``` | I know this question was posted before I even started coding but I found that simply setting `ShowSelectedMargin` to `true` did the trick |
325,075 | I am using a RichTextBox in WPF, and am trying to set the default paragraph spacing to 0 (so that there is no paragraph spacing). While I could do this in XAML, I would like to achieve it programmatically if possible. Any ideas? | 2008/11/28 | [
"https://Stackoverflow.com/questions/325075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/691/"
] | In C# 2008 WAP
```
richtextbox1.SelectionCharOffset =
-1 * ( Convert.ToInt32(R223.Txt_Space_Before.Text) * 100);
```
or
```
richtextbox1.SelectionCharOffset =
Convert.ToInt32(R223.Txt_Space_Before.Text) * 100;
```
can be used for Line Spacing.
This is the only way you can have line height spacing. | I know this question was posted before I even started coding but I found that simply setting `ShowSelectedMargin` to `true` did the trick |
325,075 | I am using a RichTextBox in WPF, and am trying to set the default paragraph spacing to 0 (so that there is no paragraph spacing). While I could do this in XAML, I would like to achieve it programmatically if possible. Any ideas? | 2008/11/28 | [
"https://Stackoverflow.com/questions/325075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/691/"
] | Using Line Height
```
RichTextBox rtb = new RichTextBox();
Paragraph p = rtb.Document.Blocks.FirstBlock as Paragraph;
p.LineHeight = 10;
``` | For me on VS2017 in WPF works this:
```
<RichTextBox HorizontalAlignment="Left" Height="126" Margin="10,280,0,0" VerticalAlignment="Top" Width="343" FontSize="14" Block.LineHeight="2"/>
```
The key is **Block.LineHeight="2"**
You can found this also in Properties view but you can't change below 6px from there. |
5,195 | I have just purchased a new CF card for my DSLR. I tested it using Xbench (Mac OS X) and it performs as expected. However, I'd like to do a "surface scan" (moving platter term) to check for "bad sectors" (moving platter term). I could bash script a processes using dd, but I get the feeling that there is a better way out there. My goal is to conclusively know that a memory card (CF, SD, etc.) is safe to use on a photo shoot, and that is doesn't need to be returned before the 30 day vendor policy window expires.
I definitely want Mac solutions given here. I would also like to get a few Linux suggestions. Let's even throw a bone to the windows users just so that this one question can meet everyone's needs. | 2010/11/27 | [
"https://photo.stackexchange.com/questions/5195",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/2363/"
] | As the controller can move the blocks wherever it wants (see wear leveling), the only chance for a whole read/write-test ist to fill the disk up and then compare. Several times with different patterns of course to be sure.
And still you won't catch faulty regions, as they are hidden too by the controller as long as he has spares. | In Linux, the command you want is `badblocks`. There appears to be a port of this to Mac OS X as part of [this ext2-for-os-x port](http://sourceforge.net/projects/ext2fsx/) -- install the whole thing and ignore everything but the `/usr/local/sbin/badblocks` command.
That said, this will help test, but I don't think it'll be conclusive, because first as Leonidas says, you don't really get raw access to the flash memory so it's hard to do a complete scan, and also because new failures could appear after the test, perhaps even triggered by it. |
5,195 | I have just purchased a new CF card for my DSLR. I tested it using Xbench (Mac OS X) and it performs as expected. However, I'd like to do a "surface scan" (moving platter term) to check for "bad sectors" (moving platter term). I could bash script a processes using dd, but I get the feeling that there is a better way out there. My goal is to conclusively know that a memory card (CF, SD, etc.) is safe to use on a photo shoot, and that is doesn't need to be returned before the 30 day vendor policy window expires.
I definitely want Mac solutions given here. I would also like to get a few Linux suggestions. Let's even throw a bone to the windows users just so that this one question can meet everyone's needs. | 2010/11/27 | [
"https://photo.stackexchange.com/questions/5195",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/2363/"
] | As the controller can move the blocks wherever it wants (see wear leveling), the only chance for a whole read/write-test ist to fill the disk up and then compare. Several times with different patterns of course to be sure.
And still you won't catch faulty regions, as they are hidden too by the controller as long as he has spares. | I found this on google, I'm not using sd cards for cameras' storage but instead I got my class 10 32 gigs sdhc sandisk completely corrupted after less then 2 years of use on my samsung galaxy S2.
I am using badblocks to see where the first badblocks start and then I will make partitions around that area if possible. this is my current, very very bad solution :/ |
5,195 | I have just purchased a new CF card for my DSLR. I tested it using Xbench (Mac OS X) and it performs as expected. However, I'd like to do a "surface scan" (moving platter term) to check for "bad sectors" (moving platter term). I could bash script a processes using dd, but I get the feeling that there is a better way out there. My goal is to conclusively know that a memory card (CF, SD, etc.) is safe to use on a photo shoot, and that is doesn't need to be returned before the 30 day vendor policy window expires.
I definitely want Mac solutions given here. I would also like to get a few Linux suggestions. Let's even throw a bone to the windows users just so that this one question can meet everyone's needs. | 2010/11/27 | [
"https://photo.stackexchange.com/questions/5195",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/2363/"
] | As the controller can move the blocks wherever it wants (see wear leveling), the only chance for a whole read/write-test ist to fill the disk up and then compare. Several times with different patterns of course to be sure.
And still you won't catch faulty regions, as they are hidden too by the controller as long as he has spares. | Reading your comment below the question, I believe [F3](https://github.com/AltraMayor/f3) does exactly what you want. It compiles on Linux/Mac OS X and is also available via Homebrew. |
5,195 | I have just purchased a new CF card for my DSLR. I tested it using Xbench (Mac OS X) and it performs as expected. However, I'd like to do a "surface scan" (moving platter term) to check for "bad sectors" (moving platter term). I could bash script a processes using dd, but I get the feeling that there is a better way out there. My goal is to conclusively know that a memory card (CF, SD, etc.) is safe to use on a photo shoot, and that is doesn't need to be returned before the 30 day vendor policy window expires.
I definitely want Mac solutions given here. I would also like to get a few Linux suggestions. Let's even throw a bone to the windows users just so that this one question can meet everyone's needs. | 2010/11/27 | [
"https://photo.stackexchange.com/questions/5195",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/2363/"
] | Flash memory does not work the same way as disks with platters. The concept of a "bad sector" does not really exist with flash memory. These days, with flash memory and SSD's, the built-in controller takes care of identifying and marking off unusable blocks of memory, dynamically moving data around to mitigate block write limitations, etc. These features are far more prevalent in SSD's, but some also exist in quality flash cards (such as SanDisk).
Most file system checking tools either make specific assumptions about the physical structure of the storage device (i.e. platter based, with physical cylinders, sectors, clusters, etc.), or work at an abstracted level and make repairs "virtually" using file or directory tables. You would need a tool specifically designed to mark bad blocks on a flash memory device, as anything else is either going to cause more problems (by assuming it can fix the problems the same way it would with a platter-based device) or make virtual fixes that don't take into account dynamic hardware-level features of flash. Even if you could mark a particular "sector" or "cluster" as 'bad', it wouldn't necessarily do any good, since those physical concepts don't actually exist in flash memory. If the flash device is more advanced, and dynamically moves data around to automatically bypass bad blocks and mitigate write limitations, the physical location of data may reside in a bad block one moment, and in a good block a moment later. (Note that the idea of a "bad" block in flash memory is much fuzzier than it is with platter disks...a flash memory block tends to die slowly, rather than suddenly, and may "flicker" between readable/not readable a bit before it becomes entirely unusable.)
Generally speaking, when it comes to flash, let the device manage itself from a bad block perspective. Different manufacturers structure and store data in different ways, and each may have different levels and amounts of dynamic behavior that moves data around to avoid some of the limitations of flash memory. Trying to manage it yourself is likely to cause more problems than it solves, and may render your flash disks useless in the long run.
If you wish to avoid bad flash cards, I highly recommend using reputable brands. I have tried a variety of flash cards in the past, however SanDisk is the only brand that I have used that, at least to date, has never failed. I have several 4, 8, and 16 gig SDHC cards that I use quite heavily, and regularly take out of my camera and insert into my laptop or computer, and they are still working perfectly. (Some are several years old.) | In Linux, the command you want is `badblocks`. There appears to be a port of this to Mac OS X as part of [this ext2-for-os-x port](http://sourceforge.net/projects/ext2fsx/) -- install the whole thing and ignore everything but the `/usr/local/sbin/badblocks` command.
That said, this will help test, but I don't think it'll be conclusive, because first as Leonidas says, you don't really get raw access to the flash memory so it's hard to do a complete scan, and also because new failures could appear after the test, perhaps even triggered by it. |
5,195 | I have just purchased a new CF card for my DSLR. I tested it using Xbench (Mac OS X) and it performs as expected. However, I'd like to do a "surface scan" (moving platter term) to check for "bad sectors" (moving platter term). I could bash script a processes using dd, but I get the feeling that there is a better way out there. My goal is to conclusively know that a memory card (CF, SD, etc.) is safe to use on a photo shoot, and that is doesn't need to be returned before the 30 day vendor policy window expires.
I definitely want Mac solutions given here. I would also like to get a few Linux suggestions. Let's even throw a bone to the windows users just so that this one question can meet everyone's needs. | 2010/11/27 | [
"https://photo.stackexchange.com/questions/5195",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/2363/"
] | In Linux, the command you want is `badblocks`. There appears to be a port of this to Mac OS X as part of [this ext2-for-os-x port](http://sourceforge.net/projects/ext2fsx/) -- install the whole thing and ignore everything but the `/usr/local/sbin/badblocks` command.
That said, this will help test, but I don't think it'll be conclusive, because first as Leonidas says, you don't really get raw access to the flash memory so it's hard to do a complete scan, and also because new failures could appear after the test, perhaps even triggered by it. | I found this on google, I'm not using sd cards for cameras' storage but instead I got my class 10 32 gigs sdhc sandisk completely corrupted after less then 2 years of use on my samsung galaxy S2.
I am using badblocks to see where the first badblocks start and then I will make partitions around that area if possible. this is my current, very very bad solution :/ |
5,195 | I have just purchased a new CF card for my DSLR. I tested it using Xbench (Mac OS X) and it performs as expected. However, I'd like to do a "surface scan" (moving platter term) to check for "bad sectors" (moving platter term). I could bash script a processes using dd, but I get the feeling that there is a better way out there. My goal is to conclusively know that a memory card (CF, SD, etc.) is safe to use on a photo shoot, and that is doesn't need to be returned before the 30 day vendor policy window expires.
I definitely want Mac solutions given here. I would also like to get a few Linux suggestions. Let's even throw a bone to the windows users just so that this one question can meet everyone's needs. | 2010/11/27 | [
"https://photo.stackexchange.com/questions/5195",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/2363/"
] | In Linux, the command you want is `badblocks`. There appears to be a port of this to Mac OS X as part of [this ext2-for-os-x port](http://sourceforge.net/projects/ext2fsx/) -- install the whole thing and ignore everything but the `/usr/local/sbin/badblocks` command.
That said, this will help test, but I don't think it'll be conclusive, because first as Leonidas says, you don't really get raw access to the flash memory so it's hard to do a complete scan, and also because new failures could appear after the test, perhaps even triggered by it. | Reading your comment below the question, I believe [F3](https://github.com/AltraMayor/f3) does exactly what you want. It compiles on Linux/Mac OS X and is also available via Homebrew. |
5,195 | I have just purchased a new CF card for my DSLR. I tested it using Xbench (Mac OS X) and it performs as expected. However, I'd like to do a "surface scan" (moving platter term) to check for "bad sectors" (moving platter term). I could bash script a processes using dd, but I get the feeling that there is a better way out there. My goal is to conclusively know that a memory card (CF, SD, etc.) is safe to use on a photo shoot, and that is doesn't need to be returned before the 30 day vendor policy window expires.
I definitely want Mac solutions given here. I would also like to get a few Linux suggestions. Let's even throw a bone to the windows users just so that this one question can meet everyone's needs. | 2010/11/27 | [
"https://photo.stackexchange.com/questions/5195",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/2363/"
] | Flash memory does not work the same way as disks with platters. The concept of a "bad sector" does not really exist with flash memory. These days, with flash memory and SSD's, the built-in controller takes care of identifying and marking off unusable blocks of memory, dynamically moving data around to mitigate block write limitations, etc. These features are far more prevalent in SSD's, but some also exist in quality flash cards (such as SanDisk).
Most file system checking tools either make specific assumptions about the physical structure of the storage device (i.e. platter based, with physical cylinders, sectors, clusters, etc.), or work at an abstracted level and make repairs "virtually" using file or directory tables. You would need a tool specifically designed to mark bad blocks on a flash memory device, as anything else is either going to cause more problems (by assuming it can fix the problems the same way it would with a platter-based device) or make virtual fixes that don't take into account dynamic hardware-level features of flash. Even if you could mark a particular "sector" or "cluster" as 'bad', it wouldn't necessarily do any good, since those physical concepts don't actually exist in flash memory. If the flash device is more advanced, and dynamically moves data around to automatically bypass bad blocks and mitigate write limitations, the physical location of data may reside in a bad block one moment, and in a good block a moment later. (Note that the idea of a "bad" block in flash memory is much fuzzier than it is with platter disks...a flash memory block tends to die slowly, rather than suddenly, and may "flicker" between readable/not readable a bit before it becomes entirely unusable.)
Generally speaking, when it comes to flash, let the device manage itself from a bad block perspective. Different manufacturers structure and store data in different ways, and each may have different levels and amounts of dynamic behavior that moves data around to avoid some of the limitations of flash memory. Trying to manage it yourself is likely to cause more problems than it solves, and may render your flash disks useless in the long run.
If you wish to avoid bad flash cards, I highly recommend using reputable brands. I have tried a variety of flash cards in the past, however SanDisk is the only brand that I have used that, at least to date, has never failed. I have several 4, 8, and 16 gig SDHC cards that I use quite heavily, and regularly take out of my camera and insert into my laptop or computer, and they are still working perfectly. (Some are several years old.) | I found this on google, I'm not using sd cards for cameras' storage but instead I got my class 10 32 gigs sdhc sandisk completely corrupted after less then 2 years of use on my samsung galaxy S2.
I am using badblocks to see where the first badblocks start and then I will make partitions around that area if possible. this is my current, very very bad solution :/ |
5,195 | I have just purchased a new CF card for my DSLR. I tested it using Xbench (Mac OS X) and it performs as expected. However, I'd like to do a "surface scan" (moving platter term) to check for "bad sectors" (moving platter term). I could bash script a processes using dd, but I get the feeling that there is a better way out there. My goal is to conclusively know that a memory card (CF, SD, etc.) is safe to use on a photo shoot, and that is doesn't need to be returned before the 30 day vendor policy window expires.
I definitely want Mac solutions given here. I would also like to get a few Linux suggestions. Let's even throw a bone to the windows users just so that this one question can meet everyone's needs. | 2010/11/27 | [
"https://photo.stackexchange.com/questions/5195",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/2363/"
] | Flash memory does not work the same way as disks with platters. The concept of a "bad sector" does not really exist with flash memory. These days, with flash memory and SSD's, the built-in controller takes care of identifying and marking off unusable blocks of memory, dynamically moving data around to mitigate block write limitations, etc. These features are far more prevalent in SSD's, but some also exist in quality flash cards (such as SanDisk).
Most file system checking tools either make specific assumptions about the physical structure of the storage device (i.e. platter based, with physical cylinders, sectors, clusters, etc.), or work at an abstracted level and make repairs "virtually" using file or directory tables. You would need a tool specifically designed to mark bad blocks on a flash memory device, as anything else is either going to cause more problems (by assuming it can fix the problems the same way it would with a platter-based device) or make virtual fixes that don't take into account dynamic hardware-level features of flash. Even if you could mark a particular "sector" or "cluster" as 'bad', it wouldn't necessarily do any good, since those physical concepts don't actually exist in flash memory. If the flash device is more advanced, and dynamically moves data around to automatically bypass bad blocks and mitigate write limitations, the physical location of data may reside in a bad block one moment, and in a good block a moment later. (Note that the idea of a "bad" block in flash memory is much fuzzier than it is with platter disks...a flash memory block tends to die slowly, rather than suddenly, and may "flicker" between readable/not readable a bit before it becomes entirely unusable.)
Generally speaking, when it comes to flash, let the device manage itself from a bad block perspective. Different manufacturers structure and store data in different ways, and each may have different levels and amounts of dynamic behavior that moves data around to avoid some of the limitations of flash memory. Trying to manage it yourself is likely to cause more problems than it solves, and may render your flash disks useless in the long run.
If you wish to avoid bad flash cards, I highly recommend using reputable brands. I have tried a variety of flash cards in the past, however SanDisk is the only brand that I have used that, at least to date, has never failed. I have several 4, 8, and 16 gig SDHC cards that I use quite heavily, and regularly take out of my camera and insert into my laptop or computer, and they are still working perfectly. (Some are several years old.) | Reading your comment below the question, I believe [F3](https://github.com/AltraMayor/f3) does exactly what you want. It compiles on Linux/Mac OS X and is also available via Homebrew. |
5,195 | I have just purchased a new CF card for my DSLR. I tested it using Xbench (Mac OS X) and it performs as expected. However, I'd like to do a "surface scan" (moving platter term) to check for "bad sectors" (moving platter term). I could bash script a processes using dd, but I get the feeling that there is a better way out there. My goal is to conclusively know that a memory card (CF, SD, etc.) is safe to use on a photo shoot, and that is doesn't need to be returned before the 30 day vendor policy window expires.
I definitely want Mac solutions given here. I would also like to get a few Linux suggestions. Let's even throw a bone to the windows users just so that this one question can meet everyone's needs. | 2010/11/27 | [
"https://photo.stackexchange.com/questions/5195",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/2363/"
] | Reading your comment below the question, I believe [F3](https://github.com/AltraMayor/f3) does exactly what you want. It compiles on Linux/Mac OS X and is also available via Homebrew. | I found this on google, I'm not using sd cards for cameras' storage but instead I got my class 10 32 gigs sdhc sandisk completely corrupted after less then 2 years of use on my samsung galaxy S2.
I am using badblocks to see where the first badblocks start and then I will make partitions around that area if possible. this is my current, very very bad solution :/ |
7,802,159 | I have the same exact problem that's in this [question](https://stackoverflow.com/questions/5070237/problemas-com-parse-xml-iphone), but it didn't get any good answers.
I'm trying to parse an XML file with an `ISO-8859-1` encoding, but everytime there's an accentuated word, it gets truncated and doesn't show properly.
```
Example:
Original Word: Interés
Word Shown: és
``` | 2011/10/18 | [
"https://Stackoverflow.com/questions/7802159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1000331/"
] | What you want is MySQL [Master-Master replication](http://dev.mysql.com/doc/refman/5.1/en/mysql-cluster-replication-multi-master.html), which will work as you request. | You want [MySQL replication](http://dev.mysql.com/doc/refman/5.0/en/replication.html). There are a number of ways to set it up; have a look at that doc. |
7,802,159 | I have the same exact problem that's in this [question](https://stackoverflow.com/questions/5070237/problemas-com-parse-xml-iphone), but it didn't get any good answers.
I'm trying to parse an XML file with an `ISO-8859-1` encoding, but everytime there's an accentuated word, it gets truncated and doesn't show properly.
```
Example:
Original Word: Interés
Word Shown: és
``` | 2011/10/18 | [
"https://Stackoverflow.com/questions/7802159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1000331/"
] | We did this once with 6 mysql servers doing replication in a circular chain. The replication chain was:
```
A -> B -> C -> D -> E -> F -> A
```
When a failover was detected the master was moved from A to B (an so forth) - DNS was updated for the master - but reads where taken from random member of the chain. | You want [MySQL replication](http://dev.mysql.com/doc/refman/5.0/en/replication.html). There are a number of ways to set it up; have a look at that doc. |
7,802,159 | I have the same exact problem that's in this [question](https://stackoverflow.com/questions/5070237/problemas-com-parse-xml-iphone), but it didn't get any good answers.
I'm trying to parse an XML file with an `ISO-8859-1` encoding, but everytime there's an accentuated word, it gets truncated and doesn't show properly.
```
Example:
Original Word: Interés
Word Shown: és
``` | 2011/10/18 | [
"https://Stackoverflow.com/questions/7802159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1000331/"
] | * Using MySQL replication.
* using active-pasive with [rdbd](http://www.drbd.org/) + [heartbeat](http://linux-ha.org/wiki/Heartbeat)
In any case you would need use DNS to automatically update the IP or VIP | You want [MySQL replication](http://dev.mysql.com/doc/refman/5.0/en/replication.html). There are a number of ways to set it up; have a look at that doc. |
7,802,159 | I have the same exact problem that's in this [question](https://stackoverflow.com/questions/5070237/problemas-com-parse-xml-iphone), but it didn't get any good answers.
I'm trying to parse an XML file with an `ISO-8859-1` encoding, but everytime there's an accentuated word, it gets truncated and doesn't show properly.
```
Example:
Original Word: Interés
Word Shown: és
``` | 2011/10/18 | [
"https://Stackoverflow.com/questions/7802159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1000331/"
] | * Using MySQL replication.
* using active-pasive with [rdbd](http://www.drbd.org/) + [heartbeat](http://linux-ha.org/wiki/Heartbeat)
In any case you would need use DNS to automatically update the IP or VIP | What you want is MySQL [Master-Master replication](http://dev.mysql.com/doc/refman/5.1/en/mysql-cluster-replication-multi-master.html), which will work as you request. |
7,802,159 | I have the same exact problem that's in this [question](https://stackoverflow.com/questions/5070237/problemas-com-parse-xml-iphone), but it didn't get any good answers.
I'm trying to parse an XML file with an `ISO-8859-1` encoding, but everytime there's an accentuated word, it gets truncated and doesn't show properly.
```
Example:
Original Word: Interés
Word Shown: és
``` | 2011/10/18 | [
"https://Stackoverflow.com/questions/7802159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1000331/"
] | * Using MySQL replication.
* using active-pasive with [rdbd](http://www.drbd.org/) + [heartbeat](http://linux-ha.org/wiki/Heartbeat)
In any case you would need use DNS to automatically update the IP or VIP | We did this once with 6 mysql servers doing replication in a circular chain. The replication chain was:
```
A -> B -> C -> D -> E -> F -> A
```
When a failover was detected the master was moved from A to B (an so forth) - DNS was updated for the master - but reads where taken from random member of the chain. |
6,258,361 | I've googled about this all over the Internet and still haven't found a solution. As an ultimate try, I hope someone can give me an exact answer.
I get that error when I try to copy a file from a directory to another in an File Explorer I'm trying to do on my own. It has a treeview control to browse for directories and a listview control to display the contents of the directory. This is how the code would look like, partially:
```
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
sourceDir = treeView1.SelectedNode.FullPath;
for (int i = 0; i < listView1.SelectedItems.Count; ++i)
{
ListViewItem l = listView1.SelectedItems[i];
toBeCopied[i] = l.Text; // string[] toBeCopied, the place where I save the file names I want to save
}
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
targetDir = treeView1.SelectedNode.FullPath;
try
{
for (int i = 0; i < toBeCopied.Length; ++i)
{
File.Copy(sourceDir + "\\" + toBeCopied[i], targetDir + "\\" + toBeCopied[i], true);
refreshToolStripMenuItem_Click(sender, e);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.TargetSite);
}
}
```
The place where I got the error is at `File.Copy(sourceDir + "\\" + toBeCopied[i] ...`.
I've read that it could be something that has to do with the mapping of devices, but I don't really know what that is. | 2011/06/06 | [
"https://Stackoverflow.com/questions/6258361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/786559/"
] | Can you take a look at the [Path.Combine](http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx) method on MSDN? This will help make sure all your entire path doesn't have extra \'s where they shouldn't be.
i.e. `Path.Combine(sourceDir, toBeCopied[i])`
If you are still getting an error, let me know what the value if the above. | Assuming both `sourceDir` and `targetDir` exist (which you can *and should* check), you might be doubling up a trailing `\`. When building paths, you should use [Path.Combine](http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx).
```
File.Copy(Path.Combine(sourceDir, toBeCopied[i]), Path.Combine(targetDir, toBeCopied[i]), true);
``` |
6,258,361 | I've googled about this all over the Internet and still haven't found a solution. As an ultimate try, I hope someone can give me an exact answer.
I get that error when I try to copy a file from a directory to another in an File Explorer I'm trying to do on my own. It has a treeview control to browse for directories and a listview control to display the contents of the directory. This is how the code would look like, partially:
```
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
sourceDir = treeView1.SelectedNode.FullPath;
for (int i = 0; i < listView1.SelectedItems.Count; ++i)
{
ListViewItem l = listView1.SelectedItems[i];
toBeCopied[i] = l.Text; // string[] toBeCopied, the place where I save the file names I want to save
}
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
targetDir = treeView1.SelectedNode.FullPath;
try
{
for (int i = 0; i < toBeCopied.Length; ++i)
{
File.Copy(sourceDir + "\\" + toBeCopied[i], targetDir + "\\" + toBeCopied[i], true);
refreshToolStripMenuItem_Click(sender, e);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.TargetSite);
}
}
```
The place where I got the error is at `File.Copy(sourceDir + "\\" + toBeCopied[i] ...`.
I've read that it could be something that has to do with the mapping of devices, but I don't really know what that is. | 2011/06/06 | [
"https://Stackoverflow.com/questions/6258361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/786559/"
] | You do not show where `toBeCopied` is created. It looks like you are probably running past the end of the values that are set in the click event, and trying to copy a bunch of files with empty names.
You should add this to the beginning of your click event
```
toBeCopied = new string[listView1.SelectedItems.Count];
```
Also (as others have noted) instead of
```
sourceDir + "\\" + toBeCopied[i]
```
you should use
```
Path.Combine(sourceDir, toBeCopied[i])
``` | Assuming both `sourceDir` and `targetDir` exist (which you can *and should* check), you might be doubling up a trailing `\`. When building paths, you should use [Path.Combine](http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx).
```
File.Copy(Path.Combine(sourceDir, toBeCopied[i]), Path.Combine(targetDir, toBeCopied[i]), true);
``` |
6,258,361 | I've googled about this all over the Internet and still haven't found a solution. As an ultimate try, I hope someone can give me an exact answer.
I get that error when I try to copy a file from a directory to another in an File Explorer I'm trying to do on my own. It has a treeview control to browse for directories and a listview control to display the contents of the directory. This is how the code would look like, partially:
```
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
sourceDir = treeView1.SelectedNode.FullPath;
for (int i = 0; i < listView1.SelectedItems.Count; ++i)
{
ListViewItem l = listView1.SelectedItems[i];
toBeCopied[i] = l.Text; // string[] toBeCopied, the place where I save the file names I want to save
}
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
targetDir = treeView1.SelectedNode.FullPath;
try
{
for (int i = 0; i < toBeCopied.Length; ++i)
{
File.Copy(sourceDir + "\\" + toBeCopied[i], targetDir + "\\" + toBeCopied[i], true);
refreshToolStripMenuItem_Click(sender, e);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.TargetSite);
}
}
```
The place where I got the error is at `File.Copy(sourceDir + "\\" + toBeCopied[i] ...`.
I've read that it could be something that has to do with the mapping of devices, but I don't really know what that is. | 2011/06/06 | [
"https://Stackoverflow.com/questions/6258361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/786559/"
] | Does the target path up to the file name exist? `File.Copy()` will not create any missing intermediate path, you would need to do this yourself. Use the debugger to see both the source and target paths you are creating and make sure the source exists and the target exists at least up to the parent of the target file. | Assuming both `sourceDir` and `targetDir` exist (which you can *and should* check), you might be doubling up a trailing `\`. When building paths, you should use [Path.Combine](http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx).
```
File.Copy(Path.Combine(sourceDir, toBeCopied[i]), Path.Combine(targetDir, toBeCopied[i]), true);
``` |
6,258,361 | I've googled about this all over the Internet and still haven't found a solution. As an ultimate try, I hope someone can give me an exact answer.
I get that error when I try to copy a file from a directory to another in an File Explorer I'm trying to do on my own. It has a treeview control to browse for directories and a listview control to display the contents of the directory. This is how the code would look like, partially:
```
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
sourceDir = treeView1.SelectedNode.FullPath;
for (int i = 0; i < listView1.SelectedItems.Count; ++i)
{
ListViewItem l = listView1.SelectedItems[i];
toBeCopied[i] = l.Text; // string[] toBeCopied, the place where I save the file names I want to save
}
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
targetDir = treeView1.SelectedNode.FullPath;
try
{
for (int i = 0; i < toBeCopied.Length; ++i)
{
File.Copy(sourceDir + "\\" + toBeCopied[i], targetDir + "\\" + toBeCopied[i], true);
refreshToolStripMenuItem_Click(sender, e);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.TargetSite);
}
}
```
The place where I got the error is at `File.Copy(sourceDir + "\\" + toBeCopied[i] ...`.
I've read that it could be something that has to do with the mapping of devices, but I don't really know what that is. | 2011/06/06 | [
"https://Stackoverflow.com/questions/6258361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/786559/"
] | Assuming both `sourceDir` and `targetDir` exist (which you can *and should* check), you might be doubling up a trailing `\`. When building paths, you should use [Path.Combine](http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx).
```
File.Copy(Path.Combine(sourceDir, toBeCopied[i]), Path.Combine(targetDir, toBeCopied[i]), true);
``` | Borrowing from Henk's loop, but I'd add the file & directory checks, since it is the path not found errors that need checking/creating that the OP has the problem with.
```
for (int i = 0; i < toBeCopied.Length; ++i)
{
string sourceFile = Path.Combine(sourceDir, toBeCopied[i]);
if(File.Exists(sourceFile))
{
string targetFile = Path.Combine(targetDir, toBeCopied[i]);
if(!Directory.Exists(targetDir))
Directory.CreateDirectory(targetDir);
File.Copy(sourceFile, targetFile, true);
}
refreshToolStripMenuItem_Click(sender, e)
}
``` |
6,258,361 | I've googled about this all over the Internet and still haven't found a solution. As an ultimate try, I hope someone can give me an exact answer.
I get that error when I try to copy a file from a directory to another in an File Explorer I'm trying to do on my own. It has a treeview control to browse for directories and a listview control to display the contents of the directory. This is how the code would look like, partially:
```
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
sourceDir = treeView1.SelectedNode.FullPath;
for (int i = 0; i < listView1.SelectedItems.Count; ++i)
{
ListViewItem l = listView1.SelectedItems[i];
toBeCopied[i] = l.Text; // string[] toBeCopied, the place where I save the file names I want to save
}
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
targetDir = treeView1.SelectedNode.FullPath;
try
{
for (int i = 0; i < toBeCopied.Length; ++i)
{
File.Copy(sourceDir + "\\" + toBeCopied[i], targetDir + "\\" + toBeCopied[i], true);
refreshToolStripMenuItem_Click(sender, e);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.TargetSite);
}
}
```
The place where I got the error is at `File.Copy(sourceDir + "\\" + toBeCopied[i] ...`.
I've read that it could be something that has to do with the mapping of devices, but I don't really know what that is. | 2011/06/06 | [
"https://Stackoverflow.com/questions/6258361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/786559/"
] | Can you take a look at the [Path.Combine](http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx) method on MSDN? This will help make sure all your entire path doesn't have extra \'s where they shouldn't be.
i.e. `Path.Combine(sourceDir, toBeCopied[i])`
If you are still getting an error, let me know what the value if the above. | Does the target path up to the file name exist? `File.Copy()` will not create any missing intermediate path, you would need to do this yourself. Use the debugger to see both the source and target paths you are creating and make sure the source exists and the target exists at least up to the parent of the target file. |
6,258,361 | I've googled about this all over the Internet and still haven't found a solution. As an ultimate try, I hope someone can give me an exact answer.
I get that error when I try to copy a file from a directory to another in an File Explorer I'm trying to do on my own. It has a treeview control to browse for directories and a listview control to display the contents of the directory. This is how the code would look like, partially:
```
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
sourceDir = treeView1.SelectedNode.FullPath;
for (int i = 0; i < listView1.SelectedItems.Count; ++i)
{
ListViewItem l = listView1.SelectedItems[i];
toBeCopied[i] = l.Text; // string[] toBeCopied, the place where I save the file names I want to save
}
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
targetDir = treeView1.SelectedNode.FullPath;
try
{
for (int i = 0; i < toBeCopied.Length; ++i)
{
File.Copy(sourceDir + "\\" + toBeCopied[i], targetDir + "\\" + toBeCopied[i], true);
refreshToolStripMenuItem_Click(sender, e);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.TargetSite);
}
}
```
The place where I got the error is at `File.Copy(sourceDir + "\\" + toBeCopied[i] ...`.
I've read that it could be something that has to do with the mapping of devices, but I don't really know what that is. | 2011/06/06 | [
"https://Stackoverflow.com/questions/6258361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/786559/"
] | Can you take a look at the [Path.Combine](http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx) method on MSDN? This will help make sure all your entire path doesn't have extra \'s where they shouldn't be.
i.e. `Path.Combine(sourceDir, toBeCopied[i])`
If you are still getting an error, let me know what the value if the above. | Borrowing from Henk's loop, but I'd add the file & directory checks, since it is the path not found errors that need checking/creating that the OP has the problem with.
```
for (int i = 0; i < toBeCopied.Length; ++i)
{
string sourceFile = Path.Combine(sourceDir, toBeCopied[i]);
if(File.Exists(sourceFile))
{
string targetFile = Path.Combine(targetDir, toBeCopied[i]);
if(!Directory.Exists(targetDir))
Directory.CreateDirectory(targetDir);
File.Copy(sourceFile, targetFile, true);
}
refreshToolStripMenuItem_Click(sender, e)
}
``` |
6,258,361 | I've googled about this all over the Internet and still haven't found a solution. As an ultimate try, I hope someone can give me an exact answer.
I get that error when I try to copy a file from a directory to another in an File Explorer I'm trying to do on my own. It has a treeview control to browse for directories and a listview control to display the contents of the directory. This is how the code would look like, partially:
```
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
sourceDir = treeView1.SelectedNode.FullPath;
for (int i = 0; i < listView1.SelectedItems.Count; ++i)
{
ListViewItem l = listView1.SelectedItems[i];
toBeCopied[i] = l.Text; // string[] toBeCopied, the place where I save the file names I want to save
}
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
targetDir = treeView1.SelectedNode.FullPath;
try
{
for (int i = 0; i < toBeCopied.Length; ++i)
{
File.Copy(sourceDir + "\\" + toBeCopied[i], targetDir + "\\" + toBeCopied[i], true);
refreshToolStripMenuItem_Click(sender, e);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.TargetSite);
}
}
```
The place where I got the error is at `File.Copy(sourceDir + "\\" + toBeCopied[i] ...`.
I've read that it could be something that has to do with the mapping of devices, but I don't really know what that is. | 2011/06/06 | [
"https://Stackoverflow.com/questions/6258361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/786559/"
] | You do not show where `toBeCopied` is created. It looks like you are probably running past the end of the values that are set in the click event, and trying to copy a bunch of files with empty names.
You should add this to the beginning of your click event
```
toBeCopied = new string[listView1.SelectedItems.Count];
```
Also (as others have noted) instead of
```
sourceDir + "\\" + toBeCopied[i]
```
you should use
```
Path.Combine(sourceDir, toBeCopied[i])
``` | Does the target path up to the file name exist? `File.Copy()` will not create any missing intermediate path, you would need to do this yourself. Use the debugger to see both the source and target paths you are creating and make sure the source exists and the target exists at least up to the parent of the target file. |
6,258,361 | I've googled about this all over the Internet and still haven't found a solution. As an ultimate try, I hope someone can give me an exact answer.
I get that error when I try to copy a file from a directory to another in an File Explorer I'm trying to do on my own. It has a treeview control to browse for directories and a listview control to display the contents of the directory. This is how the code would look like, partially:
```
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
sourceDir = treeView1.SelectedNode.FullPath;
for (int i = 0; i < listView1.SelectedItems.Count; ++i)
{
ListViewItem l = listView1.SelectedItems[i];
toBeCopied[i] = l.Text; // string[] toBeCopied, the place where I save the file names I want to save
}
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
targetDir = treeView1.SelectedNode.FullPath;
try
{
for (int i = 0; i < toBeCopied.Length; ++i)
{
File.Copy(sourceDir + "\\" + toBeCopied[i], targetDir + "\\" + toBeCopied[i], true);
refreshToolStripMenuItem_Click(sender, e);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.TargetSite);
}
}
```
The place where I got the error is at `File.Copy(sourceDir + "\\" + toBeCopied[i] ...`.
I've read that it could be something that has to do with the mapping of devices, but I don't really know what that is. | 2011/06/06 | [
"https://Stackoverflow.com/questions/6258361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/786559/"
] | You do not show where `toBeCopied` is created. It looks like you are probably running past the end of the values that are set in the click event, and trying to copy a bunch of files with empty names.
You should add this to the beginning of your click event
```
toBeCopied = new string[listView1.SelectedItems.Count];
```
Also (as others have noted) instead of
```
sourceDir + "\\" + toBeCopied[i]
```
you should use
```
Path.Combine(sourceDir, toBeCopied[i])
``` | Borrowing from Henk's loop, but I'd add the file & directory checks, since it is the path not found errors that need checking/creating that the OP has the problem with.
```
for (int i = 0; i < toBeCopied.Length; ++i)
{
string sourceFile = Path.Combine(sourceDir, toBeCopied[i]);
if(File.Exists(sourceFile))
{
string targetFile = Path.Combine(targetDir, toBeCopied[i]);
if(!Directory.Exists(targetDir))
Directory.CreateDirectory(targetDir);
File.Copy(sourceFile, targetFile, true);
}
refreshToolStripMenuItem_Click(sender, e)
}
``` |
6,258,361 | I've googled about this all over the Internet and still haven't found a solution. As an ultimate try, I hope someone can give me an exact answer.
I get that error when I try to copy a file from a directory to another in an File Explorer I'm trying to do on my own. It has a treeview control to browse for directories and a listview control to display the contents of the directory. This is how the code would look like, partially:
```
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
sourceDir = treeView1.SelectedNode.FullPath;
for (int i = 0; i < listView1.SelectedItems.Count; ++i)
{
ListViewItem l = listView1.SelectedItems[i];
toBeCopied[i] = l.Text; // string[] toBeCopied, the place where I save the file names I want to save
}
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
targetDir = treeView1.SelectedNode.FullPath;
try
{
for (int i = 0; i < toBeCopied.Length; ++i)
{
File.Copy(sourceDir + "\\" + toBeCopied[i], targetDir + "\\" + toBeCopied[i], true);
refreshToolStripMenuItem_Click(sender, e);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.TargetSite);
}
}
```
The place where I got the error is at `File.Copy(sourceDir + "\\" + toBeCopied[i] ...`.
I've read that it could be something that has to do with the mapping of devices, but I don't really know what that is. | 2011/06/06 | [
"https://Stackoverflow.com/questions/6258361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/786559/"
] | Does the target path up to the file name exist? `File.Copy()` will not create any missing intermediate path, you would need to do this yourself. Use the debugger to see both the source and target paths you are creating and make sure the source exists and the target exists at least up to the parent of the target file. | Borrowing from Henk's loop, but I'd add the file & directory checks, since it is the path not found errors that need checking/creating that the OP has the problem with.
```
for (int i = 0; i < toBeCopied.Length; ++i)
{
string sourceFile = Path.Combine(sourceDir, toBeCopied[i]);
if(File.Exists(sourceFile))
{
string targetFile = Path.Combine(targetDir, toBeCopied[i]);
if(!Directory.Exists(targetDir))
Directory.CreateDirectory(targetDir);
File.Copy(sourceFile, targetFile, true);
}
refreshToolStripMenuItem_Click(sender, e)
}
``` |
38,827,783 | All of a sudden, my Visual Studio has begun to popup a message every time I want to break my ASP.net project.
[](https://i.stack.imgur.com/VEzra.png)
How can I get rid of this dialog?
There is nothing to complete, only a debug session to get rid of. Clicking the "Stop Now" button will not immediately stop the execution, but wait some seconds.
From what I know, I have not changed any configuration to get this dialog. | 2016/08/08 | [
"https://Stackoverflow.com/questions/38827783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1427758/"
] | Deleting all breakpoints **(Menu > Debug > Delete All Breakpoints)** and running in Debug mode fixed it. Unfortunately, nothing else did it for me. I had to again set the breakpoints that I wanted.
Alternatively, you can choose to work around this problem by choosing the **Menu > Debug > Terminate All** option instead of clicking the **Stop Debugging (Shift + F5)** button.
Microsoft announced that they have fixed it in the new release of VS 2017, per this [link](https://developercommunity.visualstudio.com/content/problem/33482/asp-net-core-debugging-closing-browser-window-does.html): | I tried deleting my log files and this fixed the issue for me. I think it stalled while trying to write when the files got so large, somehow.
Inside the project folder, try deleting all the log files in `\bin\Debug\logs` (path my vary depending on your own config) |
26,374,112 | I basically want to create a timer. I have a textview where I need to show a timer like "Updating your location in 2min 29 secs" and I want the timer to decreament For eg 2min 28secs followed by 2min 27 secs.
And I want to update it even when the user is not using my app (I dont want it to update in real sense what I mean is when user opens my app after say 1 min then the timer should show 1min 27 secs).
Can some one please help me out in pointing out the correct and efficient way of doing this ? Thanks :) | 2014/10/15 | [
"https://Stackoverflow.com/questions/26374112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3064175/"
] | The most efficient way in my opinion is using [scheduleAtFixedRate](http://developer.android.com/reference/java/util/Timer.html#scheduleAtFixedRate%28java.util.TimerTask,%20long,%20long%29) when your activity is in foreground and when it is going to background you do not need any services you can just save the current time and the remaining time in a sharedpreferances and when again your activity comes to foreground read those values plus current time and then update the `textview` in a proper way. | You could use a service and send intents that your activity receives (the one with the TextView) using **LocalBroadcastManager**. You should register a *BroadcastReceiver* inside *Activity.onResume()*, and unregister it inside *onPause()*.
Using a **TimerTask** should be the default approach but you must be aware that if your activity is sent to background it can be killed by the system. That's why I recommend using a service.
Hope it helps. |
3,694,597 | >
> Show that, if $P$ and $Q$ are constants and $$y = P\cos(\ln(t)) + Q\sin(\ln(t))$$
> then
> $$t^2\frac{d^2y}{dt^2}+t\frac{dy}{dt}+y=0$$
>
>
> | 2020/05/27 | [
"https://math.stackexchange.com/questions/3694597",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/791189/"
] | Actually this is true only if $n\mid m$. Indeed
$$n\cdot\mathbf Z/m\mathbf Z=(n\mathbf Z+m\mathbf Z)/m\mathbf Z=\gcd(m,n)\mathbf Z/m\mathbf Z.$$ | $(n)/(m)$ doesn't even make sense unless $(m) \subseteq (n)$, which is equivalent to $n | m$, so I'll assume this. But your statement is false unless $n = 0$ or $m = 0$. If neither is 0, then $(n)/(m) \cong \mathbb Z/(m/n)\mathbb Z$. This is a finite group, as $m/n \neq 0$. However, $(n)$ is infinite as $n \neq 0$ so these are not isomorphic. |
66,334,998 | In Numpy, say I have a matrix A of dimensions i x j x k, and a matrix B of dimensions k x i. How do I get back a product with dimensions k x i without using a loop?
For example:
```
Let A = [[[1 2],
[3 4]],
[[5 6],
[7 8]]]
B = [[a b],
[c d]]
```
I would like to get:
```
C = [[a+2c 5b+6d],
[3a+4c 7b+8d]]
```
My current solution is
```
np.diagonal(np.dot(A, B), axis1=0, axis2=2)
```
However, the problem is I'm working with a large data set (`A` and `B` have huge dimensions) so `np.dot(A, B)` would lead to `MemoryError`. Therefore I want to figure out a better way to solve this without computing the dot product.
I have looked into functions like `einsum` and `tensordot` but I didn't find what I need (or maybe I missed something). I would appreciate if someone could help me out. Thank you! | 2021/02/23 | [
"https://Stackoverflow.com/questions/66334998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11485718/"
] | You can do this by analyzing the input and output dimensions.
```
A.shape -> i, j, k
B.shape -> k, i
```
Your example is not very good, but if you look carefully at what you're asking the output to be, the shape of `B` must match the first and last dimensions of `A`.
The sum reduction is happening along the last axis of `A` and the first axis of `B`:
```
np.einsum('ijk,ki->ji', A, B)
```
`einsum` can be intimidating, but doing this sort of analysis can save you a lot of the frustration caused by trial and error. | Looking at your output, `C[:,0]` is
```
A[0] @ B[0].T
```
and similarly, `C[:,1]` is `A[1] @ B[1].T`.
With that in mind, the `np.einsum` formula is:
```
C = np.einsum('ijk,ik->ji', A,B)
``` |
10,070,701 | The code below is in C# and I'm using Visual Studio 2010.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace FrontEnd
{
class Flow
{
long i;
private int x,y;
public int X
{
get;set;
}
public int Y
{
get;set;
}
private void Flow()
{
X = x;
Y = y;
}
public void NaturalNumbers(int x, int y)
{
for (i = 0; i < 9999; i++)
{
Console.WriteLine(i);
}
MessageBox.Show("done");
}
}
}
```
When I compile the above code I get this error:
>
> Error: 'Flow': member names cannot be the same as their enclosing type
>
>
>
Why? How can I resolve this? | 2012/04/09 | [
"https://Stackoverflow.com/questions/10070701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/961016/"
] | Constructors don't return a type , just remove the return type which is void in your case. It would run fine then. | As Constructor should be at the starting of the Class , you are facing the above issue . So, you can either change the name or if you want to use it as a constructor just copy the method at the beginning of the class. |
10,070,701 | The code below is in C# and I'm using Visual Studio 2010.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace FrontEnd
{
class Flow
{
long i;
private int x,y;
public int X
{
get;set;
}
public int Y
{
get;set;
}
private void Flow()
{
X = x;
Y = y;
}
public void NaturalNumbers(int x, int y)
{
for (i = 0; i < 9999; i++)
{
Console.WriteLine(i);
}
MessageBox.Show("done");
}
}
}
```
When I compile the above code I get this error:
>
> Error: 'Flow': member names cannot be the same as their enclosing type
>
>
>
Why? How can I resolve this? | 2012/04/09 | [
"https://Stackoverflow.com/questions/10070701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/961016/"
] | The problem is with the method:
```
private void Flow()
{
X = x;
Y = y;
}
```
Your class is named `Flow` so this method can't also be named `Flow`. You will have to change the name of the `Flow` method to something else to make this code compile.
Or did you mean to create a private constructor to initialize your class? If that's the case, you will have to remove the `void` keyword to let the compiler know that your declaring a constructor. | Constructors don't return a type , just remove the return type which is void in your case. It would run fine then. |
10,070,701 | The code below is in C# and I'm using Visual Studio 2010.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace FrontEnd
{
class Flow
{
long i;
private int x,y;
public int X
{
get;set;
}
public int Y
{
get;set;
}
private void Flow()
{
X = x;
Y = y;
}
public void NaturalNumbers(int x, int y)
{
for (i = 0; i < 9999; i++)
{
Console.WriteLine(i);
}
MessageBox.Show("done");
}
}
}
```
When I compile the above code I get this error:
>
> Error: 'Flow': member names cannot be the same as their enclosing type
>
>
>
Why? How can I resolve this? | 2012/04/09 | [
"https://Stackoverflow.com/questions/10070701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/961016/"
] | The problem is with the method:
```
private void Flow()
{
X = x;
Y = y;
}
```
Your class is named `Flow` so this method can't also be named `Flow`. You will have to change the name of the `Flow` method to something else to make this code compile.
Or did you mean to create a private constructor to initialize your class? If that's the case, you will have to remove the `void` keyword to let the compiler know that your declaring a constructor. | just remove this because constructor don't have a return type like void
it will be like this :
```
private Flow()
{
X = x;
Y = y;
}
``` |
10,070,701 | The code below is in C# and I'm using Visual Studio 2010.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace FrontEnd
{
class Flow
{
long i;
private int x,y;
public int X
{
get;set;
}
public int Y
{
get;set;
}
private void Flow()
{
X = x;
Y = y;
}
public void NaturalNumbers(int x, int y)
{
for (i = 0; i < 9999; i++)
{
Console.WriteLine(i);
}
MessageBox.Show("done");
}
}
}
```
When I compile the above code I get this error:
>
> Error: 'Flow': member names cannot be the same as their enclosing type
>
>
>
Why? How can I resolve this? | 2012/04/09 | [
"https://Stackoverflow.com/questions/10070701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/961016/"
] | The problem is with the method:
```
private void Flow()
{
X = x;
Y = y;
}
```
Your class is named `Flow` so this method can't also be named `Flow`. You will have to change the name of the `Flow` method to something else to make this code compile.
Or did you mean to create a private constructor to initialize your class? If that's the case, you will have to remove the `void` keyword to let the compiler know that your declaring a constructor. | A constructor should no have a return type .
remove void before each constructor .
Some very basic characteristic of a constructor :
a. Same name as class
b. no return type.
c. will be called every time an object is made with the class. for eg- in your program if u made two objects of Flow,
Flow flow1=new Flow();
Flow flow2=new Flow();
then Flow constructor will be called for 2 times.
d. If you want to call the constructor just for once then declare that as static (static constructor) and dont forget to remove any access modifier from static constructor .. |
10,070,701 | The code below is in C# and I'm using Visual Studio 2010.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace FrontEnd
{
class Flow
{
long i;
private int x,y;
public int X
{
get;set;
}
public int Y
{
get;set;
}
private void Flow()
{
X = x;
Y = y;
}
public void NaturalNumbers(int x, int y)
{
for (i = 0; i < 9999; i++)
{
Console.WriteLine(i);
}
MessageBox.Show("done");
}
}
}
```
When I compile the above code I get this error:
>
> Error: 'Flow': member names cannot be the same as their enclosing type
>
>
>
Why? How can I resolve this? | 2012/04/09 | [
"https://Stackoverflow.com/questions/10070701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/961016/"
] | Constructors don't return a type , just remove the return type which is void in your case. It would run fine then. | A constructor should no have a return type .
remove void before each constructor .
Some very basic characteristic of a constructor :
a. Same name as class
b. no return type.
c. will be called every time an object is made with the class. for eg- in your program if u made two objects of Flow,
Flow flow1=new Flow();
Flow flow2=new Flow();
then Flow constructor will be called for 2 times.
d. If you want to call the constructor just for once then declare that as static (static constructor) and dont forget to remove any access modifier from static constructor .. |
10,070,701 | The code below is in C# and I'm using Visual Studio 2010.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace FrontEnd
{
class Flow
{
long i;
private int x,y;
public int X
{
get;set;
}
public int Y
{
get;set;
}
private void Flow()
{
X = x;
Y = y;
}
public void NaturalNumbers(int x, int y)
{
for (i = 0; i < 9999; i++)
{
Console.WriteLine(i);
}
MessageBox.Show("done");
}
}
}
```
When I compile the above code I get this error:
>
> Error: 'Flow': member names cannot be the same as their enclosing type
>
>
>
Why? How can I resolve this? | 2012/04/09 | [
"https://Stackoverflow.com/questions/10070701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/961016/"
] | The problem is with the method:
```
private void Flow()
{
X = x;
Y = y;
}
```
Your class is named `Flow` so this method can't also be named `Flow`. You will have to change the name of the `Flow` method to something else to make this code compile.
Or did you mean to create a private constructor to initialize your class? If that's the case, you will have to remove the `void` keyword to let the compiler know that your declaring a constructor. | As Constructor should be at the starting of the Class , you are facing the above issue . So, you can either change the name or if you want to use it as a constructor just copy the method at the beginning of the class. |
10,070,701 | The code below is in C# and I'm using Visual Studio 2010.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace FrontEnd
{
class Flow
{
long i;
private int x,y;
public int X
{
get;set;
}
public int Y
{
get;set;
}
private void Flow()
{
X = x;
Y = y;
}
public void NaturalNumbers(int x, int y)
{
for (i = 0; i < 9999; i++)
{
Console.WriteLine(i);
}
MessageBox.Show("done");
}
}
}
```
When I compile the above code I get this error:
>
> Error: 'Flow': member names cannot be the same as their enclosing type
>
>
>
Why? How can I resolve this? | 2012/04/09 | [
"https://Stackoverflow.com/questions/10070701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/961016/"
] | Method names which are same as the class name are called *constructors*. Constructors do not have a return type. So correct as:
```
private Flow()
{
X = x;
Y = y;
}
```
Or rename the function as:
```
private void DoFlow()
{
X = x;
Y = y;
}
```
Though the whole code does not make any sense to me. | The problem is with the method:
```
private void Flow()
{
X = x;
Y = y;
}
```
Your class is named `Flow` so this method can't also be named `Flow`. You will have to change the name of the `Flow` method to something else to make this code compile.
Or did you mean to create a private constructor to initialize your class? If that's the case, you will have to remove the `void` keyword to let the compiler know that your declaring a constructor. |
10,070,701 | The code below is in C# and I'm using Visual Studio 2010.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace FrontEnd
{
class Flow
{
long i;
private int x,y;
public int X
{
get;set;
}
public int Y
{
get;set;
}
private void Flow()
{
X = x;
Y = y;
}
public void NaturalNumbers(int x, int y)
{
for (i = 0; i < 9999; i++)
{
Console.WriteLine(i);
}
MessageBox.Show("done");
}
}
}
```
When I compile the above code I get this error:
>
> Error: 'Flow': member names cannot be the same as their enclosing type
>
>
>
Why? How can I resolve this? | 2012/04/09 | [
"https://Stackoverflow.com/questions/10070701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/961016/"
] | Constructors don't return a type , just remove the return type which is void in your case. It would run fine then. | just remove this because constructor don't have a return type like void
it will be like this :
```
private Flow()
{
X = x;
Y = y;
}
``` |
10,070,701 | The code below is in C# and I'm using Visual Studio 2010.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace FrontEnd
{
class Flow
{
long i;
private int x,y;
public int X
{
get;set;
}
public int Y
{
get;set;
}
private void Flow()
{
X = x;
Y = y;
}
public void NaturalNumbers(int x, int y)
{
for (i = 0; i < 9999; i++)
{
Console.WriteLine(i);
}
MessageBox.Show("done");
}
}
}
```
When I compile the above code I get this error:
>
> Error: 'Flow': member names cannot be the same as their enclosing type
>
>
>
Why? How can I resolve this? | 2012/04/09 | [
"https://Stackoverflow.com/questions/10070701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/961016/"
] | Method names which are same as the class name are called *constructors*. Constructors do not have a return type. So correct as:
```
private Flow()
{
X = x;
Y = y;
}
```
Or rename the function as:
```
private void DoFlow()
{
X = x;
Y = y;
}
```
Though the whole code does not make any sense to me. | A constructor should no have a return type .
remove void before each constructor .
Some very basic characteristic of a constructor :
a. Same name as class
b. no return type.
c. will be called every time an object is made with the class. for eg- in your program if u made two objects of Flow,
Flow flow1=new Flow();
Flow flow2=new Flow();
then Flow constructor will be called for 2 times.
d. If you want to call the constructor just for once then declare that as static (static constructor) and dont forget to remove any access modifier from static constructor .. |
10,070,701 | The code below is in C# and I'm using Visual Studio 2010.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace FrontEnd
{
class Flow
{
long i;
private int x,y;
public int X
{
get;set;
}
public int Y
{
get;set;
}
private void Flow()
{
X = x;
Y = y;
}
public void NaturalNumbers(int x, int y)
{
for (i = 0; i < 9999; i++)
{
Console.WriteLine(i);
}
MessageBox.Show("done");
}
}
}
```
When I compile the above code I get this error:
>
> Error: 'Flow': member names cannot be the same as their enclosing type
>
>
>
Why? How can I resolve this? | 2012/04/09 | [
"https://Stackoverflow.com/questions/10070701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/961016/"
] | Method names which are same as the class name are called *constructors*. Constructors do not have a return type. So correct as:
```
private Flow()
{
X = x;
Y = y;
}
```
Or rename the function as:
```
private void DoFlow()
{
X = x;
Y = y;
}
```
Though the whole code does not make any sense to me. | just remove this because constructor don't have a return type like void
it will be like this :
```
private Flow()
{
X = x;
Y = y;
}
``` |
88,886 | I have a portrait with a blurred background. I'd like to use this to create a mask or for alpha channel or to erase the background.
So after editing I want to have an image with perfect white or transparency where was the background and keep the face unchanged.
Is it possible?
What I tried yet:
* made the image copy
* converted this copy B/W
* made the copy of this B/W layer
* blured this copy
* subtracted these copies:
[](https://i.stack.imgur.com/3FfUp.png)
So I hoped that *blurred blur* will be almost the same as *blur* and *blurred sharp* will differ from *sharp* parts of the picture. And the difference will be as an indication of the blureness. But I see that my idea did not worked for some reasons.
Any other thoughts? | 2017/04/23 | [
"https://photo.stackexchange.com/questions/88886",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/25684/"
] | A little confused about your question: are you attempting to keep the face and remove the existing background? Are you having difficulty making a decent selection?
If the above is correct, you'll want to make a selection of the face.There are a multitude of ways to do that in Photoshop. In this case,you'll want to make a selection of the background. If the background is solid, you could use color range. Otherwise you could make a selection of the face and then use inverse.
I have found the select and mask option invaluable in refining my selections so that I don't have a halo or that pesky little color around the edges. There is a definite learning curve but well worth it.
Once you have made the selection hit "delete" on your keyboard and there you have it! You can then make a new document and do what you want with that background - make it white or transparent.
Hope this helps. | As others pointed out, the best way would be to learn:
1. How to use masks
2. Make and enhance selections in Photoshop
This is **THE** major first step when learning how to edit an image, beyond the classic and global adjustments, such as contrast, luminosity, curves or B&W conversion.
Concerning your image, **Photoshop may have a *magic* tool to help you**:
>
> Select > Focus Area
>
>
>
It *automatically* select the image areas in focus and can create a selection from it. It is not perfect, but if your background is blurry enough it might do what you want in a single step.
Tutorial on adobe.com: <https://helpx.adobe.com/photoshop/using/select-area-focus.html> |
7,456,993 | I have a twist on a common question I've seen in here, and I'm puzzled.
What I need is simply a dialog box for each sub item of a list item. I have seen a dialog for a list item, but I need it down to the list item's item. Currently I've tried doing that within the adapter when inside the getView() method.
For example:
```
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
if (v == null)
{
LayoutInflater li = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(_resourceId, null);
}
string description = "howdy Test";
TextView description = (TextView) v.findViewById(R.id.description);
description.setText(description );
description.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
AlertDialog.Builder dia = new AlertDialog.Builder(view.getContext());
dia.setTitle(view.getContext().getResources().getString(R.string.DESCRIPTION_TITLE));
dia.create();
}
});
}
```
With that example above, it does go into the onClick() method, but nothing happens with the AlertDialog. Has anyone else tried this? is there a better way? Even better what am I doing wrong?
Thanks,
Kelly | 2011/09/17 | [
"https://Stackoverflow.com/questions/7456993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/703210/"
] | You have to call the `show()` method on your **dia** object.[Link here to the android docs!](http://developer.android.com/reference/android/app/AlertDialog.Builder.html#show%28%29) | Instead of adding a OnClickListener to each item in the list view why don't you add one to the listview itself?
```
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id){
// Create and show dialog here
}
});
``` |
5,670,745 | Works fine in firefox but does nothing in ie.
```
<script type="text/javascript">
$(document).ready(function(){
var links = $('.bound');
var west = $('.west');
var west2 = $('.west2');
var west3 = $('.west3');
var west4 = $('.west4');
west2.hide();
west3.hide();
west4.hide();
links.click(function(event){
west.hide();
west2.hide();
west3.hide();
west4.hide();
west.filter('.' + event.target.id).show();
west2.filter('.' + event.target.id).show();
west3.filter('.' + event.target.id).show();
west4.filter('.' + event.target.id).show();
});
});
</script>
```
html
```
<div class="tabset">
<div id="tab1" class="tab-box">
<div class="form-holder">
<form action="#">
<fieldset>
<label for="lb02"><strong>Choose District:</strong></label>
<select id="lb02">
<option class="bound" id="west">WEST</option>
<option class="bound" id="west2">WEST2</option>
<option class="bound" id="west3">WEST3</option>
<option class="bound" id="west4">WEST4</option>
</select>
</fieldset>
</form>
</div>
<div class="report-box">
<table>
<thead>
<tr>
<td class="name">Name</td>
<td class="department">Department</td>
<td class="title">Title</td>
<td class="district">District</td>
<td class="profile"> </td>
</tr>
</thead>
<tbody>
<tr class="west">
<td>Name1</td>
<td>Dept2</td>
<td>Title2</td>
<td>West</td>
<td><a class="btn-profile" href="#">PROFILE</a></td>
</tr>
<tr class="west2">
<td>Name2</td>
<td>Dept2</td>
<td>Title2</td>
<td>West2</td>
<td><a class="btn-profile" href="#">PROFILE</a></td>
</tr>
</tbody>
</table>
</div>
</div>
``` | 2011/04/14 | [
"https://Stackoverflow.com/questions/5670745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708908/"
] | Instead of a `click` event on the `option` elements, use a `change` event on the `select` element.
```
var links = $('#lb02'),
wests = $('.west,.west2,.west3,.west4');
wests.not('.west').hide();
links.change(function(event) {
wests.hide().filter('.' + this.options[this.selectedIndex].id).show();
});
``` | It's probably because IE doesn't recognize `event.target`, it uses a `srcElement` property instead. Also IE may not pass the event parameter to the handler so you have to grab `window.event`. For your click function try:
```
links.click(function(event){
var e = event || window.event,
et = (e.target) ? e.target : e.srcElement;
west.hide();
west2.hide();
west3.hide();
west4.hide();
west.filter('.' + et.id).show();
west2.filter('.' + et.id).show();
west3.filter('.' + et.id).show();
west4.filter('.' + et.id).show();
});
``` |
25,912,947 | I'm trying to retrieve de int value of this reg dword:
SOFTWARE\Microsoft\Windows NT\CurrentVersion\InstallDate
I'm able to retrieve a strings' value, but i cant get the int value of the dword...
At the end, i would like to have the install date of windows.
I searched an found some solutions, but none worked.
I'm starting with this:
```
public void setWindowsInstallDate()
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\NT\CurrentVersion");
if (key != null)
{
object value = key.GetValue("InstallDate");
// some extra code ??? ...
WindowsInstallDate = value;
}
}
```
Any suggestions? | 2014/09/18 | [
"https://Stackoverflow.com/questions/25912947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1663157/"
] | The issue you have is an issue between the 32 bit registry view and the 64 bit registry view as described on MSDN [here](http://msdn.microsoft.com/en-us/library/aa384129.aspx).
To solve it you can do the following. Note that the returned value is a Unix timestamp (i.e. the number of seconds from 1 Jan 1970) so you need to manipulate the result to get the correct date:
```
//get the 64-bit view first
RegistryKey key = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
key = key.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
if (key == null)
{
//we couldn't find the value in the 64-bit view so grab the 32-bit view
key = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry32);
key = key.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
}
if (key != null)
{
Int64 value = Convert.ToInt64(key.GetValue("InstallDate").ToString());
DateTime epoch = new DateTime(1970, 1, 1);
DateTime installDate = epoch.AddSeconds(value);
}
```
The return from `GetValue` is an `Object` but `AddSeconds` requires a numeric value so we need to cast the result. I could have used `uint` above as that's big enough to store the [DWORD](http://msdn.microsoft.com/en-us/library/aa383751%28VS.85%29.aspx#dword) which is (32 bits) but I went with `Int64`.
If you prefer it more terse you could rewrite the part inside the null check in one big line:
```
DateTime installDate = new DateTime(1970, 1, 1)
.AddSeconds(Convert.ToUInt32(key.GetValue("InstallDate")));
``` | It isn´t to hard to solve.
First of all - skip HKLM if using 64bit. (LocalMachine)
Use HKCU (CurrentUser)
Use a stringvalue instead of dword for a Installdate.
Get stringvalue from registry and then "parse" to DateTime. |
11,079,337 | I am doing a transform work from windows to wince.
For using iostream I choose `STLport5.2.1`.
I get the compile error on *vs2008*:
>
> am files (x86)\windows ce tools\wce500\athenapbws\mfc\include\wcealt.h(248) : error C2084: function 'void \*operator new(size\_t,void \*)' already has a body
>
>
> 2> D:\Program Files (x86)\Windows CE Tools\wce500\AthenaPBWS\include\ARMV4I../Armv4i/new(71) : see previous definition of 'new'
>
>
> 2>d:\program files (x86)\windows ce tools\wce500\athenapbws\mfc\include\wcealt.h(254) : error C2084: function 'void operator delete(void \*,void \*)' already has a body
>
>
> 2> D:\Program Files (x86)\Windows CE Tools\wce500\AthenaPBWS\include\ARMV4I../Armv4i/new(73) : see previous definition of 'delete'
>
>
> 2>Util1.cpp
> 2>D:\Program Files (x86)\Windows CE Tools\wce500\AthenaPBWS\include\ARMV4I../Armv4i/new(72) : error C2084: function 'void \*operator new(size\_t,void \*)' already has a body
>
>
> 2> d:\program files (x86)\windows ce tools\wce500\athenapbws\mfc\include\wcealt.h(247) : see previous definition of 'new'
>
>
> 2>D:\Program Files (x86)\Windows CE Tools\wce500\AthenaPBWS\include\ARMV4I../Armv4i/new(74) : error C2084: function 'void operator delete(void \*,void \*)' already has a body
>
>
> 2> d:\program files (x86)\windows ce tools\wce500\athenapbws\mfc\include\wcealt.h(253) : see previous definition of 'delete'
>
>
>
How can you solve the error? | 2012/06/18 | [
"https://Stackoverflow.com/questions/11079337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1452611/"
] | Put prefer external into your Manifest
```
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:installLocation="preferExternal"
... >
``` | You can use the installLocation xml tag in Android Manifest file like it writes here: <http://developer.android.com/guide/appendix/install-location.html> |
54,645,489 | I have a folder named "Models" located at app/models in my laravel project directory.
I want to use all models by a single line of code in controller, instead of using each one like:
```
use App/Models/User;
use App/Models/Roles;
``` | 2019/02/12 | [
"https://Stackoverflow.com/questions/54645489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8511942/"
] | If i get the question correctly, you need to get the initial text from a tag just before the child tag. A tag’s children are available in a list called [.contents](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#contents-and-children) .
You can use `.contents[0]`
```
from bs4 import BeautifulSoup
html="""
<span class="t-small summary-count"> Showing 1-25 of 131 ads for <span>"Samsung Galaxy A5"</span>.</span>
"""
soup=BeautifulSoup(html,'html.parser')
pgn = soup.find("span", {"class": "t-small summary-count"})
print(pgn.contents)
print(pgn.contents[0])
```
Output
```
[' Showing 1-25 of 131 ads for ', <span>"Samsung Galaxy A5"</span>, '.']
Showing 1-25 of 131 ads for
``` | You need to find `<span> .... </span>` with `select` and then get text before it with using `previousSibling`
All code :
```
from bs4 import BeautifulSoup
html = ''' <span class="t-small summary-count"> Showing 1-25 of 131 ads for
<span>"Samsung Galaxy A5"</span>.</span>
'''
soup = BeautifulSoup(html, 'lxml')
get_span = soup.find('span' , attrs={'class' : 't-small summary-count'})
for a in get_span.select('span'):
print a.previousSibling
``` |
19,444,188 | I want to save `numpy.array` data into XML file, then read it again. following is my code:
**array to string**
```
arr=numpy.zeros((20))
s = str(arr)
```
But This way would generate **enter key and '[',']'** characters in the string.
**string to array**
I should remove the enter key and '[',']' first. And then use `numpy.fromstring`
But I don't think that's a good way to do that. **And that can't work on 2-D array** | 2013/10/18 | [
"https://Stackoverflow.com/questions/19444188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/936332/"
] | You are mixing two different ways of doing "to string":
```
a = numpy.zeros((20))
```
you can, after stripping newlines and `[]` from it, put `str(a)` in a new `numpy.matrix()` constructor and initialize `numpy.array()` with the returned value:
```
b = numpy.array(numpy.matrix(" ".join(str(a).split()).strip('[]')))
```
or you can combine `numpy.array.tostring()` with `numpy.fromstring()`:
```
c = numpy.fromstring(a.tostring())
```
but mixing and matching like you tried to do does not work. | You can easily turn numpy arrays into regular python lists and vice versa. You could then store the string representation of the list to file, load it from file, turn it back into a list and into a numpy array.
```
>>> list(numpy.zeros(4))
[0.0, 0.0, 0.0, 0.0]
>>> numpy.array([0.0, 0.0, 0.0, 0.0])
array([ 0., 0., 0., 0.])
```
Using the `map` function, this also works for 2D-arrays.
```
>>> map(list, numpy.zeros((2, 3)))
[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
>>> numpy.array([[0.0, 0.0], [0.0, 0.0]])
array([[ 0., 0., 0.],
[ 0., 0., 0.]])
```
However, if the array is really big it might still be better to store it using `numpy.save` and `numpy.load` and use the XML file only to store the path to that file, together with a comment. |
19,444,188 | I want to save `numpy.array` data into XML file, then read it again. following is my code:
**array to string**
```
arr=numpy.zeros((20))
s = str(arr)
```
But This way would generate **enter key and '[',']'** characters in the string.
**string to array**
I should remove the enter key and '[',']' first. And then use `numpy.fromstring`
But I don't think that's a good way to do that. **And that can't work on 2-D array** | 2013/10/18 | [
"https://Stackoverflow.com/questions/19444188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/936332/"
] | You can easily turn numpy arrays into regular python lists and vice versa. You could then store the string representation of the list to file, load it from file, turn it back into a list and into a numpy array.
```
>>> list(numpy.zeros(4))
[0.0, 0.0, 0.0, 0.0]
>>> numpy.array([0.0, 0.0, 0.0, 0.0])
array([ 0., 0., 0., 0.])
```
Using the `map` function, this also works for 2D-arrays.
```
>>> map(list, numpy.zeros((2, 3)))
[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
>>> numpy.array([[0.0, 0.0], [0.0, 0.0]])
array([[ 0., 0., 0.],
[ 0., 0., 0.]])
```
However, if the array is really big it might still be better to store it using `numpy.save` and `numpy.load` and use the XML file only to store the path to that file, together with a comment. | In addition to dumping the ndarray to a .npy file using [save and load](http://docs.scipy.org/doc/numpy/reference/routines.io.html) and noting the details of that file in your xml, you could create a string with the data as noted by Nils Werner.
Note: you might want to check out [HDF](http://www.h5py.org/) or [pytables](http://www.pytables.org/moin) (which uses hdf). |
19,444,188 | I want to save `numpy.array` data into XML file, then read it again. following is my code:
**array to string**
```
arr=numpy.zeros((20))
s = str(arr)
```
But This way would generate **enter key and '[',']'** characters in the string.
**string to array**
I should remove the enter key and '[',']' first. And then use `numpy.fromstring`
But I don't think that's a good way to do that. **And that can't work on 2-D array** | 2013/10/18 | [
"https://Stackoverflow.com/questions/19444188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/936332/"
] | You are mixing two different ways of doing "to string":
```
a = numpy.zeros((20))
```
you can, after stripping newlines and `[]` from it, put `str(a)` in a new `numpy.matrix()` constructor and initialize `numpy.array()` with the returned value:
```
b = numpy.array(numpy.matrix(" ".join(str(a).split()).strip('[]')))
```
or you can combine `numpy.array.tostring()` with `numpy.fromstring()`:
```
c = numpy.fromstring(a.tostring())
```
but mixing and matching like you tried to do does not work. | In addition to dumping the ndarray to a .npy file using [save and load](http://docs.scipy.org/doc/numpy/reference/routines.io.html) and noting the details of that file in your xml, you could create a string with the data as noted by Nils Werner.
Note: you might want to check out [HDF](http://www.h5py.org/) or [pytables](http://www.pytables.org/moin) (which uses hdf). |
10,850 | I am publishing everything in the broker database and able to fetch entire component value with the help of ComponentPresentation class and ComponentFactory class. I am using ComponentPresentation.getContent(true) method to fetch the entire content. But my requirement is to retrieve some specific field value from one of the component. but i am unable to do so. Can anybody tell me with an example how I can do that? | 2015/01/20 | [
"https://tridion.stackexchange.com/questions/10850",
"https://tridion.stackexchange.com",
"https://tridion.stackexchange.com/users/1390/"
] | In broker final content (xml or html as per your architecture) is published. individual field values (as key values) are not published, so
You can not directly fetch any component value. you have to parse your Xml/Html to get that field value.
one of the possible way could be to use metadata, to directly fetch the value from broker. | Somewhere in your solution you need to transform your "naked" content into it's presentation form (usually HTML for web purposes; either directly or via ASP.Net/JSP). With Tridion this is traditionally the responsibility of your page and component templates.
Recently another approach has gained momentum which is DD4T (Dynamic Delivery For Tridion). With DD4T you publish the content "as is" to the broker and consume the content on the content delivery side in an MVC application; it appears that this is what you are doing (consuming content from the broker in your web application) so you might want to take a look at DD4T.
Alternatively you could write your own solution to push data into the broker and consume it on the other side but that seems like reinventing the wheel... |
10,850 | I am publishing everything in the broker database and able to fetch entire component value with the help of ComponentPresentation class and ComponentFactory class. I am using ComponentPresentation.getContent(true) method to fetch the entire content. But my requirement is to retrieve some specific field value from one of the component. but i am unable to do so. Can anybody tell me with an example how I can do that? | 2015/01/20 | [
"https://tridion.stackexchange.com/questions/10850",
"https://tridion.stackexchange.com",
"https://tridion.stackexchange.com/users/1390/"
] | When you publish a ComponentPresentation, Tridion renders the data from the component using the component template. The structure of the component as stored in the content manager is not available to you in the broker, just the rendered output.
The solution depends rather on what you are trying to do. If you just need to have the field available in the same piece of rendered output, then simply amend your component template to make this so.
If you need to get a specific field for some other purpose, you could also consider creating another dynamic component template that renders just the data from that specific field. Then you can query for that component presentation in your web application. (Obviously, you could go too far with this approach - it wouldn't be pretty if you had a component template for every field.)
Some people build their web applications in a way that there's only very simple templating in the content manager, usually the component template renders an XML document which contains everything from the component. Then you can build data structures in your web application that allow you to access each field. If this approach is what you want, then you should look at [Dynamic Delivery for Tridion (DD4T)](https://github.com/dd4t/dynamic-delivery-4-tridion) which is a framework which takes care of much of the work of building this kind of application. Also, have a look at the [SDL Tridion reference implementation](http://www.sdltridionworld.com/community/2011_extensions/reference_implementation.aspx), which builds on DD4T to demonstrate further useful techniques. | Somewhere in your solution you need to transform your "naked" content into it's presentation form (usually HTML for web purposes; either directly or via ASP.Net/JSP). With Tridion this is traditionally the responsibility of your page and component templates.
Recently another approach has gained momentum which is DD4T (Dynamic Delivery For Tridion). With DD4T you publish the content "as is" to the broker and consume the content on the content delivery side in an MVC application; it appears that this is what you are doing (consuming content from the broker in your web application) so you might want to take a look at DD4T.
Alternatively you could write your own solution to push data into the broker and consume it on the other side but that seems like reinventing the wheel... |
50,161,290 | I need assistance in creating a query. I have Client table that has unique client info - identified by their unique ClientID. I also have a Client\_UserDefinedFields table that contains values of custom data for clients. They are linked via the ClientID and there may be many records for a ClientID in this Client\_UserDefinedFields table.
My situation is that there are 3 custom data fields that I need to know the values for a given client (as shown by my CASE statement). My current query is bringing back the client 3 times (a row for each value) and I want to only see the client once (one row) and have these values shown as columns. Not sure if this is possible or how to that. Furthermore, when I tried using a CASE statement in my select, I cannot use AS 'fieldname' to identify it - since it's giving me an error on the AS keyword.
An example of my current SQL SELECT statement
```
SELECT
c.ClientID
, c.LastName
, c.FirstName
, c.MiddleName
, CASE WHEN cudf.UserDefinedFieldFormatULink = '93fb3820-38aa-4655-8aad-a8dce8aede' THEN cudf.UDF_ReportValue --AS 'DA Status'
WHEN cudf.UserDefinedFieldFormatULink = '2144a742-08c5-4c96-b9e4-d6f1f56c76' THEN cudf.UDF_ReportValue --AS 'FHAP Status'
WHEN cudf.UserDefinedFieldFormatULink = 'c3d29be9-af58-4241-a02d-9ae9b43ffa' THEN cudf.UDF_ReportValue --AS 'HCRA Status'
END
FROM Client_Program cp
INNER JOIN client c ON c.ulink = cp.clientulink
INNER JOIN code_program p ON p.ulink = cp.programulink
INNER JOIN Code_System_State css ON c.ContactMailingStateUlink = css.ulink
INNER JOIN Code_ClientStatus ccs ON c.ClientStatusULink = ccs.ULink
INNER JOIN Client_UserDefinedField cudf ON c.ULink = cudf.ClientULink
AND cp.ProgramStatusULink = '1' -- Open (active) program
AND c.ClientStatusULink = '10000000' --Active client
AND cp.programulink in ('7280f4a7-cd94-49be-86ad-a74421ff6f',
'0a9b94a3-edd7-4918-b79c-bf2b20f9da',
'54f6c691-2eba-49e5-8380-85f5349bca',
'ed8c497d-d4fe-41d7-a218-4235fd0734',
'5be826f0-b3c3-4ebe-871d-4d20b56da5')
AND cudf.UserDefinedFieldFormatULink IN ('93fb3820-38aa-4655-8aad-a8dce8aede', -- DA Status
'2144a742-08c5-4c96-b9e4-d6f1f56c76', --FHAP Status
'c3d29be9-af58-4241-a02d-9ae9b43ffa') --HCRA Status
```
Again, my issue is that I don't want to bring back the same client multiple times if they had more than one entry in the Client\_UserDefinedFields table. I'd like to bring this in one row with each "Status" field correctly populated as a columns. How do I do this? Here's a sample of my current output:
```
ClientID LastName FirstName MiddleName PCHP/HCH Status DA Status FHAP Status HCRA Status
XXXXXXXXXXXX River Mike Allan Active (null) - None Selected - (null)
XXXXXXXXXXXX River Mike Allan Active Active (null) (null)
XXXXXXXXXXXX River Mike Allan Active (null) (null) - None Selected -
```
Ultimately would like to see just the one record with all the values
```
ClientID LastName FirstName MiddleName PCHP/HCH Status DA Status FHAP Status HCRA Status
XXXXXXXXXXXX River Mike Allan Active Active - None Selected - - None Selected -
```
Examples are very helpful as I'm not a SQL guru. Thank you! | 2018/05/03 | [
"https://Stackoverflow.com/questions/50161290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1218207/"
] | Finally i manage to come up with the query in linq, dont know how to do it in lambda, but it works fine.
```
var obj = (from emisor in _context.DbSetEmisores
where emisor.EmisorCuenta == cuenta
select new EmisorDto
{
Segmento =
((from itemConf in _context.ItemsDeConfiguracion
where itemConf.ConfigID == "SEGM" && itemConf.ConfigItemID == emisor.SegmentoId
select new { itemConf.ConfigItemDescripcion }).FirstOrDefault().ConfigItemDescripcion),
Marca =
((from itemConf in _context.ItemsDeConfiguracion
where itemConf.ConfigID == "MRCA" && itemConf.ConfigItemID == emisor.MarcaId
select new { itemConf.ConfigItemDescripcion }).FirstOrDefault().ConfigItemDescripcion),
Producto = emisor.Producto,
Familia = emisor.Familia,
SegmentoId = emisor.SegmentoId,
MarcaId = emisor.MarcaId,
}).FirstOrDefault();
``` | When using LINQ you can use either Query syntax as shown in the LINQ below (If you are familiar with SQL then this looks more natural).
<https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/query-syntax-and-method-syntax-in-linq>
The other option is to use Method syntax, and below is a short example. This allows for chaining of methods, biggest thing to keep in mind is "var" should be used, the return type is dynamic and the compiler will help you out a lot if you just use "var"
var items = \_list.Where(x => x.Attribute1 == "NextField")
.Where(x => x.Attribute2 == "Something else");
Other things that hangs folks up sometimes is LINQ uses "delayed execution" |
9,963,367 | I am trying to make a thing, but I have hit a problem. I have tried all I know, but I am new to [MySQL](http://en.wikipedia.org/wiki/MySQL), so I have hit a dead end.
This code:
```
<?php
require('cfg.php');
mysql_connect($server, $user, $pass) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
if (isset($_GET['name'])){
$name = $_GET['name'];
}
else
if (isset($_POST['submit'])){
$name = $_POST['name'];
$name1 = $_POST['name1'];
$name2 = $_POST['name2'];
$name3 = $_POST['name3'];
mysql_query("INSERT INTO data (name, name1, name2, name3) VALUES($name, $name1, $name2, $name3 ) ") or die(mysql_error());
echo ("Data entered successfully!");
}
?>
<html>
<head>
<title>Random giffgaff simmer</title>
</head>
<body>
<form action="" method="post">
<p>Your Username: <input type="text" name="name"></p>
<p>Username 1: <input type="text" name="name1"></p>
<p>Username 2: <input type="text" name="name2"></p>
<p>Username 3: <input type="text" name="name3"></p>
<p>Username 4: <input type="text" name="name4"></p>
<p>Username 5: <input type="text" name="name5"></p>
<p>Username 6: <input type="text" name="name6"></p>
<p><input type="submit" name="submit" value="Submit"></p>
</form>
</body>
</html>
```
Brings this error:
>
> You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' )' at line 1
>
>
>
Now, that would tell me that this SQL code has a syntax error:
```
INSERT INTO data (name, name1, name2, name3) VALUES($name, $name1, $name2, $name3 )
```
But I don't think I can see one? | 2012/04/01 | [
"https://Stackoverflow.com/questions/9963367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1124470/"
] | Strings must be quoted and escaped.
```
$name = (isset($_POST['name'])) ? $_POST['name'] : '';
$name = mysql_real_escape_string($name);
$query = "INSERT INTO blah (name, ...) VALUES ('{$name}', ...)";
```
You're going to want to look into SQL injection by the way. Also, before you get too far down the road, you should really go ahead and abandon mysql\_\* in favour of PDO. PDO offers support for multiple drivers\* (MySQL/SQLite/MSSQL/etc), and can do prepared statements (cleaner/sort of safer than mysql\_real\_escape\_string).
\* this does not make SQL magically portable, but it does help. | I'm assuming that `$name`, `$name1`, etc. are strings? You should be enclosing them in single-quotes. Try:
```
"INSERT INTO `data` (`name`, `name1`, `name2`, `name3`) VALUES ('$name', '$name1', '$name2', '$name3')"
```
Remember also to escape all input **user-provided strings values that can potentially act as SQL injections** (see here: <http://php.net/manual/en/security.database.sql-injection.php>) with `mysql_real_escape_string()` before passing them into the query, or switch to the `mysqli` extension and use prepared statements (best option). |
9,963,367 | I am trying to make a thing, but I have hit a problem. I have tried all I know, but I am new to [MySQL](http://en.wikipedia.org/wiki/MySQL), so I have hit a dead end.
This code:
```
<?php
require('cfg.php');
mysql_connect($server, $user, $pass) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
if (isset($_GET['name'])){
$name = $_GET['name'];
}
else
if (isset($_POST['submit'])){
$name = $_POST['name'];
$name1 = $_POST['name1'];
$name2 = $_POST['name2'];
$name3 = $_POST['name3'];
mysql_query("INSERT INTO data (name, name1, name2, name3) VALUES($name, $name1, $name2, $name3 ) ") or die(mysql_error());
echo ("Data entered successfully!");
}
?>
<html>
<head>
<title>Random giffgaff simmer</title>
</head>
<body>
<form action="" method="post">
<p>Your Username: <input type="text" name="name"></p>
<p>Username 1: <input type="text" name="name1"></p>
<p>Username 2: <input type="text" name="name2"></p>
<p>Username 3: <input type="text" name="name3"></p>
<p>Username 4: <input type="text" name="name4"></p>
<p>Username 5: <input type="text" name="name5"></p>
<p>Username 6: <input type="text" name="name6"></p>
<p><input type="submit" name="submit" value="Submit"></p>
</form>
</body>
</html>
```
Brings this error:
>
> You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' )' at line 1
>
>
>
Now, that would tell me that this SQL code has a syntax error:
```
INSERT INTO data (name, name1, name2, name3) VALUES($name, $name1, $name2, $name3 )
```
But I don't think I can see one? | 2012/04/01 | [
"https://Stackoverflow.com/questions/9963367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1124470/"
] | You haven't quoted your query. You should quote every field like this
```
INSERT INTO data (name, name1, name2, name3) VALUES('$name', '$name1', '$name2', '$name3' )
```
As an tribute to TheCommonSense, I am providing a mysqli version using correct prepared statement for data safety
```
$db = new mysqli(...);
$stmt = $db -> prepare("INSERT INTO data (name, name1, name2, name3) VALUES(?, ?, ?, ?)");
$stmt -> bind_param("ssss", $name, $name1, $name2, $name3);
$stmt -> execute();
$db -> close()
``` | Strings must be quoted and escaped.
```
$name = (isset($_POST['name'])) ? $_POST['name'] : '';
$name = mysql_real_escape_string($name);
$query = "INSERT INTO blah (name, ...) VALUES ('{$name}', ...)";
```
You're going to want to look into SQL injection by the way. Also, before you get too far down the road, you should really go ahead and abandon mysql\_\* in favour of PDO. PDO offers support for multiple drivers\* (MySQL/SQLite/MSSQL/etc), and can do prepared statements (cleaner/sort of safer than mysql\_real\_escape\_string).
\* this does not make SQL magically portable, but it does help. |
9,963,367 | I am trying to make a thing, but I have hit a problem. I have tried all I know, but I am new to [MySQL](http://en.wikipedia.org/wiki/MySQL), so I have hit a dead end.
This code:
```
<?php
require('cfg.php');
mysql_connect($server, $user, $pass) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
if (isset($_GET['name'])){
$name = $_GET['name'];
}
else
if (isset($_POST['submit'])){
$name = $_POST['name'];
$name1 = $_POST['name1'];
$name2 = $_POST['name2'];
$name3 = $_POST['name3'];
mysql_query("INSERT INTO data (name, name1, name2, name3) VALUES($name, $name1, $name2, $name3 ) ") or die(mysql_error());
echo ("Data entered successfully!");
}
?>
<html>
<head>
<title>Random giffgaff simmer</title>
</head>
<body>
<form action="" method="post">
<p>Your Username: <input type="text" name="name"></p>
<p>Username 1: <input type="text" name="name1"></p>
<p>Username 2: <input type="text" name="name2"></p>
<p>Username 3: <input type="text" name="name3"></p>
<p>Username 4: <input type="text" name="name4"></p>
<p>Username 5: <input type="text" name="name5"></p>
<p>Username 6: <input type="text" name="name6"></p>
<p><input type="submit" name="submit" value="Submit"></p>
</form>
</body>
</html>
```
Brings this error:
>
> You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' )' at line 1
>
>
>
Now, that would tell me that this SQL code has a syntax error:
```
INSERT INTO data (name, name1, name2, name3) VALUES($name, $name1, $name2, $name3 )
```
But I don't think I can see one? | 2012/04/01 | [
"https://Stackoverflow.com/questions/9963367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1124470/"
] | Strings must be quoted and escaped.
```
$name = (isset($_POST['name'])) ? $_POST['name'] : '';
$name = mysql_real_escape_string($name);
$query = "INSERT INTO blah (name, ...) VALUES ('{$name}', ...)";
```
You're going to want to look into SQL injection by the way. Also, before you get too far down the road, you should really go ahead and abandon mysql\_\* in favour of PDO. PDO offers support for multiple drivers\* (MySQL/SQLite/MSSQL/etc), and can do prepared statements (cleaner/sort of safer than mysql\_real\_escape\_string).
\* this does not make SQL magically portable, but it does help. | ```
mysql_query("INSERT INTO data (name, name1, name2, name3) VALUES('$name', '$name1', '$name2', '$name3') ") or die(mysql_error());
```
or
```
mysql_query("INSERT INTO data (name, name1, name2, name3) VALUES('".$name."', '".$name1."', '".$name2."', '".$name3."') ") or die(mysql_error());
```
Try this |
9,963,367 | I am trying to make a thing, but I have hit a problem. I have tried all I know, but I am new to [MySQL](http://en.wikipedia.org/wiki/MySQL), so I have hit a dead end.
This code:
```
<?php
require('cfg.php');
mysql_connect($server, $user, $pass) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
if (isset($_GET['name'])){
$name = $_GET['name'];
}
else
if (isset($_POST['submit'])){
$name = $_POST['name'];
$name1 = $_POST['name1'];
$name2 = $_POST['name2'];
$name3 = $_POST['name3'];
mysql_query("INSERT INTO data (name, name1, name2, name3) VALUES($name, $name1, $name2, $name3 ) ") or die(mysql_error());
echo ("Data entered successfully!");
}
?>
<html>
<head>
<title>Random giffgaff simmer</title>
</head>
<body>
<form action="" method="post">
<p>Your Username: <input type="text" name="name"></p>
<p>Username 1: <input type="text" name="name1"></p>
<p>Username 2: <input type="text" name="name2"></p>
<p>Username 3: <input type="text" name="name3"></p>
<p>Username 4: <input type="text" name="name4"></p>
<p>Username 5: <input type="text" name="name5"></p>
<p>Username 6: <input type="text" name="name6"></p>
<p><input type="submit" name="submit" value="Submit"></p>
</form>
</body>
</html>
```
Brings this error:
>
> You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' )' at line 1
>
>
>
Now, that would tell me that this SQL code has a syntax error:
```
INSERT INTO data (name, name1, name2, name3) VALUES($name, $name1, $name2, $name3 )
```
But I don't think I can see one? | 2012/04/01 | [
"https://Stackoverflow.com/questions/9963367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1124470/"
] | You haven't quoted your query. You should quote every field like this
```
INSERT INTO data (name, name1, name2, name3) VALUES('$name', '$name1', '$name2', '$name3' )
```
As an tribute to TheCommonSense, I am providing a mysqli version using correct prepared statement for data safety
```
$db = new mysqli(...);
$stmt = $db -> prepare("INSERT INTO data (name, name1, name2, name3) VALUES(?, ?, ?, ?)");
$stmt -> bind_param("ssss", $name, $name1, $name2, $name3);
$stmt -> execute();
$db -> close()
``` | I'm assuming that `$name`, `$name1`, etc. are strings? You should be enclosing them in single-quotes. Try:
```
"INSERT INTO `data` (`name`, `name1`, `name2`, `name3`) VALUES ('$name', '$name1', '$name2', '$name3')"
```
Remember also to escape all input **user-provided strings values that can potentially act as SQL injections** (see here: <http://php.net/manual/en/security.database.sql-injection.php>) with `mysql_real_escape_string()` before passing them into the query, or switch to the `mysqli` extension and use prepared statements (best option). |
9,963,367 | I am trying to make a thing, but I have hit a problem. I have tried all I know, but I am new to [MySQL](http://en.wikipedia.org/wiki/MySQL), so I have hit a dead end.
This code:
```
<?php
require('cfg.php');
mysql_connect($server, $user, $pass) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
if (isset($_GET['name'])){
$name = $_GET['name'];
}
else
if (isset($_POST['submit'])){
$name = $_POST['name'];
$name1 = $_POST['name1'];
$name2 = $_POST['name2'];
$name3 = $_POST['name3'];
mysql_query("INSERT INTO data (name, name1, name2, name3) VALUES($name, $name1, $name2, $name3 ) ") or die(mysql_error());
echo ("Data entered successfully!");
}
?>
<html>
<head>
<title>Random giffgaff simmer</title>
</head>
<body>
<form action="" method="post">
<p>Your Username: <input type="text" name="name"></p>
<p>Username 1: <input type="text" name="name1"></p>
<p>Username 2: <input type="text" name="name2"></p>
<p>Username 3: <input type="text" name="name3"></p>
<p>Username 4: <input type="text" name="name4"></p>
<p>Username 5: <input type="text" name="name5"></p>
<p>Username 6: <input type="text" name="name6"></p>
<p><input type="submit" name="submit" value="Submit"></p>
</form>
</body>
</html>
```
Brings this error:
>
> You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' )' at line 1
>
>
>
Now, that would tell me that this SQL code has a syntax error:
```
INSERT INTO data (name, name1, name2, name3) VALUES($name, $name1, $name2, $name3 )
```
But I don't think I can see one? | 2012/04/01 | [
"https://Stackoverflow.com/questions/9963367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1124470/"
] | You haven't quoted your query. You should quote every field like this
```
INSERT INTO data (name, name1, name2, name3) VALUES('$name', '$name1', '$name2', '$name3' )
```
As an tribute to TheCommonSense, I am providing a mysqli version using correct prepared statement for data safety
```
$db = new mysqli(...);
$stmt = $db -> prepare("INSERT INTO data (name, name1, name2, name3) VALUES(?, ?, ?, ?)");
$stmt -> bind_param("ssss", $name, $name1, $name2, $name3);
$stmt -> execute();
$db -> close()
``` | ```
mysql_query("INSERT INTO data (name, name1, name2, name3) VALUES('$name', '$name1', '$name2', '$name3') ") or die(mysql_error());
```
or
```
mysql_query("INSERT INTO data (name, name1, name2, name3) VALUES('".$name."', '".$name1."', '".$name2."', '".$name3."') ") or die(mysql_error());
```
Try this |
17,293,922 | I am using a program that pastes what is in the clipboard in a modified format according to what I specify.
I would like for it to paste paths (i.e. "C:\folder\My File") without the pair of double quotes.
This, which isn't using RegEx works: Find " (I simply enter than in one line) and replace with nothing. I enter nothing in the second field. I leave it blank.
Now, though that works, it will remove double quotes in this scenario: Bob said "What are you doing?"
I would like the program to remove the quotes only if the the words enclosed in the double quotes have a backslash.
So, once again, just to make sure I am clear, I need the following:
1) RegEx Expression to find strings that have both double quotes and a backslash within those set of quotes.
2) A RegEx Expression that says: replace the backslashes with backslashes (i.e. leave them there).
Thank you for the fast response. This program has two fields. One for what to find and the other for what to replace. So, what would go in the 2nd field?

The program came with the Remove HTML entry, which has
<[^>]\*> in the match pattern
and nothing (it's blank) in the Replacement field. | 2013/06/25 | [
"https://Stackoverflow.com/questions/17293922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2519402/"
] | You didn't say which language you use, here's an example in Javascript:
```
> s = 'say "hello" and replace "C:\\folder\\My File" thanks'
"say "hello" and replace "C:\folder\My File" thanks"
> s.replace(/"([^"\\]*\\[^"]*)"/g, "$1")
"say "hello" and replace C:\folder\My File thanks"
``` | This should work in .NET:
```
^".*?\\.*?"$
``` |
20,038,409 | First thing I am not an expert in writing VBScripts.
I have a requirement of deleting files & folders of remote systems with just 1 click. I was trying to build below VBScript but somehow it’s not working. I request any of your help to correct the same or with a new script that help me to fulfill the requirement. Any help in this regard is greatly appreciated, Thanks in Advance.
With the below:
C:\Test - is the directory from where I would like to delete the files & subfolders
C:\computerList.txt – is the text file contains all remote systems IP Address.
```
Const strPath = "C:\Test"
Set computerList = objfso.OpenTextFile ("C:\computerList.txt", 1)
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Call Search (strPath)
WScript.Echo"Done."
Sub Search(str)
Do While Not computerList.AtEndOfStream
strComputer = computerList.ReadLine
Dim objFolder, objSubFolder, objFile
Set objFolder = objFSO.GetFolder("\\" & strComputer & "\" & str)
For Each objFile In objFolder.Files
If objFile.DateLastModified < (Now() - 0) Then
objFile.Delete(True)
End If
Next
For Each objSubFolder In objFolder.SubFolders
Search(objSubFolder.Path)
' Files have been deleted, now see if
' the folder is empty.
If (objSubFolder.Files.Count = 0) Then
objSubFolder.Delete True
End If
Next
loop
End Sub
```
Regards,
Balaram Reddy | 2013/11/18 | [
"https://Stackoverflow.com/questions/20038409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3002951/"
] | Your first problem is that you have the line order incorrect:
```
Set computerList = objfso.OpenTextFile ("C:\computerList.txt", 1)
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
```
Should be
```
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set computerList = objfso.OpenTextFile ("C:\computerList.txt", 1)
```
You are using objfso before declaring it | When using a UNC path, you will need to use the folder's remote share name. If you have admin privileges on the remote pc use:
```
Const strPath = "c$\Test"
``` |
31,751,705 | I'm trying to redirect to the previous page after a user logs in. I am using a bootstrap modal for login/register forms but if someone doesn't have JS enabled on their browser and are taken to the '/login' page, I want to make sure they are redirected to the root url. I know current\_page? does not work with POST requests.
I've tried tons of things so the following code is redirecting correctly from the '/login' page to the root url but I am not being redirected to ':back' when logging in using the bootstrap modal.
This is from SessionsController: (PS- I have sessions#new/sessions#create as /login in routes)
```
def create
user = User.find_by(email: params[:email])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
if request.path === '/login'
redirect_to '/'
else
redirect_to :back
end
flash[:success] = "Logged in."
else
flash.now[:danger] = "Email and password did not match. Please try again."
render :new
end
end
def destroy
session[:user_id] = nil
flash[:success] = "Logged out."
redirect_to '/'
end
```
Routes.rb:
```
Rails.application.routes.draw do
root to: 'home#home'
resources :users
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
get '/logout', to: 'sessions#destroy'
end
``` | 2015/07/31 | [
"https://Stackoverflow.com/questions/31751705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5057766/"
] | I figured it out. I basically create an order variable, name that variable the animal names, and then use that ordered variable to create the chart rather than the animals themselves. Below is the quick process:
Create an order variable
```
data test1; set test;
temp=_n_;
char_animal=put(temp,3.);
run;
```
Put your sequence of animals in a list
```
proc sql;
select distinct quote(animal)
into: animallist separated by " "
from test1 order by temp;
quit;
%put &animallist.;
```
In the `axis3` statement, use the macro list in the value statement to "name" the order variable the animal names
```
axis1 label=(f=arial h=1.5 'Time to Death (Hours Post-Exposure)') value=(f=arial h=1) order=(0 to 840 by 120) minor=(n=5) offset=(1,1);
axis2 label=(f=arial h=1.2 j=r 'Group') value=(f=arial h=1);
axis3 label=(f=arial h=1.2 j=c 'Animal') value=(f=arial h=1 &animallist.);
PATTERN1 C=BLACK;
proc gchart data=test1;
hbar char_animal /group=group nozero nostats sumvar=ttd type=sum
width=0.4 space=1 raxis=axis1 gaxis=axis2 maxis=axis3;
run; quit;
```
Notice the correct order in the graphic now:
[](https://i.stack.imgur.com/nulm2.png) | I don't think you can get it in the dataset order. (Technically, by the way, this is *ascending* order of the value of Animal - while it goes 'down' it is still considered ascending from the point of view of the proc; see how the ASCENDING/DESCENDING option order things.)
From my understanding, gplot for HBAR allows (default=ascending order of values, ASCENDING=ascending order of bars, DESCENDING=descending order of bars).
You can use SGPLOT (which has `grouporder=data` option, at least by 9.4).
```
proc sgplot data=test;
hbar group/ response=ttd group=animal groupdisplay=cluster grouporder=reversedata;
run;
```
I use `reversedata`, as the ascending/descending thing is flipped in hbars compared to what seems logical, but you can also flip the axis itself if you prefer that (or if reversedata is not available in your version). |
6,405,614 | In my XAML, I am trying to implement the folowing:
```
<DataTrigger Binding="{Binding Path=Word}" Value="\n">
```
but this does not work, even though Word is \n. I suspect that \n is not the right way to express newline in XAML, but what would be? | 2011/06/19 | [
"https://Stackoverflow.com/questions/6405614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/339843/"
] | Yes, setting a distant expiry header and the asset will not be downloaded again until that expiry.
>
> If you remove the Last-Modified and ETag header, you will totally eliminate If-Modified-Since and If-None-Match requests and their 304 Not Modified Responses, so a file will stay cached without checking for updates until the Expires header indicates new content is available!
>
>
>
[Source](http://www.askapache.com/htaccess/apache-speed-last-modified.html). | From my htaccess ...
```
<IfModule mod_headers.c>
Header unset Pragma
FileETag None
Header unset ETag
# cache images/pdf docs for 10 days
<FilesMatch "\.(ico|pdf|jpg|jpeg|png|gif|js)$">
Header set Expires "Mon, 31 Dec 2035 12:00:00 gmt"
Header unset ETag
Header unset Last-Modified
</FilesMatch>
# cache html/htm/xml/txt diles for 2 days
<FilesMatch "\.(html|htm|xml|txt|xsl)$">
Header set Cache-Control "max-age=7200, must-revalidate"
</FilesMatch>
</IfModule>
```
it seems doesn't works .... for example firebug's net panel show me always 200 status code and access.log file report me that external objects are always requested by the browser. |
43,587,165 | To get row information of currently selected row we can do this
```
var current = e.sender.dataItem(e.sender.select());
```
But how to get the same when i click on Edit button?
I tried `$("#grid").data("kendoGrid").dataItem($(e.sender).closest("tr"));` it didnt work.
**EDIT**
I tried ways as suggested on the answers below, but its still giving me null.
in the screenshot the commented code doesn't work either
[](https://i.stack.imgur.com/IQUt1.jpg)
**COMPLETE CODE**
```html
<script src="http://kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.914/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.914/styles/kendo.rtl.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.914/styles/kendo.silver.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.914/styles/kendo.mobile.all.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<!--<script src="http://kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script>-->
<!--<script src="http://kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script>-->
<script src="Scripts/KendoUI.js" type="text/javascript">
</head>
<body>
<div id="grid">
</div>
<script>
$("#grid").kendoGrid({
columns: [
{ field: "id" },
{ field: "name" },
{ field: "age" },
{ command: "edit" },
{ command: "list" }
],
dataSource: {
data: [
{ id: 1, name: "Jane Doe", age: 30 },
{ id: 2, name: "John Doe", age: 33 }
],
schema: {
model: {
id: "id",
fields: {
"id": { type: "number" }
}
}
}
},
editable: "popup",
toolbar: ["create"],
dataBound: function (e) {
//<input name="age" class="k-input k-textbox" type="text" data-bind="value:age">
},
edit: function (e) {
//This currentItem is null :(
var currentItem = $("#grid").data("kendoGrid").dataItem($(e.sender).closest("tr"));
if (!e.model.isNew()) {
$('.k-window-title').text("Newton Sheikh");
}
}
});
</script>
</body>
</html>
``` | 2017/04/24 | [
"https://Stackoverflow.com/questions/43587165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2110531/"
] | You should use `e.container` instead of `e.sender`, like this:
```
$("#grid").data("kendoGrid").dataItem($(e.container).closest("tr"))
```
**Update to make it work with a popup**
If you are using a popup editor, then the container will be the popup itself and the above will not work.
In that case, you can use the uid of the row to locate it within the table:
```
var row = $("#grid").data("kendoGrid").tbody.find("tr[data-uid='" + e.model.uid + "']");
```
If you do not need a reference to the actual row, but only the data item, then you can simply use `e.model`. I have created a dojo with your code and if you check the console after you click "edit", you will see that there is no difference: <http://dojo.telerik.com/iqAPO> | If you use the `edit` function in the grid, you can access the data item attributes which is in edit mode using:
```
var grid = $("#yourGrid").kendoGrid({
dataSource: yourGridDatasource,
...
edit: function (e) {
var attribute = e.sender.dataItem(e.container).attributeName;
// or simply
var attribute2 = e.model.attributeName;
}
});
``` |
43,587,165 | To get row information of currently selected row we can do this
```
var current = e.sender.dataItem(e.sender.select());
```
But how to get the same when i click on Edit button?
I tried `$("#grid").data("kendoGrid").dataItem($(e.sender).closest("tr"));` it didnt work.
**EDIT**
I tried ways as suggested on the answers below, but its still giving me null.
in the screenshot the commented code doesn't work either
[](https://i.stack.imgur.com/IQUt1.jpg)
**COMPLETE CODE**
```html
<script src="http://kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.914/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.914/styles/kendo.rtl.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.914/styles/kendo.silver.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.914/styles/kendo.mobile.all.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<!--<script src="http://kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script>-->
<!--<script src="http://kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script>-->
<script src="Scripts/KendoUI.js" type="text/javascript">
</head>
<body>
<div id="grid">
</div>
<script>
$("#grid").kendoGrid({
columns: [
{ field: "id" },
{ field: "name" },
{ field: "age" },
{ command: "edit" },
{ command: "list" }
],
dataSource: {
data: [
{ id: 1, name: "Jane Doe", age: 30 },
{ id: 2, name: "John Doe", age: 33 }
],
schema: {
model: {
id: "id",
fields: {
"id": { type: "number" }
}
}
}
},
editable: "popup",
toolbar: ["create"],
dataBound: function (e) {
//<input name="age" class="k-input k-textbox" type="text" data-bind="value:age">
},
edit: function (e) {
//This currentItem is null :(
var currentItem = $("#grid").data("kendoGrid").dataItem($(e.sender).closest("tr"));
if (!e.model.isNew()) {
$('.k-window-title').text("Newton Sheikh");
}
}
});
</script>
</body>
</html>
``` | 2017/04/24 | [
"https://Stackoverflow.com/questions/43587165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2110531/"
] | You should use `e.container` instead of `e.sender`, like this:
```
$("#grid").data("kendoGrid").dataItem($(e.container).closest("tr"))
```
**Update to make it work with a popup**
If you are using a popup editor, then the container will be the popup itself and the above will not work.
In that case, you can use the uid of the row to locate it within the table:
```
var row = $("#grid").data("kendoGrid").tbody.find("tr[data-uid='" + e.model.uid + "']");
```
If you do not need a reference to the actual row, but only the data item, then you can simply use `e.model`. I have created a dojo with your code and if you check the console after you click "edit", you will see that there is no difference: <http://dojo.telerik.com/iqAPO> | ```
var gridDataById= $("#grid").data("kendoGrid");
//Getting selected row
var selectedRow = gridDataById.dataItem(gridDataById.select());
console.log(selectedRow);
``` |
43,587,165 | To get row information of currently selected row we can do this
```
var current = e.sender.dataItem(e.sender.select());
```
But how to get the same when i click on Edit button?
I tried `$("#grid").data("kendoGrid").dataItem($(e.sender).closest("tr"));` it didnt work.
**EDIT**
I tried ways as suggested on the answers below, but its still giving me null.
in the screenshot the commented code doesn't work either
[](https://i.stack.imgur.com/IQUt1.jpg)
**COMPLETE CODE**
```html
<script src="http://kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.914/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.914/styles/kendo.rtl.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.914/styles/kendo.silver.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.914/styles/kendo.mobile.all.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<!--<script src="http://kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script>-->
<!--<script src="http://kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script>-->
<script src="Scripts/KendoUI.js" type="text/javascript">
</head>
<body>
<div id="grid">
</div>
<script>
$("#grid").kendoGrid({
columns: [
{ field: "id" },
{ field: "name" },
{ field: "age" },
{ command: "edit" },
{ command: "list" }
],
dataSource: {
data: [
{ id: 1, name: "Jane Doe", age: 30 },
{ id: 2, name: "John Doe", age: 33 }
],
schema: {
model: {
id: "id",
fields: {
"id": { type: "number" }
}
}
}
},
editable: "popup",
toolbar: ["create"],
dataBound: function (e) {
//<input name="age" class="k-input k-textbox" type="text" data-bind="value:age">
},
edit: function (e) {
//This currentItem is null :(
var currentItem = $("#grid").data("kendoGrid").dataItem($(e.sender).closest("tr"));
if (!e.model.isNew()) {
$('.k-window-title').text("Newton Sheikh");
}
}
});
</script>
</body>
</html>
``` | 2017/04/24 | [
"https://Stackoverflow.com/questions/43587165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2110531/"
] | If you use the `edit` function in the grid, you can access the data item attributes which is in edit mode using:
```
var grid = $("#yourGrid").kendoGrid({
dataSource: yourGridDatasource,
...
edit: function (e) {
var attribute = e.sender.dataItem(e.container).attributeName;
// or simply
var attribute2 = e.model.attributeName;
}
});
``` | ```
var gridDataById= $("#grid").data("kendoGrid");
//Getting selected row
var selectedRow = gridDataById.dataItem(gridDataById.select());
console.log(selectedRow);
``` |
57,101,872 | I fixed a bug recently.
In the following code, one of the overloaded function was const and the other one was not. The issue will be fixed by making both functions const.
My question is why compiler only complained about it when the parameter was 0.
```
#include <iostream>
#include <string>
class CppSyntaxA
{
public:
void f(int i = 0) const { i++; }
void f(const std::string&){}
};
int main()
{
CppSyntaxA a;
a.f(1); // OK
//a.f(0); //error C2666: 'CppSyntaxA::f': 2 overloads have similar conversions
return 0;
}
``` | 2019/07/18 | [
"https://Stackoverflow.com/questions/57101872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4005852/"
] | `0` is special in C++. A null pointer has the value of `0` so C++ will allow the conversion of `0` to a pointer type. That means when you call
```
a.f(0);
```
You could be calling `void f(int i = 0) const` with an `int` with the value of `0`, or you could call `void f(const std::string&)` with a `char*` initialized to null.
Normally the `int` version would be better since it is an exact match but in this case the `int` version is `const`, so it requires "converting" `a` to a `const CppSyntaxA`, where the `std::string` version does not require such a conversion but does require a conversion to `char*` and then to `std::string`. This is considered enough of a change in both cases to be considered an equal conversion and thus ambiguous. Making both functions `const` or non `const` will fix the issue and the `int` overload will be chosen since it is better. | >
> My question is why compiler only complained about it when the parameter was 0.
>
>
>
Because 0 is not only an integer literal, but it is also a null pointer literal. 1 is not a null pointer literal, so there is no ambiguity.
The ambiguity arises from the implicit converting constructor of `std::string` that accepts a pointer to a character as an argument.
Now, the identity conversion from int to int would otherwise be preferred to the conversion from pointer to string, but there is another argument that involves a conversion: The implicit object argument. In one case, the conversion is from `CppSyntaxA&` to `CppSyntaxA&` while in other case it is `CppSyntaxA&` to `const CppSyntaxA&`.
So, one overload is preferred because of one argument, and the other overload is preferred because of another argument and thus there is no unambiguously preferred overload.
>
> The issue will be fixed by making both functions const.
>
>
>
If both overloads are `const` qualified, then the implicit object argument conversion sequence is identical, and thus one of the overloads is unambiguously preferred. |
12,201,541 | can anyone give me pointers to a library/way of getting country specific calendars. THis is because I am looking to implement Quartz and would like to use different calendars for different countries.
THank you | 2012/08/30 | [
"https://Stackoverflow.com/questions/12201541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1479589/"
] | I would suggest trying Joda Time
<http://joda-time.sourceforge.net/>
, which has different Chronologies. | JodaTime is a very good api to manipulate those things.
<http://joda-time.sourceforge.net/> |
12,201,541 | can anyone give me pointers to a library/way of getting country specific calendars. THis is because I am looking to implement Quartz and would like to use different calendars for different countries.
THank you | 2012/08/30 | [
"https://Stackoverflow.com/questions/12201541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1479589/"
] | Have a look at this ->
<http://icu-project.org/docs/papers/international_calendars_in_java.html>
As Joao suggested, you can use
```
Calendar c = Calendar.getInstance(Locale.FRANCE);
```
You should also look at this
[Is there a way to get a timeZone with (only) a country code (valid ISO-3166 code)?](https://stackoverflow.com/questions/1389837/is-there-a-way-to-get-a-timezone-with-only-a-country-code-valid-iso-3166-code)
and this
[non standard locale with java.util.Calendar](https://stackoverflow.com/questions/4493976/non-standard-locale-with-java-util-calendar)
Else best is using [Joda-Time](http://joda-time.sourceforge.net/) | JodaTime is a very good api to manipulate those things.
<http://joda-time.sourceforge.net/> |
10,456,215 | I am trying to use activeX to start a windows form application written in C# from my ASP.net website. When I click a button I would like a new page to open up and activeX on that page would call my windows application.
I am using Visual Studio 2010. I have followed this tutorial: <http://dotnetslackers.com/articles/csharp/WritingAnActiveXControlInCSharp.aspx>
However, that tutorial is only for 1 C# file which you compile via console.
My questions are the following:
1.How would I compile the entire windows form project to use the /t:library and regasm?
2.I have followed this question answer to modify my windows form application: [How do I create an ActiveX control (COM) in C#?](https://stackoverflow.com/questions/3360160/how-do-i-create-an-activex-com-in-c). However, like in both examples, they do not have a Main method. When I tried to modify the code of my windows form app, I get the error saying the program does not have a Main method for entry if I take it out and replace it with a Launch() method. I am sure I am missing something?
3.Would I just write the java script on the new .aspx page to access the application?
P.S. I am trying to open this open source windows form application: <http://www.codeproject.com/Articles/239849/Multiple-face-detection-and-recognition-in-real-ti>
Thank you kindly | 2012/05/04 | [
"https://Stackoverflow.com/questions/10456215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/849509/"
] | *The question to ask yourself is, how long do you need to persist the data?*
If you only need to save the data to pass it to the next action you can use **POST** or **GET**, the **GET** would pass through the url and the **POST** would not(*typically*).
The example you presented would suggest that you need to persist the data just long enough to validate, filter and process the data. So you would likely be very satisfied passing the few pieces of data around as parameters(**POST** or **GET**). This would provide the temporary persistence you need and also provide the added benefit of the data expiring as soon as a request was made that did not pass the variables.
A quick example (assume your form passes data with the **POST** method):
```
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost()){
$data = $form->getValues();//filtered values from form
$model = new Appliction_Model_DbTable_MyTable();
$model->save($data);
//but you need to pass the users name from the form to another action
//there are many tools in ZF to do this with, this is just one example
return $this->getHelper('Redirector')->gotoSimple(
'action' => 'newaction',
array('name' => $data['name'])//passed data
);
}
}
```
if you need to persist data for a longer period of time then the **$\_SESSION** may come in handy. In ZF you will typically use `Zend_Session_Namespace()` to manipulate session data.
It's easy to use `Zend_Session_Namespace`, here is an example of how I often use it.
```
class IndexController extends Zend_Controller_Action {
protected $_session;
public function init() {
//assign the session to the property and give the namespace a name.
$this->_session = new Zend_Session_Namespace('User');
}
public function indexAction() {
//using the previous example
$form = new Application_Form_MyForm();
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost()){
$data = $form->getValues();//filtered values from form
//this time we'll add the data to the session
$this->_session->userName = $data['user'];//assign a string to the session
//we can also assign all of the form data to one session variable as an array or object
$this->_session->formData = $data;
return $this->getHelper('Redirector')->gotoSimple('action'=>'next');
}
}
$this->view->form = $form;
}
public function nextAction() {
//retrieve session variables and assign them to the view for demonstration
$this->view->userData = $this->_session->formData;//an array of values from previous actions form
$this->view->userName = $this->_session->userName;//a string value
}
}
}
```
any data you need to persist in your application can sent to any action, controller or module. Just remember that if you resubmit that form the information saved to those particular session variables will be over written.
There is one more option in ZF that kind of falls between passing parameters around and storing data in sessions, `Zend_Registry`. It's use is very similar to `Zend_Session_Namespace` and is often used to save configuration data in the bootstrap (but can store almost anything you need to store) and is also used by a number of internal Zend classes most notably the [flashmessenger action helper](http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelpers.flashmessenger).
```
//Bootstrap.php
protected function _initRegistry() {
//make application.ini configuration available in registry
$config = new Zend_Config($this->getOptions());
//set data in registry
Zend_Registry::set('config', $config);
}
protected function _initView() {
//Initialize view
$view = new Zend_View();
//get data from registry
$view->doctype(Zend_Registry::get('config')->resources->view->doctype);
//...truncated...
//Return it, so that it can be stored by the bootstrap
return $view;
}
```
I hope this helps. Pleas check out these links if you have more questions:
[The ZF Request Object](http://framework.zend.com/manual/en/zend.controller.request.html)
[Zend\_Session\_Namespace](http://framework.zend.com/manual/en/zend.session.basic_usage.html)
[Zend\_Registry](http://framework.zend.com/manual/en/zend.registry.using.html) | Option 1 is better, although in your example this is not a POST (but it could be done with a POST).
The problems with option 2 are:
* If a user had multiple windows or tabs open at the same time, relating to different events, how would you track which event ID should be used?
* If a user bookmarked the add event page and came back later, the session var may not be set
Option 2 is also a little more complicated to implement, and adds a reliance on sessions. |
50,364 | I've wandered into some dungeon and encountered some necromancers or bandits. I killed some with sneak attack by bow and some turned hostile and they rush to me and I killed them directly. When I sleep, there are no Dark Brotherhood members approaching me. Why? | 2012/02/10 | [
"https://gaming.stackexchange.com/questions/50364",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/7993/"
] | According to the [Elder Scrolls wiki](http://www.uesp.net/wiki/Oblivion:A_Knife_in_the_Dark),
>
> you must murder someone in cold blood. In other words, you must murder an innocent without provocation (note that Bandits and the like do not count as the required murder). Once the deed is done, regardless of who is there, the cryptic message "Your killing has been observed by forces unknown..." will appear in the corner of your screen, indicating you will be visited the next time you sleep.
>
>
>
Basically any non-essential NPC will do. (Note that unlike in Morrowind, Oblivion's predecessor, you cannot kill an essential NPC, so you don't have to worry about killing the "wrong" person. If an NPC is involved in a quest you haven't completed, you won't be able to kill them.) If you are looking for a specific set of targets, the wiki has a [list of them](http://www.uesp.net/wiki/Oblivion:Dark_Brotherhood#Targets). I've listed a few of the best targets below:
>
> -- The Skooma Den in Bravil has 4 residents, 3 with 0 responsibility, so your crime will likely go unreported.
>
> -- Camonna Tong Thug: Killing one of the two Camonna Tong thugs at Walker camp will give you no bounty, as they both have low responsibility. If you attack one of them before he attacked you, killing him is counted as a murder, and will allow you to join the Dark Brotherhood. They both respawn in a few days, as well.
>
> -- Alval Uvani has a rather low responsibility, and since he does a lot of traveling (see the Dark Brotherhood mission A Matter of Honor for details) it's rather easy to dispose of him on the road without witnesses. The benefit of killing Alval is that you will have already completed one of the later Brotherhood missions.
>
>
> | You have to murder someone who is not by default hostile to you, for example a random townsperson. You will get a message on your screen that you've been "witnessed by unseen forces" and after you go to sleep you will be contacted. |
50,364 | I've wandered into some dungeon and encountered some necromancers or bandits. I killed some with sneak attack by bow and some turned hostile and they rush to me and I killed them directly. When I sleep, there are no Dark Brotherhood members approaching me. Why? | 2012/02/10 | [
"https://gaming.stackexchange.com/questions/50364",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/7993/"
] | You have to murder someone who is not by default hostile to you, for example a random townsperson. You will get a message on your screen that you've been "witnessed by unseen forces" and after you go to sleep you will be contacted. | The one you kill must be an innocent.
I wanted to do the Brotherhood quest early in the game because it bugs me to be a murderer. So, I killed that drug dealer (sells skooma and poisons at night) who stands outside the north wall of the Imperial City, but even though he had not gone aggro on me, his death did not count.
Just thought you might like to know how some characters don't qualify at all. |
50,364 | I've wandered into some dungeon and encountered some necromancers or bandits. I killed some with sneak attack by bow and some turned hostile and they rush to me and I killed them directly. When I sleep, there are no Dark Brotherhood members approaching me. Why? | 2012/02/10 | [
"https://gaming.stackexchange.com/questions/50364",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/7993/"
] | According to the [Elder Scrolls wiki](http://www.uesp.net/wiki/Oblivion:A_Knife_in_the_Dark),
>
> you must murder someone in cold blood. In other words, you must murder an innocent without provocation (note that Bandits and the like do not count as the required murder). Once the deed is done, regardless of who is there, the cryptic message "Your killing has been observed by forces unknown..." will appear in the corner of your screen, indicating you will be visited the next time you sleep.
>
>
>
Basically any non-essential NPC will do. (Note that unlike in Morrowind, Oblivion's predecessor, you cannot kill an essential NPC, so you don't have to worry about killing the "wrong" person. If an NPC is involved in a quest you haven't completed, you won't be able to kill them.) If you are looking for a specific set of targets, the wiki has a [list of them](http://www.uesp.net/wiki/Oblivion:Dark_Brotherhood#Targets). I've listed a few of the best targets below:
>
> -- The Skooma Den in Bravil has 4 residents, 3 with 0 responsibility, so your crime will likely go unreported.
>
> -- Camonna Tong Thug: Killing one of the two Camonna Tong thugs at Walker camp will give you no bounty, as they both have low responsibility. If you attack one of them before he attacked you, killing him is counted as a murder, and will allow you to join the Dark Brotherhood. They both respawn in a few days, as well.
>
> -- Alval Uvani has a rather low responsibility, and since he does a lot of traveling (see the Dark Brotherhood mission A Matter of Honor for details) it's rather easy to dispose of him on the road without witnesses. The benefit of killing Alval is that you will have already completed one of the later Brotherhood missions.
>
>
> | The one you kill must be an innocent.
I wanted to do the Brotherhood quest early in the game because it bugs me to be a murderer. So, I killed that drug dealer (sells skooma and poisons at night) who stands outside the north wall of the Imperial City, but even though he had not gone aggro on me, his death did not count.
Just thought you might like to know how some characters don't qualify at all. |
3,175,607 | Im trying to define an array of arrays as a Constant in one of my classes, the code looks like this:
```
Constant = [[1,2,3,4],
[5,6,7,8]]
```
When I load up the class in irb I get:
```
NoMethodError: undefined method `[]' for nil:NilClass
```
I tried using %w and all that did was turn each one into a string so i got "[1,2,3,4]" instead of [1,2,3,4]
how do I define an array of arrays as a constant?
Im using ruby 1.8.7.
When I define the constant in IRB its fine, but when I load up the class with it in i get an error.
```
require 'file_with_class.rb'
NoMethodError: undefined method `[]' for nil:NilClass
from ./trainbbcode/tags.rb:2
from /usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require'
from (irb):1
```
That file looks like this:
```
class TBBC
Tags = [[/\[b\](.*?)\[\/b\]/,'<strong>\1</strong>',@config[:strong_enabled]],
...
[/\[th\](.*?)\[\/th\]/,'<th>\1</th>',@config[:table_enabled]]]
``` | 2010/07/04 | [
"https://Stackoverflow.com/questions/3175607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/222018/"
] | The code you showed works just fine. You're definitely not getting that error message for that particular line. The error is caused elsewhere.
And yes, `%w` creates an array of strings. To create normal arrays use `[]` like you did.
Edit now that you've shown the real code:
`@config` is `nil` in the scope where you use it, so you get an exception when you do `@config[:strong_enabled]`.
Note that inside of a class definition but outside of any method definition `@foo` refers to the instance variable of the class object, not that of any particular instance (because which one would it refer to? There aren't even any instances yet, when the constant is initialized). | It's a bit strange to use a TitleCase name for a constant. But regardless, it works for me:
```
$ ruby --version
ruby 1.8.7 (2009-06-12 patchlevel 174) [i686-darwin9.7.0]
$ irb --version
irb 0.9.5(05/04/13)
$ irb
irb(main):001:0> Constant = [[1,2,3,4],[5,6,7,8]]
=> [[1, 2, 3, 4], [5, 6, 7, 8]]
```
I also tested it in Ruby 1.9.1. Could you be more specific? |
2,417 | ```
cleos --url http://127.0.0.1:8888 --wallet-url http://127.0.0.1:8899 push action eosio.token create '["eosio", "2000000000.0000 KBS"]' --permission eosio.token@active
cleos --url http://127.0.0.1:8888 --wallet-url http://127.0.0.1:8899 push action eosio.token issue '["eosio", "100000000.0000 KBS", ""]' --permission eosio@active
cleos --url http://127.0.0.1:8888 --wallet-url http://127.0.0.1:8899 system newaccount eosio intblue11112 EOS6w5oLk1NcLvvnfW4YVqeohoX3GV3t79LT8CJEZczBTEJVKYzeC EOS6w5oLk1NcLvvnfW4YVqeohoX3GV3t79LT8CJEZczBTEJVKYzeC --stake-net "10000.0000 KBS" --stake-cpu "10000.0000 KBS" --buy-ram-kbytes 8192
assertion failure with message: symbol precision mismatch
```
why ? | 2018/09/21 | [
"https://eosio.stackexchange.com/questions/2417",
"https://eosio.stackexchange.com",
"https://eosio.stackexchange.com/users/2283/"
] | When you build from source, you can specify what the core symbol token will be by adding the flag `-s`:
`./eosio_build.sh -s "KBS"`
```
printf "Usage: %s \\n[Build Option -o <Debug|Release|RelWithDebInfo|MinSizeRel>] \\n[CodeCoverage -c] \\n[Doxygen -d] \\n[CoreSymbolName -s <1-7 characters>] \\n[Avoid Compiling -a]\\n[Noninteractive -y]\\n\\n" "$0" 1>&2
# ... \\n[CoreSymbolName -s <1-7 characters>]
```
<https://github.com/EOSIO/eos/blob/master/scripts/eosio_build.sh#L104>
```
# CORE_SYMBOL_NAME="SYS"
CORE_SYMBOL_NAME="KBS"
```
<https://github.com/EOSIO/eos/blob/master/scripts/eosio_build.sh#L38> | It only accept system token for **newaccount action** . It could be "SYS" or "EOS" ...
You can check it at eos/contracts/eosiolib/core\_symbol.hpp.
And change token name to **KBS** |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.