qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
106,947 | I've been able to add a Google Calendar (CalDAV) account to OS X Calendar (v6, Mountain Lion 10.8.5) without problem, and all my own calendars show up.
Is there a way of seeing calendars others have shared with me (these show up under 'Other Calendars' in the Google Calendar website settings)?
(Same situation on my iPhone.) | 2013/10/26 | [
"https://apple.stackexchange.com/questions/106947",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/37070/"
]
| Yes, this question is answered by google here:
<https://www.google.com/calendar/syncselect>
You can click on the link and select shared calendars you wanna sync with your device. | You could use a Calendar Program like Informant for macOS. it allows you to combine numerous calendars into a single app. |
12,859,824 | I am parsing through the subviews of a parent view,
It has various subviews, all custom classes, of 10 different UIView subclasses.
There is just one class which is a normal UIView.
Now when I am looping thru, I need to get hold of the UIView subview, isKindOfClass is failing to do so as it returns 1 for all the UIView subclasses as well.
Do I have to write a a big if-else construct to check if its an object of any other custom UIView subclass and then in the last else come to a conclusion that its a normal UIView.
Or is there a method that tells me exact class of the view ? | 2012/10/12 | [
"https://Stackoverflow.com/questions/12859824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/961021/"
]
| You shoud use :
```
[currentView isMemberOfClass:[UIView class]];
``` | <http://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/isMemberOfClass>: |
12,523,776 | ```
#ifndef UNICODE
#define UNICODE
#endif
#include <iostream>
#include <Windows.h>
#include <queue>
using namespace std;
void addSomeContent(queue<TCHAR*> &s)
{
static int counter=0;
TCHAR* buffer = new TCHAR[250]; //Allocate memory on heap
wsprintf(buffer,TEXT("foo%d"),counter);
s.push(buffer);
counter++;
if(counter < 10)
addSomeContent(s);
}
int main (void)
{
queue<TCHAR*> strings;
addSomeContent(strings);
while(!strings.empty())
{
wcout<<strings.front()<<endl;
strings.pop();
}
//Here I want to destroy the "buffer" from the function "addSomeContent"
wcout<<TEXT("Memory has been cleaned!\n");
system("pause");
return (0);
}
```
If I had deleted the wide char array at the end of the function, I couldn't have processed my queue which references to it. Now, my simple program compiles and works fine, but obviously keeping a garbage in heap isn't considered as a safe programming practice.
How to delete the "buffer" just after using it last time? | 2012/09/21 | [
"https://Stackoverflow.com/questions/12523776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1349442/"
]
| Agree with Seth about using unique\_ptr for your queue, or you can simply call
```
delete[] strings.front()
```
before the `strings.pop()`
`front()` should be used to ensure we clean the element we are about to `pop()` i.e. the oldest element in the queue rather than `back()`, which is the newest! | If you just want to work with strings, I would consider to just use
```
typedef std::basic_string<TCHAR> tstring;
std::queue<tstring> strings;
```
Otherwise you could use
```
std::queue<std::unique_ptr<TCHAR[]>> strings; // notice the [], they are important!
```
unique\_ptr is C++11, but I think it's supported by all major compilers. I would not even consider to delete[] this manually. It is very vulnerable to errors, and not exception safe. |
12,523,776 | ```
#ifndef UNICODE
#define UNICODE
#endif
#include <iostream>
#include <Windows.h>
#include <queue>
using namespace std;
void addSomeContent(queue<TCHAR*> &s)
{
static int counter=0;
TCHAR* buffer = new TCHAR[250]; //Allocate memory on heap
wsprintf(buffer,TEXT("foo%d"),counter);
s.push(buffer);
counter++;
if(counter < 10)
addSomeContent(s);
}
int main (void)
{
queue<TCHAR*> strings;
addSomeContent(strings);
while(!strings.empty())
{
wcout<<strings.front()<<endl;
strings.pop();
}
//Here I want to destroy the "buffer" from the function "addSomeContent"
wcout<<TEXT("Memory has been cleaned!\n");
system("pause");
return (0);
}
```
If I had deleted the wide char array at the end of the function, I couldn't have processed my queue which references to it. Now, my simple program compiles and works fine, but obviously keeping a garbage in heap isn't considered as a safe programming practice.
How to delete the "buffer" just after using it last time? | 2012/09/21 | [
"https://Stackoverflow.com/questions/12523776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1349442/"
]
| You can use a `queue<unique_ptr<TCHAR[]>>` to avoid memory deallocation entirely, or you can simply deallocate the memory before you remove it from the `queue` like so:
```
delete[] strings.front();
strings.pop();
``` | Agree with Seth about using unique\_ptr for your queue, or you can simply call
```
delete[] strings.front()
```
before the `strings.pop()`
`front()` should be used to ensure we clean the element we are about to `pop()` i.e. the oldest element in the queue rather than `back()`, which is the newest! |
12,523,776 | ```
#ifndef UNICODE
#define UNICODE
#endif
#include <iostream>
#include <Windows.h>
#include <queue>
using namespace std;
void addSomeContent(queue<TCHAR*> &s)
{
static int counter=0;
TCHAR* buffer = new TCHAR[250]; //Allocate memory on heap
wsprintf(buffer,TEXT("foo%d"),counter);
s.push(buffer);
counter++;
if(counter < 10)
addSomeContent(s);
}
int main (void)
{
queue<TCHAR*> strings;
addSomeContent(strings);
while(!strings.empty())
{
wcout<<strings.front()<<endl;
strings.pop();
}
//Here I want to destroy the "buffer" from the function "addSomeContent"
wcout<<TEXT("Memory has been cleaned!\n");
system("pause");
return (0);
}
```
If I had deleted the wide char array at the end of the function, I couldn't have processed my queue which references to it. Now, my simple program compiles and works fine, but obviously keeping a garbage in heap isn't considered as a safe programming practice.
How to delete the "buffer" just after using it last time? | 2012/09/21 | [
"https://Stackoverflow.com/questions/12523776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1349442/"
]
| You can use a `queue<unique_ptr<TCHAR[]>>` to avoid memory deallocation entirely, or you can simply deallocate the memory before you remove it from the `queue` like so:
```
delete[] strings.front();
strings.pop();
``` | If you just want to work with strings, I would consider to just use
```
typedef std::basic_string<TCHAR> tstring;
std::queue<tstring> strings;
```
Otherwise you could use
```
std::queue<std::unique_ptr<TCHAR[]>> strings; // notice the [], they are important!
```
unique\_ptr is C++11, but I think it's supported by all major compilers. I would not even consider to delete[] this manually. It is very vulnerable to errors, and not exception safe. |
11,736,566 | I'm trying to retrieve the month using `date`.
```
$year= 2012;
$mon = date( 'F', mktime(0, 0, 0, $month,$year) );
```
In the above code snippet, `$month` is dynamically incremented. I have used a while loop with `$month++`. But it doesn't give me the correct date.
For example, let's say I gave `$month=5` at the beginning, then it's incremented till `$month=12`. Then the output should be something like
```
May
June
July...
```
but, it's output is:
```
November
December
January.....
```
why is this? Am I doing anything wrong here? | 2012/07/31 | [
"https://Stackoverflow.com/questions/11736566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1503607/"
]
| You forgot $date parameter. THe correct syntax of mktime is
```
mktime($hour,$minute,$second,$month,$day,$year);
```
so in your example $year will be considered as 'date'
try something like
```
mktime(0,0,0,$month,1,$year);
``` | there's an error in `mktime`: should be `mktime(0, 0, 0, $month, 1,$year)`, cause the 5th argument is `day`, but not the `year` |
11,736,566 | I'm trying to retrieve the month using `date`.
```
$year= 2012;
$mon = date( 'F', mktime(0, 0, 0, $month,$year) );
```
In the above code snippet, `$month` is dynamically incremented. I have used a while loop with `$month++`. But it doesn't give me the correct date.
For example, let's say I gave `$month=5` at the beginning, then it's incremented till `$month=12`. Then the output should be something like
```
May
June
July...
```
but, it's output is:
```
November
December
January.....
```
why is this? Am I doing anything wrong here? | 2012/07/31 | [
"https://Stackoverflow.com/questions/11736566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1503607/"
]
| You forgot $date parameter. THe correct syntax of mktime is
```
mktime($hour,$minute,$second,$month,$day,$year);
```
so in your example $year will be considered as 'date'
try something like
```
mktime(0,0,0,$month,1,$year);
``` | Your problem stems from these lines:
```
$year= 2012;
$mon = date( 'F', mktime(0, 0, 0, $month,$year) );
```
To be exact from the mktime command. The exact syntax is: mktime($hour,$minute,$second,$month,$day,$year);
As you have given $year as 5th parameter it is interpreted as "day" instead of "year". Thus when you set the month to 5 you get month 5 +2012 days which means the 1st day of may is incremented by 2011 days and that results in november then.
You should use the following line instead to get the desired result:
```
$mon = date( 'F', mktime(0, 0, 0, $month,1,$year) );
```
That way you get the desired month (and the day is always the first of this month....so it does not interfere with your calculation. |
1,231,785 | I have two .Net applications running on client machine.One is IMSOperations and other is IMSInvoice.Both are windows forms application using C#.
What happens is when both of these applications are running,after some time IMSOperations gets automatically closed.
What i tried is to find reason of closing by subscribing to main form's Form\_Closing() event.IS there any other way to figure out what's going on and why is that application getting closed. | 2009/08/05 | [
"https://Stackoverflow.com/questions/1231785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139357/"
]
| Might I suggest adding these to make sure no exception is being thrown:
You need to add this line to your Main():
```
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
```
and add appropriate handlers to display any exceptions.
(ThreadException handles exceptions UI thread exceptions. UnhandledException handles non-UI thread exceptions.) | Is it a clean exit? or its throwing an exception?
If its the first there must be some code that checks the status of the other application. If its the latter you have to find the source of the crash. |
3,880,339 | I have a referenced library, inside there I want to perform a different action if the assembly that references it is in DEBUG/RELEASE mode.
Is it possible to switch on the condition that the calling assembly is in DEBUG/RELEASE mode?
Is there a way to do this without resorting to something like:
```
bool debug = false;
#if DEBUG
debug = true;
#endif
referencedlib.someclass.debug = debug;
```
The referencing assembly will always be the starting point of the application (i.e. web application. | 2010/10/07 | [
"https://Stackoverflow.com/questions/3880339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28543/"
]
| [Google says](http://stevesmithblog.com/blog/determine-whether-an-assembly-was-compiled-in-debug-mode/) it is very simple. You get the information from the [DebuggableAttribute](http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggableattribute.aspx) of the assembly in question:
```
IsAssemblyDebugBuild(Assembly.GetCallingAssembly());
private bool IsAssemblyDebugBuild(Assembly assembly)
{
foreach (var attribute in assembly.GetCustomAttributes(false))
{
var debuggableAttribute = attribute as DebuggableAttribute;
if(debuggableAttribute != null)
{
return debuggableAttribute.IsJITTrackingEnabled;
}
}
return false;
}
``` | You can use [reflection](http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getcallingassembly.aspx) to get the calling assembly and use [this method](http://stevesmithblog.com/blog/determine-whether-an-assembly-was-compiled-in-debug-mode/) to check if it is in debug mode. |
3,880,339 | I have a referenced library, inside there I want to perform a different action if the assembly that references it is in DEBUG/RELEASE mode.
Is it possible to switch on the condition that the calling assembly is in DEBUG/RELEASE mode?
Is there a way to do this without resorting to something like:
```
bool debug = false;
#if DEBUG
debug = true;
#endif
referencedlib.someclass.debug = debug;
```
The referencing assembly will always be the starting point of the application (i.e. web application. | 2010/10/07 | [
"https://Stackoverflow.com/questions/3880339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28543/"
]
| [Google says](http://stevesmithblog.com/blog/determine-whether-an-assembly-was-compiled-in-debug-mode/) it is very simple. You get the information from the [DebuggableAttribute](http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggableattribute.aspx) of the assembly in question:
```
IsAssemblyDebugBuild(Assembly.GetCallingAssembly());
private bool IsAssemblyDebugBuild(Assembly assembly)
{
foreach (var attribute in assembly.GetCustomAttributes(false))
{
var debuggableAttribute = attribute as DebuggableAttribute;
if(debuggableAttribute != null)
{
return debuggableAttribute.IsJITTrackingEnabled;
}
}
return false;
}
``` | The accepted answer is correct. Here's an alternative version that skips the iteration stage and is provided as an extension method:
```
public static class AssemblyExtensions
{
public static bool IsDebugBuild(this Assembly assembly)
{
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
return assembly.GetCustomAttribute<DebuggableAttribute>()?.IsJITTrackingEnabled ?? false;
}
}
``` |
3,880,339 | I have a referenced library, inside there I want to perform a different action if the assembly that references it is in DEBUG/RELEASE mode.
Is it possible to switch on the condition that the calling assembly is in DEBUG/RELEASE mode?
Is there a way to do this without resorting to something like:
```
bool debug = false;
#if DEBUG
debug = true;
#endif
referencedlib.someclass.debug = debug;
```
The referencing assembly will always be the starting point of the application (i.e. web application. | 2010/10/07 | [
"https://Stackoverflow.com/questions/3880339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28543/"
]
| The accepted answer is correct. Here's an alternative version that skips the iteration stage and is provided as an extension method:
```
public static class AssemblyExtensions
{
public static bool IsDebugBuild(this Assembly assembly)
{
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
return assembly.GetCustomAttribute<DebuggableAttribute>()?.IsJITTrackingEnabled ?? false;
}
}
``` | You can use [reflection](http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getcallingassembly.aspx) to get the calling assembly and use [this method](http://stevesmithblog.com/blog/determine-whether-an-assembly-was-compiled-in-debug-mode/) to check if it is in debug mode. |
54,014,561 | I have the following array:
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35];
I want to get 15 random numbers from this array, where there can't be duplicates. I have no idea on how to do it.
Also, if it'd be easier, I would like to know if there is a way to generate an array with 15 numbers from 1 to 35, with no duplicates, instead of picking them from the array I showed.
Thanks in advance! | 2019/01/02 | [
"https://Stackoverflow.com/questions/54014561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10860157/"
]
| If you are just trying to get a number between 1 and 35 then you could do this,
```
Math.floor(Math.random() * 35) + 1
```
Math.random() returns a number between 0 and 1, multiplying this by 35 gives a number between 0 and 35 (not inclusive) as a float, you then take a floor add 1 to get the desired range.
You can then loop over this and use this to populate your array.
If you don't want any repeats then I recommend you look at using a `Set` to make sure you don't have any repeats, then just loop until the set has the desired number of values.
Sets are documented [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) | Here is a simple method,.
First create the array of numbers from 1 to 35.
Then randomly delete one from this array until the length is equal to 15.
```js
const nums = Array.from(new Array(35),(v,i)=>i+1);
while (nums.length > 15) nums.splice(Math.random() * nums.length, 1);
console.log(nums.join(", "));
``` |
41,413 | My friend asked me for help with an IQ test and after she did it online she came back at me with the ones she couldn't solve.
Two of them however, I discovered are the same puzzle type, but no matter how much I look at it, I just can't see the logic in it. We redid the test and this puzzle occurred yet again, so now I have three versions of the same type of sequence written below.
>
> 19 43 83 233 59 61 283 ?
>
>
> 11 35 75 225 51 53 275 ?
>
>
> 5 29 69 219 45 47 269 ?
>
>
>
I get the feeling that this puzzle is easy, yet I just can't see it.
[Update]
By request, I give the five options for the answer of the top row that I wrote down during the second test.
The options are: 800 778 793 58 176.
I'm actually leaning towards Jonathan Allan's explanation of a mistake in some data entry for their automated question generation right now, since no one here seems to have solved it yet.
Prior to my post here, my friend emailed them asking them about this sequence, so most likely we will know between now and a few days.
[Update]
Looking at the options again, this puzzle is really really simple. Thank you smriti. | 2016/08/25 | [
"https://puzzling.stackexchange.com/questions/41413",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/29405/"
]
| The Answer to number 2:
>
> 793: Why? They are all odd numbers! (Only possible to guess given the multiple choice nature of the question) The pattern means diddle squat.
>
>
>
---
None of the below matters, these were early attempts, which turned out to be wrong
----------------------------------------------------------------------------------
In addition to @Daniel (Sorry, no rights to comment)
>
> 1**9** 43 **83** 233 5**9** 61 2**83** | 9 and 83
>
>
> 1**1** 35 **75** 225 5**1** 53 2**75** |1 and 75
>
>
> 0**5** 29 **69** 219 4**5** 47 2**69** | 5 and 69
>
>
>
then there is
>
> **19** 43 83 2**33** **59** 61 2**83** | 59-19=40, 283-233=50
>
>
> **11** 35 75 2**25** **51** 53 2**75** | 51-11=40, 275-225=50
>
>
> **05** 29 69 2**19** **45** 47 2**69** | 45-05=40, 269-219=50
>
>
>
There are a few other simple additions with nice round numbers
>
> d5-d1 = 40, d3-d2 = 40, d4-d2 = 140 (100+40)
>
>
> d7-d4 = 50, d4-d3 = 150 (100+50)
>
>
> d7-d3 = 200
>
>
>
Another pattern exists in the second digit... but this might be seeing patterns where there aren't any. It might also be giving even more credibility to the modulo + offset theory. (base+offset)%10 works for the patterns below.
>
> 9, 3, 1 -> 9, 1, 3 -> **9**+2=1**1**+2=1**3**(drop the 10's)
>
>
> 1, 3, 5 -> **1**+2=**3**+2=**5**
>
>
> 5, 9, 7 -> 5, 7, 9 -> **5**+2=**7**+2=**9**
>
>
>
So:
>
> If d1 + 40 = d5, and d4 + 50 = d7, then I will guess d6+60 = d8
>
>
> logic: 5-1 = 4, 7-4 = 3, so 8-X = 2. X must be 6
>
>
> 61+60=121
>
>
> 53+60=113
>
>
> 47+60=107
>
>
> | Answers:
>
> 75, 67, 61
>
>
>
$N\_2-N\_1=24\\N\_3-N\_1=64\\N\_4-N\_1=214$
Assume that each sequence is structured as an initial number
followed by a succession of groups of three numbers:
$$\{N\_1\}\quad\{N\_2,N\_3,N\_4\}\quad\{N\_5,N\_6,N\_7\}\quad\dots$$
$N\_5-N\_2=16\\N\_6-N\_3=-12\\N\_7-N\_4=50$
So, for an arbitrary seed/starting number $x$, the sequence is
\begin{array}l
N\_1=x\\[3ex]
N\_2=x+24&N\_3=x+64&N\_4=x+214\\[3ex]
N\_5=\,x+24+16&N\_6=\,x+64-12&N\_7=\,x+214+50\\
\phantom{N\_5}=\:~~~N\_2~~~+16\quad&\phantom{N\_6}=\:~~~N\_3~~~-12\quad&
\phantom{N\_7}=\:~~~~N\_4~~~~+50\\[3ex]
\llap{\text{assume }}N\_8=\:~~~N\_5~~~+16&N\_9=\:~~~N\_6~~~-12&N\_{10}=~~~~N\_7\:~~~+50&\dots
\end{array}
And so the three sequences, extended to ten numbers, are
\begin{array}{c|ccc|ccc|ccc}
19&43&83&233&59&61&283&\boxed{75}&39&333\dots\\
11&35&75&225&51&53&275&\boxed{67}&31&325\dots\\
5&29&69&219&45&47&269&\boxed{61}&25&319\dots
\end{array} |
41,413 | My friend asked me for help with an IQ test and after she did it online she came back at me with the ones she couldn't solve.
Two of them however, I discovered are the same puzzle type, but no matter how much I look at it, I just can't see the logic in it. We redid the test and this puzzle occurred yet again, so now I have three versions of the same type of sequence written below.
>
> 19 43 83 233 59 61 283 ?
>
>
> 11 35 75 225 51 53 275 ?
>
>
> 5 29 69 219 45 47 269 ?
>
>
>
I get the feeling that this puzzle is easy, yet I just can't see it.
[Update]
By request, I give the five options for the answer of the top row that I wrote down during the second test.
The options are: 800 778 793 58 176.
I'm actually leaning towards Jonathan Allan's explanation of a mistake in some data entry for their automated question generation right now, since no one here seems to have solved it yet.
Prior to my post here, my friend emailed them asking them about this sequence, so most likely we will know between now and a few days.
[Update]
Looking at the options again, this puzzle is really really simple. Thank you smriti. | 2016/08/25 | [
"https://puzzling.stackexchange.com/questions/41413",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/29405/"
]
| The Answer to number 2:
>
> 793: Why? They are all odd numbers! (Only possible to guess given the multiple choice nature of the question) The pattern means diddle squat.
>
>
>
---
None of the below matters, these were early attempts, which turned out to be wrong
----------------------------------------------------------------------------------
In addition to @Daniel (Sorry, no rights to comment)
>
> 1**9** 43 **83** 233 5**9** 61 2**83** | 9 and 83
>
>
> 1**1** 35 **75** 225 5**1** 53 2**75** |1 and 75
>
>
> 0**5** 29 **69** 219 4**5** 47 2**69** | 5 and 69
>
>
>
then there is
>
> **19** 43 83 2**33** **59** 61 2**83** | 59-19=40, 283-233=50
>
>
> **11** 35 75 2**25** **51** 53 2**75** | 51-11=40, 275-225=50
>
>
> **05** 29 69 2**19** **45** 47 2**69** | 45-05=40, 269-219=50
>
>
>
There are a few other simple additions with nice round numbers
>
> d5-d1 = 40, d3-d2 = 40, d4-d2 = 140 (100+40)
>
>
> d7-d4 = 50, d4-d3 = 150 (100+50)
>
>
> d7-d3 = 200
>
>
>
Another pattern exists in the second digit... but this might be seeing patterns where there aren't any. It might also be giving even more credibility to the modulo + offset theory. (base+offset)%10 works for the patterns below.
>
> 9, 3, 1 -> 9, 1, 3 -> **9**+2=1**1**+2=1**3**(drop the 10's)
>
>
> 1, 3, 5 -> **1**+2=**3**+2=**5**
>
>
> 5, 9, 7 -> 5, 7, 9 -> **5**+2=**7**+2=**9**
>
>
>
So:
>
> If d1 + 40 = d5, and d4 + 50 = d7, then I will guess d6+60 = d8
>
>
> logic: 5-1 = 4, 7-4 = 3, so 8-X = 2. X must be 6
>
>
> 61+60=121
>
>
> 53+60=113
>
>
> 47+60=107
>
>
> | I interpreted it a different way, with each sequence as two strings with a prime as an index. It makes me think it's the same sequence that's been modified by the first number:
```
19
43 83 233
59 61 283
+16 -22 +50
11
35 75 225
51 53 275
+16 -22 +50
5
29 69 219
45 47 269
+16 -22 +50
```
Multiplying the 2 digit pairs and brings you products unusually close to each other(<100 in each case), but I didn't get any further than that.
Also Not sure how it helps, but those sequences are each unfairly weighted to a single digit, in the same positions.
>
> 19 4**3** 8**3** 23**3** 59 61 28**3** | 3
>
>
> 11 3**5** 7**5** 22**5** 51 53 27**5** | 5
>
>
> 05 2**9** 6**9** 21**9** 45 47 26**9** | 9
>
>
> |
41,413 | My friend asked me for help with an IQ test and after she did it online she came back at me with the ones she couldn't solve.
Two of them however, I discovered are the same puzzle type, but no matter how much I look at it, I just can't see the logic in it. We redid the test and this puzzle occurred yet again, so now I have three versions of the same type of sequence written below.
>
> 19 43 83 233 59 61 283 ?
>
>
> 11 35 75 225 51 53 275 ?
>
>
> 5 29 69 219 45 47 269 ?
>
>
>
I get the feeling that this puzzle is easy, yet I just can't see it.
[Update]
By request, I give the five options for the answer of the top row that I wrote down during the second test.
The options are: 800 778 793 58 176.
I'm actually leaning towards Jonathan Allan's explanation of a mistake in some data entry for their automated question generation right now, since no one here seems to have solved it yet.
Prior to my post here, my friend emailed them asking them about this sequence, so most likely we will know between now and a few days.
[Update]
Looking at the options again, this puzzle is really really simple. Thank you smriti. | 2016/08/25 | [
"https://puzzling.stackexchange.com/questions/41413",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/29405/"
]
| The Answer to number 2:
>
> 793: Why? They are all odd numbers! (Only possible to guess given the multiple choice nature of the question) The pattern means diddle squat.
>
>
>
---
None of the below matters, these were early attempts, which turned out to be wrong
----------------------------------------------------------------------------------
In addition to @Daniel (Sorry, no rights to comment)
>
> 1**9** 43 **83** 233 5**9** 61 2**83** | 9 and 83
>
>
> 1**1** 35 **75** 225 5**1** 53 2**75** |1 and 75
>
>
> 0**5** 29 **69** 219 4**5** 47 2**69** | 5 and 69
>
>
>
then there is
>
> **19** 43 83 2**33** **59** 61 2**83** | 59-19=40, 283-233=50
>
>
> **11** 35 75 2**25** **51** 53 2**75** | 51-11=40, 275-225=50
>
>
> **05** 29 69 2**19** **45** 47 2**69** | 45-05=40, 269-219=50
>
>
>
There are a few other simple additions with nice round numbers
>
> d5-d1 = 40, d3-d2 = 40, d4-d2 = 140 (100+40)
>
>
> d7-d4 = 50, d4-d3 = 150 (100+50)
>
>
> d7-d3 = 200
>
>
>
Another pattern exists in the second digit... but this might be seeing patterns where there aren't any. It might also be giving even more credibility to the modulo + offset theory. (base+offset)%10 works for the patterns below.
>
> 9, 3, 1 -> 9, 1, 3 -> **9**+2=1**1**+2=1**3**(drop the 10's)
>
>
> 1, 3, 5 -> **1**+2=**3**+2=**5**
>
>
> 5, 9, 7 -> 5, 7, 9 -> **5**+2=**7**+2=**9**
>
>
>
So:
>
> If d1 + 40 = d5, and d4 + 50 = d7, then I will guess d6+60 = d8
>
>
> logic: 5-1 = 4, 7-4 = 3, so 8-X = 2. X must be 6
>
>
> 61+60=121
>
>
> 53+60=113
>
>
> 47+60=107
>
>
> | >
> The pattern is simply odd numbers. Of the choices, only one of them is an odd number.
>
>
> |
41,413 | My friend asked me for help with an IQ test and after she did it online she came back at me with the ones she couldn't solve.
Two of them however, I discovered are the same puzzle type, but no matter how much I look at it, I just can't see the logic in it. We redid the test and this puzzle occurred yet again, so now I have three versions of the same type of sequence written below.
>
> 19 43 83 233 59 61 283 ?
>
>
> 11 35 75 225 51 53 275 ?
>
>
> 5 29 69 219 45 47 269 ?
>
>
>
I get the feeling that this puzzle is easy, yet I just can't see it.
[Update]
By request, I give the five options for the answer of the top row that I wrote down during the second test.
The options are: 800 778 793 58 176.
I'm actually leaning towards Jonathan Allan's explanation of a mistake in some data entry for their automated question generation right now, since no one here seems to have solved it yet.
Prior to my post here, my friend emailed them asking them about this sequence, so most likely we will know between now and a few days.
[Update]
Looking at the options again, this puzzle is really really simple. Thank you smriti. | 2016/08/25 | [
"https://puzzling.stackexchange.com/questions/41413",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/29405/"
]
| I think numbers should be 111,103,97 respectively.[](https://i.stack.imgur.com/IN2gp.jpg)
We take difference only those number whose last digit is same. | I don't know where it can lead, but (and for the first sequence only) :
(43 + 83) \* **2 -** 19 = 233
(59 + 61) \* **2 +** 43 = 283
Coincidence...? but this is not working for the 2 other sequences.
That was just to contribute a bit or give an idea to someone...
Above all that, either the scenario of the question is a reality... so nothing proves that the 3 sequences follow the same law... or it is a scenario to embed the question and, yes probably, the 3 sequences may follow one law... |
41,413 | My friend asked me for help with an IQ test and after she did it online she came back at me with the ones she couldn't solve.
Two of them however, I discovered are the same puzzle type, but no matter how much I look at it, I just can't see the logic in it. We redid the test and this puzzle occurred yet again, so now I have three versions of the same type of sequence written below.
>
> 19 43 83 233 59 61 283 ?
>
>
> 11 35 75 225 51 53 275 ?
>
>
> 5 29 69 219 45 47 269 ?
>
>
>
I get the feeling that this puzzle is easy, yet I just can't see it.
[Update]
By request, I give the five options for the answer of the top row that I wrote down during the second test.
The options are: 800 778 793 58 176.
I'm actually leaning towards Jonathan Allan's explanation of a mistake in some data entry for their automated question generation right now, since no one here seems to have solved it yet.
Prior to my post here, my friend emailed them asking them about this sequence, so most likely we will know between now and a few days.
[Update]
Looking at the options again, this puzzle is really really simple. Thank you smriti. | 2016/08/25 | [
"https://puzzling.stackexchange.com/questions/41413",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/29405/"
]
| What these three have in common is that in all of these sequences the addition to the next is in this order:
>
> 24 40 150 -174 2 222 ?
>
>
>
So as these three sequences share the same changing sequence then the changing isn't related to the numbers themselves but the differences between the numbers.
Got some hints from @Shimizoki's reasoning, but this might be totally wrong:
N1 + 40 = N5
N4 + 50 = N7
This could mean that:
N7 + 60 = N8
Because in the next equation:
The first in the equation is the number that is three positions further in the sequence.
The second number increases with ten.
The difference between the first in the equations place in the sequence and the sums number in the sequence increases by one less for each equation.
Therefore for the last number in the row for the first sequence would be 283+60=343.
This would mean the there are some decoy numbers and we have only deduced the pattern from two cases which makes me doubt that this is the right answer. | I think numbers should be 111,103,97 respectively.[](https://i.stack.imgur.com/IN2gp.jpg)
We take difference only those number whose last digit is same. |
41,413 | My friend asked me for help with an IQ test and after she did it online she came back at me with the ones she couldn't solve.
Two of them however, I discovered are the same puzzle type, but no matter how much I look at it, I just can't see the logic in it. We redid the test and this puzzle occurred yet again, so now I have three versions of the same type of sequence written below.
>
> 19 43 83 233 59 61 283 ?
>
>
> 11 35 75 225 51 53 275 ?
>
>
> 5 29 69 219 45 47 269 ?
>
>
>
I get the feeling that this puzzle is easy, yet I just can't see it.
[Update]
By request, I give the five options for the answer of the top row that I wrote down during the second test.
The options are: 800 778 793 58 176.
I'm actually leaning towards Jonathan Allan's explanation of a mistake in some data entry for their automated question generation right now, since no one here seems to have solved it yet.
Prior to my post here, my friend emailed them asking them about this sequence, so most likely we will know between now and a few days.
[Update]
Looking at the options again, this puzzle is really really simple. Thank you smriti. | 2016/08/25 | [
"https://puzzling.stackexchange.com/questions/41413",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/29405/"
]
| The Answer to number 2:
>
> 793: Why? They are all odd numbers! (Only possible to guess given the multiple choice nature of the question) The pattern means diddle squat.
>
>
>
---
None of the below matters, these were early attempts, which turned out to be wrong
----------------------------------------------------------------------------------
In addition to @Daniel (Sorry, no rights to comment)
>
> 1**9** 43 **83** 233 5**9** 61 2**83** | 9 and 83
>
>
> 1**1** 35 **75** 225 5**1** 53 2**75** |1 and 75
>
>
> 0**5** 29 **69** 219 4**5** 47 2**69** | 5 and 69
>
>
>
then there is
>
> **19** 43 83 2**33** **59** 61 2**83** | 59-19=40, 283-233=50
>
>
> **11** 35 75 2**25** **51** 53 2**75** | 51-11=40, 275-225=50
>
>
> **05** 29 69 2**19** **45** 47 2**69** | 45-05=40, 269-219=50
>
>
>
There are a few other simple additions with nice round numbers
>
> d5-d1 = 40, d3-d2 = 40, d4-d2 = 140 (100+40)
>
>
> d7-d4 = 50, d4-d3 = 150 (100+50)
>
>
> d7-d3 = 200
>
>
>
Another pattern exists in the second digit... but this might be seeing patterns where there aren't any. It might also be giving even more credibility to the modulo + offset theory. (base+offset)%10 works for the patterns below.
>
> 9, 3, 1 -> 9, 1, 3 -> **9**+2=1**1**+2=1**3**(drop the 10's)
>
>
> 1, 3, 5 -> **1**+2=**3**+2=**5**
>
>
> 5, 9, 7 -> 5, 7, 9 -> **5**+2=**7**+2=**9**
>
>
>
So:
>
> If d1 + 40 = d5, and d4 + 50 = d7, then I will guess d6+60 = d8
>
>
> logic: 5-1 = 4, 7-4 = 3, so 8-X = 2. X must be 6
>
>
> 61+60=121
>
>
> 53+60=113
>
>
> 47+60=107
>
>
> | I think numbers should be 111,103,97 respectively.[](https://i.stack.imgur.com/IN2gp.jpg)
We take difference only those number whose last digit is same. |
41,413 | My friend asked me for help with an IQ test and after she did it online she came back at me with the ones she couldn't solve.
Two of them however, I discovered are the same puzzle type, but no matter how much I look at it, I just can't see the logic in it. We redid the test and this puzzle occurred yet again, so now I have three versions of the same type of sequence written below.
>
> 19 43 83 233 59 61 283 ?
>
>
> 11 35 75 225 51 53 275 ?
>
>
> 5 29 69 219 45 47 269 ?
>
>
>
I get the feeling that this puzzle is easy, yet I just can't see it.
[Update]
By request, I give the five options for the answer of the top row that I wrote down during the second test.
The options are: 800 778 793 58 176.
I'm actually leaning towards Jonathan Allan's explanation of a mistake in some data entry for their automated question generation right now, since no one here seems to have solved it yet.
Prior to my post here, my friend emailed them asking them about this sequence, so most likely we will know between now and a few days.
[Update]
Looking at the options again, this puzzle is really really simple. Thank you smriti. | 2016/08/25 | [
"https://puzzling.stackexchange.com/questions/41413",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/29405/"
]
| How about we try to normalize the numbers by removing the first from all subsequent. Hereby we get
>
> 0 24 64 214 40 42 264
>
>
>
Every number has a 4 in it, with many 2's and 6's.
Work in progress for others to consider. Is there a pattern to the numbers now? | I think numbers should be 111,103,97 respectively.[](https://i.stack.imgur.com/IN2gp.jpg)
We take difference only those number whose last digit is same. |
41,413 | My friend asked me for help with an IQ test and after she did it online she came back at me with the ones she couldn't solve.
Two of them however, I discovered are the same puzzle type, but no matter how much I look at it, I just can't see the logic in it. We redid the test and this puzzle occurred yet again, so now I have three versions of the same type of sequence written below.
>
> 19 43 83 233 59 61 283 ?
>
>
> 11 35 75 225 51 53 275 ?
>
>
> 5 29 69 219 45 47 269 ?
>
>
>
I get the feeling that this puzzle is easy, yet I just can't see it.
[Update]
By request, I give the five options for the answer of the top row that I wrote down during the second test.
The options are: 800 778 793 58 176.
I'm actually leaning towards Jonathan Allan's explanation of a mistake in some data entry for their automated question generation right now, since no one here seems to have solved it yet.
Prior to my post here, my friend emailed them asking them about this sequence, so most likely we will know between now and a few days.
[Update]
Looking at the options again, this puzzle is really really simple. Thank you smriti. | 2016/08/25 | [
"https://puzzling.stackexchange.com/questions/41413",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/29405/"
]
| What these three have in common is that in all of these sequences the addition to the next is in this order:
>
> 24 40 150 -174 2 222 ?
>
>
>
So as these three sequences share the same changing sequence then the changing isn't related to the numbers themselves but the differences between the numbers.
Got some hints from @Shimizoki's reasoning, but this might be totally wrong:
N1 + 40 = N5
N4 + 50 = N7
This could mean that:
N7 + 60 = N8
Because in the next equation:
The first in the equation is the number that is three positions further in the sequence.
The second number increases with ten.
The difference between the first in the equations place in the sequence and the sums number in the sequence increases by one less for each equation.
Therefore for the last number in the row for the first sequence would be 283+60=343.
This would mean the there are some decoy numbers and we have only deduced the pattern from two cases which makes me doubt that this is the right answer. | Answers:
>
> 75, 67, 61
>
>
>
$N\_2-N\_1=24\\N\_3-N\_1=64\\N\_4-N\_1=214$
Assume that each sequence is structured as an initial number
followed by a succession of groups of three numbers:
$$\{N\_1\}\quad\{N\_2,N\_3,N\_4\}\quad\{N\_5,N\_6,N\_7\}\quad\dots$$
$N\_5-N\_2=16\\N\_6-N\_3=-12\\N\_7-N\_4=50$
So, for an arbitrary seed/starting number $x$, the sequence is
\begin{array}l
N\_1=x\\[3ex]
N\_2=x+24&N\_3=x+64&N\_4=x+214\\[3ex]
N\_5=\,x+24+16&N\_6=\,x+64-12&N\_7=\,x+214+50\\
\phantom{N\_5}=\:~~~N\_2~~~+16\quad&\phantom{N\_6}=\:~~~N\_3~~~-12\quad&
\phantom{N\_7}=\:~~~~N\_4~~~~+50\\[3ex]
\llap{\text{assume }}N\_8=\:~~~N\_5~~~+16&N\_9=\:~~~N\_6~~~-12&N\_{10}=~~~~N\_7\:~~~+50&\dots
\end{array}
And so the three sequences, extended to ten numbers, are
\begin{array}{c|ccc|ccc|ccc}
19&43&83&233&59&61&283&\boxed{75}&39&333\dots\\
11&35&75&225&51&53&275&\boxed{67}&31&325\dots\\
5&29&69&219&45&47&269&\boxed{61}&25&319\dots
\end{array} |
41,413 | My friend asked me for help with an IQ test and after she did it online she came back at me with the ones she couldn't solve.
Two of them however, I discovered are the same puzzle type, but no matter how much I look at it, I just can't see the logic in it. We redid the test and this puzzle occurred yet again, so now I have three versions of the same type of sequence written below.
>
> 19 43 83 233 59 61 283 ?
>
>
> 11 35 75 225 51 53 275 ?
>
>
> 5 29 69 219 45 47 269 ?
>
>
>
I get the feeling that this puzzle is easy, yet I just can't see it.
[Update]
By request, I give the five options for the answer of the top row that I wrote down during the second test.
The options are: 800 778 793 58 176.
I'm actually leaning towards Jonathan Allan's explanation of a mistake in some data entry for their automated question generation right now, since no one here seems to have solved it yet.
Prior to my post here, my friend emailed them asking them about this sequence, so most likely we will know between now and a few days.
[Update]
Looking at the options again, this puzzle is really really simple. Thank you smriti. | 2016/08/25 | [
"https://puzzling.stackexchange.com/questions/41413",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/29405/"
]
| The Answer to number 2:
>
> 793: Why? They are all odd numbers! (Only possible to guess given the multiple choice nature of the question) The pattern means diddle squat.
>
>
>
---
None of the below matters, these were early attempts, which turned out to be wrong
----------------------------------------------------------------------------------
In addition to @Daniel (Sorry, no rights to comment)
>
> 1**9** 43 **83** 233 5**9** 61 2**83** | 9 and 83
>
>
> 1**1** 35 **75** 225 5**1** 53 2**75** |1 and 75
>
>
> 0**5** 29 **69** 219 4**5** 47 2**69** | 5 and 69
>
>
>
then there is
>
> **19** 43 83 2**33** **59** 61 2**83** | 59-19=40, 283-233=50
>
>
> **11** 35 75 2**25** **51** 53 2**75** | 51-11=40, 275-225=50
>
>
> **05** 29 69 2**19** **45** 47 2**69** | 45-05=40, 269-219=50
>
>
>
There are a few other simple additions with nice round numbers
>
> d5-d1 = 40, d3-d2 = 40, d4-d2 = 140 (100+40)
>
>
> d7-d4 = 50, d4-d3 = 150 (100+50)
>
>
> d7-d3 = 200
>
>
>
Another pattern exists in the second digit... but this might be seeing patterns where there aren't any. It might also be giving even more credibility to the modulo + offset theory. (base+offset)%10 works for the patterns below.
>
> 9, 3, 1 -> 9, 1, 3 -> **9**+2=1**1**+2=1**3**(drop the 10's)
>
>
> 1, 3, 5 -> **1**+2=**3**+2=**5**
>
>
> 5, 9, 7 -> 5, 7, 9 -> **5**+2=**7**+2=**9**
>
>
>
So:
>
> If d1 + 40 = d5, and d4 + 50 = d7, then I will guess d6+60 = d8
>
>
> logic: 5-1 = 4, 7-4 = 3, so 8-X = 2. X must be 6
>
>
> 61+60=121
>
>
> 53+60=113
>
>
> 47+60=107
>
>
> | Not sure about this answer but it's worth the try
Using the first sequence and repeadetly finding (negative) differences:
```
19 43 83 233 59 61 283 / -3929
24 40 150 -174 2 222/-4212
16 110 -324 176 220/-4434
94 -434 500 44/-4654
-528 934 -456/-4698
1462 -1390/-4242
-2852/-2852
```
I added numbers after the slash based off the bottom.
Then, I offset it by 8 and 14 for the other patterns, so I get
-3929
-3937
-3943 |
41,413 | My friend asked me for help with an IQ test and after she did it online she came back at me with the ones she couldn't solve.
Two of them however, I discovered are the same puzzle type, but no matter how much I look at it, I just can't see the logic in it. We redid the test and this puzzle occurred yet again, so now I have three versions of the same type of sequence written below.
>
> 19 43 83 233 59 61 283 ?
>
>
> 11 35 75 225 51 53 275 ?
>
>
> 5 29 69 219 45 47 269 ?
>
>
>
I get the feeling that this puzzle is easy, yet I just can't see it.
[Update]
By request, I give the five options for the answer of the top row that I wrote down during the second test.
The options are: 800 778 793 58 176.
I'm actually leaning towards Jonathan Allan's explanation of a mistake in some data entry for their automated question generation right now, since no one here seems to have solved it yet.
Prior to my post here, my friend emailed them asking them about this sequence, so most likely we will know between now and a few days.
[Update]
Looking at the options again, this puzzle is really really simple. Thank you smriti. | 2016/08/25 | [
"https://puzzling.stackexchange.com/questions/41413",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/29405/"
]
| How about we try to normalize the numbers by removing the first from all subsequent. Hereby we get
>
> 0 24 64 214 40 42 264
>
>
>
Every number has a 4 in it, with many 2's and 6's.
Work in progress for others to consider. Is there a pattern to the numbers now? | I don't know where it can lead, but (and for the first sequence only) :
(43 + 83) \* **2 -** 19 = 233
(59 + 61) \* **2 +** 43 = 283
Coincidence...? but this is not working for the 2 other sequences.
That was just to contribute a bit or give an idea to someone...
Above all that, either the scenario of the question is a reality... so nothing proves that the 3 sequences follow the same law... or it is a scenario to embed the question and, yes probably, the 3 sequences may follow one law... |
23,293,043 | Hi I have question about HTML form array and PHP. For example I have name and email but ask 6 times and I want to send this mail. What I should edit to work? thank you!
**HTML:**
```
<form method="Post" action="send.php" onSubmit="return validate();">
<?php
$amount=6; //amount shows the number of data I want to repeat
for( $i = 0; $i < $amount; $i++ ) {
?>
<b>Data <?php echo $i+1 ?>º</b>
<input type="edit" name="Name[]" size="40">
<input type="edit" name="email[]" size="40">
<br>
<?php } ?>
<input type="submit" name="Submit" value="send 6 data mail">
</form>
```
**send.php:**
```
<?php
require('phpmailer/class.phpmailer.php');
$name= $_POST['name[]'];
$email= $_POST['email[]'];
$mail = new PHPMailer();
...
$mail->Body = ' Data<br> '
<?php
$amount=6; //amount shows the number of data I want to repeat
for( $i = 0; $i < $amount; $i++ ) {
?> '
name: '.$name[$i].' email: '.$email[$i];
...
$mail->Send();
?>
```
should send:
```
Data
name: nameinput1 email: emailinput1
name: nameinput2 email: emailinput2
name: nameinput3 email: emailinput3
name: nameinput4 email: emailinput4
name: nameinput5 email: emailinput5
name: nameinput6 email: emailinput6
``` | 2014/04/25 | [
"https://Stackoverflow.com/questions/23293043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3572757/"
]
| I personally prefer to avoid dynamic stuff like ViewBag /ViewData as much as possible to transfer data between action methods and views. Let's build a strongly typed Viewmodel.
```
public class CreateCustomerVM
{
public string MidName{ get; set; }
[Required]
public string FirstName{ get; set; }
public string Surname{ get; set; }
public List<SelectListItem> MidNames { set;get;}
public CreateCustomerVM()
{
MidNames=new List<SelectListItem>();
}
}
```
and in your `Create` action method
```
public ActionResult Create()
{
var vm=new CreateCustomerVM();
vm.MidNames=GetMidNames();
return View(vm);
}
private List<SelectListItem> GetMidNames()
{
return new List<SelectListItem> {
new SelectListItem { Value="Mr", Text="Mr"},
new SelectListItem { Value="Ms", Text="Ms"},
};
}
```
and in your view, which is strongly typed to our viewmodel
```
@model CreateCustomerVM
@using(Html.Beginform())
{
<div>
Mid name : @Html.DropdownListFor(s=>s.MidName,Model.MidNames)
FirstName : @Html.TextBoxFor(s=>s.FirstName)
<input type="submit" />
</div>
}
```
Now when your form is posted, You will get the selected item value in the `MidName` property of the viewmodel.
```
[HttpPost]
public ActionResult Create(CreateCustomerVM customer)
{
if(ModelState.IsValid)
{
//read customer.FirstName , customer.MidName
// Map it to the properties of your DB entity object
// and save it to DB
}
//Let's reload the MidNames collection again.
customer.MidNames=GetMidNames();
return View(customer);
}
``` | Use this in your view:
```
@Html.DropDownListFor(x => x.ID, ViewBag.Names, new Dictionary<string, object>{{"class", "control-label col-md-2"}})
```
That should work. |
23,293,043 | Hi I have question about HTML form array and PHP. For example I have name and email but ask 6 times and I want to send this mail. What I should edit to work? thank you!
**HTML:**
```
<form method="Post" action="send.php" onSubmit="return validate();">
<?php
$amount=6; //amount shows the number of data I want to repeat
for( $i = 0; $i < $amount; $i++ ) {
?>
<b>Data <?php echo $i+1 ?>º</b>
<input type="edit" name="Name[]" size="40">
<input type="edit" name="email[]" size="40">
<br>
<?php } ?>
<input type="submit" name="Submit" value="send 6 data mail">
</form>
```
**send.php:**
```
<?php
require('phpmailer/class.phpmailer.php');
$name= $_POST['name[]'];
$email= $_POST['email[]'];
$mail = new PHPMailer();
...
$mail->Body = ' Data<br> '
<?php
$amount=6; //amount shows the number of data I want to repeat
for( $i = 0; $i < $amount; $i++ ) {
?> '
name: '.$name[$i].' email: '.$email[$i];
...
$mail->Send();
?>
```
should send:
```
Data
name: nameinput1 email: emailinput1
name: nameinput2 email: emailinput2
name: nameinput3 email: emailinput3
name: nameinput4 email: emailinput4
name: nameinput5 email: emailinput5
name: nameinput6 email: emailinput6
``` | 2014/04/25 | [
"https://Stackoverflow.com/questions/23293043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3572757/"
]
| I personally prefer to avoid dynamic stuff like ViewBag /ViewData as much as possible to transfer data between action methods and views. Let's build a strongly typed Viewmodel.
```
public class CreateCustomerVM
{
public string MidName{ get; set; }
[Required]
public string FirstName{ get; set; }
public string Surname{ get; set; }
public List<SelectListItem> MidNames { set;get;}
public CreateCustomerVM()
{
MidNames=new List<SelectListItem>();
}
}
```
and in your `Create` action method
```
public ActionResult Create()
{
var vm=new CreateCustomerVM();
vm.MidNames=GetMidNames();
return View(vm);
}
private List<SelectListItem> GetMidNames()
{
return new List<SelectListItem> {
new SelectListItem { Value="Mr", Text="Mr"},
new SelectListItem { Value="Ms", Text="Ms"},
};
}
```
and in your view, which is strongly typed to our viewmodel
```
@model CreateCustomerVM
@using(Html.Beginform())
{
<div>
Mid name : @Html.DropdownListFor(s=>s.MidName,Model.MidNames)
FirstName : @Html.TextBoxFor(s=>s.FirstName)
<input type="submit" />
</div>
}
```
Now when your form is posted, You will get the selected item value in the `MidName` property of the viewmodel.
```
[HttpPost]
public ActionResult Create(CreateCustomerVM customer)
{
if(ModelState.IsValid)
{
//read customer.FirstName , customer.MidName
// Map it to the properties of your DB entity object
// and save it to DB
}
//Let's reload the MidNames collection again.
customer.MidNames=GetMidNames();
return View(customer);
}
``` | populate in viewbag again in post action of create:
```
public ActionResult Create(){
ViewBag.Names= new SelectList(db.TbName, "ID", "MidName");
return View();
}
[HttpPost]
public ActionResult Create(){
ViewBag.Names= new SelectList(db.TbName, "ID", "MidName");
return View();
}
```
or try with helper like this:
```
@Html.DropDownListFor(x => x.ID, (SelectList)ViewBag.Names,
new Dictionary<string, object>{{"class", "control-label col-md-2"}})
``` |
57,575,105 | Is there a way to search for multiple conditions in the same column and then count the number of occurrences?
For example, I want to figure out how many times a specific combination of values (x and then y, x then w, x then z) occur after one another for each respective person.
I tried writing an IF statement but was told that dplyr would be a better route.
```
Dataframe:
c1 c2
person1 x
person1 y
person1 a
person1 a
person2 x
person2 w
person1 x
person1 z
df %>% select(c1, c2)
%>% tally(filter(c2 == "x")
%>% lead(filter(c2=="y")))
```
Expected results: a subset that displays the total number of times x then y, x then w, x then z, appear for each person.
```
c1 xy xw xz
Person 1 1 0 1
Person 2 0 1 0
```
R gives me the following error:
===============================
```
Error in UseMethod("filter_") :
no applicable methord for 'filter_' applied to an object of class
"logical"
``` | 2019/08/20 | [
"https://Stackoverflow.com/questions/57575105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9867193/"
]
| ```
library(dplyr)
c1 = c("person1",
"person1",
"person1",
"person1",
"person2",
"person2",
"person1",
"person1")
c2 = c("x","y","a","a","x","w","x","z")
df = as_tibble(cbind(c1,c2))
df %>%
group_by(c1) %>%
summarise(xy = sum(c2 == "x" & lead(c2, 1) == "y" ),
xw = sum(c2 == "x" & lead(c2, 1) == "w"),
xz = sum(c2 == "x" & lead(c2, 1) == "z"))
```
Gives you
```
# A tibble: 2 x 4
c1 xy xw xz
<chr> <int> <int> <int>
1 person1 1 0 1
2 person2 0 1 0
``` | An option using `spread`. Create a column by `paste`ing the 'c2' with the `lead` values of 'c2', `filter` only the selected elementss in 'newcol' using `%in%` and `spread` from 'long' to 'wide' format
```
library(tidyverse)
df %>%
mutate(newcol = str_c(c2, lead(c2)), ind = 1) %>%
select(-c2) %>%
filter(newcol %in% c('xy', 'xw', 'xz')) %>%
spread(newcol, ind, fill = 0)
```
### data
```
df <- structure(list(c1 = c("person1", "person1", "person1", "person1",
"person2", "person2", "person1", "person1"), c2 = c("x", "y",
"a", "a", "x", "w", "x", "z")), row.names = c(NA, -8L), class = c("tbl_df",
"tbl", "data.frame"))
``` |
17,449,157 | Having made the move to C++11, I am now systematically passing my strings by value in my constructors. But now, I realize that it makes it easier to introduce bugs when also using the value in the body of the constructor:
```
class A(std::string val):
_val(std::move(val))
{
std::cout << val << std::endl; // Bug!!!
}
```
What can I do to reduce the chances of getting it wrong? | 2013/07/03 | [
"https://Stackoverflow.com/questions/17449157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16877/"
]
| Name arguments whose purpose is to be moved-from in some distinctive manner, at least within the implementation of the constructor
```
A::A(std::string val_moved_from):
_val(std::move(val_moved_from))
{
std::cout << val_moved_from << std::endl; // Bug, but obvious
}
```
then move from them as early as possible (in the construction list, say).
If you have such a long construction list you can miss two uses of `val_moved_from` in it, this doesn't help.
An alternative would be to write up a proposal to fix this problem. Say, extend C++ so that the types or scopes of local variables can be changed by operations on them, so `std::safe_move(X)` both moves from `X` and marks `X` as an expired variable, no longer valid to use, for the remainder of its scope. Working out what to do when a variable is half-expired (expired in one branch, but not in another) is an interesting question.
Because that is insane, we can instead attack it as a library problem. To a certain limited extent, we can fake those kind of tricks (a variable whose type changes) at run time. This is crude, but gives the idea:
```
template<typename T>
struct read_once : std::tr2::optional<T> {
template<typename U, typename=typename std::enable_if<std::is_convertible<U&&, T>::value>::type>
read_once( U&& u ):std::tr2::optional<T>(std::forward<U>(u)) {}
T move() && {
Assert( *this );
T retval = std::move(**this);
*this = std::tr2::none_t;
return retval;
}
// block operator*?
};
```
ie, write a linear type that can only be read from via `move`, and after that time reading `Assert`s or throws.
Then modify your constructor:
```
A::A( read_once<std::string> val ):
_val( val.move() )
{
std::cout << val << std::endl; // does not compile
std::cout << val.move() << std::endl; // compiles, but asserts or throws
}
```
with forwarding constructors, you can expose a less ridiculous interface with no `read_once` types, then forward your constructors to your "safe" (possibly `private`) versions with `read_once<>` wrappers around the arguments.
If your tests cover all code paths, you'll get nice `Assert`s instead of just empty `std::string`s, even if you go and `move` more than once from your `read_once` variables. | "Having made the move to C++11, I am now systematically passing my strings by value in my constructors."
I'm sorry, I don't see why one would want to do this. What improvement does this provide in relation to the traditional method? (which is basically bug proof).
````
class A(const std::string & s):
_val(s)
{
std::cout << s << std::endl; // no Bug!!!
std::cout << _val << std::endl; // no Bug either !!!
}
```` |
23,395,932 | Is it possible to overload = operator of type double?
I have the following:
```
double operator=(double a, Length b) {
return a = (b.getInches()/12+b.getFeet())*3.2808*0.9144;
}
```
It throws the following error:
```
'double operator=(double, Length)' must be a nonstatic member function
```
What am I doing wrong? | 2014/04/30 | [
"https://Stackoverflow.com/questions/23395932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1527217/"
]
| You cannot overload operators for builtin (integral or floating point) types like `double`, and also you cannot globally overload the `=` operator for *any* type. The `=` operator can only be overloaded as a class member function.
See also: [Can I define an operator overload that works with built-in / intrinsic / primitive types?](http://www.parashift.com/c++-faq/intrinsics-and-operator-overloading.html) | You cannot overload the assignment operator for a primitive type, but you can supply an operator that converts `Length` to `double`, giving you the desired effect:
```
class Length {
...
public:
operator double() {
return (getInches()/12+getFeet())*3.2808*0.9144;
}
};
main() {
Length len = ...;
...
double d = len;
}
```
Note that this conversion should be done only when the conversion is perfectly clear to the reader. For example, in this case you should make a `get_yard` member function, like this:
```
class Length {
...
public:
double get_yards() {
return (getInches()+12*getFeet())/ 36.0;
}
};
```
Note that you do not need to convert feet to meters and then to yards - you can go straight from feet to yards; the conversion factor is `3.0`. You can also do the division last - see the modified expression above. |
57,748,100 | When any element with `.mytrigger` is clicked, `.myactive` will be toggled on element with `#mytarget`.
I have the following code:
```js
var navclick = document.getElementsByClassName("mytrigger");
for (var i = 0; i < navclick.length; i++) {
navclick[i].onclick = function() {
document.getElementById('mytarget').classList.toggle("myactive");
}
}
```
```css
.myactive {
background-color: blue;
color: white;
}
```
```html
<a class="mytrigger">Button</a>
<div id="mytarget"><p>Hello</p></div>
<a class="mytrigger">Button</a>
```
I need to have multiple triggers and from that this became confusing so I am unable to figure out the correct code. I can't use jquery for this. | 2019/09/01 | [
"https://Stackoverflow.com/questions/57748100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11282590/"
]
| Make as many as elements you want with class ".mytrigger" Just put onclick function as mentioned.
I hope this helps:-
If not then please clarify your problem
**HTML CODE**
```
<a onclick="myFunction()" class="mytrigger">Button</a>
<div id="mytarget"><p>Hello</p></div>
<a onclick="myFunction()" class="mytrigger">Button</a>
```
**Javascript CODE**
```
function myFunction() {
var element = document.getElementById("mytarget");
element.classList.toggle("myactive");
}
``` | Using your code, I just changed *document.getElementsById* to *document.getElementById* (removing the s).
```js
var navclick = document.getElementsByClassName("mytrigger");
for (var i = 0; i < navclick.length; i++) {
navclick[i].onclick = function() {
document.getElementById("mytarget").classList.toggle('myactive');
}
}
```
```css
.myactive {
background-color: blue;
color: white;
}
```
```html
<button class="mytrigger">Button
</button>
<div id="mytarget"><p>Hello</p>
</div>
<button class="mytrigger">Button
</button>
``` |
57,748,100 | When any element with `.mytrigger` is clicked, `.myactive` will be toggled on element with `#mytarget`.
I have the following code:
```js
var navclick = document.getElementsByClassName("mytrigger");
for (var i = 0; i < navclick.length; i++) {
navclick[i].onclick = function() {
document.getElementById('mytarget').classList.toggle("myactive");
}
}
```
```css
.myactive {
background-color: blue;
color: white;
}
```
```html
<a class="mytrigger">Button</a>
<div id="mytarget"><p>Hello</p></div>
<a class="mytrigger">Button</a>
```
I need to have multiple triggers and from that this became confusing so I am unable to figure out the correct code. I can't use jquery for this. | 2019/09/01 | [
"https://Stackoverflow.com/questions/57748100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11282590/"
]
| Make as many as elements you want with class ".mytrigger" Just put onclick function as mentioned.
I hope this helps:-
If not then please clarify your problem
**HTML CODE**
```
<a onclick="myFunction()" class="mytrigger">Button</a>
<div id="mytarget"><p>Hello</p></div>
<a onclick="myFunction()" class="mytrigger">Button</a>
```
**Javascript CODE**
```
function myFunction() {
var element = document.getElementById("mytarget");
element.classList.toggle("myactive");
}
``` | Using [addEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener):
It sets up a function that will be called whenever the specified event is delivered to the target.
```
document.getElementsByClassName('mytrigger').addEventListener('click', function() {
document.getElementById('mytarget').classList.toggle("myactive");
});
```
Using `document.bind`:
```
document.bind('click', '.mytrigger', function(){
document.getElementById('mytarget').classList.toggle("myactive");
});
``` |
48,057,433 | The following query returns
```
select to_char( trunc(sysdate) - numtoyminterval(level - 1, 'month'), 'mon-yy') as month from dual connect by level <= 12
```
last 12 months according to today's date(i.e. 2-Jan-18).
[](https://i.stack.imgur.com/Sd9ZQ.png)
Say if today's date is 29-DEC-17 it gives oracle sql error:
**ORA-01839: date not valid for month specified**
(since on subtracting there would be a date in the result as **'29-FEB-17'** which is not possible). So on specific dates this error would pop-up. How do you suggest to overcome this? | 2018/01/02 | [
"https://Stackoverflow.com/questions/48057433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7906671/"
]
| `char` is `signed` on your platform.
If you use `unsigned char` for your types for `c2` and `c1` then the implicit promotion to `int` for each term in your expression will have the effect you are after. | You can use multiplication instead of shifting:
```
int i = (int)c2 * 256 + c1;
``` |
22,499,848 | I am looking for a way to get the content of the webpage using the url. For instance lets say when you go to www.example.com, you see the text "hello world". I want to get the text hello world in razor c#.
In other words, I need a replacement of the following jquery code using c#:
```
$.post("www.example.com",{},function(data){
useme(data);
})
``` | 2014/03/19 | [
"https://Stackoverflow.com/questions/22499848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/991609/"
]
| ```
var html = Html.Raw(new System.Net.WebClient().DownloadString("http://www.example.com"));
```
`Html.Raw` allows in parsing to HTML while a new instance of `WebClient` can help with directly fetching the string. | You can use the [WebClient class DownloadString](http://msdn.microsoft.com/en-us/library/ms144200%28v=vs.110%29.aspx) method to obtain the content of a remote page:
```
using (var client = new WebClient()){
var response = client.DownloadString("http://www.example.com");
// process response
}
```
If the response type is `text/plain`, you should get just "Hello World", but of the response type is `text/html`, you will need to parse out the text. You can use the [HtmlAgilityPack](http://htmlagilitypack.codeplex.com/) for that. |
61,544,349 | *"Do not embed secrets related to authentication in source code"* - [one may hear frequently](https://cloud.google.com/docs/authentication/production#best_practices_for_managing_credentials). Okay, so I use the [Key Management Service](https://cloud.google.com/kms) and [Secret Manager](https://cloud.google.com/secret-manager).
But then, **how do I correctly access secrets stored there from Compute Engine's VM and from my local dev environment?**
I can think of either:
1. Accessing the secrets using the [default Service Account credentials](https://cloud.google.com/docs/authentication/production#obtaining_credentials_on_compute_engine_kubernetes_engine_app_engine_flexible_environment_and_cloud_functions), but then how do I access the secrets in the local development environment and inside of my local Docker containers (ie. outside the Compute Engine)?
2. Accessing the secrets using a [custom Service Account](https://cloud.google.com/docs/authentication/production#creating_a_service_account), but then I need to store its JSON key somewhere and access it from my code. For that I have two options:
2.1. Store it with the source code, so I have it on dev machine and in the Docker container. But then that goes against the opening statement *"Do not embed secrets ... in source code"*. Bad idea.
2.2. Store it somewhere on my dev machine. But then how do my Docker container accesses it? I could provide the key as Docker secret, but wouldn't that be yet again *"embedding in source code"*? Upon starting the container on my VM I'd need to provide that secret from somewhere, yet again going back to question of how the secret arrives at the VM in the first place.
I know that [Application Default Credentials](https://cloud.google.com/docs/authentication/production#finding_credentials_automatically) (ADC) can try to use option 2 and then fallback on option 1 - yet, how do I solve the conflict from option 2? Where should the Service Account credentials reside to be accesible in both my local dev and in a local container - and not *embedded in the source code*? | 2020/05/01 | [
"https://Stackoverflow.com/questions/61544349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3508719/"
]
| I found one way to make this work, (*sortof*):
* On local dev env rely on `GOOGLE_APPLICATION_CREDENTIALS` to point to the Service Account credentials manually downloaded from the GCP.
* On local Docker container, provide that same file as a secret. My app then searches `/run/secrets/` for it if `GOOGLE_APPLICATION_CREDENTIALS` is not set.
* On Compute Engine VM, download that file from a Google Storage bucket (having previously uploaded it). [Given that the default Service Account is used](https://cloud.google.com/docs/authentication/production#obtaining_credentials_on_compute_engine_kubernetes_engine_app_engine_flexible_environment_and_cloud_functions) if no other credential is specified, I'm able to [`gutils cp`](https://cloud.google.com/storage/docs/downloading-objects#gsutil) that file from a bucket. Then provide that downloaded file as a secret to the container.
Still, I'm still not sure if that's good from the side of *not embedding in the source code*. It also feels quite manual with all the uploading and downloading the credentials from the bucket. Any hints on how to improve this authentication most welcome. | Your Idea with cloud storage is good and workaround your needs; The easiest way to access the secrets stored on Secret Manager from a VM instance will be by curl, gcloud command or python script by ["accessing a secret version"](https://cloud.google.com/secret-manager/docs/creating-and-accessing-secrets#access_a_secret_version) then store them as an ephemeral variable in the code it's meant to be used. The service account to use could be CE default service account just keep in mind it has to have secretmanager.secretAccessor and/or secretmanager.admin roles to be able to grab them from SM. Additional make sure the VM instance has the correct API scopes for all GCP resources or at least to security API's. |
31,415,188 | I have an ASP.NET MVC app written in C#. One of my actions looks like this:
```
[HttpPost]
public async Task<ActionResult> Save(int id, MyViewModel viewModel)
{
viewModel.SaveToDb();
await Backup.Save(viewModel);
return View(viewModel);
}
```
...
```
public class Backup
{
async public static Task Save(IBackup item)
{
// do stuff
}
}
```
There is actually a lot going on in the Backup.Save function. In fact, `await Backup.Save(...)` is currently taking 10 seconds. For that reason, I want to run it in the background (asynchronously) and not (a)wait on it. I thought if I just removed the `await` keyword, it would work. However, it does not appear that is the case.
How can I run Backup does save asynchronously in the background so that my users can continue using the app without long wait times?
Thank you! | 2015/07/14 | [
"https://Stackoverflow.com/questions/31415188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1185425/"
]
| See here for a discussion of this:
[Can I use threads to carry out long-running jobs on IIS?](https://stackoverflow.com/questions/536681/can-i-use-threads-to-carry-out-long-running-jobs-on-iis)
One simple alternative without having to use threads or queues would be to make an additional async call via the client, possibly via Ajax assuming the client is a browser.
If you need the view model back immediately, then potentially split this into two methods. One that gets the view model, and then you call a second method that does the save in the background.
This should work fine since if you are happy to return right away, you have already implicitly agreed to decoupled the dependency between the two actions.
It is a bit of a hack, since the client is now requesting an action it may not need to know or care about. | you can make a method that takes an action or a function (whatever you need), and runs a thread with whatever you need to run in the background.
Basically whatever way you choose to make it, run the method in a separate thread. |
10,947,628 | I want to get distance text from following link. i have used NSXML parsing but unable to get the result. please tell me which xml method should i used for following xml.
<http://maps.googleapis.com/maps/api/directions/xml?origin=30.9165904,75.8634752&destination=30.89314000,75.86938000&sensor=true>
Thanks to all | 2012/06/08 | [
"https://Stackoverflow.com/questions/10947628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1314522/"
]
| Grid view can be really powerful if used correctly, one of the things you can do is hook onto an event (on data row bound) which will allow you to manipulate each row at a time.
ASP.NET is more event driven than PHP, however if you still want to do things the PHP way you could in theory loop through each result.
```
using (
var oConn =
new SqlConnection(
ConfigurationManager.ConnectionStrings["myConnectionStringNameFromWebConfig"].ConnectionString)
)
{
oConn.Open();
using (SqlCommand oCmd = oConn.CreateCommand())
{
oCmd.CommandType = CommandType.StoredProcedure;
oCmd.CommandText = "p_jl_GetThemeForPortal";
oCmd.Parameters.Add(new SqlParameter("@gClientID", clientID));
}
using(var oDR = oCmd.ExecuteReader())
{
while(oDR.Read())
{
string x = (string)oDR["ColumnName"];
int y = (int) oDR["ColumnName2"];
// Do something with the string and int
}
}
}
```
This pattern (by using using statements) ensures your connections are closed at the end of each fetch sequence, so you don't have lots of open DB connections kicking around | For more control over the rendering, you can use a [ListView](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview). Scroll down to the bottom of that page for an example. |
10,947,628 | I want to get distance text from following link. i have used NSXML parsing but unable to get the result. please tell me which xml method should i used for following xml.
<http://maps.googleapis.com/maps/api/directions/xml?origin=30.9165904,75.8634752&destination=30.89314000,75.86938000&sensor=true>
Thanks to all | 2012/06/08 | [
"https://Stackoverflow.com/questions/10947628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1314522/"
]
| Grid view can be really powerful if used correctly, one of the things you can do is hook onto an event (on data row bound) which will allow you to manipulate each row at a time.
ASP.NET is more event driven than PHP, however if you still want to do things the PHP way you could in theory loop through each result.
```
using (
var oConn =
new SqlConnection(
ConfigurationManager.ConnectionStrings["myConnectionStringNameFromWebConfig"].ConnectionString)
)
{
oConn.Open();
using (SqlCommand oCmd = oConn.CreateCommand())
{
oCmd.CommandType = CommandType.StoredProcedure;
oCmd.CommandText = "p_jl_GetThemeForPortal";
oCmd.Parameters.Add(new SqlParameter("@gClientID", clientID));
}
using(var oDR = oCmd.ExecuteReader())
{
while(oDR.Read())
{
string x = (string)oDR["ColumnName"];
int y = (int) oDR["ColumnName2"];
// Do something with the string and int
}
}
}
```
This pattern (by using using statements) ensures your connections are closed at the end of each fetch sequence, so you don't have lots of open DB connections kicking around | example aspx:
```
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="CountryID" HeaderText="ID" ItemStyle-HorizontalAlign="Center" />
<asp:TemplateField HeaderText="Flag" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<img src='<%# "img/flags/" + Eval("CountryFlag").ToString()%>' alt="flag" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CountryName" HeaderStyle-HorizontalAlign="Left" HeaderText="Name" ItemStyle-CssClass="dg_title"/>
<asp:TemplateField HeaderText="VAT" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<%# CheckBool(Convert.ToBoolean(Eval("CalculateVat"))) %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
```
in the code behind the `CheckBool` is a function I have made:
```
public string CheckBool(bool toCheck)
{
if (toCheck)
return "<img src=\"img/checked.png\" alt=\"Yes\" />";
else
return "<img src=\"img/deleted.png\" alt=\"No\" />";
}
```
and in the `Page_Load`
```
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = SsUtils.GetCountries();
GridView1.DataBind();
}
```
`SsUtils` is a static class and the `GetCountries` returns a `List<Country>` which is a collection of the class country. But you can also use a `DataSet` or `DataTable` as datasource for your gridview.
This is just a sample, to show some possibilities. You can also have edit buttons, paging, sorting etc. with a gridview. |
10,947,628 | I want to get distance text from following link. i have used NSXML parsing but unable to get the result. please tell me which xml method should i used for following xml.
<http://maps.googleapis.com/maps/api/directions/xml?origin=30.9165904,75.8634752&destination=30.89314000,75.86938000&sensor=true>
Thanks to all | 2012/06/08 | [
"https://Stackoverflow.com/questions/10947628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1314522/"
]
| first: Write your code on server side on Page\_load or in any other method for selecting
record.
and for selecting record from database you can use the following code
```
string myConnectionString="server=dbserver;database=mydatabase;uid=user;pwd=password;Connect Timeout=120;pooling=true;Max Pool Size=60;";// you can place your connection string in web.config
SqlConnection con = new SqlConnection(myConnectionString);
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = @"SELECT [stuff] FROM [tableOfStuff]";
con.Open();
SqlDataReader dr = null;
try
{
dr = cmd.ExecuteReader();
while(dr.Read())
{
// construct your html for your table data here
}
}
catch(SomeTypeOfException ex){ /* handle exception */ }
``` | For more control over the rendering, you can use a [ListView](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview). Scroll down to the bottom of that page for an example. |
10,947,628 | I want to get distance text from following link. i have used NSXML parsing but unable to get the result. please tell me which xml method should i used for following xml.
<http://maps.googleapis.com/maps/api/directions/xml?origin=30.9165904,75.8634752&destination=30.89314000,75.86938000&sensor=true>
Thanks to all | 2012/06/08 | [
"https://Stackoverflow.com/questions/10947628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1314522/"
]
| first: Write your code on server side on Page\_load or in any other method for selecting
record.
and for selecting record from database you can use the following code
```
string myConnectionString="server=dbserver;database=mydatabase;uid=user;pwd=password;Connect Timeout=120;pooling=true;Max Pool Size=60;";// you can place your connection string in web.config
SqlConnection con = new SqlConnection(myConnectionString);
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = @"SELECT [stuff] FROM [tableOfStuff]";
con.Open();
SqlDataReader dr = null;
try
{
dr = cmd.ExecuteReader();
while(dr.Read())
{
// construct your html for your table data here
}
}
catch(SomeTypeOfException ex){ /* handle exception */ }
``` | example aspx:
```
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="CountryID" HeaderText="ID" ItemStyle-HorizontalAlign="Center" />
<asp:TemplateField HeaderText="Flag" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<img src='<%# "img/flags/" + Eval("CountryFlag").ToString()%>' alt="flag" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CountryName" HeaderStyle-HorizontalAlign="Left" HeaderText="Name" ItemStyle-CssClass="dg_title"/>
<asp:TemplateField HeaderText="VAT" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<%# CheckBool(Convert.ToBoolean(Eval("CalculateVat"))) %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
```
in the code behind the `CheckBool` is a function I have made:
```
public string CheckBool(bool toCheck)
{
if (toCheck)
return "<img src=\"img/checked.png\" alt=\"Yes\" />";
else
return "<img src=\"img/deleted.png\" alt=\"No\" />";
}
```
and in the `Page_Load`
```
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = SsUtils.GetCountries();
GridView1.DataBind();
}
```
`SsUtils` is a static class and the `GetCountries` returns a `List<Country>` which is a collection of the class country. But you can also use a `DataSet` or `DataTable` as datasource for your gridview.
This is just a sample, to show some possibilities. You can also have edit buttons, paging, sorting etc. with a gridview. |
27,216,471 | I'm trying to create a custom iOS 8 keyboard. I am using Interface Builder to arrange the keyboard layout. I have two NIB files, one for iPhone 6 and one for iPhone 5.
There are certain apps that are "scaled" up for the iPhone 6. For these apps, I want to load the iPhone 5 NIB (the iPhone 6 NIB goes off the screen).
**Is there any way to determine if the current app running is running on "scaled" mode?**
Unfortunately checking UIScreen mainScreen's attributes does not give me a difference between native iPhone 6 app vs scaled iPhone 6 app. | 2014/11/30 | [
"https://Stackoverflow.com/questions/27216471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834310/"
]
| In scaled app `[UIScreen mainScreen].scale` and `[UIScreen mainScreen].nativeScale` not be the same. | If your app is designed for iPhone 5 the `scale` and `nativeScale` properties will match when running your app on an iPhone 6 because both phones have a 2.0x native scale factor.
Instead, you can use `[[UIScreen mainScreen] nativeBounds]` to see the bounds of the screen in pixels. For example, when running an app designed for iPhone 5 on an iPhone 6 you'll see the bounds of an iPhone 5 (640x1136):
`Native Bounds: {{0, 0}, {640, 1136}}`
But when running an app designed for iPhone 6 you'll get the bounds of an iPhone 6 (750x1334):
`Native Bounds: {{0, 0}, {750, 1334}}`
You can log the `CGRect` returned by the `nativeBounds` property with the `NSStringFromCGRect()` function.
Additionally, there's an awesome guide to iOS screen sizes from the folks at PaintCode: <http://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions>. |
465,531 | I have tried right clicking on the file selecting properties and then the permissions tab and setting it to execute. However, when I double click the file it opens in gedit. What do I do? | 2014/05/14 | [
"https://askubuntu.com/questions/465531",
"https://askubuntu.com",
"https://askubuntu.com/users/276476/"
]
| To run your script by double clicking on its icon, you will need to create a `.desktop` file for it:
```
[Desktop Entry]
Name=My script
Comment=Test hello world script
Exec=/home/user/yourscript.sh
Icon=/home/user/youricon.gif
Terminal=false
Type=Application
```
Save the above as a file on your Desktop with a `.desktop` extension. Change `/home/user/yourscript.sh` and `/home/user/youricon.gif` to the paths of your script and whichever icon you want it ot have respectively and then you'll be able to launch by double clicking it.
---
Specifically, for your situation, you need to do:
1. Create a script that runs `mono LOIC.exe`. To do so, create a new text file with these contents:
```
#!/bin/bash
mono /home/logan/.loic/LOIC.exe
```
Save this as `/home/locan/run_loic.sh` and then run this command to make it executable (or right click => properties and choose "Allow executing file as program"):
```
chmod +x /home/logan/.loic/LOIC.exe
```
2. Create a `.desktop` file that launches that script. Create a new text file on your Desktop called `run_loic.desktop` with these contents:
```
[Desktop Entry]
Name=Run LOIC
Comment=Run LOIC
Exec=/home/logan/run_loic.sh
Icon=
Terminal=false
Type=Application
``` | File Manager > Edit > Preferences > Behaviour forExecutable Text Files. In Ubuntu it is set to View Executable Files when they are opened
i prefer set it to "Ask each time" like the previous version of ubuntu. |
45,235,912 | In the main window I can set CSS styles for different standard widgets:
>
> setStyleSheet("QComboBox { background-color: red; } QLabel { background-color: blue; }")
>
>
>
These styles will be applied in child widgets with those names.
But is it possible to set styles for widgets defined by me in the same fashion?
Then this widget should obtain its style by its class name. I can't seem to find corresponding function that would obtain the style sheet by class name.
Here is an example.
---custom-widget.h---
```
#include <QWidget>
class MyCustomWidget : public QWidget {
Q_OBJECT
public:
MyCustomWidget(QWidget *parent) : QWidget(parent) { }
};
```
---main.cpp---
```
#include <QApplication>
#include <QWidget>
#include <QLayout>
#include <QLabel>
#include "custom-widget.h"
int main(int argc, char **argv) {
QApplication app (argc, argv);
QWidget mainWindow;
QVBoxLayout mainLayout(&mainWindow);
QLabel label("I am a label", &mainWindow);
MyCustomWidget customWidget(&mainWindow);
mainLayout.addWidget(&label);
mainLayout.addWidget(&customWidget);
customWidget.setMinimumSize(100, 300);
mainWindow.setStyleSheet(
"QLabel { background-color: #5ea6e3; }"
"MyCustomWidget { background-color: #f00000; }"
);
mainWindow.show();
return app.exec();
}
```
---main.pro---
```
CONFIG += qt
QT += core gui widgets
TEMPLATE = app
TARGET = main
HEADERS = main.h custom-widget.h
SOURCES = main.cpp
``` | 2017/07/21 | [
"https://Stackoverflow.com/questions/45235912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7827768/"
]
| Yes, styles will work just fine on your own widgets.
If you have non-standard properties you want to set, you'll need to declare them using `Q_PROPERTY`. For example:
```c++
class MyWidget : public QWidget
{
Q_OBJECT
Q_PROPERTY(QString extra READ extra WRITE setExtra)
//...
};
```
You can then style it:
```css
MyWidget {
background-color: blue;
color: yellow;
qproperty-extra: "Some extra text";
}
```
For the widget in your code sample, the background is never drawn. Its constructor needs to be changed to ask Qt to draw the background using the style information:
```
MyCustomWidget(QWidget *parent) : QWidget(parent) {
setAttribute(Qt::WA_StyledBackground);
}
``` | When applying stylesheets to a custom QWidget-derived class, do not forget to override the paintEvent as mentionned in [the documentation](http://doc.qt.io/qt-5/stylesheet-reference.html):
>
> QWidget Supports only the background, background-clip and
> background-origin properties.
>
>
> If you subclass from QWidget, you need to provide a paintEvent for
> your custom QWidget as below
>
>
> Warning: Make sure you define the Q\_OBJECT macro for your custom widget.
>
>
>
```
void CustomWidget::paintEvent(QPaintEvent *)
{
QStyleOption opt;
opt.init(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
``` |
12,929,165 | how to create sql server cte from a while loop
my loop like this
```
declare @ind as int
declare @code as nvarchar
set @ind = 0
while @ind < 884
begin
select @ind = @ind + 1
--here execute Procedure
--and set return value to variable
set @code = cast (@ind as nvarchar)
end
``` | 2012/10/17 | [
"https://Stackoverflow.com/questions/12929165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1743326/"
]
| If you need table:
```
;WITH Sec(Number) AS
(
SELECT 0 AS Number
UNION ALL
SELECT Number + 1
FROM Sec
WHERE Number < 884
)
SELECT * FROM Sec
OPTION(MAXRECURSION 0)
```
If you need one string:
```
;WITH Sec(Number) AS
(
SELECT 0 AS Number
UNION ALL
SELECT Number + 1
FROM Sec
WHERE Number < 884
)
SELECT STUFF(a.[Str], 1, 1, '')
FROM
(
SELECT (SELECT ',' + CAST(Number AS NVARCHAR(3))
FROM Sec
FOR XML PATH(''), TYPE
).value('.','varchar(max)') AS [Str]
) AS a
OPTION(MAXRECURSION 0)
``` | Below query selects values from 0 to 884:
```
;WITH T(Num)AS
(
SELECT 0
UNION ALL
SELECT Num+1 FROM T WHERE T.Num < 884
)SELECT Num FROM T
OPTION (MAXRECURSION 0);
``` |
67,681,547 | I want to set some variables getting they from the values of 5 select elements, the multiselect IDs have the same name that the variable names in the script....
Inside HTML part:
```
<select id="variable1">
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
</select>
<select id="variable2">
<option value="algo1">algo1</option>
<option value="algo2">algo2</option>
<option value="algo3">algo3</option>
</select>
<!-- etc -->
```
and in the jQuery script:
```
var variable1;
var variable2;
var variable3;
var variable4;
var variable5;
$("#variable1, #variable2, #variable3, #variable4, #variable5").change(function(){
var valorAcambiar = $(this).attr('id');
valorAcambiar = $(this).val();
});
```
So I'm trying this, but doesn't work... I think the problem is that the script is not running the selected strings values from the ID attr of the select elements as variable names for the script, some one could please help me?
I mean, I want that "valorAcambiar" takes the name of variable1 (coming from id attr of select element) or any other, to change global variable1 (or any other) value in the script.
So I can get variable1 = 20 for example if someone changes variable1 select, or variable2 = algo3 for example if someone changes variable2 select, and this for the 5 multiselect elements.
Thanks. | 2021/05/25 | [
"https://Stackoverflow.com/questions/67681547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10950209/"
]
| Use a setInterval and set it to one **second** => `1000`
```js
let display = document.getElementById('display')
let x = display.textContent;
// textContent returns a string value
setInterval(()=>{
// lets change the string value into an integer using parseInt()
// parseInt would not be needed if the value of x was `typeof` integer already
display.textContent = parseInt(x++)
}, 1000)
```
```html
<div id="display">2</div>
``` | You can use javascript setInterval function <https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval>
For example:
```
var x = 0;
setInterval(() => {
x = x + 1;
}, 1000); //1000ms = 1 second
```
Then each second it will increment the "x" variable. |
40,827,044 | I'm using SQLite's `last_insert_rowid()` to grab the last inserted row ID following a batch insert. Is there any risk of race conditions that could cause this value to not return the last id of the batch insert? For example, is it possible that in between the completion of the insert and the calling of `last_insert_rowid()` some other process may have written to the table again? | 2016/11/27 | [
"https://Stackoverflow.com/questions/40827044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/411954/"
]
| `last_insert_rowid()` returns information about the last insert done in this specific connection; it cannot return a value written by some other process.
To ensure that the returned value corresponds to the current state of the database, take advantage of SQLite's [ACID](http://en.wikipedia.org/wiki/ACID) guarantees (here: atomicity): wrap the batch inserts, the `last_insert_rowid()` call, and whatever you're doing with the ID inside a single transaction.
In any case, the return value of `last_insert_rowid()` changes only when some insert is done through this connection, so you should never access the same connection from multiple threads, or if you really want to do so, manually serialize entire transactions. | `last_insert_rowid()` is connection-dependent, so there is a risk when multiple threads are using the same connection, without SQLite switched to Serialized threading mode. |
35,555,849 | I'm fairly new to Qt and therefor try to find out how things are working. Especially for QTreeView this seems to be quite difficult: the documentation and the example that come from Qt are (at least for me) more or less cryptic. I'd guess one will understand this documentation only when one already knows how it works.
So: could someone give an example or an link to an example which is beginner-suitable and demonstrates the usage of QTreeView? Means which demonstrates how to add a node and some child nodes to it?
Thanks! | 2016/02/22 | [
"https://Stackoverflow.com/questions/35555849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1138160/"
]
| Maybe [this mini example](http://www.java2s.com/Code/Cpp/Qt/QTreeViewdemoandQStandardItem.htm) can help you.
But to understand it you have to grasp the Model-View concept. The idea is that you **don't** add to the view, you add to the model and the view updates itself. | You can start with the combination of `QStandardItemModel` and `QTreeView`.
Set the proper row and column count of your model by `QStandadItemModel::setRowCount()` and `QStandardItemModel::columnCount()`.
Then you can insert a QStandardItem instance into the particular cell of the model with the `QStandardItemModel::setItem()`.
`QStandardItem` has a similar interface to `QStandardItemModel` for creating child rows and columns and inserting a child items: `QStandardItem::setRowCount()`, `QStandardItem::setColumnCount()` and `QStandartItem::setChild()`.
I can prepare an example if you need one. |
54,662,572 | It seems the backward compatibility of SSIS covered from SQL server 2008R2 to SQL server 2017 (since an instance with SQL server 2017 installed can proceed SSIS package with PackageFormatVersion = 3)
The question is why do we need to update the SSIS package (.dtsx)
Is there any performance boost or other necessaries by updating the SSIS package? | 2019/02/13 | [
"https://Stackoverflow.com/questions/54662572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3686334/"
]
| It is highly recommended to update packages because each new release of SQL Server contains new features, bug fixes, performance improvement. There are many articles describing the features of each release as example:
* in SQL Server 2016 package parts was founded which guarantee high re-usability
* ODATA components were added later than 2008 R2
You can refer to the following pages for more information:
* [SQL Server Integration Services SSIS Versions and Tools](https://www.mssqltips.com/sqlservertutorial/9054/sql-server-integration-services-ssis-versions-and-tools/)
* [Stackoverflow - SSIS tag info](https://stackoverflow.com/tags/ssis/info)
**Also not that [the support of SQL Server 2008 R2 will end soon](https://blogs.msdn.microsoft.com/sqlreleaseservices/end-of-mainstream-support-for-sql-server-2008-and-sql-server-2008-r2/)** *(July 9, 2019)* | The SSIS execution engine can run packages that are current version or older. That's been a feature since the second release.
Why then should we upgrade SSIS packages from an older version to the current version since the execution engine can run them "as is?" I can think of a few reasons why you would want to do this.
Execution performance
=====================
The SSIS engines reads the XML that is an SSIS package from disk. It identifies that the package version does not match the runtime engine version so before it can do anything else, it must first upgrade the in-memory representation of that package to the current version. Package execution can then commence. Package completes and then it throws away all the work it did to upgrade to current version. Maybe that takes a picosecond, maybe it takes a minute for that upgrade to occur. You'll be paying that penalty for each and every package execution.
With SSIS, the addition of a second or two and the ensuing CPU usage for upgrade may not factor much into the overall load on the server as package run times usually measure in minutes if not hours, but I always believed in being a good steward of my resources.
New Features
============
As Yahfoufi mentions, there's lots of new features packed into the varying releases. I find the leap from 2008 to 2012 especially compelling as the move from the Package Deployment model to Project Deployment model is exceptionally compelling as logging, configuration are automagic and execution from SSMS is easily accomplished. |
15,202,513 | I am trying to calculate the monthly payment of a loan and it always comes out wrong.
The formula is as follows where i is interest
```
((1 + i)^months /
(1 + i)^months - 1)
* principal * i
```
Assuming that annual interest rate and principal is an invisible floating point, can you tell me what's wrong with my formula?
```
double calculatePaymentAmount(int annualInterestRate,
int loanSize,
int numberOfPayments;
{
double monthlyInterest = annualInterestRate / 1200.0;
return
(
pow(1 + monthlyInterest, numberOfPayments) /
(pow(1 + monthlyInterest, numberOfPayments) - 1)
)
* (loanSize / 100)
* monthlyInterest;
}
```
For example: an interest rate of 1.25 and a loan size of 250 for 12 months gives 22.27 instead of 20.97.
Thank you in advance.
Edit 1: Changed monthly interest to annualInterestRate / 1200 | 2013/03/04 | [
"https://Stackoverflow.com/questions/15202513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1892641/"
]
| If you didn't, `john.property` would be undefined. | The `this` keyword is used to refer to the owner of the function executed:
<http://www.quirksmode.org/js/this.html>
As said, you need it to define the `john.property`, because the `property` variable passed to the function will expire once the function is executed. |
22,912,327 | I have the following PHP code to resize an image (i know this image will be a png so no need for checking...)
```
// The file
//$filename = $_POST['original'];
$filename = 'planets.png';
// Set a maximum height and width
$width = 200;
$height = 200;
// Content type
header('Content-Type: image/png');
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Resample
$image_p = imagecreatetruecolor($width, $height);
imagecreatefrompng($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output
imagepng($image_p);
```
However, I would like to be able to return this to my page via ajax... see the code below:
```
<div data-img-src="planets.png"></div>
<script type="text/javascript">
$("div[data-img-src]").each( function() {
$.ajax({
type: "POST",
url: "/image-resize.php",
data: {
original: $(this).attr("data-img-src")
},
dataType: "html",
success: function(result) {
$(this).append(result);
}
});
});
</script>
```
Any ideas what I need to do to make this work??
**EDIT!**
Alternatively, is this an acceptable way to achieve the same desired result?
```
$("div[data-img-src]").each( function() {
$(this).append("<img src='/image-resize.php?original="+$(this).attr("data-img-src")+"' />");
// COUPLED WITH $_GET... in the php
});
``` | 2014/04/07 | [
"https://Stackoverflow.com/questions/22912327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/457148/"
]
| Basically you need index for the `cell` which has to be deleted when delete is pressed.
you can set the `tag` property and when button is pressed you can check the tag propery of the button which is sending event.
see below code,
```
UIButton *removeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
removeButton.tag = indexPath.row;
removeButton.frame = CGRectMake(200.0f, 5.0f, 75.0f, 30.0f);
[removeButton setTitle:@"Remove" forState:UIControlStateNormal];
removeButton.tintColor = [UIColor colorWithRed:0.667 green:0.667 blue:0.667 alpha:1]; /*#aaaaaa*/
removeButton.titleLabel.font = [UIFont systemFontOfSize:15];
[cell addSubview:removeButton];
[removeButton addTarget:self
action:@selector(removeItem:)
forControlEvents:UIControlEventTouchUpInside];
-(void) removeItem:(id) sender
{
UIButton *button = (UIButton*)sender;
int index = button.tag;
}
``` | Try this,
```
- (IBAction)removeItem:(id)sender {
UIButton *button = (UIButton *)sender;
CGPoint pointInTable = [button convertPoint:button.bounds.origin toView:_tableView];
NSIndexPath *indexPath = [_tableView indexPathForRowAtPoint:pointInTable];
//Remove the cell at indexPath
}
``` |
22,912,327 | I have the following PHP code to resize an image (i know this image will be a png so no need for checking...)
```
// The file
//$filename = $_POST['original'];
$filename = 'planets.png';
// Set a maximum height and width
$width = 200;
$height = 200;
// Content type
header('Content-Type: image/png');
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Resample
$image_p = imagecreatetruecolor($width, $height);
imagecreatefrompng($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output
imagepng($image_p);
```
However, I would like to be able to return this to my page via ajax... see the code below:
```
<div data-img-src="planets.png"></div>
<script type="text/javascript">
$("div[data-img-src]").each( function() {
$.ajax({
type: "POST",
url: "/image-resize.php",
data: {
original: $(this).attr("data-img-src")
},
dataType: "html",
success: function(result) {
$(this).append(result);
}
});
});
</script>
```
Any ideas what I need to do to make this work??
**EDIT!**
Alternatively, is this an acceptable way to achieve the same desired result?
```
$("div[data-img-src]").each( function() {
$(this).append("<img src='/image-resize.php?original="+$(this).attr("data-img-src")+"' />");
// COUPLED WITH $_GET... in the php
});
``` | 2014/04/07 | [
"https://Stackoverflow.com/questions/22912327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/457148/"
]
| Basically you need index for the `cell` which has to be deleted when delete is pressed.
you can set the `tag` property and when button is pressed you can check the tag propery of the button which is sending event.
see below code,
```
UIButton *removeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
removeButton.tag = indexPath.row;
removeButton.frame = CGRectMake(200.0f, 5.0f, 75.0f, 30.0f);
[removeButton setTitle:@"Remove" forState:UIControlStateNormal];
removeButton.tintColor = [UIColor colorWithRed:0.667 green:0.667 blue:0.667 alpha:1]; /*#aaaaaa*/
removeButton.titleLabel.font = [UIFont systemFontOfSize:15];
[cell addSubview:removeButton];
[removeButton addTarget:self
action:@selector(removeItem:)
forControlEvents:UIControlEventTouchUpInside];
-(void) removeItem:(id) sender
{
UIButton *button = (UIButton*)sender;
int index = button.tag;
}
``` | //1. add tag to the button, for identifing later
```
removeButton.tag = indexPath.row;
```
//2. Get the cell
```
UITableViewCell *cellToBeDeleted = [tableView cellForRowAtIndexPath:sender.tag];
``` |
34,713,996 | I have this code:
```
<?php echo $form->fileField($model, 'avatar_url', array('style' => 'display:none')) ?>
<a href="#" class="thumbnail" style="width: 96px" id="avatar">
<?php if (empty($model->avatar_url)) { ?>
<img data-src="holder.js/96x96" id="avatar-img">
<?php } else { ?>
<img src="<?= Yii::app()->baseUrl . $model->avatar_url ?>" id="avatar-img">
<?php } ?>
```
When I replace `<?php` to `<?` , the code does not work and the browser shows an error.
>
> PHP notice Undefined variable: class
>
>
>
Maybe I missed an extension in PHP? | 2016/01/11 | [
"https://Stackoverflow.com/questions/34713996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3750963/"
]
| Sounds like you need to enable `short_open_tag` in your php.ini.
Find the line `short_open_tag` in your php.ini and set the value to `1`:
```
short_open_tag = 1
```
After you make the change, restart your web server.
Read more here: <http://php.net/manual/en/ini.core.php#ini.short-open-tag>
>
> **short\_open\_tag**
>
>
> Tells PHP whether the short form (`<? ?>`) of PHP's open tag should be allowed. If you want to use PHP in combination with XML, you can disable this option in order to use `<?xml ?>` inline. Otherwise, you can print it with PHP, for example: `<?php echo '<?xml version="1.0"?>'; ?>`. Also, if disabled, you must use the long form of the PHP open tag (`<?php ?>`).
>
>
> | Although technically `<?` can be used with PHP it's [considered best practice](http://www.php-fig.org/psr/psr-1/) to always use `<?php` instead. |
34,713,996 | I have this code:
```
<?php echo $form->fileField($model, 'avatar_url', array('style' => 'display:none')) ?>
<a href="#" class="thumbnail" style="width: 96px" id="avatar">
<?php if (empty($model->avatar_url)) { ?>
<img data-src="holder.js/96x96" id="avatar-img">
<?php } else { ?>
<img src="<?= Yii::app()->baseUrl . $model->avatar_url ?>" id="avatar-img">
<?php } ?>
```
When I replace `<?php` to `<?` , the code does not work and the browser shows an error.
>
> PHP notice Undefined variable: class
>
>
>
Maybe I missed an extension in PHP? | 2016/01/11 | [
"https://Stackoverflow.com/questions/34713996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3750963/"
]
| Sounds like you need to enable `short_open_tag` in your php.ini.
Find the line `short_open_tag` in your php.ini and set the value to `1`:
```
short_open_tag = 1
```
After you make the change, restart your web server.
Read more here: <http://php.net/manual/en/ini.core.php#ini.short-open-tag>
>
> **short\_open\_tag**
>
>
> Tells PHP whether the short form (`<? ?>`) of PHP's open tag should be allowed. If you want to use PHP in combination with XML, you can disable this option in order to use `<?xml ?>` inline. Otherwise, you can print it with PHP, for example: `<?php echo '<?xml version="1.0"?>'; ?>`. Also, if disabled, you must use the long form of the PHP open tag (`<?php ?>`).
>
>
> | In PHP5 `<?` is not allowed any more. We always should use `<?php`. By the way you can do this doing some tricks. But `<?php` is a good practice so don't leave it. |
59,080,359 | I have a sequence of numbers that I somehow obtain from an external source, not separated by any commas and not in a data structure, e.g: 1 1.5 120202.4343 58 -2442.5
Where distinct numbers are separated by a space(s).
Is there a way for me to write a program to quickly convert this sequence into a list or numpy array [1, 1.5, 120202.4343, 58 ,-2442.5]. | 2019/11/28 | [
"https://Stackoverflow.com/questions/59080359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448955/"
]
| I can't believe nobody came up with the obvious:
```
np.array(your_string.split(),dtype=float)
``` | You can use `split()` and split the spaces to get a list of strings. Then simply convert each string to a float using type casting. This is achieved in one line using list comprehension.
For example:
```
x = '1 1.5 120202.4343 58 -2442.5'
output = [float(i) for i in x.split(" ")]
```
**Output:**
```
[1, 1.5, 120202.4343, 58 ,-2442.5]
```
---
If you input numbers come in one after another, then you can simply append to an existing list:
```
output = []
# Loop until an escape string is provided and get append input number to list
while True:
x = input() # Next input number
if x == 'escape_string_of_your_choice':
break
else:
output.append(x)
```
Likewise, if your sequence length is known in advance, you can initialize the list to a certain length and use indexing to assign the next input number in the sequence (you need a counter to keep track of where you are):
```
counter = 0 # First index has value 0
output = [0]*N # N is the length of the sequence
# Now looping is better defined (no need to provide escape strings)
while counter < N:
x = input() # Next input number
output[counter] = x
counter += 1 # Increment after element added to list
```
---
Lastly, comparing list comprehension to astype array forming in numpy provided in some answers we see that list comprehension is vastly superior in terms of execution speed.
```
import timeit
code_to_test = '''
import numpy as np
number_string = "1 1.5 120202.4343 58 -2442.5"
number_list = number_string.split(" ")
numbers_array = np.array(number_list).astype(np.float)'''
code_comp = '''
import numpy as np # Not needed but just to compare fairly
x = '1 1.5 120202.4343 58 -2442.5'
output = [float(i) for i in x.split(" ")]'''
test_time = timeit.timeit(code_to_test, number=10000)
compt_time = timeit.timeit(code_comp, number=10000)
print(test_time) # 0.6834872080944479
print(compt_time) # 0.028420873917639256
print(test_time/compt_time) # 24.048775209204436
```
Obviously these numbers will change each run but you can see that most of the time comprehension will be faster. |
59,080,359 | I have a sequence of numbers that I somehow obtain from an external source, not separated by any commas and not in a data structure, e.g: 1 1.5 120202.4343 58 -2442.5
Where distinct numbers are separated by a space(s).
Is there a way for me to write a program to quickly convert this sequence into a list or numpy array [1, 1.5, 120202.4343, 58 ,-2442.5]. | 2019/11/28 | [
"https://Stackoverflow.com/questions/59080359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448955/"
]
| ```
>>> in_str = '1 1.5 120202.4343 58 -2442.5'
>>> list(map(float, in_str.split(' ')))
[1, 1.5, 120202.4343, 58, -2442.5]
``` | Like the other answers say using split() can be used for this problem once you get the data as a string. I feel like it is valuable to show that
```
with open(filename,'r') as fil:
f = fil.read().split()
```
will let you put your external source file in a variable *filename* and then split that data into a list saved as f. |
59,080,359 | I have a sequence of numbers that I somehow obtain from an external source, not separated by any commas and not in a data structure, e.g: 1 1.5 120202.4343 58 -2442.5
Where distinct numbers are separated by a space(s).
Is there a way for me to write a program to quickly convert this sequence into a list or numpy array [1, 1.5, 120202.4343, 58 ,-2442.5]. | 2019/11/28 | [
"https://Stackoverflow.com/questions/59080359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448955/"
]
| Like the other answers say using split() can be used for this problem once you get the data as a string. I feel like it is valuable to show that
```
with open(filename,'r') as fil:
f = fil.read().split()
```
will let you put your external source file in a variable *filename* and then split that data into a list saved as f. | You can use `split()` and split the spaces to get a list of strings. Then simply convert each string to a float using type casting. This is achieved in one line using list comprehension.
For example:
```
x = '1 1.5 120202.4343 58 -2442.5'
output = [float(i) for i in x.split(" ")]
```
**Output:**
```
[1, 1.5, 120202.4343, 58 ,-2442.5]
```
---
If you input numbers come in one after another, then you can simply append to an existing list:
```
output = []
# Loop until an escape string is provided and get append input number to list
while True:
x = input() # Next input number
if x == 'escape_string_of_your_choice':
break
else:
output.append(x)
```
Likewise, if your sequence length is known in advance, you can initialize the list to a certain length and use indexing to assign the next input number in the sequence (you need a counter to keep track of where you are):
```
counter = 0 # First index has value 0
output = [0]*N # N is the length of the sequence
# Now looping is better defined (no need to provide escape strings)
while counter < N:
x = input() # Next input number
output[counter] = x
counter += 1 # Increment after element added to list
```
---
Lastly, comparing list comprehension to astype array forming in numpy provided in some answers we see that list comprehension is vastly superior in terms of execution speed.
```
import timeit
code_to_test = '''
import numpy as np
number_string = "1 1.5 120202.4343 58 -2442.5"
number_list = number_string.split(" ")
numbers_array = np.array(number_list).astype(np.float)'''
code_comp = '''
import numpy as np # Not needed but just to compare fairly
x = '1 1.5 120202.4343 58 -2442.5'
output = [float(i) for i in x.split(" ")]'''
test_time = timeit.timeit(code_to_test, number=10000)
compt_time = timeit.timeit(code_comp, number=10000)
print(test_time) # 0.6834872080944479
print(compt_time) # 0.028420873917639256
print(test_time/compt_time) # 24.048775209204436
```
Obviously these numbers will change each run but you can see that most of the time comprehension will be faster. |
59,080,359 | I have a sequence of numbers that I somehow obtain from an external source, not separated by any commas and not in a data structure, e.g: 1 1.5 120202.4343 58 -2442.5
Where distinct numbers are separated by a space(s).
Is there a way for me to write a program to quickly convert this sequence into a list or numpy array [1, 1.5, 120202.4343, 58 ,-2442.5]. | 2019/11/28 | [
"https://Stackoverflow.com/questions/59080359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448955/"
]
| ```
>>> in_str = '1 1.5 120202.4343 58 -2442.5'
>>> list(map(float, in_str.split(' ')))
[1, 1.5, 120202.4343, 58, -2442.5]
``` | I can't believe nobody came up with the obvious:
```
np.array(your_string.split(),dtype=float)
``` |
59,080,359 | I have a sequence of numbers that I somehow obtain from an external source, not separated by any commas and not in a data structure, e.g: 1 1.5 120202.4343 58 -2442.5
Where distinct numbers are separated by a space(s).
Is there a way for me to write a program to quickly convert this sequence into a list or numpy array [1, 1.5, 120202.4343, 58 ,-2442.5]. | 2019/11/28 | [
"https://Stackoverflow.com/questions/59080359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448955/"
]
| I can't believe nobody came up with the obvious:
```
np.array(your_string.split(),dtype=float)
``` | You're on the right track. You can load the numbers as a single string, then `split` the string by spaces. This will give you a list of strings:
```py
number_string = "1 1.5 120202.4343 58 -2442.5"
number_list = number_string.split(" ")
```
Then, you can easily convert that list of strings into a numpy array of floats using `astype`:
```py
numbers_array = np.array(number_list).astype(np.float)
``` |
59,080,359 | I have a sequence of numbers that I somehow obtain from an external source, not separated by any commas and not in a data structure, e.g: 1 1.5 120202.4343 58 -2442.5
Where distinct numbers are separated by a space(s).
Is there a way for me to write a program to quickly convert this sequence into a list or numpy array [1, 1.5, 120202.4343, 58 ,-2442.5]. | 2019/11/28 | [
"https://Stackoverflow.com/questions/59080359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448955/"
]
| ```
>>> in_str = '1 1.5 120202.4343 58 -2442.5'
>>> list(map(float, in_str.split(' ')))
[1, 1.5, 120202.4343, 58, -2442.5]
``` | You're on the right track. You can load the numbers as a single string, then `split` the string by spaces. This will give you a list of strings:
```py
number_string = "1 1.5 120202.4343 58 -2442.5"
number_list = number_string.split(" ")
```
Then, you can easily convert that list of strings into a numpy array of floats using `astype`:
```py
numbers_array = np.array(number_list).astype(np.float)
``` |
59,080,359 | I have a sequence of numbers that I somehow obtain from an external source, not separated by any commas and not in a data structure, e.g: 1 1.5 120202.4343 58 -2442.5
Where distinct numbers are separated by a space(s).
Is there a way for me to write a program to quickly convert this sequence into a list or numpy array [1, 1.5, 120202.4343, 58 ,-2442.5]. | 2019/11/28 | [
"https://Stackoverflow.com/questions/59080359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448955/"
]
| ```
>>> in_str = '1 1.5 120202.4343 58 -2442.5'
>>> list(map(float, in_str.split(' ')))
[1, 1.5, 120202.4343, 58, -2442.5]
``` | You can use `split()` and split the spaces to get a list of strings. Then simply convert each string to a float using type casting. This is achieved in one line using list comprehension.
For example:
```
x = '1 1.5 120202.4343 58 -2442.5'
output = [float(i) for i in x.split(" ")]
```
**Output:**
```
[1, 1.5, 120202.4343, 58 ,-2442.5]
```
---
If you input numbers come in one after another, then you can simply append to an existing list:
```
output = []
# Loop until an escape string is provided and get append input number to list
while True:
x = input() # Next input number
if x == 'escape_string_of_your_choice':
break
else:
output.append(x)
```
Likewise, if your sequence length is known in advance, you can initialize the list to a certain length and use indexing to assign the next input number in the sequence (you need a counter to keep track of where you are):
```
counter = 0 # First index has value 0
output = [0]*N # N is the length of the sequence
# Now looping is better defined (no need to provide escape strings)
while counter < N:
x = input() # Next input number
output[counter] = x
counter += 1 # Increment after element added to list
```
---
Lastly, comparing list comprehension to astype array forming in numpy provided in some answers we see that list comprehension is vastly superior in terms of execution speed.
```
import timeit
code_to_test = '''
import numpy as np
number_string = "1 1.5 120202.4343 58 -2442.5"
number_list = number_string.split(" ")
numbers_array = np.array(number_list).astype(np.float)'''
code_comp = '''
import numpy as np # Not needed but just to compare fairly
x = '1 1.5 120202.4343 58 -2442.5'
output = [float(i) for i in x.split(" ")]'''
test_time = timeit.timeit(code_to_test, number=10000)
compt_time = timeit.timeit(code_comp, number=10000)
print(test_time) # 0.6834872080944479
print(compt_time) # 0.028420873917639256
print(test_time/compt_time) # 24.048775209204436
```
Obviously these numbers will change each run but you can see that most of the time comprehension will be faster. |
59,080,359 | I have a sequence of numbers that I somehow obtain from an external source, not separated by any commas and not in a data structure, e.g: 1 1.5 120202.4343 58 -2442.5
Where distinct numbers are separated by a space(s).
Is there a way for me to write a program to quickly convert this sequence into a list or numpy array [1, 1.5, 120202.4343, 58 ,-2442.5]. | 2019/11/28 | [
"https://Stackoverflow.com/questions/59080359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448955/"
]
| I'm not sure what you mean by "not in a data structure", that doesn't make much sense. But assuming you have a string, then `numpy` even provides a utility method for this:
```
>>> import numpy as np
>>> data = '1 1.5 120202.4343 58 -2442.5'
>>> np.fromstring(data, sep=' ')
array([ 1.00000000e+00, 1.50000000e+00, 1.20202434e+05, 5.80000000e+01,
-2.44250000e+03])
``` | Like the other answers say using split() can be used for this problem once you get the data as a string. I feel like it is valuable to show that
```
with open(filename,'r') as fil:
f = fil.read().split()
```
will let you put your external source file in a variable *filename* and then split that data into a list saved as f. |
59,080,359 | I have a sequence of numbers that I somehow obtain from an external source, not separated by any commas and not in a data structure, e.g: 1 1.5 120202.4343 58 -2442.5
Where distinct numbers are separated by a space(s).
Is there a way for me to write a program to quickly convert this sequence into a list or numpy array [1, 1.5, 120202.4343, 58 ,-2442.5]. | 2019/11/28 | [
"https://Stackoverflow.com/questions/59080359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448955/"
]
| I'm not sure what you mean by "not in a data structure", that doesn't make much sense. But assuming you have a string, then `numpy` even provides a utility method for this:
```
>>> import numpy as np
>>> data = '1 1.5 120202.4343 58 -2442.5'
>>> np.fromstring(data, sep=' ')
array([ 1.00000000e+00, 1.50000000e+00, 1.20202434e+05, 5.80000000e+01,
-2.44250000e+03])
``` | ```
>>> in_str = '1 1.5 120202.4343 58 -2442.5'
>>> list(map(float, in_str.split(' ')))
[1, 1.5, 120202.4343, 58, -2442.5]
``` |
59,080,359 | I have a sequence of numbers that I somehow obtain from an external source, not separated by any commas and not in a data structure, e.g: 1 1.5 120202.4343 58 -2442.5
Where distinct numbers are separated by a space(s).
Is there a way for me to write a program to quickly convert this sequence into a list or numpy array [1, 1.5, 120202.4343, 58 ,-2442.5]. | 2019/11/28 | [
"https://Stackoverflow.com/questions/59080359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448955/"
]
| Like the other answers say using split() can be used for this problem once you get the data as a string. I feel like it is valuable to show that
```
with open(filename,'r') as fil:
f = fil.read().split()
```
will let you put your external source file in a variable *filename* and then split that data into a list saved as f. | You're on the right track. You can load the numbers as a single string, then `split` the string by spaces. This will give you a list of strings:
```py
number_string = "1 1.5 120202.4343 58 -2442.5"
number_list = number_string.split(" ")
```
Then, you can easily convert that list of strings into a numpy array of floats using `astype`:
```py
numbers_array = np.array(number_list).astype(np.float)
``` |
17,706,823 | I need create an Email List.
For each Folder, I need get all email from owners.
But, I have an error in listRequest.Email = reader["Email"].ToList();
The error is in "ToList()", I'm declaring namespace System.Collections.Generic but don't resolves.
```
public class ListRequest
{
public List<string> Email { get; set; }
public string FolderAccess { get; set; }
}
public List<ListRequest> PreencheValores(SqlDataReader reader)
{
var lista = new List<ListRequest>();
while (reader.Read())
{
var listRequest = new ListRequest();
listRequest.Email = reader["Email"].ToList();
listRequest.FolderAccess = reader["FolderAccess"].ToString();
lista.Add(listRequest);
}
return lista;
}
``` | 2013/07/17 | [
"https://Stackoverflow.com/questions/17706823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2456471/"
]
| Below statement is not valid.
```
listRequest.Email = reader["Email"].ToList();
```
Using SqlDataReader you can read only single element but not list like what you did to retrieve folder access.
```
listRequest.FolderAccess = reader["FolderAccess"].ToString();
```
One thing you could do is retrieve email addresses as comma separated values and then split them. Also consider using string[] instead of List
```
public class ListRequest
{
public string[] Email { get; set; }
public string FolderAccess { get; set; }
}
public List<ListRequest> PreencheValores(SqlDataReader reader)
{
var lista = new List<ListRequest>();
while (reader.Read())
{
var listRequest = new ListRequest();
if(reader["Email"] != null)
listRequest.Email = reader["Email"].ToString().Split(',');
if(reader["FolderAccess"] != null)
listRequest.FolderAccess = reader["FolderAccess"].ToString();
lista.Add(listRequest);
}
return lista;
}
``` | `reader["Email"]` is an object. There is no method `object.ToList()`
If it is supposed to be a delimited string, I recommend doing a `ToString()`, then `Split()` before your `ToList()`.
Example:
```
listRequest.Email = reader["Email"]
.ToString()
.Split(new [] {","}, StringSplitOptions.RemoveEmptyEntries)
.ToList();
``` |
17,706,823 | I need create an Email List.
For each Folder, I need get all email from owners.
But, I have an error in listRequest.Email = reader["Email"].ToList();
The error is in "ToList()", I'm declaring namespace System.Collections.Generic but don't resolves.
```
public class ListRequest
{
public List<string> Email { get; set; }
public string FolderAccess { get; set; }
}
public List<ListRequest> PreencheValores(SqlDataReader reader)
{
var lista = new List<ListRequest>();
while (reader.Read())
{
var listRequest = new ListRequest();
listRequest.Email = reader["Email"].ToList();
listRequest.FolderAccess = reader["FolderAccess"].ToString();
lista.Add(listRequest);
}
return lista;
}
``` | 2013/07/17 | [
"https://Stackoverflow.com/questions/17706823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2456471/"
]
| `reader["Email"]` is an object. There is no method `object.ToList()`
If it is supposed to be a delimited string, I recommend doing a `ToString()`, then `Split()` before your `ToList()`.
Example:
```
listRequest.Email = reader["Email"]
.ToString()
.Split(new [] {","}, StringSplitOptions.RemoveEmptyEntries)
.ToList();
``` | reader["Email"] is not a collection. Its gets the value of the specified column in the native format given the column name.
So do this
```
var lstEmail = new List<string>();
using (connection)
{
SqlCommand command = new SqlCommand("SELECT Email FROM TableName;",connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
lstEmail .add(reader.GetString(0))
}
}
reader.Close();
}
``` |
17,706,823 | I need create an Email List.
For each Folder, I need get all email from owners.
But, I have an error in listRequest.Email = reader["Email"].ToList();
The error is in "ToList()", I'm declaring namespace System.Collections.Generic but don't resolves.
```
public class ListRequest
{
public List<string> Email { get; set; }
public string FolderAccess { get; set; }
}
public List<ListRequest> PreencheValores(SqlDataReader reader)
{
var lista = new List<ListRequest>();
while (reader.Read())
{
var listRequest = new ListRequest();
listRequest.Email = reader["Email"].ToList();
listRequest.FolderAccess = reader["FolderAccess"].ToString();
lista.Add(listRequest);
}
return lista;
}
``` | 2013/07/17 | [
"https://Stackoverflow.com/questions/17706823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2456471/"
]
| Below statement is not valid.
```
listRequest.Email = reader["Email"].ToList();
```
Using SqlDataReader you can read only single element but not list like what you did to retrieve folder access.
```
listRequest.FolderAccess = reader["FolderAccess"].ToString();
```
One thing you could do is retrieve email addresses as comma separated values and then split them. Also consider using string[] instead of List
```
public class ListRequest
{
public string[] Email { get; set; }
public string FolderAccess { get; set; }
}
public List<ListRequest> PreencheValores(SqlDataReader reader)
{
var lista = new List<ListRequest>();
while (reader.Read())
{
var listRequest = new ListRequest();
if(reader["Email"] != null)
listRequest.Email = reader["Email"].ToString().Split(',');
if(reader["FolderAccess"] != null)
listRequest.FolderAccess = reader["FolderAccess"].ToString();
lista.Add(listRequest);
}
return lista;
}
``` | reader["Email"] is not a collection. Its gets the value of the specified column in the native format given the column name.
So do this
```
var lstEmail = new List<string>();
using (connection)
{
SqlCommand command = new SqlCommand("SELECT Email FROM TableName;",connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
lstEmail .add(reader.GetString(0))
}
}
reader.Close();
}
``` |
27,651,730 | I have the following string example:
```
[14:48:51.690] LOGON error group: 103
```
I get many different from them. The only thing is, that the beginning is always the same expect the date (always in brackets) and name of `LOGON`. I want to remove thi in front.
How can I achieve this efficiently? Regex? Splitting and remove from array?
The only thing I want to have finally is
```
error group: 103
``` | 2014/12/26 | [
"https://Stackoverflow.com/questions/27651730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2257374/"
]
| You can split the string based on regex `\[\d{1,2}:\d{1,2}:\d{1,2}\.\d{1,3}\]\s*\w*\s*`
```
import java.util.regex.Pattern;
public class T {
public static void main(String[] args) {
String s = "[14:48:51.690] LOGON error group: 103";
String[] split = s.split("\\[\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}\\]\\s*\\w*\\s*");
System.out.println(split[1]);
}
}
```
Output
```
error group: 103
``` | Here is another way using a simple regular expression:
```
Pattern pattern = Pattern.compile("\\[.*\\]\\s*LOGON\\s*(.*)\\s*");
Matcher matcher = pattern.matcher("[14:48:51.690] LOGON error group: 103");
if (matcher.find()) {
System.out.println(matcher.group(1));
}
```
So essentially we scan the opening bracket, the date inside it, the closing bracket, any whitespace
in between until and capture the part you're looking for using `(.*)`. |
27,651,730 | I have the following string example:
```
[14:48:51.690] LOGON error group: 103
```
I get many different from them. The only thing is, that the beginning is always the same expect the date (always in brackets) and name of `LOGON`. I want to remove thi in front.
How can I achieve this efficiently? Regex? Splitting and remove from array?
The only thing I want to have finally is
```
error group: 103
``` | 2014/12/26 | [
"https://Stackoverflow.com/questions/27651730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2257374/"
]
| You can split the string based on regex `\[\d{1,2}:\d{1,2}:\d{1,2}\.\d{1,3}\]\s*\w*\s*`
```
import java.util.regex.Pattern;
public class T {
public static void main(String[] args) {
String s = "[14:48:51.690] LOGON error group: 103";
String[] split = s.split("\\[\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}\\]\\s*\\w*\\s*");
System.out.println(split[1]);
}
}
```
Output
```
error group: 103
``` | Assuming the event text ("LOGIN" in your case) is all caps and one word:
```
String target = str.replaceAll(".*?\\]\\s*[A-Z]+\\s*", "");
``` |
27,651,730 | I have the following string example:
```
[14:48:51.690] LOGON error group: 103
```
I get many different from them. The only thing is, that the beginning is always the same expect the date (always in brackets) and name of `LOGON`. I want to remove thi in front.
How can I achieve this efficiently? Regex? Splitting and remove from array?
The only thing I want to have finally is
```
error group: 103
``` | 2014/12/26 | [
"https://Stackoverflow.com/questions/27651730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2257374/"
]
| You can split the string based on regex `\[\d{1,2}:\d{1,2}:\d{1,2}\.\d{1,3}\]\s*\w*\s*`
```
import java.util.regex.Pattern;
public class T {
public static void main(String[] args) {
String s = "[14:48:51.690] LOGON error group: 103";
String[] split = s.split("\\[\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}\\]\\s*\\w*\\s*");
System.out.println(split[1]);
}
}
```
Output
```
error group: 103
``` | Regex is a very expensive task. If you're searching into a log file with 100,000 lines, it will take too much time! If your string always has the same pattern, TRY TO TAKE ADVANTAGE OF IT!
I'm assuming your line is:
```
[some_time] some_event some event description
```
Simplest way I can see now is just to search for the second space and get everything after it.
```
public class HelloWorld{
public static void main(String []args){
String s = "[14:48:51.690] LOGON error group: 103";
int pos = getPosOfFirstAlphaNumericCharAfterSecondSpace(s);
if (pos > 0)
System.out.println(s.substring(pos));
}
private static int getPosOfFirstAlphaNumericCharAfterSecondSpace(String s) {
int countSpaces = 0;
for(int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ')
countSpaces++;
else if (countSpaces >= 2)
return i;
}
return -1;
}
}
``` |
27,651,730 | I have the following string example:
```
[14:48:51.690] LOGON error group: 103
```
I get many different from them. The only thing is, that the beginning is always the same expect the date (always in brackets) and name of `LOGON`. I want to remove thi in front.
How can I achieve this efficiently? Regex? Splitting and remove from array?
The only thing I want to have finally is
```
error group: 103
``` | 2014/12/26 | [
"https://Stackoverflow.com/questions/27651730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2257374/"
]
| Here is another way using a simple regular expression:
```
Pattern pattern = Pattern.compile("\\[.*\\]\\s*LOGON\\s*(.*)\\s*");
Matcher matcher = pattern.matcher("[14:48:51.690] LOGON error group: 103");
if (matcher.find()) {
System.out.println(matcher.group(1));
}
```
So essentially we scan the opening bracket, the date inside it, the closing bracket, any whitespace
in between until and capture the part you're looking for using `(.*)`. | Assuming the event text ("LOGIN" in your case) is all caps and one word:
```
String target = str.replaceAll(".*?\\]\\s*[A-Z]+\\s*", "");
``` |
27,651,730 | I have the following string example:
```
[14:48:51.690] LOGON error group: 103
```
I get many different from them. The only thing is, that the beginning is always the same expect the date (always in brackets) and name of `LOGON`. I want to remove thi in front.
How can I achieve this efficiently? Regex? Splitting and remove from array?
The only thing I want to have finally is
```
error group: 103
``` | 2014/12/26 | [
"https://Stackoverflow.com/questions/27651730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2257374/"
]
| Regex is a very expensive task. If you're searching into a log file with 100,000 lines, it will take too much time! If your string always has the same pattern, TRY TO TAKE ADVANTAGE OF IT!
I'm assuming your line is:
```
[some_time] some_event some event description
```
Simplest way I can see now is just to search for the second space and get everything after it.
```
public class HelloWorld{
public static void main(String []args){
String s = "[14:48:51.690] LOGON error group: 103";
int pos = getPosOfFirstAlphaNumericCharAfterSecondSpace(s);
if (pos > 0)
System.out.println(s.substring(pos));
}
private static int getPosOfFirstAlphaNumericCharAfterSecondSpace(String s) {
int countSpaces = 0;
for(int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ')
countSpaces++;
else if (countSpaces >= 2)
return i;
}
return -1;
}
}
``` | Assuming the event text ("LOGIN" in your case) is all caps and one word:
```
String target = str.replaceAll(".*?\\]\\s*[A-Z]+\\s*", "");
``` |
489,035 | It is a simple exercise to prove using mathematical induction that if a natural number n > 1 is not divisible by 2, then n can be written as m + m + 1 for some natural number m. (Depending on your definition of odd number, this can either be stated as "every number is even or odd", or as "every odd number is one greater than an even number". My question is, can this be proven without induction? In other words, can this be proven in Robinson arithmetic? If not, what is example of a nonstandard model of Robinson arithmetic that doesn't have this property?
The reason I'm asking this is that the proof of the irrationality of the square root of 2 is usually presented with only one use of induction (or an equivalent technique). But the proof depends on the fact if k^2 is even, then k is even, and that fact in turn depends on the fact that the square of a number not divisible by 2 is a number not divisible by 2. And that fact is, as far as I can tell, is a result of the proposition above. (I'm open to correction on that point.) So if that proposition depended on induction, then the proof that sqrt(2) is irrational would depend on two applications of induction. (The reason that the ancient Greeks wouldn't have been aware of this is that Euclid implicitly assumes the proposition above, when he defines an odd number as "that which is not divisible into two equal parts, or that which differs by a unit from an even number".)
Any help would greatly appreciated.
Thank You in Advance. | 2013/09/10 | [
"https://math.stackexchange.com/questions/489035",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/71829/"
]
| This is just a partial answer. Let $\mathcal L =\{S,<\}$ be the language with an unary function $S$ and a binary relation $<$. Consider the structure $(\mathbb N, S,<)$ ($S$ is the successor function), then $E=\{2n:n\in\mathbb N\}$ is not definable in $(\mathbb N, S,<)$. To see this consider the elementary extension $\mathfrak C=(\mathbb N\sqcup \mathbb Z, S,<)$, and define an automorphism $\Phi:\mathfrak C\to \mathfrak C$ as follows $\Phi(n)=n$ if $n\in\mathbb N$ and $\Phi(n)=S(n)$ otherwise. It is easy to see, using $\Phi$, that there is no formula defining $E$. | I appear to have found an answer to my own question, from page 49 of Edward Nelson's book [The Elements](http://kolany.pl/KNMaT/r%C3%B3%C5%BCno%C5%9Bci/PA/dane/2.%20elem.pdf) (which was a failed attempt to prove that Peano arithmetic is inconsistent):
"Here is a semantic indication that induction is necessary to prove this. Take a nonstandard model of $P$ and let $\alpha$ be a nonstandard number. Take the external set $U$ of all standard numbers together with all numbers obtained by repeatedly applying the functions symbols of $Q\_{90}$ to $\alpha$. Then U is the universe of a model of $Q\_{90}$, but there is no individual $\beta$ in $U$ such that either $2 \beta = \alpha $
or $2 \beta + 1= \alpha $."
Here $P$ denotes Peano arithmetic and $Q\_{90}$ denotes Robinson arithmetic with basic properties of addition, multiplication, and order added.
Can anyone explain what Nelson's reasoning? Why can't there be a $\beta$ in $U$ such that either $2 \beta = \alpha $
or $2 \beta + 1= \alpha $? |
489,035 | It is a simple exercise to prove using mathematical induction that if a natural number n > 1 is not divisible by 2, then n can be written as m + m + 1 for some natural number m. (Depending on your definition of odd number, this can either be stated as "every number is even or odd", or as "every odd number is one greater than an even number". My question is, can this be proven without induction? In other words, can this be proven in Robinson arithmetic? If not, what is example of a nonstandard model of Robinson arithmetic that doesn't have this property?
The reason I'm asking this is that the proof of the irrationality of the square root of 2 is usually presented with only one use of induction (or an equivalent technique). But the proof depends on the fact if k^2 is even, then k is even, and that fact in turn depends on the fact that the square of a number not divisible by 2 is a number not divisible by 2. And that fact is, as far as I can tell, is a result of the proposition above. (I'm open to correction on that point.) So if that proposition depended on induction, then the proof that sqrt(2) is irrational would depend on two applications of induction. (The reason that the ancient Greeks wouldn't have been aware of this is that Euclid implicitly assumes the proposition above, when he defines an odd number as "that which is not divisible into two equal parts, or that which differs by a unit from an even number".)
Any help would greatly appreciated.
Thank You in Advance. | 2013/09/10 | [
"https://math.stackexchange.com/questions/489035",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/71829/"
]
| Take $M = \{P = a\_nx^n + \ldots + a\_0 \in \Bbb Z[x] / a\_n > 0 \}$, with the usual addition and multiplication on polynomials. Interprete $S(P)$ as $P(X)+1$.
Then $M$ is a model of Robinson arithmetic, but there are long strings of "not-even" numbers, such as $X,X+1,X+2,\ldots$. So in this model, it is false that if $n$ is not even then $n+1$ is even.
If you define "$n$ is odd" as "$\exists k / n= k+k+1$", then it is false that every number is even or odd.
However, it is still true in $M$ that addition is associative and commutative, and so if $n$ is odd then $n+1$ is even, and if $n$ is even, then $n+1$ is odd. (you will need a stranger model for this to fail)
---
If you want a model in which $a^2-2b^2 = 0$ has a solution, you can pick $M = \{ P \in \Bbb Z[X,Y]/(X^2-2Y^2) / \lim\_{y \to \infty} P(\sqrt 2 y,y) = + \infty$ or $P \in \Bbb N \}$ | This is just a partial answer. Let $\mathcal L =\{S,<\}$ be the language with an unary function $S$ and a binary relation $<$. Consider the structure $(\mathbb N, S,<)$ ($S$ is the successor function), then $E=\{2n:n\in\mathbb N\}$ is not definable in $(\mathbb N, S,<)$. To see this consider the elementary extension $\mathfrak C=(\mathbb N\sqcup \mathbb Z, S,<)$, and define an automorphism $\Phi:\mathfrak C\to \mathfrak C$ as follows $\Phi(n)=n$ if $n\in\mathbb N$ and $\Phi(n)=S(n)$ otherwise. It is easy to see, using $\Phi$, that there is no formula defining $E$. |
489,035 | It is a simple exercise to prove using mathematical induction that if a natural number n > 1 is not divisible by 2, then n can be written as m + m + 1 for some natural number m. (Depending on your definition of odd number, this can either be stated as "every number is even or odd", or as "every odd number is one greater than an even number". My question is, can this be proven without induction? In other words, can this be proven in Robinson arithmetic? If not, what is example of a nonstandard model of Robinson arithmetic that doesn't have this property?
The reason I'm asking this is that the proof of the irrationality of the square root of 2 is usually presented with only one use of induction (or an equivalent technique). But the proof depends on the fact if k^2 is even, then k is even, and that fact in turn depends on the fact that the square of a number not divisible by 2 is a number not divisible by 2. And that fact is, as far as I can tell, is a result of the proposition above. (I'm open to correction on that point.) So if that proposition depended on induction, then the proof that sqrt(2) is irrational would depend on two applications of induction. (The reason that the ancient Greeks wouldn't have been aware of this is that Euclid implicitly assumes the proposition above, when he defines an odd number as "that which is not divisible into two equal parts, or that which differs by a unit from an even number".)
Any help would greatly appreciated.
Thank You in Advance. | 2013/09/10 | [
"https://math.stackexchange.com/questions/489035",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/71829/"
]
| This is just a partial answer. Let $\mathcal L =\{S,<\}$ be the language with an unary function $S$ and a binary relation $<$. Consider the structure $(\mathbb N, S,<)$ ($S$ is the successor function), then $E=\{2n:n\in\mathbb N\}$ is not definable in $(\mathbb N, S,<)$. To see this consider the elementary extension $\mathfrak C=(\mathbb N\sqcup \mathbb Z, S,<)$, and define an automorphism $\Phi:\mathfrak C\to \mathfrak C$ as follows $\Phi(n)=n$ if $n\in\mathbb N$ and $\Phi(n)=S(n)$ otherwise. It is easy to see, using $\Phi$, that there is no formula defining $E$. | I know this is a pretty old post, but I want to share some of my own insights.
First, I want to highlight a slight error in the answer by mercio. It is a correct model of PA - induction, but Robinson Arithmetic is PA - induction + $\forall n (n = 0 \vee \exists m (n = S(m)))$. Their model does not satisfy this additional axiom, as $X$ does not have a predecessor. Now that I think of it, I am not sure if this is also addressed in the model in the Elements?
Let me add a model of my own. Take $N$ together with two non-standard elements $a$ and $b$. Extend $S$ by $S(a) = a$ and $S(b) = b$, addition by $a + n = a$ for $n \in N$ and all other new combinations result in $b$, and multiplication by $n \* 0 = 0$ always, and any other new combination results in $b$.
It is some annoying work to check that this satisfies all the axioms (which I formalized in Agda, for good measure), and it can be verified that $a$ is neither even nor odd (i.e. there does not exist $n$ such that any of $n + n = a$, $2\*n=a$, $n + n + 1 = a$ or $2\*n+1=a$ are true). |
489,035 | It is a simple exercise to prove using mathematical induction that if a natural number n > 1 is not divisible by 2, then n can be written as m + m + 1 for some natural number m. (Depending on your definition of odd number, this can either be stated as "every number is even or odd", or as "every odd number is one greater than an even number". My question is, can this be proven without induction? In other words, can this be proven in Robinson arithmetic? If not, what is example of a nonstandard model of Robinson arithmetic that doesn't have this property?
The reason I'm asking this is that the proof of the irrationality of the square root of 2 is usually presented with only one use of induction (or an equivalent technique). But the proof depends on the fact if k^2 is even, then k is even, and that fact in turn depends on the fact that the square of a number not divisible by 2 is a number not divisible by 2. And that fact is, as far as I can tell, is a result of the proposition above. (I'm open to correction on that point.) So if that proposition depended on induction, then the proof that sqrt(2) is irrational would depend on two applications of induction. (The reason that the ancient Greeks wouldn't have been aware of this is that Euclid implicitly assumes the proposition above, when he defines an odd number as "that which is not divisible into two equal parts, or that which differs by a unit from an even number".)
Any help would greatly appreciated.
Thank You in Advance. | 2013/09/10 | [
"https://math.stackexchange.com/questions/489035",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/71829/"
]
| Take $M = \{P = a\_nx^n + \ldots + a\_0 \in \Bbb Z[x] / a\_n > 0 \}$, with the usual addition and multiplication on polynomials. Interprete $S(P)$ as $P(X)+1$.
Then $M$ is a model of Robinson arithmetic, but there are long strings of "not-even" numbers, such as $X,X+1,X+2,\ldots$. So in this model, it is false that if $n$ is not even then $n+1$ is even.
If you define "$n$ is odd" as "$\exists k / n= k+k+1$", then it is false that every number is even or odd.
However, it is still true in $M$ that addition is associative and commutative, and so if $n$ is odd then $n+1$ is even, and if $n$ is even, then $n+1$ is odd. (you will need a stranger model for this to fail)
---
If you want a model in which $a^2-2b^2 = 0$ has a solution, you can pick $M = \{ P \in \Bbb Z[X,Y]/(X^2-2Y^2) / \lim\_{y \to \infty} P(\sqrt 2 y,y) = + \infty$ or $P \in \Bbb N \}$ | I appear to have found an answer to my own question, from page 49 of Edward Nelson's book [The Elements](http://kolany.pl/KNMaT/r%C3%B3%C5%BCno%C5%9Bci/PA/dane/2.%20elem.pdf) (which was a failed attempt to prove that Peano arithmetic is inconsistent):
"Here is a semantic indication that induction is necessary to prove this. Take a nonstandard model of $P$ and let $\alpha$ be a nonstandard number. Take the external set $U$ of all standard numbers together with all numbers obtained by repeatedly applying the functions symbols of $Q\_{90}$ to $\alpha$. Then U is the universe of a model of $Q\_{90}$, but there is no individual $\beta$ in $U$ such that either $2 \beta = \alpha $
or $2 \beta + 1= \alpha $."
Here $P$ denotes Peano arithmetic and $Q\_{90}$ denotes Robinson arithmetic with basic properties of addition, multiplication, and order added.
Can anyone explain what Nelson's reasoning? Why can't there be a $\beta$ in $U$ such that either $2 \beta = \alpha $
or $2 \beta + 1= \alpha $? |
489,035 | It is a simple exercise to prove using mathematical induction that if a natural number n > 1 is not divisible by 2, then n can be written as m + m + 1 for some natural number m. (Depending on your definition of odd number, this can either be stated as "every number is even or odd", or as "every odd number is one greater than an even number". My question is, can this be proven without induction? In other words, can this be proven in Robinson arithmetic? If not, what is example of a nonstandard model of Robinson arithmetic that doesn't have this property?
The reason I'm asking this is that the proof of the irrationality of the square root of 2 is usually presented with only one use of induction (or an equivalent technique). But the proof depends on the fact if k^2 is even, then k is even, and that fact in turn depends on the fact that the square of a number not divisible by 2 is a number not divisible by 2. And that fact is, as far as I can tell, is a result of the proposition above. (I'm open to correction on that point.) So if that proposition depended on induction, then the proof that sqrt(2) is irrational would depend on two applications of induction. (The reason that the ancient Greeks wouldn't have been aware of this is that Euclid implicitly assumes the proposition above, when he defines an odd number as "that which is not divisible into two equal parts, or that which differs by a unit from an even number".)
Any help would greatly appreciated.
Thank You in Advance. | 2013/09/10 | [
"https://math.stackexchange.com/questions/489035",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/71829/"
]
| Take $M = \{P = a\_nx^n + \ldots + a\_0 \in \Bbb Z[x] / a\_n > 0 \}$, with the usual addition and multiplication on polynomials. Interprete $S(P)$ as $P(X)+1$.
Then $M$ is a model of Robinson arithmetic, but there are long strings of "not-even" numbers, such as $X,X+1,X+2,\ldots$. So in this model, it is false that if $n$ is not even then $n+1$ is even.
If you define "$n$ is odd" as "$\exists k / n= k+k+1$", then it is false that every number is even or odd.
However, it is still true in $M$ that addition is associative and commutative, and so if $n$ is odd then $n+1$ is even, and if $n$ is even, then $n+1$ is odd. (you will need a stranger model for this to fail)
---
If you want a model in which $a^2-2b^2 = 0$ has a solution, you can pick $M = \{ P \in \Bbb Z[X,Y]/(X^2-2Y^2) / \lim\_{y \to \infty} P(\sqrt 2 y,y) = + \infty$ or $P \in \Bbb N \}$ | I know this is a pretty old post, but I want to share some of my own insights.
First, I want to highlight a slight error in the answer by mercio. It is a correct model of PA - induction, but Robinson Arithmetic is PA - induction + $\forall n (n = 0 \vee \exists m (n = S(m)))$. Their model does not satisfy this additional axiom, as $X$ does not have a predecessor. Now that I think of it, I am not sure if this is also addressed in the model in the Elements?
Let me add a model of my own. Take $N$ together with two non-standard elements $a$ and $b$. Extend $S$ by $S(a) = a$ and $S(b) = b$, addition by $a + n = a$ for $n \in N$ and all other new combinations result in $b$, and multiplication by $n \* 0 = 0$ always, and any other new combination results in $b$.
It is some annoying work to check that this satisfies all the axioms (which I formalized in Agda, for good measure), and it can be verified that $a$ is neither even nor odd (i.e. there does not exist $n$ such that any of $n + n = a$, $2\*n=a$, $n + n + 1 = a$ or $2\*n+1=a$ are true). |
37,770,930 | I have a JSON file and need to get the parameter ' fulltext ' , but I'm new to JSON and do not know how to retrieve it in Java . Could someone explain to me how caught this value fulltext ?
Here a piece of the file in JSON.
```
{
"head": {
"vars": [ "author" , "title" , "paper" , "fulltext" ]
} ,
"results": {
"bindings": [
{
"author": { "type": "uri" , "value": "http://data.linkededucation.org/resource/lak/person/richard-scheines" } ,
"title": { "type": "literal" , "value": "Discovering Prerequisite Relationships among Knowledge Components" } ,
"paper": { "type": "uri" , "value": "http://data.linkededucation.org/resource/lak/conference/edm2014/paper/492" } ,
"fulltext": { "type": "literal" , "value": "GET TEXT" }
} ,
``` | 2016/06/12 | [
"https://Stackoverflow.com/questions/37770930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6363322/"
]
| Json library download from here **jar** dowonload form [here](http://central.maven.org/maven2/org/json/json/20160212/json-20160212.jar)
Add this code in **JSonParsing.java**
```
import org.json.*;
public class JSonParsing {
public static void main(String[] args){
String source = "{\n" +
" \"head\": {\n" +
" \"vars\": [ \"author\" , \"title\" , \"paper\" , \"fulltext\" ]\n" +
" } ,\n" +
" \"results\": {\n" +
" \"bindings\": [\n" +
" {\n" +
" \"author\": { \"type\": \"uri\" , \"value\": \"http://data.linkededucation.org/resource/lak/person/richard-scheines\" } ,\n" +
" \"title\": { \"type\": \"literal\" , \"value\": \"Discovering Prerequisite Relationships among Knowledge Components\" } ,\n" +
" \"paper\": { \"type\": \"uri\" , \"value\": \"http://data.linkededucation.org/resource/lak/conference/edm2014/paper/492\" } ,\n" +
" \"fulltext\": { \"type\": \"literal\" , \"value\": \"GET TEXT\" }\n" +
" }\n" +
" ]\n" +
" }\n" +
"}\n" +
"";
JSONObject main = new JSONObject(source);
JSONObject results = main.getJSONObject("results");
JSONArray bindings = results.getJSONArray("bindings");
JSONObject firstObject = bindings.getJSONObject(0);
JSONObject fulltextOfFirstObject = firstObject.getJSONObject("fulltext");
String type = fulltextOfFirstObject.getString("type");
String value = fulltextOfFirstObject.getString("value");
System.out.println("Type :"+ type+"\nValue :"+value);
}
}
```
NOTE: In JSON **`{}`** represents jsonObject and `[]` represents jsonArray. | You can use org.json/Jackson to convert this string to JSONObject.
If it is a JSONObject called val;
then `val.get("results").get("bindings").get(0).get("fulltext")`
will give you the full text of first element of bindings. |
37,770,930 | I have a JSON file and need to get the parameter ' fulltext ' , but I'm new to JSON and do not know how to retrieve it in Java . Could someone explain to me how caught this value fulltext ?
Here a piece of the file in JSON.
```
{
"head": {
"vars": [ "author" , "title" , "paper" , "fulltext" ]
} ,
"results": {
"bindings": [
{
"author": { "type": "uri" , "value": "http://data.linkededucation.org/resource/lak/person/richard-scheines" } ,
"title": { "type": "literal" , "value": "Discovering Prerequisite Relationships among Knowledge Components" } ,
"paper": { "type": "uri" , "value": "http://data.linkededucation.org/resource/lak/conference/edm2014/paper/492" } ,
"fulltext": { "type": "literal" , "value": "GET TEXT" }
} ,
``` | 2016/06/12 | [
"https://Stackoverflow.com/questions/37770930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6363322/"
]
| Json library download from here **jar** dowonload form [here](http://central.maven.org/maven2/org/json/json/20160212/json-20160212.jar)
Add this code in **JSonParsing.java**
```
import org.json.*;
public class JSonParsing {
public static void main(String[] args){
String source = "{\n" +
" \"head\": {\n" +
" \"vars\": [ \"author\" , \"title\" , \"paper\" , \"fulltext\" ]\n" +
" } ,\n" +
" \"results\": {\n" +
" \"bindings\": [\n" +
" {\n" +
" \"author\": { \"type\": \"uri\" , \"value\": \"http://data.linkededucation.org/resource/lak/person/richard-scheines\" } ,\n" +
" \"title\": { \"type\": \"literal\" , \"value\": \"Discovering Prerequisite Relationships among Knowledge Components\" } ,\n" +
" \"paper\": { \"type\": \"uri\" , \"value\": \"http://data.linkededucation.org/resource/lak/conference/edm2014/paper/492\" } ,\n" +
" \"fulltext\": { \"type\": \"literal\" , \"value\": \"GET TEXT\" }\n" +
" }\n" +
" ]\n" +
" }\n" +
"}\n" +
"";
JSONObject main = new JSONObject(source);
JSONObject results = main.getJSONObject("results");
JSONArray bindings = results.getJSONArray("bindings");
JSONObject firstObject = bindings.getJSONObject(0);
JSONObject fulltextOfFirstObject = firstObject.getJSONObject("fulltext");
String type = fulltextOfFirstObject.getString("type");
String value = fulltextOfFirstObject.getString("value");
System.out.println("Type :"+ type+"\nValue :"+value);
}
}
```
NOTE: In JSON **`{}`** represents jsonObject and `[]` represents jsonArray. | There are many good JSON parsing libraries for Java. Try out [Org.JSON](https://github.com/stleary/JSON-java) [(Maven)](http://mvnrepository.com/artifact/org.json/json) or [Jackson Library](https://github.com/FasterXML/jackson) ([Maven](http://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind)) or my personal favorite [Google's GSON Library](https://github.com/google/gson) [(Maven)](http://mvnrepository.com/artifact/com.google.code.gson/gson) that can convert Java Objects into JSON and back. |
37,770,930 | I have a JSON file and need to get the parameter ' fulltext ' , but I'm new to JSON and do not know how to retrieve it in Java . Could someone explain to me how caught this value fulltext ?
Here a piece of the file in JSON.
```
{
"head": {
"vars": [ "author" , "title" , "paper" , "fulltext" ]
} ,
"results": {
"bindings": [
{
"author": { "type": "uri" , "value": "http://data.linkededucation.org/resource/lak/person/richard-scheines" } ,
"title": { "type": "literal" , "value": "Discovering Prerequisite Relationships among Knowledge Components" } ,
"paper": { "type": "uri" , "value": "http://data.linkededucation.org/resource/lak/conference/edm2014/paper/492" } ,
"fulltext": { "type": "literal" , "value": "GET TEXT" }
} ,
``` | 2016/06/12 | [
"https://Stackoverflow.com/questions/37770930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6363322/"
]
| Json library download from here **jar** dowonload form [here](http://central.maven.org/maven2/org/json/json/20160212/json-20160212.jar)
Add this code in **JSonParsing.java**
```
import org.json.*;
public class JSonParsing {
public static void main(String[] args){
String source = "{\n" +
" \"head\": {\n" +
" \"vars\": [ \"author\" , \"title\" , \"paper\" , \"fulltext\" ]\n" +
" } ,\n" +
" \"results\": {\n" +
" \"bindings\": [\n" +
" {\n" +
" \"author\": { \"type\": \"uri\" , \"value\": \"http://data.linkededucation.org/resource/lak/person/richard-scheines\" } ,\n" +
" \"title\": { \"type\": \"literal\" , \"value\": \"Discovering Prerequisite Relationships among Knowledge Components\" } ,\n" +
" \"paper\": { \"type\": \"uri\" , \"value\": \"http://data.linkededucation.org/resource/lak/conference/edm2014/paper/492\" } ,\n" +
" \"fulltext\": { \"type\": \"literal\" , \"value\": \"GET TEXT\" }\n" +
" }\n" +
" ]\n" +
" }\n" +
"}\n" +
"";
JSONObject main = new JSONObject(source);
JSONObject results = main.getJSONObject("results");
JSONArray bindings = results.getJSONArray("bindings");
JSONObject firstObject = bindings.getJSONObject(0);
JSONObject fulltextOfFirstObject = firstObject.getJSONObject("fulltext");
String type = fulltextOfFirstObject.getString("type");
String value = fulltextOfFirstObject.getString("value");
System.out.println("Type :"+ type+"\nValue :"+value);
}
}
```
NOTE: In JSON **`{}`** represents jsonObject and `[]` represents jsonArray. | I recommend you using <https://github.com/alibaba/fastjson> , It's easy to use. |
19,250 | Can the [psychology](http://en.wikipedia.org/wiki/Psychology) of a middle-aged person alter their immune health? I have read about the different types of linkage between nervous system and immune system.
Can someone outline the general facts about what is understood about this? | 2014/06/22 | [
"https://biology.stackexchange.com/questions/19250",
"https://biology.stackexchange.com",
"https://biology.stackexchange.com/users/8101/"
]
| I'm not sure what you mean by psychology exactly, but assuming you are referring to a persons mental state there is a known link between stress and immunity. This link occurs through neuro-endocrine pathways. The central nervous system and endocrine (hormonal) systems are linked through the hypothalamus, a key controller of hormone release in the central nervous system. In a state of stress our central nervous system reacts by increasing the release of hormones such as the steroid cortisol and catacholamines such as adrenaline (a.k.a epinephrine in USA).
We know that steroids have an effect of dampening down the immune system (in fact steroids are often used for this intentionally in the case of autoimmune conditions for example). Thus based on this we have a scenario where stress can lead to increase in cortisol (and other hormones) which in turn can have an effect on your immunity. The effect to which this impacts on your life is then further dependent on your psychology and social support.
More generally, the links between illness and psychology are integrated together in what is called the biopsychosocial model of illness. I suggest you look this up to gain a more in depth understanding of this complicated issue. | **Yes.** It's called Psychoneuroimmunology [Ziemssen & Kern 2007](https://pubmed.ncbi.nlm.nih.gov/17503136/):
>
> There is evidence for rich neural connections with
> lymphoid tissue [Steinman et al.(2004)](https://pubmed.ncbi.nlm.nih.gov/15164017/). Receptors for various neurotrans
> mitters beyond acetylcholine and norepinephrine are
> also present on lymphocytes. Whereas the parasympa
> thetic neurotransmitter acetylcholine potently modu
> lates several classical immune reactions via the vagus
> nerve, the sympathetic nervous system can alter the
> TH1/TH2 balance through stimulation of the beta-
> adrenergic receptor for example [Elenkov et al. 2000](https://pubmed.ncbi.nlm.nih.gov/11121511/)
>
>
>
In general: Personal well being (PWB) makes you healthier, Psychological Ill-Being (PIB) makes you unhealthier, here are some snippets of a review ([Abdurachman & Herawati 2018](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5876785/)):
**Coping mechanisms improved the outcome of AIDS patients**
>
> Religious coping and social support as an effort towards PWB showed to boost the immune responses in people living with HIV/AIDS (Dalmida et al, 2013). They used CD4 + cell count to prove their findings. Then, the effort to PWB via religious coping was definitely associated with reduced psychological distress, increased health-related quality of life (HRQoL), and better medication adherence (8-item Morisky Medication Adherence). [Dalmida et al, 2013](https://journals.sagepub.com/doi/10.2190/PM.46.1.e)
>
>
>
**Weeks of Playing music shifts your immune system from inflammatory to anti-inflammatory**
>
> Researchers found an increased immune response through various indicators obtained through saliva samples such as: cortisol, cytokines and interleukin (IL) -4, IL-6, IL-17, tumor necrosis factor-alpha (TNF-α), and monocyte protein chemoattractant (MCP) -1 ([Fancourt et al., 2016b](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4790847/)). This study shows the psychological benefits of group drumming and shows the underlying biological effects, supporting the therapeutic potential for mental health.
>
>
>
---
One might think that this all comes down to happy = no stress. Since there is tons of research out there proving that
***STRESS makes you unhealthy***
Spinorial already mentioned the stress hormone cortisol and its effect on dampening the immune system. Here I wanna provide some more facts that I took from this review ([Yaribeygi et al. 2017](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5579396/) doi: 10.17179/excli2017-480):
**Stress makes your immune system to attack your guts**
Stress can re-activate previous inflammation of your gastrointestinal system. It can get worse:
>
> As a result, there is an increase in the permeability of cells and recruitment of T lymphocytes. Lymphocyte aggregation leads to the production of inflammatory markers, activates key pathways in the hypothalamus, and results in negative feedback due to CRH secretion, which ultimately results in the appearance of [gastrointestinal system] inflammatory diseases. [...] It has been suggested that even childhood stress can lead to these diseases in adulthood ([Schwartz and Schwartz, 1983](https://pubmed.ncbi.nlm.nih.gov/7095983/), found in [Yaribeygi et al. 2017](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5579396/)).
>
>
>
**Stress stops the immune system from killing cancer**
>
> stress can decrease the activity of cytotoxic T lymphocytes and natural killer cells and lead to growth of malignant cells, genetic instability, and tumor expansion ([Reiche et al. 2004](https://pubmed.ncbi.nlm.nih.gov/15465465/) found in [Yaribeygi et al. 2017](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5579396/))
>
>
>
**Stress slowly kills you by damaging your blood vessels and heart**
Most human deaths can be related to accumulated damages to the cardiovascular system (So stop worrying about immune system). The mechanism behind stress killing you seems to be fairly simple:
>
> Stress can stimulate the autonomic sympathetic nervous system to increase vasoconstriction, which can mediate an increase in blood pressure, an increase in blood lipids, disorders in blood clotting, vascular changes, atherogenesis; all, of which, can cause cardiac arrhythmias and subsequent myocardial infarction
>
>
>
**Stress Shortens Telomeres**
I came across a paper when I was answering a question about telomeres. Mental stress shortens telomeres ([Epel et al 2004](https://www.pnas.org/doi/10.1073/pnas.0407162101)). To understand how short telomeres affect the immune system, aging and health see [Does Telomere length shortening cause our cells to stop functioning properly?](https://biology.stackexchange.com/questions/106963/does-telomere-length-shortening-with-age-actually-cause-our-cells-to-age-and-sto/109201#109201) |
25,103 | In WC3 TFT when you're doing ladder, you can view a lot of statistics online, e.g:
<http://classic.battle.net/war3/ladder/w3xp-player-stats.aspx?Gateway=Azeroth&PlayerName=Jorgie>
I've been trying to find the similar information for SC2 but the most I can see is a basic match history and the # of wins, am I missing something? It would be nice to view a detailed statistical information about your profile.
Thanks! | 2011/06/22 | [
"https://gaming.stackexchange.com/questions/25103",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/1789/"
]
| [SC2 Ranks](http://sc2ranks.com) has a match history, and can also show win percentage by map, but I believe they skim off the Battle.Net API, so it won't be any more than Blizzard provides in the first place.
If you want more information about *your own* matches, [SC2 Gears](https://sites.google.com/site/sc2gears/) can look through all your past replays and give you much more information. What it can do is too extensive to list here, check out their [features page](https://sites.google.com/site/sc2gears/features/replay-analyzer). | Check out [sc2drill](http://sc2drill.com)

You can filter by matchup/type and team size too. |
192,976 | I have a similar problem to [this post](https://stackoverflow.com/questions/174535/google-maps-overlays). I need to display up to 1000 polygons on an embedded Google map. The polygons are in a SQL database, and I can render each one as a single KML file on the fly using a custom HttpHandler (in ASP.NET), like this <http://alpha.foresttransparency.org/concession.1.kml> .
Even on my (very fast) development machine, it takes a while to load up even a couple dozen shapes. So two questions, really:
1. What would be a good strategy for rendering these as markers instead of overlays once I'm beyond a certain zoom level?
2. Is there a publicly available algorithm for simplifying a polygon (reducing the number of points) so that I'm not showing more points than make sense at a certain zoom level? | 2008/10/10 | [
"https://Stackoverflow.com/questions/192976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
]
| For your second question: you need the [Douglas-Peucker Generalization Algorithm](http://everything2.com/index.pl?node_id=859282) | I don't know much aobut KML, but I think the usual solution to question #2 involves iterating over the points, and deleting any line segments under a certain size. This will cause some "unfortunate" effects in some cases, but it's relatively fast and easy to do. |
192,976 | I have a similar problem to [this post](https://stackoverflow.com/questions/174535/google-maps-overlays). I need to display up to 1000 polygons on an embedded Google map. The polygons are in a SQL database, and I can render each one as a single KML file on the fly using a custom HttpHandler (in ASP.NET), like this <http://alpha.foresttransparency.org/concession.1.kml> .
Even on my (very fast) development machine, it takes a while to load up even a couple dozen shapes. So two questions, really:
1. What would be a good strategy for rendering these as markers instead of overlays once I'm beyond a certain zoom level?
2. Is there a publicly available algorithm for simplifying a polygon (reducing the number of points) so that I'm not showing more points than make sense at a certain zoom level? | 2008/10/10 | [
"https://Stackoverflow.com/questions/192976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
]
| For your first question, could you calculate the area of a particular polygon, and relate each zoom level to a particular minimum area, so as you zoom in or out polygon's disappear and markers appear depending on the zoom level.
For the second question, I'd use Mark Bessey's suggestion. | I don't know much aobut KML, but I think the usual solution to question #2 involves iterating over the points, and deleting any line segments under a certain size. This will cause some "unfortunate" effects in some cases, but it's relatively fast and easy to do. |
192,976 | I have a similar problem to [this post](https://stackoverflow.com/questions/174535/google-maps-overlays). I need to display up to 1000 polygons on an embedded Google map. The polygons are in a SQL database, and I can render each one as a single KML file on the fly using a custom HttpHandler (in ASP.NET), like this <http://alpha.foresttransparency.org/concession.1.kml> .
Even on my (very fast) development machine, it takes a while to load up even a couple dozen shapes. So two questions, really:
1. What would be a good strategy for rendering these as markers instead of overlays once I'm beyond a certain zoom level?
2. Is there a publicly available algorithm for simplifying a polygon (reducing the number of points) so that I'm not showing more points than make sense at a certain zoom level? | 2008/10/10 | [
"https://Stackoverflow.com/questions/192976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
]
| For your second question: you need the [Douglas-Peucker Generalization Algorithm](http://everything2.com/index.pl?node_id=859282) | I would recommend 2 things:
- Calculate and combine polygons that are touching. This involves a LOT of processing and hard math, but I've done it so I know it's possible.
- Create your own overlay instead of using KML in PNG format, while you combine them in the previous suggestion. You'll have to create a LOT of PNGs but it is blazing fast on the client.
Good luck :) |
192,976 | I have a similar problem to [this post](https://stackoverflow.com/questions/174535/google-maps-overlays). I need to display up to 1000 polygons on an embedded Google map. The polygons are in a SQL database, and I can render each one as a single KML file on the fly using a custom HttpHandler (in ASP.NET), like this <http://alpha.foresttransparency.org/concession.1.kml> .
Even on my (very fast) development machine, it takes a while to load up even a couple dozen shapes. So two questions, really:
1. What would be a good strategy for rendering these as markers instead of overlays once I'm beyond a certain zoom level?
2. Is there a publicly available algorithm for simplifying a polygon (reducing the number of points) so that I'm not showing more points than make sense at a certain zoom level? | 2008/10/10 | [
"https://Stackoverflow.com/questions/192976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
]
| For your first question, could you calculate the area of a particular polygon, and relate each zoom level to a particular minimum area, so as you zoom in or out polygon's disappear and markers appear depending on the zoom level.
For the second question, I'd use Mark Bessey's suggestion. | I would recommend 2 things:
- Calculate and combine polygons that are touching. This involves a LOT of processing and hard math, but I've done it so I know it's possible.
- Create your own overlay instead of using KML in PNG format, while you combine them in the previous suggestion. You'll have to create a LOT of PNGs but it is blazing fast on the client.
Good luck :) |
192,976 | I have a similar problem to [this post](https://stackoverflow.com/questions/174535/google-maps-overlays). I need to display up to 1000 polygons on an embedded Google map. The polygons are in a SQL database, and I can render each one as a single KML file on the fly using a custom HttpHandler (in ASP.NET), like this <http://alpha.foresttransparency.org/concession.1.kml> .
Even on my (very fast) development machine, it takes a while to load up even a couple dozen shapes. So two questions, really:
1. What would be a good strategy for rendering these as markers instead of overlays once I'm beyond a certain zoom level?
2. Is there a publicly available algorithm for simplifying a polygon (reducing the number of points) so that I'm not showing more points than make sense at a certain zoom level? | 2008/10/10 | [
"https://Stackoverflow.com/questions/192976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
]
| For your second question: you need the [Douglas-Peucker Generalization Algorithm](http://everything2.com/index.pl?node_id=859282) | For your first question, could you calculate the area of a particular polygon, and relate each zoom level to a particular minimum area, so as you zoom in or out polygon's disappear and markers appear depending on the zoom level.
For the second question, I'd use Mark Bessey's suggestion. |
192,976 | I have a similar problem to [this post](https://stackoverflow.com/questions/174535/google-maps-overlays). I need to display up to 1000 polygons on an embedded Google map. The polygons are in a SQL database, and I can render each one as a single KML file on the fly using a custom HttpHandler (in ASP.NET), like this <http://alpha.foresttransparency.org/concession.1.kml> .
Even on my (very fast) development machine, it takes a while to load up even a couple dozen shapes. So two questions, really:
1. What would be a good strategy for rendering these as markers instead of overlays once I'm beyond a certain zoom level?
2. Is there a publicly available algorithm for simplifying a polygon (reducing the number of points) so that I'm not showing more points than make sense at a certain zoom level? | 2008/10/10 | [
"https://Stackoverflow.com/questions/192976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
]
| For your second question: you need the [Douglas-Peucker Generalization Algorithm](http://everything2.com/index.pl?node_id=859282) | I needed a solution to your #2 question a little bit ago and after looking at a few of the available line-simplification algorithms, I created my own.
The process is simple and it seems to work well, though it can be a bit slow if you don't implement it correctly:
**`P[0..n]`** is your array of points
Let **`T[n]`** be defined as the triangle formed by points **`P[n-1], P[n], P[n+1]`**
**`Max`** is the number of points you are trying to reduce this line to.
1. Calculate the area of every possible triangle `T[1..n-1]` in the set.
2. Choose the triangle `T[i]` with the smallest area
3. Remove the point `P[i]` to essentially flatten the triangle
4. Recalculate the area of the affected triangles `T[n-1], T[n+1]`
5. Go To Step #2 if the number of points > `Max` |
192,976 | I have a similar problem to [this post](https://stackoverflow.com/questions/174535/google-maps-overlays). I need to display up to 1000 polygons on an embedded Google map. The polygons are in a SQL database, and I can render each one as a single KML file on the fly using a custom HttpHandler (in ASP.NET), like this <http://alpha.foresttransparency.org/concession.1.kml> .
Even on my (very fast) development machine, it takes a while to load up even a couple dozen shapes. So two questions, really:
1. What would be a good strategy for rendering these as markers instead of overlays once I'm beyond a certain zoom level?
2. Is there a publicly available algorithm for simplifying a polygon (reducing the number of points) so that I'm not showing more points than make sense at a certain zoom level? | 2008/10/10 | [
"https://Stackoverflow.com/questions/192976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
]
| For your first question, could you calculate the area of a particular polygon, and relate each zoom level to a particular minimum area, so as you zoom in or out polygon's disappear and markers appear depending on the zoom level.
For the second question, I'd use Mark Bessey's suggestion. | I needed a solution to your #2 question a little bit ago and after looking at a few of the available line-simplification algorithms, I created my own.
The process is simple and it seems to work well, though it can be a bit slow if you don't implement it correctly:
**`P[0..n]`** is your array of points
Let **`T[n]`** be defined as the triangle formed by points **`P[n-1], P[n], P[n+1]`**
**`Max`** is the number of points you are trying to reduce this line to.
1. Calculate the area of every possible triangle `T[1..n-1]` in the set.
2. Choose the triangle `T[i]` with the smallest area
3. Remove the point `P[i]` to essentially flatten the triangle
4. Recalculate the area of the affected triangles `T[n-1], T[n+1]`
5. Go To Step #2 if the number of points > `Max` |
19,343,518 | I have an edittext for which I want to set below background
but when I set this as background it stretches itself to fit in whole EditText like below image.
and below is my code for xml file for editext
```
<LinearLayout
android:id="@+id/footer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:visibility="visible" >
<EditText
android:id="@+id/comment"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:hint="@string/add_your_comment"
android:imeOptions="actionDone"
android:padding="5dp"
android:background="@drawable/bg_search_field"
android:scrollHorizontally="true"
android:singleLine="true" />
<ImageView
android:id="@+id/post_comment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:padding="5dp"
android:layout_marginRight="@dimen/fifteen_dp"
android:src="@drawable/tick_selection" />
</LinearLayout>
```
How can I set the background correctly? | 2013/10/13 | [
"https://Stackoverflow.com/questions/19343518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1109493/"
]
| Ok So issue resolved simply by using nine patch image i have got from actionBarsherlock library which is using it for it's search view. | This line.-
```
android:layout_weight="1"
```
makes your `TextView` fill the empty width in the `LinearLayout`. Just try and remove it. You should also replace
```
android:padding="5dp"
```
for
```
android:layout_margin="5dp"
``` |
19,343,518 | I have an edittext for which I want to set below background
but when I set this as background it stretches itself to fit in whole EditText like below image.
and below is my code for xml file for editext
```
<LinearLayout
android:id="@+id/footer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:visibility="visible" >
<EditText
android:id="@+id/comment"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:hint="@string/add_your_comment"
android:imeOptions="actionDone"
android:padding="5dp"
android:background="@drawable/bg_search_field"
android:scrollHorizontally="true"
android:singleLine="true" />
<ImageView
android:id="@+id/post_comment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:padding="5dp"
android:layout_marginRight="@dimen/fifteen_dp"
android:src="@drawable/tick_selection" />
</LinearLayout>
```
How can I set the background correctly? | 2013/10/13 | [
"https://Stackoverflow.com/questions/19343518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1109493/"
]
| Ok So issue resolved simply by using nine patch image i have got from actionBarsherlock library which is using it for it's search view. | ```
// try this
<LinearLayout
android:id="@+id/footer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:visibility="visible" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center_vertical">
<EditText
android:id="@+id/comment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="add_your_comment"
android:imeOptions="actionDone"
android:padding="5dp"
android:background="@drawable/bg_search_field"
android:scrollHorizontally="true"
android:singleLine="true" />
</LinearLayout>
<ImageView
android:id="@+id/post_comment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:padding="5dp"
android:layout_marginRight="@dimen/fifteen_dp"
android:src="@drawable/tick_selection" />
</LinearLayout>
// also use my uploaded image which is editext background i'm apply 9-patch so now it not stretched if editext width is large.
```
 |
57,433,195 | Unable to locate image hyperlink on my profile.
Tried using `xpath`, `css locator` but nothing worked.
1. `driver.findElement(By.cssSelector("//img[contains(@src,'https://d3ejdag3om7lbm.cloudfront.net/assets/img/Default User.png')]")).click();`
2. `driver.findElement(By.xpath("//span[@class='user_name']")).click();`
3. `driver.findElement(By.cssSelector("span[class='user_name']")).click();`
Selenium fails to find the element.
[enter image description here](https://i.stack.imgur.com/xOo1t.png) | 2019/08/09 | [
"https://Stackoverflow.com/questions/57433195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11908159/"
]
| Converting my comments to answer to help out future visitors to easily find a quick solution.
```
Options +FollowSymlinks -MultiViews
RewriteEngine On
# redirect to https
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# pass query parameter to a php file internally
RewriteRule ^services/([\w-]+)/?$ services.php?param=$1 [L,NC,QSA]
# handle .php extension
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^.]+)/?$ $1.php [L]
``` | I modified your rules, check it:
```
Options +FollowSymlinks
RewriteEngine On
RewriteRule ^services\/(.*)$ /services#$1 [R=301,L]
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
``` |
14,496,831 | This is the code I am using to get string coming through a SBJson parsing:
```
NSMutableArray *abc=[jsonData valueForKey:@"items"];
NSString *imgStr=(NSString *)[abc valueForKey:@"image"];
NSLog(@"%@",imgStr);
```
here abc is `NSMutableArray`
and the exception it is throwing is
```
> -[__NSArrayI stringByReplacingOccurrencesOfString:withString:]: unrecognized selector sent to instance
``` | 2013/01/24 | [
"https://Stackoverflow.com/questions/14496831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1983242/"
]
| In the first line you declare `abc` to be an `NSMutableArray`
In the second line you attempt to access it as an `NSDictionary`.
In your case (and I am guessing here), I expect you have an array of items, and each item is a dictionary with an "image" key.
So to get your first item you might use
```
NSDictionary* firstItem = [abc objectAtIndex:0];
```
Then you can extract your image from that:
~~NSString \*imgStr=(NSString \*)[firstItem valueForKey:@"image"];~~1
```
NSString *imgStr = [abc objectForKey:@"image"];
```
1 see comment from @Stig | Your code has several problems:
1. For NSArray, `valueForKey:` returns another array. It does *not* return an NSString, regardless of your cast. You need get a reference to the first entry in the array, then call `objectForKey:` on that.
2. You're using the NSKeyValueCoding method `valueForKey:` where you're probably intending to use the NSDictionary method `objectForKey:`. For dictionaries they are roughly interchangeable, but if you'd used `objectForKey:` you would have got an easy to understand error about not being able to call `objectForKey:` on an array. **Use `valueForKey:` only when you really want key-value-coding semantics.**
3. You almost *never* need to cast `id` in Objective-C. You're only hiding errors that way. (It may or may not be hiding your problem in this instance, but it's certainly uglier, incorrect (because you're trying to cast an array to a string) and just fooling you into thinking you have a string because the cast didn't fail.)
You probably meant to write something like this:
```
NSArray *abc = [jsonData valueForKey:@"items"];
NSDictionary *entry = [abc objectAtIndex:0];
NSString *imgStr = [entry objectForKey:@"image"];
NSLog(@"%@", imgStr);
``` |
53,755,508 | I would like to run multiple Hive queries, preferably in parallel rather than sequentially, and store the output of each query into a csv file. For example, `query1` output in `csv1`, `query2` output in `csv2`, etc. I would be running these queries after leaving work with the goal of having output to analyze during the next business day. I am interested in using a bash shell script because then I'd be able to set-up a `cron` task to run it at a specific time of day.
I know how to store the results of a HiveQL query in a CSV file, one query at a time. I do that with something like the following:
```
hive -e
"SELECT * FROM db.table;"
" | tr "\t" "," > example.csv;
```
The problem with the above is that I have to monitor when the process finishes and manually start the next query. I also know how to run multiple queries, in sequence, like so:
```
hive -f hivequeries.hql
```
Is there a way to combine these two methods? Is there a smarter way to achieve my goals?
Code answers are preferred since I do not know bash well enough to write it from scratch.
This question is a variant of another question: [How do I output the results of a HiveQL query to CSV?](https://stackoverflow.com/questions/18129581/how-do-i-output-the-results-of-a-hiveql-query-to-csv) | 2018/12/13 | [
"https://Stackoverflow.com/questions/53755508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2205916/"
]
| You can run and monitor parallel jobs in a shell script:
```
#!/bin/bash
#Run parallel processes and wait for their completion
#Add loop here or add more calls
hive -e "SELECT * FROM db.table1;" | tr "\t" "," > example1.csv &
hive -e "SELECT * FROM db.table2;" | tr "\t" "," > example2.csv &
hive -e "SELECT * FROM db.table3;" | tr "\t" "," > example3.csv &
#Note the ampersand in above commands says to create parallel process
#You can wrap hive call in a function an do some logging in it, etc
#And call a function as parallel process in the same way
#Modify this script to fit your needs
#Now wait for all processes to complete
#Failed processes count
FAILED=0
for job in `jobs -p`
do
echo "job=$job"
wait $job || let "FAILED+=1"
done
#Final status check
if [ "$FAILED" != "0" ]; then
echo "Execution FAILED! ($FAILED)"
#Do something here, log or send messege, etc
exit 1
fi
#Normal exit
#Do something else here
exit 0
```
There are other ways (using XARGS, GNU parallel) to run parallel processes in shell and a lot of resources on it. Read also <https://www.slashroot.in/how-run-multiple-commands-parallel-linux> and <https://thoughtsimproved.wordpress.com/2015/05/18/parellel-processing-in-bash/> | With GNU Parallel it looks like this:
```
doit() {
id="$1"
hive -e "SELECT * FROM db.table$id;" | tr "\t" "," > example"$id".csv
}
export -f doit
parallel --bar doit ::: 1 2 3 4
```
If your queries do not share the same template you can do:
```
queries.txt:
SELECT * FROM db.table1;
SELECT id,name FROM db.person;
... other queries ...
cat queries.txt | parallel --bar 'hive -e {} | tr "\t" "," > example{#}.csv'
```
Spend 15 minute on reading chapter 1+2 of <https://doi.org/10.5281/zenodo.1146014> to learn the basics and chapter 7 to learn more on how to run more jobs in parallel. |
231,859 | I am working with a library that has a base class Base, and three class descending from it Destination, Amenity and Landmarks.
The Base class looks something like this
```
public class Base {
public Integer id;
public String externalId;
public Base() {
}
public int getId() {
return this.id;
}
public String getExternalId() {
return this.externalId != null ? this.externalId : "";
}
}
```
The children classes look like this
```
public class Destination extends Base implements Parcelable {
private String name;
private String description;
private Point[] points
public String getName() {
return this.name;
}
public String getDescription() {
return this.description;
}
public Point[] getPoints(){
return this.points;
}
}
```
The important thing to note here is that the three child classes have the points property and the getPoints getter for accessing it. If it was my implementation, I would bring the points field into the base class to avoid replicating multiple times in the child classes but like I said, it's a library and I cannot modify the source.
While working with the library I have ran into a situation where I have had to use the `instanceof` function multiple times and since this is considered a code smell, I'd like to know if there is a better way of going about it. The situation I'm describing happens when I try to get one of the child objects when a point item is specidied, the code looks like this right now
```
public static <T> T getCurrentMapObjectWithPoint(Point point, T [] bases){
T base = null;
for(T model: bases){
Point[] points = getpointsArrayFromMapObject(model);
for(Point currentpoint: points){
if(currentpoint.id.equals(point.id)){
return base;
}
}
}
return base;
}
private static <T> point[] getpointsArrayFromMapObject(T base){
if(base instanceof Amenity ){
return ((Amenity) base).getpoints();
} else if(base instanceof Destination){
return ((Destination) base).getpoints();
} else if (base instanceof LandMark){
return ((LandMark) base).getpoints();
}
return new point[]{};
}
```
So simply put, given a `Point` and list of map items(`T[] base` - which means and array of either Amenity, Destination or Landmark) I'm trying to figure out which Amenity, Destination or LandMark the point belongs to which means I have to go throgh the list of map items and for each item, go through the points for that item and whenever the point id is equal to the id of the point given at the start I break out of the loop and return the current map item. Is there a better way of doing this without using `instanceof` multiple times? | 2019/11/05 | [
"https://codereview.stackexchange.com/questions/231859",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/212659/"
]
| Create a class that extends `Base` that has the `points` field and have your 3 classes extend that class.
Your improved method would look like this: (Note: you should give it a better name)
```
private static <T> point[] getpointsArrayFromMapObject(T base){
if(base instanceof MyBase ){
return ((MyBase) base).getpoints();
}
return new point[]{};
}
```
However It looks like these methods only relate to the type `Base`. If so you can change your generic to extend from it:
```
private static <T extends MyBase> point[] getpointsArrayFromMapObject(T base)
{
return base.getpoints();
}
```
You should note it does not matter if each class implements its own `getPoints` method. The correct method will be executed based on the type of Object passed. This is known as `polymorphism`.
At which point, there is no need for an additional method:
```
public static <T extends Base> T getCurrentMapObjectWithPoint(Point point, T [] bases){
T base = null;
for(T model: bases){
Point[] points = base.getPoints();
for(Point currentpoint: points){
if(currentpoint.id.equals(point.id)){
return base;
}
}
}
return base;
}
``` | You *cannot* avoid some kind of `instanceof` checks but you can do them once only. This is useful if you intend to check the *same* objects multiple times. It seems like a lot of effort but I've had to deal with co-mingled types a few times over the years so it's a useful pattern to know.
### Example 1 - group by Class
Here we map a stream of unrelated classes into something that can be operated on by type-specific code. There is some ugly (but semantically safe) type-erasure going on in there.
```java
@SuppressWarnings("unchecked")
private static Object findByPoint(String target, Map<Class, List> mapped ) {
for( String s : (List<String>)mapped.get(String.class) ) {
if ( s.equals(target)) return s;
}
for( Long l : (List<Long>)mapped.get(Long.class) ) {
if ( l.toString().equals(target)) return l;
}
for( Float f : (List<Float>)mapped.get(Float.class) ) {
if ( f.toString().equals(target)) return f;
}
return null;
}
public static void main(String[] args) {
Object[] things = {"", 1L, 2f};
Map<Class, List> mapped = (Map)Arrays.stream(things)
.collect(groupingBy(Object::getClass));
Object o = findByPoint("1", mapped);
}
```
### Example 2 - group by Enum
If you want something more "runtime optimisable" then separate the conditional code into discrete classes. `Enums` and `EnumMap` are good for this.
```java
@SuppressWarnings( {"unchecked", "unused"})
private enum BaseType {
StringType() {
@Override
String findByPoint(String target, List items) {
for (String s : (List<String>)items) {
if (s.equals(target)) {
return s;
}
}
return null;
}
},
LongType() {
@Override
Long findByPoint(String target, List items) {
for (Long l : (List<Long>)items) {
if (l.toString().equals(target)) {
return l;
}
}
return null;
}
},
FloatType() {
@Override
Float findByPoint(String target, List items) {
for (Float f : (List<Float>)items) {
if (f.toString().equals(target)) {
return f;
}
}
return null;
}
};
abstract <T> T findByPoint(String target, List items);
public static BaseType typeForObject(Object o) {
return BaseType.valueOf(o.getClass().getSimpleName() + "Type"); // TODO Neither clever nor safe
}
}
private static Object findByPoint(String target, Map<BaseType, List<Object>> mapped) {
Object o;
for (Map.Entry<BaseType, List<Object>> entry : mapped.entrySet()) {
if ((o = entry.getKey().findByPoint(target, entry.getValue())) != null) {
return o;
}
}
return null;
}
public static void main(String[] args) {
Object[] things = {"", 1L, 2f};
Map<BaseType, List<Object>> mapped = Arrays.stream(things)
.collect(groupingBy(BaseType::typeForObject, () -> new EnumMap<>(BaseType.class), toList()));
Object o = findByPoint("1", mapped);
}
````
``` |
231,859 | I am working with a library that has a base class Base, and three class descending from it Destination, Amenity and Landmarks.
The Base class looks something like this
```
public class Base {
public Integer id;
public String externalId;
public Base() {
}
public int getId() {
return this.id;
}
public String getExternalId() {
return this.externalId != null ? this.externalId : "";
}
}
```
The children classes look like this
```
public class Destination extends Base implements Parcelable {
private String name;
private String description;
private Point[] points
public String getName() {
return this.name;
}
public String getDescription() {
return this.description;
}
public Point[] getPoints(){
return this.points;
}
}
```
The important thing to note here is that the three child classes have the points property and the getPoints getter for accessing it. If it was my implementation, I would bring the points field into the base class to avoid replicating multiple times in the child classes but like I said, it's a library and I cannot modify the source.
While working with the library I have ran into a situation where I have had to use the `instanceof` function multiple times and since this is considered a code smell, I'd like to know if there is a better way of going about it. The situation I'm describing happens when I try to get one of the child objects when a point item is specidied, the code looks like this right now
```
public static <T> T getCurrentMapObjectWithPoint(Point point, T [] bases){
T base = null;
for(T model: bases){
Point[] points = getpointsArrayFromMapObject(model);
for(Point currentpoint: points){
if(currentpoint.id.equals(point.id)){
return base;
}
}
}
return base;
}
private static <T> point[] getpointsArrayFromMapObject(T base){
if(base instanceof Amenity ){
return ((Amenity) base).getpoints();
} else if(base instanceof Destination){
return ((Destination) base).getpoints();
} else if (base instanceof LandMark){
return ((LandMark) base).getpoints();
}
return new point[]{};
}
```
So simply put, given a `Point` and list of map items(`T[] base` - which means and array of either Amenity, Destination or Landmark) I'm trying to figure out which Amenity, Destination or LandMark the point belongs to which means I have to go throgh the list of map items and for each item, go through the points for that item and whenever the point id is equal to the id of the point given at the start I break out of the loop and return the current map item. Is there a better way of doing this without using `instanceof` multiple times? | 2019/11/05 | [
"https://codereview.stackexchange.com/questions/231859",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/212659/"
]
| I will assume that you really, really want to use the classes defined in the library and not make your own. Presumably the library classes offer other benefits that were not otherwise relevant to the question.
One thought is that you could define an interface that offers a function with the same signature as `getPoints`, though with a different function name.
```
public interface PointListGettable {
public Point[] getPointList();
}
```
(You'd probably want to come up with a better name than `PointListGettable`, however.)
Extend the offending classes so they implement this interface. For example:
```
public MyDestination extends Destination implements PointListGettable {
public Point[] getPointList() {
return getPoints();
}
}
```
Now you can implement a function with a signature like
```
public PointListGettable getCurrentMapObjectWithPoint(Point point, PointListGettable [] bases)
```
but rather than define a function like your `getpointsArrayFromMapObject`, within the body of the `for(PointListGettable model: bases)` loop you can just write `model.getPointList()`.
If it's just a matter of getting around one perceived defect in the inheritance scheme without using `instanceof`, however, I'm not sure all this is worth it. | You *cannot* avoid some kind of `instanceof` checks but you can do them once only. This is useful if you intend to check the *same* objects multiple times. It seems like a lot of effort but I've had to deal with co-mingled types a few times over the years so it's a useful pattern to know.
### Example 1 - group by Class
Here we map a stream of unrelated classes into something that can be operated on by type-specific code. There is some ugly (but semantically safe) type-erasure going on in there.
```java
@SuppressWarnings("unchecked")
private static Object findByPoint(String target, Map<Class, List> mapped ) {
for( String s : (List<String>)mapped.get(String.class) ) {
if ( s.equals(target)) return s;
}
for( Long l : (List<Long>)mapped.get(Long.class) ) {
if ( l.toString().equals(target)) return l;
}
for( Float f : (List<Float>)mapped.get(Float.class) ) {
if ( f.toString().equals(target)) return f;
}
return null;
}
public static void main(String[] args) {
Object[] things = {"", 1L, 2f};
Map<Class, List> mapped = (Map)Arrays.stream(things)
.collect(groupingBy(Object::getClass));
Object o = findByPoint("1", mapped);
}
```
### Example 2 - group by Enum
If you want something more "runtime optimisable" then separate the conditional code into discrete classes. `Enums` and `EnumMap` are good for this.
```java
@SuppressWarnings( {"unchecked", "unused"})
private enum BaseType {
StringType() {
@Override
String findByPoint(String target, List items) {
for (String s : (List<String>)items) {
if (s.equals(target)) {
return s;
}
}
return null;
}
},
LongType() {
@Override
Long findByPoint(String target, List items) {
for (Long l : (List<Long>)items) {
if (l.toString().equals(target)) {
return l;
}
}
return null;
}
},
FloatType() {
@Override
Float findByPoint(String target, List items) {
for (Float f : (List<Float>)items) {
if (f.toString().equals(target)) {
return f;
}
}
return null;
}
};
abstract <T> T findByPoint(String target, List items);
public static BaseType typeForObject(Object o) {
return BaseType.valueOf(o.getClass().getSimpleName() + "Type"); // TODO Neither clever nor safe
}
}
private static Object findByPoint(String target, Map<BaseType, List<Object>> mapped) {
Object o;
for (Map.Entry<BaseType, List<Object>> entry : mapped.entrySet()) {
if ((o = entry.getKey().findByPoint(target, entry.getValue())) != null) {
return o;
}
}
return null;
}
public static void main(String[] args) {
Object[] things = {"", 1L, 2f};
Map<BaseType, List<Object>> mapped = Arrays.stream(things)
.collect(groupingBy(BaseType::typeForObject, () -> new EnumMap<>(BaseType.class), toList()));
Object o = findByPoint("1", mapped);
}
````
``` |
201,832 | Okay so I am part of two Mage the Awakening 2ed campaigns and the two GM's disagree on the rules for prime sight. What they disagree on is if prime sight is able to see if a mage have active spells.
The rule stats: "... and the presence (if not the composition) of any awakened spell ...".
One of the GMs interpret this as being able to see the spells active in another mages pattern while the other believe it only applies to the spells on objects. Therefore if someone, as an example, has nightvision active (forces dot one spell) another mage with prime sight turned on would or would not be able to see this.
Which interpretation is correct? | 2022/10/03 | [
"https://rpg.stackexchange.com/questions/201832",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/43898/"
]
| **Yes, a mage with prime sight active would be able to see that another mage has a spell active on themselves**
The rules are on page 91. In my opinion, the part you quoted already answers the question. Someone with active prime sight would would at least be able to see that there was an awakened spell affecting the target, even if it was a spell the mage cast on themselves.
I believe expanding the quote removes all reasonable doubt:
>
> Prime Sight highlights anything the mage can use as a Yantra, and the
> presence (if not the composition) of any Awakened spell or Attainment
> effect.
>
>
>
Note the discussion of seeing attainment effects. While there are definitely exceptions, particularly if you allow in some of the older 1e stuff as expanded material, most attainments only affect the mage and are **generally** harder to detect and with less chance of side effects than spells. If prime sight shows attainments, it makes sense for it to show spells affecting the mage. | In my Opinion, it would be yes.
I also agree with Timothy who answered, If you expand the quote even more with more additional text, it infers that you can detect upon a subject as well, which applies to more than objects since somebody is also able to be considered a subject.
* Highlights anything that can be used as a Yantra
* Detects the presence (if not the composition) of any Awakened spell or Attainment effect
* Detects tass or if a subject has mana
* Detects if they are in a Hallow or Node.
* Prime Knowing/Unveiling Spells that add to Prime Sight (but are separate spells): |
41,596,491 | If I remove the part `$this->upload->do_upload('filefoto')` my data is saved into the database, but the image file is not saved to the folder path.
[enter link description here](http://pastebin.com/hHQgt1ap)
Copied from pastebin
```
public function tambahanggota() {
$this->load->library('upload');
$nmfile = "file_".time();
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|bmp';
$config['max_size'] = '3072';
$config['max_width'] = '5000';
$config['max_height'] = '5000';
$config['file_name'] = $nmfile;
$this->upload->initialize($config);
if($_FILES['filefoto']['tmp_name'])
{
if ($this->upload->do_upload('filefoto'))
{
$gbr = $this->upload->data();
$data = array(
'nm_gbr' =>$gbr['file_name']
);
$res = $this->M_tambahdata->tambahdata("anggota",$data);
$config2['image_library'] = 'gd2';
$config2['source_image'] = $this->upload->upload_path.$this->upload->file_name;
$config2['new_image'] = './assets/hasil_resize/';
$config2['maintain_ratio'] = TRUE;
$config2['width'] = 100;
$config2['height'] = 100;
$this->load->library('image_lib',$config2);
if ($res>=1) {
echo "<script>alert('Data berhasil disimpan')</script>";
echo "<script>window.location='".base_url()."dataanggota'</script>";
}
else{
$this->session->set_flashdata('pesan', 'Maaf, ulangi data gagal di inputkan.');
redirect('dashboard/index');
}
}
}
}
```
How can I upload my images? | 2017/01/11 | [
"https://Stackoverflow.com/questions/41596491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6752036/"
]
| on a shared server hosting you may need to provide the **complete relative path** to your upload folder. Also make sure you have all permissions to write a file to that directory!
you can use on a localhost environment
```
$config['upload_path'] = './assets/upload';
```
but on a shared hosting, you'll need to get more specific, normally something like
```
$config['upload_path'] = '/home/yourserver/public_html/assets/upload';
```
You can find this upload\_path, e.g. in your accounts cPanel main page on the left column or might want to call your provider's helpdesk for more info on the correct path. | you missed this
```
$this->upload->upload_path.'/'.$this->upload->file_name;
``` |
9,219,010 | I have a child layer that I'm adding to the scene which contains a menu, it is initialized like so:
```
- (id) init
{
if((self=[super init]))
{
CGSize winSize = [[CCDirector sharedDirector] winSize];
CCMenuItemImage* attackButton = [CCMenuItemImage
itemFromNormalImage:@"btnAttack.png"
selectedImage:@"btnAttack.png"
target: self
selector:@selector(attack)];
CCMenu* menu = [CCMenu menuWithItems:attackButton, nil];
menu.position = ccp(winSize.width-80,winSize.height-140);
[menu alignItemsHorizontally];
[self addChild:menu];
}
return self;
}
```
This crashes with a SIGABRT error unless I change the target: to 'nil'. Why is this not working and how can I fix it? | 2012/02/09 | [
"https://Stackoverflow.com/questions/9219010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/744306/"
]
| I would follow the native API of your tablet. Your tablet's vendor has very well described SDK including several [`examples`](http://www.wacomeng.com/windows/index.html) (in Visual C++).
What you are specifically looking for is [`the eraser detection`](http://www.wacomeng.com/windows/docs/Wintab_v140.htm#_Toc275759917) | Dealing with WinTab is easy enough if all you want is to detect device type. However it can get a lot more confusing if you want to process absolute positions, pen orientation and pressure. There's a good C++ lib for dealing with this:
<http://www.billbaxter.com/projects/bbtablet/index.html>
Even if you don't want to go through the effort of wrapping it to use it directly, you can learn from the source if you get stuck. |
8,034,657 | I have a moveable and closable jquery pop-up notification box. It works well aside from the fact that it pops up every time the page is loaded. What method would I need to implement to allow a user to permanently (or at least semi permanently) close the pop-up box?
If I need to use cookies how would I tie a cookie to a specific action like closing the div? | 2011/11/07 | [
"https://Stackoverflow.com/questions/8034657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1709066/"
]
| yes you can use cookies. when user click on the close button you can write it to the cookies. and when page load, if cookie is not available display the popup | session would be another candidate and its secure than cookies. And you don't have to do anything else than setting a variable on loading popup on first time and check afterwards if that variable is set or not. |
8,034,657 | I have a moveable and closable jquery pop-up notification box. It works well aside from the fact that it pops up every time the page is loaded. What method would I need to implement to allow a user to permanently (or at least semi permanently) close the pop-up box?
If I need to use cookies how would I tie a cookie to a specific action like closing the div? | 2011/11/07 | [
"https://Stackoverflow.com/questions/8034657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1709066/"
]
| yes you can use cookies. when user click on the close button you can write it to the cookies. and when page load, if cookie is not available display the popup | Yes you can use cookies to do the trick, basically you're checking to see if the variable in the cookie is set, if not update the variable:
<http://www.w3schools.com/js/js_cookies.asp>
Don't forget that on close, you should update the cookie variable. |
8,034,657 | I have a moveable and closable jquery pop-up notification box. It works well aside from the fact that it pops up every time the page is loaded. What method would I need to implement to allow a user to permanently (or at least semi permanently) close the pop-up box?
If I need to use cookies how would I tie a cookie to a specific action like closing the div? | 2011/11/07 | [
"https://Stackoverflow.com/questions/8034657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1709066/"
]
| yes you can use cookies. when user click on the close button you can write it to the cookies. and when page load, if cookie is not available display the popup | You could simply use client side cookies: <http://www.w3schools.com/js/js_cookies.asp>
If the user doesn't have a cookie present, display box;
If the user has the cookie present and cookie specifies the user has already closed the box, keep it closed; etc..
It's simple, and doesn't put any extra weight on the server, you can also set a large expiry date if you want the popup not to show on theusers next visit for example.
Although this does depend on what it's for as sessions may also be another way of handling this. (Sessions may mean that if the user comes back the next day for instance, the popup will show again depending on how it's set up) |
8,034,657 | I have a moveable and closable jquery pop-up notification box. It works well aside from the fact that it pops up every time the page is loaded. What method would I need to implement to allow a user to permanently (or at least semi permanently) close the pop-up box?
If I need to use cookies how would I tie a cookie to a specific action like closing the div? | 2011/11/07 | [
"https://Stackoverflow.com/questions/8034657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1709066/"
]
| You could simply use client side cookies: <http://www.w3schools.com/js/js_cookies.asp>
If the user doesn't have a cookie present, display box;
If the user has the cookie present and cookie specifies the user has already closed the box, keep it closed; etc..
It's simple, and doesn't put any extra weight on the server, you can also set a large expiry date if you want the popup not to show on theusers next visit for example.
Although this does depend on what it's for as sessions may also be another way of handling this. (Sessions may mean that if the user comes back the next day for instance, the popup will show again depending on how it's set up) | session would be another candidate and its secure than cookies. And you don't have to do anything else than setting a variable on loading popup on first time and check afterwards if that variable is set or not. |
8,034,657 | I have a moveable and closable jquery pop-up notification box. It works well aside from the fact that it pops up every time the page is loaded. What method would I need to implement to allow a user to permanently (or at least semi permanently) close the pop-up box?
If I need to use cookies how would I tie a cookie to a specific action like closing the div? | 2011/11/07 | [
"https://Stackoverflow.com/questions/8034657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1709066/"
]
| You could simply use client side cookies: <http://www.w3schools.com/js/js_cookies.asp>
If the user doesn't have a cookie present, display box;
If the user has the cookie present and cookie specifies the user has already closed the box, keep it closed; etc..
It's simple, and doesn't put any extra weight on the server, you can also set a large expiry date if you want the popup not to show on theusers next visit for example.
Although this does depend on what it's for as sessions may also be another way of handling this. (Sessions may mean that if the user comes back the next day for instance, the popup will show again depending on how it's set up) | Yes you can use cookies to do the trick, basically you're checking to see if the variable in the cookie is set, if not update the variable:
<http://www.w3schools.com/js/js_cookies.asp>
Don't forget that on close, you should update the cookie variable. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.