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
|
---|---|---|---|---|---|
155,797 | Given a list of positive integers determine if there is an element that is either greater than its two neighbors or less than its two neighbors (a "bump"). To be clear a bump can never be the first or last item of the list because they only have one neighbor.
Your program should output one of two consistent values each corresponding to either a list with no bumps or a list with bumps. What the values are is unimportant you may choose them yourself.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
Test cases
----------
```
[] -> False
[1] -> False
[1,2] -> False
[1,2,1] -> True
[1,2,2] -> False
[1,2,3] -> False
[1,2,2,1] -> False
[1,2,2,3] -> False
[1,2,1,2] -> True
[1,3,2] -> True
[3,1,2] -> True
[2,2,2] -> False
``` | 2018/02/14 | [
"https://codegolf.stackexchange.com/questions/155797",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/56656/"
]
| [MATL](https://github.com/lmendo/MATL), 8 bytes
===============================================
```
dZSd|1>a
```
[Try it online!](https://tio.run/##y00syfn/PyUqOKXG0C7xv716SFFpqnqtultiTnGq@v9oQx1jIDTUMdAxjAUA "MATL – Try It Online") | C (gcc), 78 bytes
=================
*Variant: loop*
```
r,i;f(a,n)int*a;{for(r=n>2,i=0;i<n-2;)r=(a[i++]-a[i])*(a[i]-a[i+1])<0&&r;i=r;}
```
[Try it online!](https://tio.run/##jdPdboIwFAfwe57ihETTakloAT9S2Ys4LoiOpclWFyS7ITw7ayvooE2oN8ih/Z0/R3uJPi@Xvq@J4BUqicRCNpuSt9WtRnUu3xgReczFSUaM4zpH5Vlst0WkLgXe6DvzfUsLfIrX65qLvOZd/3sTV/gS9wYpDjYlAX2VOGgDGD4/tSpVgMI2xPxZVW3B7Bm6ctUNw2uXtXt1DQmYNNxaJNQCnZxi69HUQSH8D9HZITv9vAsCHe27FBKNr6ILzce9oecCcmi7hzKy73J1hVMEKmOFzDICMR5amfk8izyYeOzhAYUlkhGgFmmKMzIZSQJsUU3UIks1xZma/lOJR9yUQGLBpjiDswm8nDhzwZkD3k3gZBHeueCdA95PE/tMY08gtWxTnNmHub2c@@CyDw77OP0JfYZ9dNlHh03jF574yDR2jftRndvDodOwV2pKnTZ12eMBZJ5/P8qcNnPZiTVwrw7qNTO7g6nOO6ST9L5nk6bODunQoev/AA)
*Variant: recursive*
```
f(a,n)int*a;{n=(n<3)?0:((a[--n]-a[--n])*(a[n]-a[n-1])<0&&((n<2)?1:f(a,n+1)));}
```
[Try it online!](https://tio.run/##jdPNjoIwEAfwO08xIdG0WhLagl9gfBCXA9Fl02S3bpTshfDsbCmgQptQLoQ/7W@G0V6Cr8ulaQqUE4mFLFd5UskjkinHp/CAUH4OApkF3Q2v1LN@kgHNcBoul0gtZfhED1pYU4xxUjd/N3GFb/EokSJhlRNo7xJ7lQf99XtXUQHIr3ycPNPidge9RxzDRKQyEes1htcuY/fi6hPIzyJ7Q4ZLqAXKCCg2Xo0d5MN7E7XZZN2@rz2vbe0nFxINn9IG5eejpOcMjlDVnTKwH3JxhTQA1WOB9DICIe5L6fk8w8QbeazzgMIcyQhQg9ThhOQDSYDNqlwtMlQdTtToTSUO7UYEuAHrcALHI3i@49gGxxZ4M4L5LLyxwRsLvB137DKNLYHIsHU4sXdTe77vnc3eWez9@Cd0GfbeZu8tNg1fOHeRaWgbd5dO7f7QtbBT15RabWqzhwPIHP9@lFltZrO5MXCnCuozY7OCTqcVolH3rmeTRtYKUV@hbv4B)
The criteria is that `a[i]-a[i+1] and a[i+1]-a[i+2]` are non-zero and have opposite sign. `i=r` is just a way to return the value ([described here](https://stackoverflow.com/questions/4644860/function-returns-value-without-return-statement)).
P. S. Additional two test cases may reveal bugs: `{ 1, 2, 1, 2, 2 }` and `{ 2, 2, 1, 2, 1 }` |
155,797 | Given a list of positive integers determine if there is an element that is either greater than its two neighbors or less than its two neighbors (a "bump"). To be clear a bump can never be the first or last item of the list because they only have one neighbor.
Your program should output one of two consistent values each corresponding to either a list with no bumps or a list with bumps. What the values are is unimportant you may choose them yourself.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
Test cases
----------
```
[] -> False
[1] -> False
[1,2] -> False
[1,2,1] -> True
[1,2,2] -> False
[1,2,3] -> False
[1,2,2,1] -> False
[1,2,2,3] -> False
[1,2,1,2] -> True
[1,3,2] -> True
[3,1,2] -> True
[2,2,2] -> False
``` | 2018/02/14 | [
"https://codegolf.stackexchange.com/questions/155797",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/56656/"
]
| [J](http://jsoftware.com/), 16 15 bytes
=======================================
-1 byte thanks to FrownyFrog
```
1 e.0>2*/\2-/\]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DRVS9QzsjLT0Y4x09WNi/2tyKXClJmfkK6QpGKgYwJiGcIaCERITRRxVxhhFBk0hqiyKmcYIjjGyDEiX0X8A "J – Try It Online")
Original: 16 bytes
------------------
```
0>[:<./2*/\2-/\]
```
`2-/\]` - differences of each adjacent items
`2*/\` - products of each adjacent items
`[:<./` - the minimum
`0>` - is negative?
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DeyirWz09I209GOMdPVjYv9rcilwpSZn5CukKRioGMCYhnCGghESE0UcVcYYRQZNIaosipnGCI4xsgxIl9F/AA "J – Try It Online") | [Husk](https://github.com/barbuz/Husk), 9 bytes
===============================================
```
▼mεẊ-Ẋo±-
```
[Try it online!](https://tio.run/##yygtzv7//9G0Pbnntj7c1aULxPmHNur@//8/2kgHCGMB "Husk – Try It Online")
Uses Dennis's algorithm. |
155,797 | Given a list of positive integers determine if there is an element that is either greater than its two neighbors or less than its two neighbors (a "bump"). To be clear a bump can never be the first or last item of the list because they only have one neighbor.
Your program should output one of two consistent values each corresponding to either a list with no bumps or a list with bumps. What the values are is unimportant you may choose them yourself.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
Test cases
----------
```
[] -> False
[1] -> False
[1,2] -> False
[1,2,1] -> True
[1,2,2] -> False
[1,2,3] -> False
[1,2,2,1] -> False
[1,2,2,3] -> False
[1,2,1,2] -> True
[1,3,2] -> True
[3,1,2] -> True
[2,2,2] -> False
``` | 2018/02/14 | [
"https://codegolf.stackexchange.com/questions/155797",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/56656/"
]
| [Python 2](https://docs.python.org/2/), 43 bytes
================================================
```python
f=lambda x,y,z,*t:0>(y-x)*(z-y)or f(y,z,*t)
```
Returns *True* if there's a bump, errors if there isn't. ([allowed by default](https://codegolf.meta.stackexchange.com/a/11908/12012))
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRoUKnUqdKR6vEysBOo1K3QlNLo0q3UjO/SCFNAyKh@T8NyCtRyMxTiI7VUYg2BBM6RlBKB8ZHiBjDRZAkEaJwvcYQhjFMxAhsiBUXZ0lRJZDkLCjKzCsBugPoBi7O1Irk1IIShZDKglTXoqL8IoQCt8Sc4tT/AA "Python 2 – Try It Online") | [APL (Dyalog Classic)](https://www.dyalog.com/), 15 bytes
=========================================================
```apl
0∨.>2×/2-/⊃,⊃,⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/00Dko44VenZGh6frG@nqP@pq1oHgRf//lwBlqx/1bn3UuagIyEx71LvLSj0tMTNHHcgCihc96m5Rz89Wr@V61LtGAQJKFAy4NHQMNWFsQwUjBWS2IZhtCGYbIYkbI7FBqhBsYyS9RlC9xlC9hlzGCoZwthHCTAA "APL (Dyalog Classic) – Try It Online") |
155,797 | Given a list of positive integers determine if there is an element that is either greater than its two neighbors or less than its two neighbors (a "bump"). To be clear a bump can never be the first or last item of the list because they only have one neighbor.
Your program should output one of two consistent values each corresponding to either a list with no bumps or a list with bumps. What the values are is unimportant you may choose them yourself.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
Test cases
----------
```
[] -> False
[1] -> False
[1,2] -> False
[1,2,1] -> True
[1,2,2] -> False
[1,2,3] -> False
[1,2,2,1] -> False
[1,2,2,3] -> False
[1,2,1,2] -> True
[1,3,2] -> True
[3,1,2] -> True
[2,2,2] -> False
``` | 2018/02/14 | [
"https://codegolf.stackexchange.com/questions/155797",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/56656/"
]
| [MATL](https://github.com/lmendo/MATL), 8 bytes
===============================================
```
dZSd|1>a
```
[Try it online!](https://tio.run/##y00syfn/PyUqOKXG0C7xv716SFFpqnqtultiTnGq@v9oQx1jIDTUMdAxjAUA "MATL – Try It Online") | [Julia 0.6](http://julialang.org/), 57 56 bytes
===============================================
```julia
l->any(p>c<n||p<c>n for(p,c,n)=zip(l,l[2:end],l[3:end]))
```
Basically just totallyhuman's python answer. -1 byte from user71546
[Try it online!](https://tio.run/##yyrNyUw0@59mm5Sanpn3P0fXLjGvUqPALtkmr6amwCbZLk8hLb9Io0AnWSdP07Yqs0AjRycn2sgqNS8lFsgwBjM0Nf8DKa7S4sy8dAWnxOJUvZDU4hIuhxIgWZxaoqAEYigkAyWKlRTAFkHkFNI0og11jHQMYzXRBHSMUIXMzVHEFGGCQISi0kjHAMk0RahxRmhiQA7Qvf8B "Julia 0.6 – Try It Online")
[Julia 0.6](http://julialang.org/), 39 bytes
============================================
```julia
f(x,y,z,a...)=x>y<z||x<y>z||f(y,z,a...)
```
Lispy recursion style, aka Dennis's python answer. Returns `true` when a bump exists, otherwise throws an error. This should maybe be 42 bytes since you have to splat it when calling. Eg for `a=[1,2,1]` you call as `f(a...)`. `f(a)=f(a...)` would remove that need, but is longer. I need to get better a recursion, and I don't really like writing code that throws an error.
[Try it online!](https://tio.run/##yyrNyUw0@/8/TaNCp1KnSidRT09P07bCrtKmqqamwqbSDkilacBl/pcWZ@alKzglFqfqhaQWl3A5lADJ4tQSBSUQQyEZKFGspJCUmp6ZB5FTSNOINtQx0jGMBelHE9MxwhA1N0cTji/JKMovL1bwTS3JyE9xLSrKL4KrBCJ0E4x0DFDswqndCM1ROBRCVKTmpfwHAA "Julia 0.6 – Try It Online") |
40,917,189 | I want to use WhereIn and Groupby in the same query to fetch Result.
I've tried this:
```
$loadids=explode("#@*",$reciptdet->loading_id);
$loadingdatas=DB::table('loading')->groupBy('vehicle_no')->whereIn('id',$loadids)->get();
```
But I got this error message:
>
> SQLSTATE[42000]: Syntax error or access violation: 1055 'sbrtpt.loading.id' isn't in GROUP BY (SQL: select \* from loading where id in (14, 15, 16) group by vehicle\_no)
>
>
> | 2016/12/01 | [
"https://Stackoverflow.com/questions/40917189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5829419/"
]
| You can leave `'strict' => true` and add modes to "mysql" option in.
```
'mysql' => [
...
....
'strict' => true,
'modes' => [
//'ONLY_FULL_GROUP_BY', // Disable this to allow grouping by one column
'STRICT_TRANS_TABLES',
'NO_ZERO_IN_DATE',
'NO_ZERO_DATE',
'ERROR_FOR_DIVISION_BY_ZERO',
// 'NO_AUTO_CREATE_USER', // This has been deprecated and will throw an error in mysql v8
'NO_ENGINE_SUBSTITUTION'
],
]
``` | This is on laravel doc 8.x , it works well
```
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();
``` |
40,917,189 | I want to use WhereIn and Groupby in the same query to fetch Result.
I've tried this:
```
$loadids=explode("#@*",$reciptdet->loading_id);
$loadingdatas=DB::table('loading')->groupBy('vehicle_no')->whereIn('id',$loadids)->get();
```
But I got this error message:
>
> SQLSTATE[42000]: Syntax error or access violation: 1055 'sbrtpt.loading.id' isn't in GROUP BY (SQL: select \* from loading where id in (14, 15, 16) group by vehicle\_no)
>
>
> | 2016/12/01 | [
"https://Stackoverflow.com/questions/40917189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5829419/"
]
| Without modifiying `config\database.php` file
=============================================
**Set `'strict' => false`** in the `config\database.php` could be a **security issue**. So, a simple Laravel solution could be **first call `get()` and then `groupBy('vehicle_no)`**:
```
$loadids = explode("#@*", $reciptdet->loading_id);
$loadingdatas = DB::table('loading')->whereIn('id', $loadids)->get();
$grouped = $loadingdatas->groupBy('vehicle_no');
``` | update `config/database.php`
set:
```
'mysql' => [
'strict' => false,
],
```
instead of:
```
'mysql' => [
'strict' => true,
],
```
and don't forget to clear cache:
```
php artisan config:cache
``` |
40,917,189 | I want to use WhereIn and Groupby in the same query to fetch Result.
I've tried this:
```
$loadids=explode("#@*",$reciptdet->loading_id);
$loadingdatas=DB::table('loading')->groupBy('vehicle_no')->whereIn('id',$loadids)->get();
```
But I got this error message:
>
> SQLSTATE[42000]: Syntax error or access violation: 1055 'sbrtpt.loading.id' isn't in GROUP BY (SQL: select \* from loading where id in (14, 15, 16) group by vehicle\_no)
>
>
> | 2016/12/01 | [
"https://Stackoverflow.com/questions/40917189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5829419/"
]
| Without modifiying `config\database.php` file
=============================================
**Set `'strict' => false`** in the `config\database.php` could be a **security issue**. So, a simple Laravel solution could be **first call `get()` and then `groupBy('vehicle_no)`**:
```
$loadids = explode("#@*", $reciptdet->loading_id);
$loadingdatas = DB::table('loading')->whereIn('id', $loadids)->get();
$grouped = $loadingdatas->groupBy('vehicle_no');
``` | This restriction makes sense as when you use `GROUP BY` in MySQL, it returns one row for each value in the columns used in `GROUP BY`. So, the values of other columns in the selected rows do not make sense to use anywhere. So, it's always recommended to use the best practice and I would recommend not to disable MySQL Strict Mode.
Often developers may need rows of a query grouped by the value of a column. Here they don't need only one row per the unique values of the columns. But they need multiple rows grouped by the unique values of a particular column. For some reason, they use `groupBy` Query Builder method of Laravel which generates a MySQL `GROUP BY` query and the developers encounter the above error.
The solution to their problem is to use `groupBy` Collection method instead. For example,
```
$loadingData = DB::table('loading')
->whereIn('id', $loadIds)
->get()
->groupBy('vehicle_no');
```
This will give them the desired result. |
40,917,189 | I want to use WhereIn and Groupby in the same query to fetch Result.
I've tried this:
```
$loadids=explode("#@*",$reciptdet->loading_id);
$loadingdatas=DB::table('loading')->groupBy('vehicle_no')->whereIn('id',$loadids)->get();
```
But I got this error message:
>
> SQLSTATE[42000]: Syntax error or access violation: 1055 'sbrtpt.loading.id' isn't in GROUP BY (SQL: select \* from loading where id in (14, 15, 16) group by vehicle\_no)
>
>
> | 2016/12/01 | [
"https://Stackoverflow.com/questions/40917189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5829419/"
]
| Without modifiying `config\database.php` file
=============================================
**Set `'strict' => false`** in the `config\database.php` could be a **security issue**. So, a simple Laravel solution could be **first call `get()` and then `groupBy('vehicle_no)`**:
```
$loadids = explode("#@*", $reciptdet->loading_id);
$loadingdatas = DB::table('loading')->whereIn('id', $loadids)->get();
$grouped = $loadingdatas->groupBy('vehicle_no');
``` | Later, after googling for a while, I learnt that the problem was caused by the `sql_mode` setting, and modified the configuration of **config/database.php** as `strict => false`.
Refer to: <https://stdworkflow.com/147/laravel-syntax-error-or-access-violation-1055-error> |
40,917,189 | I want to use WhereIn and Groupby in the same query to fetch Result.
I've tried this:
```
$loadids=explode("#@*",$reciptdet->loading_id);
$loadingdatas=DB::table('loading')->groupBy('vehicle_no')->whereIn('id',$loadids)->get();
```
But I got this error message:
>
> SQLSTATE[42000]: Syntax error or access violation: 1055 'sbrtpt.loading.id' isn't in GROUP BY (SQL: select \* from loading where id in (14, 15, 16) group by vehicle\_no)
>
>
> | 2016/12/01 | [
"https://Stackoverflow.com/questions/40917189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5829419/"
]
| update `config/database.php`
set:
```
'mysql' => [
'strict' => false,
],
```
instead of:
```
'mysql' => [
'strict' => true,
],
```
and don't forget to clear cache:
```
php artisan config:cache
``` | This restriction makes sense as when you use `GROUP BY` in MySQL, it returns one row for each value in the columns used in `GROUP BY`. So, the values of other columns in the selected rows do not make sense to use anywhere. So, it's always recommended to use the best practice and I would recommend not to disable MySQL Strict Mode.
Often developers may need rows of a query grouped by the value of a column. Here they don't need only one row per the unique values of the columns. But they need multiple rows grouped by the unique values of a particular column. For some reason, they use `groupBy` Query Builder method of Laravel which generates a MySQL `GROUP BY` query and the developers encounter the above error.
The solution to their problem is to use `groupBy` Collection method instead. For example,
```
$loadingData = DB::table('loading')
->whereIn('id', $loadIds)
->get()
->groupBy('vehicle_no');
```
This will give them the desired result. |
40,917,189 | I want to use WhereIn and Groupby in the same query to fetch Result.
I've tried this:
```
$loadids=explode("#@*",$reciptdet->loading_id);
$loadingdatas=DB::table('loading')->groupBy('vehicle_no')->whereIn('id',$loadids)->get();
```
But I got this error message:
>
> SQLSTATE[42000]: Syntax error or access violation: 1055 'sbrtpt.loading.id' isn't in GROUP BY (SQL: select \* from loading where id in (14, 15, 16) group by vehicle\_no)
>
>
> | 2016/12/01 | [
"https://Stackoverflow.com/questions/40917189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5829419/"
]
| No need to change any where in your System jut use code like in laravel
```
\DB::statement("SET SQL_MODE=''");//this is the trick use it just before your query
$data=Task::where('user_id', Auth::user()->id)->where('status', 0)->groupBy('task_code')->get(['id','task_code', 'title']);
``` | Later, after googling for a while, I learnt that the problem was caused by the `sql_mode` setting, and modified the configuration of **config/database.php** as `strict => false`.
Refer to: <https://stdworkflow.com/147/laravel-syntax-error-or-access-violation-1055-error> |
40,917,189 | I want to use WhereIn and Groupby in the same query to fetch Result.
I've tried this:
```
$loadids=explode("#@*",$reciptdet->loading_id);
$loadingdatas=DB::table('loading')->groupBy('vehicle_no')->whereIn('id',$loadids)->get();
```
But I got this error message:
>
> SQLSTATE[42000]: Syntax error or access violation: 1055 'sbrtpt.loading.id' isn't in GROUP BY (SQL: select \* from loading where id in (14, 15, 16) group by vehicle\_no)
>
>
> | 2016/12/01 | [
"https://Stackoverflow.com/questions/40917189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5829419/"
]
| I was having this problem also but after changing `'strict' => true`, to `'strict' => false`, the error disappeared.
You can find this setting in:
**config\database.php**
```
'mysql' => [
...
'strict' => false,
...
]
``` | You might as well use:
**distinct('vehicle\_no')**
instead of groupBy('vehicle\_no') each case scenario is different, but looking at your query, distinct might be the way to go since you're not aggregating data. |
40,917,189 | I want to use WhereIn and Groupby in the same query to fetch Result.
I've tried this:
```
$loadids=explode("#@*",$reciptdet->loading_id);
$loadingdatas=DB::table('loading')->groupBy('vehicle_no')->whereIn('id',$loadids)->get();
```
But I got this error message:
>
> SQLSTATE[42000]: Syntax error or access violation: 1055 'sbrtpt.loading.id' isn't in GROUP BY (SQL: select \* from loading where id in (14, 15, 16) group by vehicle\_no)
>
>
> | 2016/12/01 | [
"https://Stackoverflow.com/questions/40917189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5829419/"
]
| No need to change any where in your System jut use code like in laravel
```
\DB::statement("SET SQL_MODE=''");//this is the trick use it just before your query
$data=Task::where('user_id', Auth::user()->id)->where('status', 0)->groupBy('task_code')->get(['id','task_code', 'title']);
``` | Without modifiying `config\database.php` file
=============================================
**Set `'strict' => false`** in the `config\database.php` could be a **security issue**. So, a simple Laravel solution could be **first call `get()` and then `groupBy('vehicle_no)`**:
```
$loadids = explode("#@*", $reciptdet->loading_id);
$loadingdatas = DB::table('loading')->whereIn('id', $loadids)->get();
$grouped = $loadingdatas->groupBy('vehicle_no');
``` |
40,917,189 | I want to use WhereIn and Groupby in the same query to fetch Result.
I've tried this:
```
$loadids=explode("#@*",$reciptdet->loading_id);
$loadingdatas=DB::table('loading')->groupBy('vehicle_no')->whereIn('id',$loadids)->get();
```
But I got this error message:
>
> SQLSTATE[42000]: Syntax error or access violation: 1055 'sbrtpt.loading.id' isn't in GROUP BY (SQL: select \* from loading where id in (14, 15, 16) group by vehicle\_no)
>
>
> | 2016/12/01 | [
"https://Stackoverflow.com/questions/40917189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5829419/"
]
| Short answer
------------
In `config\database.php` --> `"mysql"` array
Set `'strict' => false` to disable all.
.... or
-------
You can leave `'strict' => true` and add modes to `"mysql"` option in
```
'mysql' => [
...
....
'strict' => true,
'modes' => [
//'ONLY_FULL_GROUP_BY', // Disable this to allow grouping by one column
'STRICT_TRANS_TABLES',
'NO_ZERO_IN_DATE',
'NO_ZERO_DATE',
'ERROR_FOR_DIVISION_BY_ZERO',
'NO_AUTO_CREATE_USER',
'NO_ENGINE_SUBSTITUTION'
],
]
```
---
Detailed answer
---------------
You may not need to disable all **strict** options ...
Kindly have a look on this [answer](https://github.com/laravel/framework/issues/14997#issuecomment-242129087) about this issue. | Without modifiying `config\database.php` file
=============================================
**Set `'strict' => false`** in the `config\database.php` could be a **security issue**. So, a simple Laravel solution could be **first call `get()` and then `groupBy('vehicle_no)`**:
```
$loadids = explode("#@*", $reciptdet->loading_id);
$loadingdatas = DB::table('loading')->whereIn('id', $loadids)->get();
$grouped = $loadingdatas->groupBy('vehicle_no');
``` |
40,917,189 | I want to use WhereIn and Groupby in the same query to fetch Result.
I've tried this:
```
$loadids=explode("#@*",$reciptdet->loading_id);
$loadingdatas=DB::table('loading')->groupBy('vehicle_no')->whereIn('id',$loadids)->get();
```
But I got this error message:
>
> SQLSTATE[42000]: Syntax error or access violation: 1055 'sbrtpt.loading.id' isn't in GROUP BY (SQL: select \* from loading where id in (14, 15, 16) group by vehicle\_no)
>
>
> | 2016/12/01 | [
"https://Stackoverflow.com/questions/40917189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5829419/"
]
| I was having this problem also but after changing `'strict' => true`, to `'strict' => false`, the error disappeared.
You can find this setting in:
**config\database.php**
```
'mysql' => [
...
'strict' => false,
...
]
``` | I solve a similar issue with using group by by first getting the columns i needed to sort then use the group by.
```
$SampleData= DB::table('tableExampleName')->get(['col1','col2'])->groupBy('col3');
```
then you can dd() the values and check if they are the right grouping. You can all assign it and pass it into your view for further testing.
**Note**: This is using **Laravel 8**. |
16,761,854 | I have found different behavior of code when function is called / returned in different ways. It is quite confusing. So to clear my doubts I have stripped down the whole code to minumum:
Let us consider a simple function:
```
function f()
{
//some code
}
var objf = f();
```
**Q1. Now `objf` is undefined. Why? What does `f()` returns?**
```
function f()
{
//some code
return this;
}
var objf = f();
```
**Q2. What does `f()` returns? global object?** | 2013/05/26 | [
"https://Stackoverflow.com/questions/16761854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1317018/"
]
| Q1. Functions in javascript always return values. The default value is `undefined`, except for constructors, where the default return value is `this`. Since no return value is specified in your Q1 example, the interpreter returns the default value, `undefined`.
Q2. `this` is a javascript keyword that gets updated by the interpreter depending on application context. In the case of a function that is not called from an object, as in your Q2 example, `this` will refer to the global object.
[How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/javascript-this-keyword) | In the first case, `objf` will indeed be undefined. As the function doesn't return anything, it wouldn't be sensible to just invent something and return that.
In the second case, `objf` will be the `Window` object. |
16,761,854 | I have found different behavior of code when function is called / returned in different ways. It is quite confusing. So to clear my doubts I have stripped down the whole code to minumum:
Let us consider a simple function:
```
function f()
{
//some code
}
var objf = f();
```
**Q1. Now `objf` is undefined. Why? What does `f()` returns?**
```
function f()
{
//some code
return this;
}
var objf = f();
```
**Q2. What does `f()` returns? global object?** | 2013/05/26 | [
"https://Stackoverflow.com/questions/16761854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1317018/"
]
| When you do...
```
function f()
{
//some code
}
var objf = f();
```
...you're getting the return value of the "f" function, which in this case is undefined, once there's no "return something" statement.
If you do...
```
function f()
{
//some code
}
var objf = new f();
```
...you'll instance a new object based on the "f" function prototype. Your objf variable will receive a new object reference, even if your "f" function is empty.
And doing this...
```
function f()
{
//some code
return this;
}
var objf = f();
```
..."this", in your case, will be the global object, that's the window object for browsers.
The this keywork is a reference to the object to which the function is bound, look at this:
```
someobj = {
f:function(){
return this;
}
}
var objf = someobj.f();
objf === someobj; //==>true!!!
``` | In the first case, `objf` will indeed be undefined. As the function doesn't return anything, it wouldn't be sensible to just invent something and return that.
In the second case, `objf` will be the `Window` object. |
16,761,854 | I have found different behavior of code when function is called / returned in different ways. It is quite confusing. So to clear my doubts I have stripped down the whole code to minumum:
Let us consider a simple function:
```
function f()
{
//some code
}
var objf = f();
```
**Q1. Now `objf` is undefined. Why? What does `f()` returns?**
```
function f()
{
//some code
return this;
}
var objf = f();
```
**Q2. What does `f()` returns? global object?** | 2013/05/26 | [
"https://Stackoverflow.com/questions/16761854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1317018/"
]
| Q1. Functions in javascript always return values. The default value is `undefined`, except for constructors, where the default return value is `this`. Since no return value is specified in your Q1 example, the interpreter returns the default value, `undefined`.
Q2. `this` is a javascript keyword that gets updated by the interpreter depending on application context. In the case of a function that is not called from an object, as in your Q2 example, `this` will refer to the global object.
[How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/javascript-this-keyword) | When you do...
```
function f()
{
//some code
}
var objf = f();
```
...you're getting the return value of the "f" function, which in this case is undefined, once there's no "return something" statement.
If you do...
```
function f()
{
//some code
}
var objf = new f();
```
...you'll instance a new object based on the "f" function prototype. Your objf variable will receive a new object reference, even if your "f" function is empty.
And doing this...
```
function f()
{
//some code
return this;
}
var objf = f();
```
..."this", in your case, will be the global object, that's the window object for browsers.
The this keywork is a reference to the object to which the function is bound, look at this:
```
someobj = {
f:function(){
return this;
}
}
var objf = someobj.f();
objf === someobj; //==>true!!!
``` |
12,557,589 | I am wondering if it's possible to post something on a user's facebook wall using SLComposeViewController but without showing the share sheet/dialog?
Following is the code I am using:
```
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result){
if (result == SLComposeViewControllerResultCancelled) {
NSLog(@"Cancelled");
} else
{
NSLog(@"Done");
}
[controller dismissViewControllerAnimated:YES completion:Nil];
};
controller.completionHandler =myBlock;
[controller setInitialText:eventInfoToFacebook];
[self presentViewController:controller animated:YES completion:Nil];
}
```
Thanks in advance. | 2012/09/24 | [
"https://Stackoverflow.com/questions/12557589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693199/"
]
| Import the Social Framework:
```
#import <Social/Social.h>
```
-
```
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result){
if (result == SLComposeViewControllerResultCancelled) {
NSLog(@"Cancelled");
} else
{
NSLog(@"Done");
}
[controller dismissViewControllerAnimated:YES completion:Nil];
};
controller.completionHandler =myBlock;
[controller setInitialText:@"Test Post from mobile.safilsunny.com"];
[controller addURL:[NSURL URLWithString:@"http://www.mobile.safilsunny.com"]];
[controller addImage:[UIImage imageNamed:@"fb.png"]];
[self presentViewController:controller animated:YES completion:Nil];
}
else{
NSLog(@"UnAvailable");
}
}
```
/
```
//Deprecated in iOS6
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
[accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) {
ACAccount *account = [[ACAccount alloc] initWithAccountType:accountType];
NSLog(@"%@, %@", account.username, account.description);
}];
``` | this is possible in facebook-ios-sdk 3.0.
[here](https://developers.facebook.com/ios/)
i am making the share with this code.
```
[FBRequestConnection startWithGraphPath:@"me/feed"
parameters:params
HTTPMethod:@"POST"
completionHandler:^(FBRequestConnection *connection,
NSDictionary * result,
NSError *error) {
if (error) {
NSLog(@"Error: %@", [error localizedDescription]);
} else {
}
}];
```
i called this method when user clicks share button and there is no dialog with the user it directly post to the users wall. params is parameters that sharing includes. |
12,557,589 | I am wondering if it's possible to post something on a user's facebook wall using SLComposeViewController but without showing the share sheet/dialog?
Following is the code I am using:
```
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result){
if (result == SLComposeViewControllerResultCancelled) {
NSLog(@"Cancelled");
} else
{
NSLog(@"Done");
}
[controller dismissViewControllerAnimated:YES completion:Nil];
};
controller.completionHandler =myBlock;
[controller setInitialText:eventInfoToFacebook];
[self presentViewController:controller animated:YES completion:Nil];
}
```
Thanks in advance. | 2012/09/24 | [
"https://Stackoverflow.com/questions/12557589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693199/"
]
| Here I got the answer, for posting `image data` and `url` together we need to add Social.framework, this framework is available in iOS6.
Just add the `Social.framework` in your project and add the blew code.
```
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
{
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result){
if (result == SLComposeViewControllerResultCancelled) {
NSLog(@"ResultCancelled");
} else
{
NSLog(@"Success");
}
[controller dismissViewControllerAnimated:YES completion:Nil];
};
controller.completionHandler =myBlock;
[controller addURL:[NSURL URLWithString:@"https://itunes.apple.com/us/app/social-checkin/id504791401?mt=8"]];
if (encoded_ImageData == nil) {
[controller addImage:[UIImage imageNamed:@"No_ImageFound.png"]];
}
else
{
[controller addImage:[UIImage imageWithData:encoded_ImageData]];
}
NSString *businessName;
//Set business name string to be passed on facebook
if (m_BusinessNameString == nil || [m_BusinessNameString isEqualToString:@""])
{
businessName = @"Business name not specified!";
}
else
{
businessName = [m_BusinessNameString uppercaseString];
}
NSString *nameString = [NSString stringWithFormat:@"CHECKED IN @"];
//user has checked in with his friends if sc-merchant
NSString *friendsString;
if ([checkedFriendsNameArray count] > 0)
{
NSMutableString *checkedFriendsTempStr = [[NSMutableString alloc] init];
for (NSMutableString *checkedStr in checkedFriendsNameArray)
{
[checkedFriendsTempStr appendFormat:[NSString stringWithFormat:@"%@,",checkedStr]];
friendsString = [NSString stringWithFormat:@"WITH %@",checkedFriendsTempStr];
}
}
else
{
friendsString = [NSString stringWithFormat:@"WITH NO FRIENDS"];
}
NSString *fname= [[NSUserDefaults standardUserDefaults] valueForKey:@"userfname"];
NSString *lname= [[NSUserDefaults standardUserDefaults] valueForKey:@"userlname"];
NSString *name=[fname stringByAppendingString:[NSString stringWithFormat:@"%@",lname]];
NSString *main_TextString =[NSString stringWithFormat:@"%@ \n %@ %@ %@ %@",upperCaseStatusString,name,nameString,businessName,friendsString];
[controller setInitialText:main_TextString];
[self presentViewController:controller animated:YES completion:Nil];
}
else{
NSLog(@"UnAvailable");
}
``` | this is possible in facebook-ios-sdk 3.0.
[here](https://developers.facebook.com/ios/)
i am making the share with this code.
```
[FBRequestConnection startWithGraphPath:@"me/feed"
parameters:params
HTTPMethod:@"POST"
completionHandler:^(FBRequestConnection *connection,
NSDictionary * result,
NSError *error) {
if (error) {
NSLog(@"Error: %@", [error localizedDescription]);
} else {
}
}];
```
i called this method when user clicks share button and there is no dialog with the user it directly post to the users wall. params is parameters that sharing includes. |
12,557,589 | I am wondering if it's possible to post something on a user's facebook wall using SLComposeViewController but without showing the share sheet/dialog?
Following is the code I am using:
```
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result){
if (result == SLComposeViewControllerResultCancelled) {
NSLog(@"Cancelled");
} else
{
NSLog(@"Done");
}
[controller dismissViewControllerAnimated:YES completion:Nil];
};
controller.completionHandler =myBlock;
[controller setInitialText:eventInfoToFacebook];
[self presentViewController:controller animated:YES completion:Nil];
}
```
Thanks in advance. | 2012/09/24 | [
"https://Stackoverflow.com/questions/12557589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693199/"
]
| Add below Code in your ViewController and import below framework.
```
import FBSDKCoreKit
import FBSDKLoginKit
import FBSDKShareKit
@IBAction func btnPostClick(_ sender: Any)
{
if (FBSDKAccessToken.current() != nil)
{
if FBSDKAccessToken.current().hasGranted("publish_actions"){
postOnFB()
}
else
{
let loginManager = FBSDKLoginManager()
loginManager.logIn(withPublishPermissions: ["publish_actions"], from: self, handler: { (result, error) in
if error == nil{
self.postOnFB()
}
else{
print(error?.localizedDescription ?? "")
}
})
}
}
else
{
let loginManager = FBSDKLoginManager()
loginManager.logIn(withPublishPermissions: ["publish_actions"], from: self, handler: { (result, error) in
if error == nil{
self.postOnFB()
}
})
}
}
func postOnFB()
{
FBSDKGraphRequest(graphPath: "me/feed", parameters: ["message": "YOUR MESSAGE"], httpMethod: "POST").start { (connection, result, error) in
if error == nil{
print("post id \(result ?? "")")
}
else{
print("error is \(error?.localizedDescription ?? "")")
}
}
}
``` | this is possible in facebook-ios-sdk 3.0.
[here](https://developers.facebook.com/ios/)
i am making the share with this code.
```
[FBRequestConnection startWithGraphPath:@"me/feed"
parameters:params
HTTPMethod:@"POST"
completionHandler:^(FBRequestConnection *connection,
NSDictionary * result,
NSError *error) {
if (error) {
NSLog(@"Error: %@", [error localizedDescription]);
} else {
}
}];
```
i called this method when user clicks share button and there is no dialog with the user it directly post to the users wall. params is parameters that sharing includes. |
12,557,589 | I am wondering if it's possible to post something on a user's facebook wall using SLComposeViewController but without showing the share sheet/dialog?
Following is the code I am using:
```
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result){
if (result == SLComposeViewControllerResultCancelled) {
NSLog(@"Cancelled");
} else
{
NSLog(@"Done");
}
[controller dismissViewControllerAnimated:YES completion:Nil];
};
controller.completionHandler =myBlock;
[controller setInitialText:eventInfoToFacebook];
[self presentViewController:controller animated:YES completion:Nil];
}
```
Thanks in advance. | 2012/09/24 | [
"https://Stackoverflow.com/questions/12557589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693199/"
]
| Import the Social Framework:
```
#import <Social/Social.h>
```
-
```
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result){
if (result == SLComposeViewControllerResultCancelled) {
NSLog(@"Cancelled");
} else
{
NSLog(@"Done");
}
[controller dismissViewControllerAnimated:YES completion:Nil];
};
controller.completionHandler =myBlock;
[controller setInitialText:@"Test Post from mobile.safilsunny.com"];
[controller addURL:[NSURL URLWithString:@"http://www.mobile.safilsunny.com"]];
[controller addImage:[UIImage imageNamed:@"fb.png"]];
[self presentViewController:controller animated:YES completion:Nil];
}
else{
NSLog(@"UnAvailable");
}
}
```
/
```
//Deprecated in iOS6
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
[accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) {
ACAccount *account = [[ACAccount alloc] initWithAccountType:accountType];
NSLog(@"%@, %@", account.username, account.description);
}];
``` | Here I got the answer, for posting `image data` and `url` together we need to add Social.framework, this framework is available in iOS6.
Just add the `Social.framework` in your project and add the blew code.
```
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
{
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result){
if (result == SLComposeViewControllerResultCancelled) {
NSLog(@"ResultCancelled");
} else
{
NSLog(@"Success");
}
[controller dismissViewControllerAnimated:YES completion:Nil];
};
controller.completionHandler =myBlock;
[controller addURL:[NSURL URLWithString:@"https://itunes.apple.com/us/app/social-checkin/id504791401?mt=8"]];
if (encoded_ImageData == nil) {
[controller addImage:[UIImage imageNamed:@"No_ImageFound.png"]];
}
else
{
[controller addImage:[UIImage imageWithData:encoded_ImageData]];
}
NSString *businessName;
//Set business name string to be passed on facebook
if (m_BusinessNameString == nil || [m_BusinessNameString isEqualToString:@""])
{
businessName = @"Business name not specified!";
}
else
{
businessName = [m_BusinessNameString uppercaseString];
}
NSString *nameString = [NSString stringWithFormat:@"CHECKED IN @"];
//user has checked in with his friends if sc-merchant
NSString *friendsString;
if ([checkedFriendsNameArray count] > 0)
{
NSMutableString *checkedFriendsTempStr = [[NSMutableString alloc] init];
for (NSMutableString *checkedStr in checkedFriendsNameArray)
{
[checkedFriendsTempStr appendFormat:[NSString stringWithFormat:@"%@,",checkedStr]];
friendsString = [NSString stringWithFormat:@"WITH %@",checkedFriendsTempStr];
}
}
else
{
friendsString = [NSString stringWithFormat:@"WITH NO FRIENDS"];
}
NSString *fname= [[NSUserDefaults standardUserDefaults] valueForKey:@"userfname"];
NSString *lname= [[NSUserDefaults standardUserDefaults] valueForKey:@"userlname"];
NSString *name=[fname stringByAppendingString:[NSString stringWithFormat:@"%@",lname]];
NSString *main_TextString =[NSString stringWithFormat:@"%@ \n %@ %@ %@ %@",upperCaseStatusString,name,nameString,businessName,friendsString];
[controller setInitialText:main_TextString];
[self presentViewController:controller animated:YES completion:Nil];
}
else{
NSLog(@"UnAvailable");
}
``` |
12,557,589 | I am wondering if it's possible to post something on a user's facebook wall using SLComposeViewController but without showing the share sheet/dialog?
Following is the code I am using:
```
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result){
if (result == SLComposeViewControllerResultCancelled) {
NSLog(@"Cancelled");
} else
{
NSLog(@"Done");
}
[controller dismissViewControllerAnimated:YES completion:Nil];
};
controller.completionHandler =myBlock;
[controller setInitialText:eventInfoToFacebook];
[self presentViewController:controller animated:YES completion:Nil];
}
```
Thanks in advance. | 2012/09/24 | [
"https://Stackoverflow.com/questions/12557589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693199/"
]
| Import the Social Framework:
```
#import <Social/Social.h>
```
-
```
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result){
if (result == SLComposeViewControllerResultCancelled) {
NSLog(@"Cancelled");
} else
{
NSLog(@"Done");
}
[controller dismissViewControllerAnimated:YES completion:Nil];
};
controller.completionHandler =myBlock;
[controller setInitialText:@"Test Post from mobile.safilsunny.com"];
[controller addURL:[NSURL URLWithString:@"http://www.mobile.safilsunny.com"]];
[controller addImage:[UIImage imageNamed:@"fb.png"]];
[self presentViewController:controller animated:YES completion:Nil];
}
else{
NSLog(@"UnAvailable");
}
}
```
/
```
//Deprecated in iOS6
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
[accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) {
ACAccount *account = [[ACAccount alloc] initWithAccountType:accountType];
NSLog(@"%@, %@", account.username, account.description);
}];
``` | Add below Code in your ViewController and import below framework.
```
import FBSDKCoreKit
import FBSDKLoginKit
import FBSDKShareKit
@IBAction func btnPostClick(_ sender: Any)
{
if (FBSDKAccessToken.current() != nil)
{
if FBSDKAccessToken.current().hasGranted("publish_actions"){
postOnFB()
}
else
{
let loginManager = FBSDKLoginManager()
loginManager.logIn(withPublishPermissions: ["publish_actions"], from: self, handler: { (result, error) in
if error == nil{
self.postOnFB()
}
else{
print(error?.localizedDescription ?? "")
}
})
}
}
else
{
let loginManager = FBSDKLoginManager()
loginManager.logIn(withPublishPermissions: ["publish_actions"], from: self, handler: { (result, error) in
if error == nil{
self.postOnFB()
}
})
}
}
func postOnFB()
{
FBSDKGraphRequest(graphPath: "me/feed", parameters: ["message": "YOUR MESSAGE"], httpMethod: "POST").start { (connection, result, error) in
if error == nil{
print("post id \(result ?? "")")
}
else{
print("error is \(error?.localizedDescription ?? "")")
}
}
}
``` |
54,972 | I bought a tablet Samsung Nexus 10, it came with latest Android 4.3 installed. Android 4.2 and higher supports multiple user accounts which is awesome.
My question is, if let's say I have Facebook application installed on two accounts, does it install it two times (taking 2x place necessary) or is it efficient and it installs it once and changes only login settings for separate users? | 2013/10/12 | [
"https://android.stackexchange.com/questions/54972",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/43182/"
]
| The second user will have to explicitly install the wanted app (in your example: Facebook) – as otherwise all accounts' app drawers would be cluttered with a bunch of apps not wanted by everybody, except for those who installed them. But if the app already had been installed before by another account, it will rather be a "fake install" (i.e. it appears as if the app would be installed anew, but it's not downloaded again from Playstore, and thus doesn't consume "double space").
One side-effect to that is: whenever a user decides to *update* the app, that update applies to all other accounts of the device as well. | You can install facebook once and log in with different user/pwd to have different setting for different account |
54,972 | I bought a tablet Samsung Nexus 10, it came with latest Android 4.3 installed. Android 4.2 and higher supports multiple user accounts which is awesome.
My question is, if let's say I have Facebook application installed on two accounts, does it install it two times (taking 2x place necessary) or is it efficient and it installs it once and changes only login settings for separate users? | 2013/10/12 | [
"https://android.stackexchange.com/questions/54972",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/43182/"
]
| The second user will have to explicitly install the wanted app (in your example: Facebook) – as otherwise all accounts' app drawers would be cluttered with a bunch of apps not wanted by everybody, except for those who installed them. But if the app already had been installed before by another account, it will rather be a "fake install" (i.e. it appears as if the app would be installed anew, but it's not downloaded again from Playstore, and thus doesn't consume "double space").
One side-effect to that is: whenever a user decides to *update* the app, that update applies to all other accounts of the device as well. | A couple of points for those swinging in from Google..
Uninstalling an app in one user account doesn't remove it from the other, unless you use Titanium or similar, in which case it is GONE.
If you install an app at the Play Store web site, it installs into the *primary* user "desktop", even if you are logged into another desktop using the exact same account on your Android device. Theoretically, it should quickly appear in your "My Apps" list, so it's easy enough to install into the second user desktop.
So if you installed an app and see no notification or icon, this is why. Switch to the primary desktop and there it is! |
14,790,137 | I'd really like to use case classes' copy feature in my project, but unfortunately I also need inheritance, which doesn't work well with case classes.
So, I'm wondering if it's possible to write a macro which will generate a method for creating copy-with-changes object for an arbitrary class. What stops me there at the moment is the fact that AFAIK macros don't support named parameters. Has anyone found a way around that or, alternatively, can suggest other way for easy creating of copies which use inheritance? | 2013/02/09 | [
"https://Stackoverflow.com/questions/14790137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2052791/"
]
| That will be possible with type macros and/or annotation macros. The current macros do not support this.
Do look at lenses work, though. There's quite a few macro-based versions around, such as Shapeless. | You could also take a look at <https://github.com/dicarlo2/ScalaEquals> |
8,113,701 | I have an Android app, in which Activities fire long running operations that run in the background. These operations interact with the Activities when done. I'm developing a component that handles the Activity/Long-Running-Task coupling, taking care of activities being destroyed and recreated.
Right now that component is implemented as an Android service. The activities call bindService and use the resulting IBinder to start and track tasks. I decided against using startService, because I prefer the richer API possible through a Java interface.
Now the problem. Activity A start ups, binds to the service and calls serviceApi.runTask(...). Activity A is then destroyed (because the user flips the phone, for instance) and recreated as Activity A'. A' then binds again to the service, announces its existence and everything should be running nicely.
Except that my Service gets destroyed. When Activity A is destroyed, it unbinds from the service. Android sees there are no more clients, and kills the service. When Activity A' is created, the service is created again, and I lose everything the old service had.
The only solution I can see is using a singleton for the service. And then it doesn't really have to be an Android service, just an instance that's accessible to everyone. Is that frowned upon in Android? Is there a better design that fits this problem?
---
Editted: Even if I call startService and then bind to it, nothing guarantees that the service instance will exist as long as the application is running. Android can kill sticky services if resources are low. Killing the service will cause the application to malfunction, and I can't have that. | 2011/11/13 | [
"https://Stackoverflow.com/questions/8113701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/871910/"
]
| Call startService and in onStartCommand return START\_STICKY. It should keep the service going.
You may also want to look into foreground services:
<http://developer.android.com/reference/android/app/Service.html#startForeground(int>, android.app.Notification) | Yo have to create persistent service. Refer to [this manual](http://developer.android.com/reference/android/content/Context.html#startService%28android.content.Intent%29).
In a few words - don't call `bindService`, call `startService`. |
8,113,701 | I have an Android app, in which Activities fire long running operations that run in the background. These operations interact with the Activities when done. I'm developing a component that handles the Activity/Long-Running-Task coupling, taking care of activities being destroyed and recreated.
Right now that component is implemented as an Android service. The activities call bindService and use the resulting IBinder to start and track tasks. I decided against using startService, because I prefer the richer API possible through a Java interface.
Now the problem. Activity A start ups, binds to the service and calls serviceApi.runTask(...). Activity A is then destroyed (because the user flips the phone, for instance) and recreated as Activity A'. A' then binds again to the service, announces its existence and everything should be running nicely.
Except that my Service gets destroyed. When Activity A is destroyed, it unbinds from the service. Android sees there are no more clients, and kills the service. When Activity A' is created, the service is created again, and I lose everything the old service had.
The only solution I can see is using a singleton for the service. And then it doesn't really have to be an Android service, just an instance that's accessible to everyone. Is that frowned upon in Android? Is there a better design that fits this problem?
---
Editted: Even if I call startService and then bind to it, nothing guarantees that the service instance will exist as long as the application is running. Android can kill sticky services if resources are low. Killing the service will cause the application to malfunction, and I can't have that. | 2011/11/13 | [
"https://Stackoverflow.com/questions/8113701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/871910/"
]
| >
> Even if I call startService and then bind to it, nothing guarantees that the service instance will exist as long as the application is running.
>
>
>
Correct.
>
> Android can kill sticky services if resources are low.
>
>
>
Also correct. All "sticky" means is that Android might restart the service.
>
> Killing the service will cause the application to malfunction, and I can't have that.
>
>
>
It is impossible to create a service that is guaranteed to run forever. For starters, users can get rid of your service whenever they want, because users detest developers who have pointless services that run forever. Writing everlasting services is necessary only in very few cases; otherwise, it's just sloppy programming.
>
> The only solution I can see is using a singleton for the service. And then it doesn't really have to be an Android service, just an instance that's accessible to everyone. Is that frowned upon in Android?
>
>
>
Singletons (a.k.a., static data members) will go away when the process is terminated. The process will be terminated eventually, particularly if there are no active services and none of your activities is in the foreground.. | Yo have to create persistent service. Refer to [this manual](http://developer.android.com/reference/android/content/Context.html#startService%28android.content.Intent%29).
In a few words - don't call `bindService`, call `startService`. |
8,113,701 | I have an Android app, in which Activities fire long running operations that run in the background. These operations interact with the Activities when done. I'm developing a component that handles the Activity/Long-Running-Task coupling, taking care of activities being destroyed and recreated.
Right now that component is implemented as an Android service. The activities call bindService and use the resulting IBinder to start and track tasks. I decided against using startService, because I prefer the richer API possible through a Java interface.
Now the problem. Activity A start ups, binds to the service and calls serviceApi.runTask(...). Activity A is then destroyed (because the user flips the phone, for instance) and recreated as Activity A'. A' then binds again to the service, announces its existence and everything should be running nicely.
Except that my Service gets destroyed. When Activity A is destroyed, it unbinds from the service. Android sees there are no more clients, and kills the service. When Activity A' is created, the service is created again, and I lose everything the old service had.
The only solution I can see is using a singleton for the service. And then it doesn't really have to be an Android service, just an instance that's accessible to everyone. Is that frowned upon in Android? Is there a better design that fits this problem?
---
Editted: Even if I call startService and then bind to it, nothing guarantees that the service instance will exist as long as the application is running. Android can kill sticky services if resources are low. Killing the service will cause the application to malfunction, and I can't have that. | 2011/11/13 | [
"https://Stackoverflow.com/questions/8113701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/871910/"
]
| >
> Even if I call startService and then bind to it, nothing guarantees that the service instance will exist as long as the application is running.
>
>
>
Correct.
>
> Android can kill sticky services if resources are low.
>
>
>
Also correct. All "sticky" means is that Android might restart the service.
>
> Killing the service will cause the application to malfunction, and I can't have that.
>
>
>
It is impossible to create a service that is guaranteed to run forever. For starters, users can get rid of your service whenever they want, because users detest developers who have pointless services that run forever. Writing everlasting services is necessary only in very few cases; otherwise, it's just sloppy programming.
>
> The only solution I can see is using a singleton for the service. And then it doesn't really have to be an Android service, just an instance that's accessible to everyone. Is that frowned upon in Android?
>
>
>
Singletons (a.k.a., static data members) will go away when the process is terminated. The process will be terminated eventually, particularly if there are no active services and none of your activities is in the foreground.. | Call startService and in onStartCommand return START\_STICKY. It should keep the service going.
You may also want to look into foreground services:
<http://developer.android.com/reference/android/app/Service.html#startForeground(int>, android.app.Notification) |
1,421,538 | I have two points on a map, I want to create a rectangle where the two points are the line that intersect the rectangle. I understand that there is no true rectangle on a sphere, but the areas I am dealing with are small, the length of the rectangles are no more than a few km and the heights a few hundred meters. So if the calculation is approximate that's fine. Any help appreciated! Thanks,
Philip | 2015/09/04 | [
"https://math.stackexchange.com/questions/1421538",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/267807/"
]
| The simplest case: Let the two points be $(x\_1,y\_1)$ and $(x\_2,y\_1)$ and the thickness of rectangle is $t$. The coordinates of the rectangle are:
$(x\_1,y\_1+t/2),(x\_1,y\_1-t/2),(x\_2,y\_1-t/2),(x\_2,y\_1+t/2)$ | My algorithm/calculation almost works, however in some directions the rectangles aren't right angled. I want to know why, there is a fair amount of approximation in my code, which should be fine based on the scales I use (a few km). I shouldn't have to worry about the curvature of the earth.
Anybody know how I can improve my code?
Here are my references:
[calculate points](https://math.stackexchange.com/questions/64823/how-to-find-the-third-coordinate-of-a-right-triangle-given-2-coordinates-and-len)
[lat and long to meters](https://gis.stackexchange.com/questions/2951/algorithm-for-offsetting-a-latitude-longitude-by-some-amount-of-meters)
here is the image :[map retangles](https://i.stack.imgur.com/IZN48.png)
```
public static MapRectangle CreatMapRectangle(BalingZone zone, double thickness)
{
MapsCoordinate rectpoint2;
MapsCoordinate rectPoint1 ;
MapsCoordinate rectPoint3 ;
MapsCoordinate rectPoint4 ;
var point1 = zone.Coordinates[0];
var point2 = zone.Coordinates[1];
var latitudeDiff = LatitudeDiffToMeters(point2.Latitude - point1.Latitude);
var longitudeDiff = LongitudeDiffToMeters(point1.Longitude - point2.Longitude, point1.Latitude);
var slopeB = longitudeDiff / latitudeDiff;
double latOffset = thickness * (slopeB / Math.Sqrt(1 + slopeB * slopeB));
double longOffset = thickness * (1 / Math.Sqrt(1 + slopeB * slopeB));
double p3Lat = CalculateLatitude(point1.Latitude, latOffset);
double p3Long = CalculateLongitude( point1.Longitude, p3Lat , longOffset);
rectPoint1 = new MapsCoordinate(p3Lat, p3Long);
double p4Lat = CalculateLatitude(point1.Latitude, -latOffset);
double p4Long = CalculateLongitude(point1.Longitude, p4Lat, -longOffset);
rectpoint2 = new MapsCoordinate(p4Lat, p4Long);
double p5Lat = CalculateLatitude(point2.Latitude, latOffset);
double p5Long = CalculateLongitude( point2.Longitude, p5Lat , longOffset);
rectPoint4 = new MapsCoordinate(p5Lat, p5Long);
double p6Lat = CalculateLatitude(point2.Latitude, -latOffset);
double p6Long = CalculateLongitude( point2.Longitude, p6Lat , -longOffset);
rectPoint3 = new MapsCoordinate(p6Lat, p6Long);
return new MapRectangle(rectPoint4, rectPoint3, rectPoint1, rectpoint2, thickness);
}
//use the quick and dirty estimate that 111,111 meters (111.111 km) in the y direction is 1 degree (of latitude)
// and 111,111 * cos(latitude) meters in the x direction is 1 degree (of longitude).
private static double LatitudeDiffToMeters(double latitudeDiff)
{
return 111111.0 * latitudeDiff;
}
private static double LongitudeDiffToMeters(double longitudeDiff, double latitude)
{
return 111111.0*Math.Cos(latitude)*longitudeDiff;
}
private static double CalculateLatitude(double latitude, double offset)
{
return latitude + offset/111111.0;
}
private static double CalculateLongitude(double longitude, double latitude, double offset)
{
return longitude + offset/(111111.0*Math.Cos(latitude));
}
}
``` |
52,358,998 | Before upgrading to `android 3.1`.I usually just change the theme to a theme. app compact. `NoTitleBar` but the new version of `android studio` is having errors recognizing it.I solved this problem by adding base to the beginning. But I can seem to find any answer regarding a style theme that supports removing the custom bar. | 2018/09/16 | [
"https://Stackoverflow.com/questions/52358998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10372416/"
]
| In your `res/values/styles.xml` you have this similar block of code.
Ensure that you use `Theme.AppCompat.Light.NoActionBar` as `parent` of your theme
```
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
``` | In my case, i had to change parent theme in res/values/themes.xml
[](https://i.stack.imgur.com/Jbc7L.png) |
52,358,998 | Before upgrading to `android 3.1`.I usually just change the theme to a theme. app compact. `NoTitleBar` but the new version of `android studio` is having errors recognizing it.I solved this problem by adding base to the beginning. But I can seem to find any answer regarding a style theme that supports removing the custom bar. | 2018/09/16 | [
"https://Stackoverflow.com/questions/52358998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10372416/"
]
| ```
Add this style in style file . where other styles are mentioned .
<!-- Base application theme. -->
<style name="AppThemeNoActionBar" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimaryDark</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorPrimaryDark</item>
<item name="android:statusBarColor">@color/lightgreycolor</item>
</style>
``` | In my case, i had to change parent theme in res/values/themes.xml
[](https://i.stack.imgur.com/Jbc7L.png) |
58,301,330 | I'm trying to implement the default window with the default trigger to evaluate the behavior but it's not emitting any result.
According to Apache Beam:
>
> The default trigger for a PCollection is based on event time, and
> emits the results of the window when the Beam’s watermark passes the
> end of the window, and then fires each time late data arrives.
>
>
>
---
>
> If you are using both the default windowing configuration and
> the default trigger, the default trigger emits exactly once, and late
> data is discarded. This is because the default windowing configuration
> has an allowed lateness value of 0.
>
>
>
my code:
```
Nb_items = lines | beam.CombineGlobally(beam.combiners.CountCombineFn()).without_defaults() \
| 'print' >> beam.ParDo(PrintFn())
```
It only emits the data if I set a trigger
```
Nb_items = lines | 'window' >> beam.WindowInto(window.GlobalWindows(),
trigger=trigger.AfterProcessingTime(10),
accumulation_mode=trigger.AccumulationMode.DISCARDING) \
| 'CountGlobally' >> beam.CombineGlobally(beam.combiners.CountCombineFn()).without_defaults() \
| 'print' >> beam.ParDo(PrintFn())
```
How can I observe the default behavior without setting a trigger?
Is the problem in the combine transform?
>
> If your input PCollection
> uses the default global windowing, the default behavior is to return a
> PCollection containing one item. That item’s value comes from the
> accumulator in the combine function that you specified when applying
> Combine
>
>
> | 2019/10/09 | [
"https://Stackoverflow.com/questions/58301330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8248386/"
]
| The current issue is that the watermark never reaches the end of the `GlobalWindow`. To have a default trigger, you can use any other window where the watermark can reach the end, e.g.: `'window' >> beam.WindowInto(window.FixedWindows(10))`
As Guillaume rightly asks, if you're running on Batch, triggers are basically ignored. | See Sources Below:
<https://github.com/apache/beam/blob/828b897a2439437d483b1bd7f2a04871f077bde0/examples/java/src/main/java/org/apache/beam/examples/complete/game/LeaderBoard.java#L274>
For more information regarding Google Cloud Dataflow
<https://stackoverflow.com/a/54151029/12149235> |
18,472 | How do you translate the adjective ‘pacifist’ into Latin?
‘pacifistus, a, um’ seems incorrect to me since all the words I’ve found with the suffix *-ista* are nouns, not adjectives.
>
> **alchemist:** \*alchĕmista or alcumista, ae, m.: Erasm.: Bacon.
> (Smith & Hall)
>
>
>
>
> † **ēvangĕlista (eua-),** ae, m., = εὐαγγελιστής, an evangelist, Prud. Cathem. 6, 77 et saep.; Vulg. Act. 21, 8.
> (Lewis & Short)
>
>
> | 2022/07/10 | [
"https://latin.stackexchange.com/questions/18472",
"https://latin.stackexchange.com",
"https://latin.stackexchange.com/users/-1/"
]
| *Pacifista* and *pacifismus* (both employed by [Vicipaedia](https://la.wikipedia.org/wiki/Pacifismus), by the way) are not exactly the sort of coinage that pleases *Latini* of the old school in the first place. Too literal, unclassical, would stick out like a sore thumb in a letter of Cicero's.
Now if a revolutionary is *novis rebus studens* ([1 Cat 3](https://www.thelatinlibrary.com/cicero/cat1.shtml#3)), does it not stand to reason that a pacifist is ***paci studens***? This has the advantage that it can be used adjectively as well as substantively.
The downside is that this sort of expression sounds pretty general and does not convey it is referring to a fixed idea. Pacifism is an ideology and a movement (however amorphous) that has a name; being zealous for peace is a character trait. (1) Nevertheless, the adjective *pacifist* is also often used generically to describe a personal disposition without wanting to make reference to the pacifist movement, and if that is the meaning you are aiming for, you may find *paci studens* to your liking (or, indeed, you may use other forms of *studere*).
(1) A particularly egregious example for this issue was the translation for "fascism" I read in a certain book, which was *exaggeratum suae gentis studium*. | The suffix *-isticus* seems quite productive in neo-Latin, and even in classical Latin we have *sophisticus* and *syllogisticus*. If you aren't looking for something fancier, I'd go with that. |
238,129 | So I have done some googling and experimenting to change the GDM icon (Ubuntu 10.04) and have found the following ways:
1. UbuntTweak
2. Replace `/usr/share/icons/LoginIcons/apps/64/computer.svg` with your own svg
3. Change the gconf config setting `/apps/gdm/simple-greeter/logo_icon_name` to be the name of your icon in the theme. Then copy that file to the icon theme path: `/usr/share/icons/LoginIcons/apps/64/`.
I have gotten #1 and #2 to work. I am not sure how UbuntuTweak is actually doing it's magic (but would love to know). I do not like #2 as it seems messy and what not.
I can *not* get #3 to work. I have found post after post that says it should. I have tried editing the gconf DB in multiple ways:
1. `gksu gconf-editor`
2. `gksu -u gdm gconf-editor`
3. `sudo -u gdm gconftool-2 --set --type string /apps/gdm/simple-greeter/logo_icon_name MYICONFILE`
4. `sudo gconftool-2 --set --type string /apps/gdm/simple-greeter/logo_icon_name MYICONFILE`
And while all of those methods show that the value has been edited NONE of them actually change the icon (did a `service gdm restart` to check).
Given that:
1. The official docs state that this should work
2. By replacing the `computer.svg` file it does work (so I know I am copying my file to the correct path)
I am completly confused as to why this doesn't work. I know I must be missing something obvious. | 2011/01/26 | [
"https://superuser.com/questions/238129",
"https://superuser.com",
"https://superuser.com/users/4754/"
]
| ```
update-icon-caches /usr/share/icons/LoginIcons/apps/64/
```
or wherever your icon is placed | According to the official GDM Doc for GDM 2.32, the Gconf value edition only works if the user "gdm" has a $HOME directory to write and read theses parameters :
<http://library.gnome.org/admin/gdm/2.32/gdm.html#greeterconfiguration> |
26,144,013 | I have a simple blog, and each blog post has a number of images ranging from 1 to 10. If you click on any of the images in the post, it should scroll you down to the next post. I thought something as simple as this would've worked:
```
$('.each-journal-entry .slider-container .journal-slider .each-slide img').on('click', function () {
var $this = $(this);
$('.journal-container').animate({
scrollTop: $this.closest('.each-journal-entry').next().offset().top
}, 500);
});
```
But when I click another image, except for the first one, it just scrolls to an odd position.
I managed to achieve this with some help, and you can see the output here: <http://jsfiddle.net/w7rtcmp0/3/> which works great, but the difference for me is that my content is in a scrollable div (hence `.journal-container` and not `html, body`.
Any ideas why I am having this issue? I have created a jsFiddle with the scrollable div, and if you click an image further down... it replicates this issue... so hopefully this helps.
<http://jsfiddle.net/w7rtcmp0/5/>
Thanks. | 2014/10/01 | [
"https://Stackoverflow.com/questions/26144013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1043706/"
]
| jQuery adjusts `offset().top()` based on the current scroll position.
Using JavaScript's `offsetTop` property should fix the problem:
```
scrollTop: $this.closest('.each-journal-entry').next()[0].offsetTop
```
Fiddle: **<http://jsfiddle.net/m7cm5oL6/>** | You may want to look at [Ariel Flesler's jQuery `scrollTo` plugin](http://demos.flesler.com/jquery/scrollTo/), I had the same issue and using this saved me hours of debugging. |
26,144,013 | I have a simple blog, and each blog post has a number of images ranging from 1 to 10. If you click on any of the images in the post, it should scroll you down to the next post. I thought something as simple as this would've worked:
```
$('.each-journal-entry .slider-container .journal-slider .each-slide img').on('click', function () {
var $this = $(this);
$('.journal-container').animate({
scrollTop: $this.closest('.each-journal-entry').next().offset().top
}, 500);
});
```
But when I click another image, except for the first one, it just scrolls to an odd position.
I managed to achieve this with some help, and you can see the output here: <http://jsfiddle.net/w7rtcmp0/3/> which works great, but the difference for me is that my content is in a scrollable div (hence `.journal-container` and not `html, body`.
Any ideas why I am having this issue? I have created a jsFiddle with the scrollable div, and if you click an image further down... it replicates this issue... so hopefully this helps.
<http://jsfiddle.net/w7rtcmp0/5/>
Thanks. | 2014/10/01 | [
"https://Stackoverflow.com/questions/26144013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1043706/"
]
| jQuery adjusts `offset().top()` based on the current scroll position.
Using JavaScript's `offsetTop` property should fix the problem:
```
scrollTop: $this.closest('.each-journal-entry').next()[0].offsetTop
```
Fiddle: **<http://jsfiddle.net/m7cm5oL6/>** | So I think you were trying to use the wrong height.
Here I set a variable of height and set it to the height of the current journal/blog object. This allows me to scroll my height all the way down to the next available blog object.
<http://jsfiddle.net/w7rtcmp0/24/>
```
$('.each-journal-entry .slider-container .journal-slider .each-slide img').on('click', function() {
$this = $(this);
var height = $this.closest('.each-journal-entry').height();
$('.scrollable').animate({
scrollTop: height
}, 2000);
});
``` |
49,145,372 | My continuing saga:
I have *Artifactory Pro 5.8.4* running on a *CentOS 7.4* system that uses Artifactory's built-in *Nginx* service as a reverse proxy. Most of the time, during download of a large object, **the connection fails**. Additionally, the last few kilobytes of data that are transferred in the failed connection appear to be garbage; as a result, the file, when resumed, has a section in the middle somewhere that is invalid.
Nginx logs around the time of failure provide the following error message:
>
> 2018/01/22 23:26:32 [error] 884#0: \*48048865 readv() failed (104: Connection reset by peer) while reading upstream, client: 12.2.178.130, server: ~(?.+).artifactory.common.mycoolco.com, request: "GET /controller/release/20171218-2119-2aa9f0e8c32bf3f08dd96a97127204d1f400f895fa2e67100a3830861c0becb0bfae28244c058510c8312e98378c0b77251b4bb7926ceae2d465ce2d533b88dc HTTP/1.1", upstream: "<http://127.0.0.1:8081/artifactory/controller/release/20171218-2119-2aa9f0e8c32bf3f08dd96a97127204d1f400f895fa2e67100a3830861c0becb0bfae28244c058510c8312e98378c0b77251b4bb7926ceae2d465ce2d533b88dc>", host: "artifactory.common.mycoolco.com"
>
>
>
The Artifactory logs usually, but not always, have an error that looks something like this:
>
> 2018-01-22 23:14:20,106 [http-nio-8081-exec-87] [WARN ] (o.a.r.ArtifactoryResponseBase:137) - Client Closed Request 499: java.net.SocketTimeoutException
>
>
>
Any further suggestions for diagnosis would be appreciated.
THIS DID NOT AFFECT ANY NOTICEABLE CHANGE:
As a follow-through, I will be changing some settings for testing over this weekend (SUN, MAR. 18TH) during my maintenance window by editing the nginx.conf file (/etc/opt/rh/rh-nginx18/nginx/nginx.conf) to contain the settings "worker\_processes 2" (was currently 1), upping worker connections from 1024 to 2048 and changing the keepalive\_timeout from 65 to 130.
We have a single Artifactory instance hosted in AWS with no other proxies nor load balancers; just a single instance and a route 53 entry pointing to the private ip address. We are seeing a baseline 10%cpu usage with spikes to 100% every 15 minutes ...apparently from the from the java process. java -version: openjdk version "1.8.0\_161" OpenJDK Runtime Environment (build 1.8.0\_161-b14) OpenJDK 64-Bit Server VM (build 25.161-b14, mixed mode). now on artifactory.version: 5.8.4
```
> --2018-03-08 22:09:42-- https://artifactory.common.mycoolco.com/controller/pre-release/20180308-2216-023a0b8309af8889
Resolving artifactory.common.mycoolco.com (artifactory.common.mycoolco.com)... 55.111.66.99
Connecting to artifactory.common.mycoolco.com (artifactory.common.mycoolco.com)|55.111.66.99|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1241911191 (1.2G) [application/octet-stream]
Saving to: ‘20180308-2216-023a0b8309af8889’
20180308-2216-c3499ea023a0b8309 86%[=============================================> ] 1.00G 568KB/s in 1m 31s
2018-03-08 22:30:14 (857 KB/s) - Connection closed at byte 1079774172. Retrying.
--2018-03-08 22:30:15-- (try: 2) https://artifactory.common.mycoolco.com/controller-os/pre-release/20180308-2216-023a0b8309af8889
Connecting to artifactory.common.mycoolco.com (artifactory.common.mycoolco.com)|55.111.66.99|:443... connected.
HTTP request sent, awaiting response... 206 Partial Content
Length: 1241911191 (1.2G), 162137019 (155M) remaining [application/octet-stream]
Saving to: ‘20180308-2216-023a0b8309af8889’
20180308-2216-c3499ea023a0b8309 100%[++++++++++++++++++++++++++++++++++++++++++++++=======>] 1.16G 1.08MB/s in 0m 22s
2018-03-08 22:32:38 (1.09 MB/s) - ‘20180308-2216-023a0b8309af8889’ saved [1241911191/1241911191]
```
[top command showing java high cpu usage](https://i.stack.imgur.com/ZOHk5.png)
[AWS cpu spikes](https://i.stack.imgur.com/Voe3K.png) | 2018/03/07 | [
"https://Stackoverflow.com/questions/49145372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5905820/"
]
| The issue could be due to [proxy\_max\_temp\_file\_size](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_max_temp_file_size). The default value is 1GB. Check if `proxy_max_temp_file_size 0` helps. | By the error message, it seems that the issue is the 'Socket Timeout (MS)' parameter on your remote repository (as you mentioned in your comment).
In order to resolve the issue go to Artifactory UI --> Remote repositories --> Edit the repository that is having the issue --> Go to Advanced Tab --> Edit the 'Socket Timeout (MS)' param and extend it.
If this is not a remote repository but local repository on a remote instance, it probably an issue with the proxy in front of Artifactory. |
1,711,170 | What is the best way for unit testing code paths involving a failed `malloc()`? In most instances, it probably doesn't matter because you're doing something like
```
thingy *my_thingy = malloc(sizeof(thingy));
if (my_thingy == NULL) {
fprintf(stderr, "We're so screwed!\n");
exit(EXIT_FAILURE);
}
```
but in some instances you have choices other than dying, because you've allocated some extra stuff for caching or whatever, and you can reclaim that memory.
However, in those instances where you can try to recover from a failed `malloc()` that you're doing something tricky and error prone in a code path that's pretty unusual, making testing especially important. How do you actually go about doing this? | 2009/11/10 | [
"https://Stackoverflow.com/questions/1711170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85467/"
]
| I saw a cool solution to this problem which was presented to me by S. Paavolainen. The idea is to override the standard `malloc()`, which you can do just in the linker, by a custom allocator which
1. reads the current execution stack of the thread calling `malloc()`
2. checks if the stack exists in a database that is stored on hard disk
1. if the stack does not exist, adds the stack to the database and returns `NULL`
2. if the stack did exist already, allocates memory normally and returns
Then you just run your unit test many times: this system automatically enumerates through different control paths to `malloc()` failure and is much more efficient and reliable than e.g. random testing. | I suggest creating a specific function for your special malloc code that you expect could fail and you could handle gracefully. For example:
```
void* special_malloc(size_t bytes) {
void* ptr = malloc(bytes);
if(ptr == NULL) {
/* Do something crafty */
} else {
return ptr;
}
}
```
Then you could unit-test this crafty business in here by passing in some bad values for bytes. You could put this in a separate library and make a mock-library that does behaves special for your testing of the functions which call this one. |
1,711,170 | What is the best way for unit testing code paths involving a failed `malloc()`? In most instances, it probably doesn't matter because you're doing something like
```
thingy *my_thingy = malloc(sizeof(thingy));
if (my_thingy == NULL) {
fprintf(stderr, "We're so screwed!\n");
exit(EXIT_FAILURE);
}
```
but in some instances you have choices other than dying, because you've allocated some extra stuff for caching or whatever, and you can reclaim that memory.
However, in those instances where you can try to recover from a failed `malloc()` that you're doing something tricky and error prone in a code path that's pretty unusual, making testing especially important. How do you actually go about doing this? | 2009/11/10 | [
"https://Stackoverflow.com/questions/1711170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85467/"
]
| write your own library that implements malloc by randomly failing or calling the real malloc (either staticly linked or explicitly dlopened)
then LD\_PRELOAD it | In FreeBSD I once simply overloaded C library malloc.o module (symbols there were weak) and replaced malloc() implementation with one which had controlled probability to fail.
So I linked statically and started to perform testing. srandom() finished the picture with controlled pseudo-random sequence.
Also look [here](http://valgrind.org/) for a set of good tools that you seems to need by my opinion. At least they overload malloc() / free() to track leaks so it seems as usable point to add anything you want. |
1,711,170 | What is the best way for unit testing code paths involving a failed `malloc()`? In most instances, it probably doesn't matter because you're doing something like
```
thingy *my_thingy = malloc(sizeof(thingy));
if (my_thingy == NULL) {
fprintf(stderr, "We're so screwed!\n");
exit(EXIT_FAILURE);
}
```
but in some instances you have choices other than dying, because you've allocated some extra stuff for caching or whatever, and you can reclaim that memory.
However, in those instances where you can try to recover from a failed `malloc()` that you're doing something tricky and error prone in a code path that's pretty unusual, making testing especially important. How do you actually go about doing this? | 2009/11/10 | [
"https://Stackoverflow.com/questions/1711170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85467/"
]
| I suggest creating a specific function for your special malloc code that you expect could fail and you could handle gracefully. For example:
```
void* special_malloc(size_t bytes) {
void* ptr = malloc(bytes);
if(ptr == NULL) {
/* Do something crafty */
} else {
return ptr;
}
}
```
Then you could unit-test this crafty business in here by passing in some bad values for bytes. You could put this in a separate library and make a mock-library that does behaves special for your testing of the functions which call this one. | You could hijack malloc by using some defines and global parameter to control it... It's a bit hackish but seems to work.
```
#include <stdio.h>
#include <stdlib.h>
#define malloc(x) fake_malloc(x)
struct {
size_t last_request;
int should_fail;
void *(*real_malloc)(size_t);
} fake_malloc_params;
void *fake_malloc(size_t size) {
fake_malloc_params.last_request = size;
if (fake_malloc_params.should_fail) {
return NULL;
}
return (fake_malloc_params.real_malloc)(size);;
}
int main(void) {
fake_malloc_params.real_malloc = malloc;
void *ptr = NULL;
ptr = malloc(1);
printf("last: %d\n", (int) fake_malloc_params.last_request);
printf("ptr: 0x%p\n", ptr);
return 0;
}
``` |
1,711,170 | What is the best way for unit testing code paths involving a failed `malloc()`? In most instances, it probably doesn't matter because you're doing something like
```
thingy *my_thingy = malloc(sizeof(thingy));
if (my_thingy == NULL) {
fprintf(stderr, "We're so screwed!\n");
exit(EXIT_FAILURE);
}
```
but in some instances you have choices other than dying, because you've allocated some extra stuff for caching or whatever, and you can reclaim that memory.
However, in those instances where you can try to recover from a failed `malloc()` that you're doing something tricky and error prone in a code path that's pretty unusual, making testing especially important. How do you actually go about doing this? | 2009/11/10 | [
"https://Stackoverflow.com/questions/1711170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85467/"
]
| I saw a cool solution to this problem which was presented to me by S. Paavolainen. The idea is to override the standard `malloc()`, which you can do just in the linker, by a custom allocator which
1. reads the current execution stack of the thread calling `malloc()`
2. checks if the stack exists in a database that is stored on hard disk
1. if the stack does not exist, adds the stack to the database and returns `NULL`
2. if the stack did exist already, allocates memory normally and returns
Then you just run your unit test many times: this system automatically enumerates through different control paths to `malloc()` failure and is much more efficient and reliable than e.g. random testing. | This is a kinda gross, but if you really want unit testing, you could do it with #ifdefs:
```
thingy *my_thingy = malloc(sizeof(thingy));
#ifdef MALLOC_UNIT_TEST_1
my_thingy = NULL;
#endif
if (my_thingy == NULL) {
fprintf(stderr, "We're so screwed!\n");
exit(EXIT_FAILURE);
}
```
Unfortunately, you'd have to recompile a lot with this solution.
If you're using linux, you could also consider running your code under memory pressure by using [ulimit](http://www.phy.ohiou.edu/cgi-bin/man-cgi.sol?limit+1), but be careful. |
1,711,170 | What is the best way for unit testing code paths involving a failed `malloc()`? In most instances, it probably doesn't matter because you're doing something like
```
thingy *my_thingy = malloc(sizeof(thingy));
if (my_thingy == NULL) {
fprintf(stderr, "We're so screwed!\n");
exit(EXIT_FAILURE);
}
```
but in some instances you have choices other than dying, because you've allocated some extra stuff for caching or whatever, and you can reclaim that memory.
However, in those instances where you can try to recover from a failed `malloc()` that you're doing something tricky and error prone in a code path that's pretty unusual, making testing especially important. How do you actually go about doing this? | 2009/11/10 | [
"https://Stackoverflow.com/questions/1711170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85467/"
]
| This is a kinda gross, but if you really want unit testing, you could do it with #ifdefs:
```
thingy *my_thingy = malloc(sizeof(thingy));
#ifdef MALLOC_UNIT_TEST_1
my_thingy = NULL;
#endif
if (my_thingy == NULL) {
fprintf(stderr, "We're so screwed!\n");
exit(EXIT_FAILURE);
}
```
Unfortunately, you'd have to recompile a lot with this solution.
If you're using linux, you could also consider running your code under memory pressure by using [ulimit](http://www.phy.ohiou.edu/cgi-bin/man-cgi.sol?limit+1), but be careful. | In FreeBSD I once simply overloaded C library malloc.o module (symbols there were weak) and replaced malloc() implementation with one which had controlled probability to fail.
So I linked statically and started to perform testing. srandom() finished the picture with controlled pseudo-random sequence.
Also look [here](http://valgrind.org/) for a set of good tools that you seems to need by my opinion. At least they overload malloc() / free() to track leaks so it seems as usable point to add anything you want. |
1,711,170 | What is the best way for unit testing code paths involving a failed `malloc()`? In most instances, it probably doesn't matter because you're doing something like
```
thingy *my_thingy = malloc(sizeof(thingy));
if (my_thingy == NULL) {
fprintf(stderr, "We're so screwed!\n");
exit(EXIT_FAILURE);
}
```
but in some instances you have choices other than dying, because you've allocated some extra stuff for caching or whatever, and you can reclaim that memory.
However, in those instances where you can try to recover from a failed `malloc()` that you're doing something tricky and error prone in a code path that's pretty unusual, making testing especially important. How do you actually go about doing this? | 2009/11/10 | [
"https://Stackoverflow.com/questions/1711170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85467/"
]
| This is a kinda gross, but if you really want unit testing, you could do it with #ifdefs:
```
thingy *my_thingy = malloc(sizeof(thingy));
#ifdef MALLOC_UNIT_TEST_1
my_thingy = NULL;
#endif
if (my_thingy == NULL) {
fprintf(stderr, "We're so screwed!\n");
exit(EXIT_FAILURE);
}
```
Unfortunately, you'd have to recompile a lot with this solution.
If you're using linux, you could also consider running your code under memory pressure by using [ulimit](http://www.phy.ohiou.edu/cgi-bin/man-cgi.sol?limit+1), but be careful. | You could hijack malloc by using some defines and global parameter to control it... It's a bit hackish but seems to work.
```
#include <stdio.h>
#include <stdlib.h>
#define malloc(x) fake_malloc(x)
struct {
size_t last_request;
int should_fail;
void *(*real_malloc)(size_t);
} fake_malloc_params;
void *fake_malloc(size_t size) {
fake_malloc_params.last_request = size;
if (fake_malloc_params.should_fail) {
return NULL;
}
return (fake_malloc_params.real_malloc)(size);;
}
int main(void) {
fake_malloc_params.real_malloc = malloc;
void *ptr = NULL;
ptr = malloc(1);
printf("last: %d\n", (int) fake_malloc_params.last_request);
printf("ptr: 0x%p\n", ptr);
return 0;
}
``` |
1,711,170 | What is the best way for unit testing code paths involving a failed `malloc()`? In most instances, it probably doesn't matter because you're doing something like
```
thingy *my_thingy = malloc(sizeof(thingy));
if (my_thingy == NULL) {
fprintf(stderr, "We're so screwed!\n");
exit(EXIT_FAILURE);
}
```
but in some instances you have choices other than dying, because you've allocated some extra stuff for caching or whatever, and you can reclaim that memory.
However, in those instances where you can try to recover from a failed `malloc()` that you're doing something tricky and error prone in a code path that's pretty unusual, making testing especially important. How do you actually go about doing this? | 2009/11/10 | [
"https://Stackoverflow.com/questions/1711170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85467/"
]
| I suggest creating a specific function for your special malloc code that you expect could fail and you could handle gracefully. For example:
```
void* special_malloc(size_t bytes) {
void* ptr = malloc(bytes);
if(ptr == NULL) {
/* Do something crafty */
} else {
return ptr;
}
}
```
Then you could unit-test this crafty business in here by passing in some bad values for bytes. You could put this in a separate library and make a mock-library that does behaves special for your testing of the functions which call this one. | In FreeBSD I once simply overloaded C library malloc.o module (symbols there were weak) and replaced malloc() implementation with one which had controlled probability to fail.
So I linked statically and started to perform testing. srandom() finished the picture with controlled pseudo-random sequence.
Also look [here](http://valgrind.org/) for a set of good tools that you seems to need by my opinion. At least they overload malloc() / free() to track leaks so it seems as usable point to add anything you want. |
1,711,170 | What is the best way for unit testing code paths involving a failed `malloc()`? In most instances, it probably doesn't matter because you're doing something like
```
thingy *my_thingy = malloc(sizeof(thingy));
if (my_thingy == NULL) {
fprintf(stderr, "We're so screwed!\n");
exit(EXIT_FAILURE);
}
```
but in some instances you have choices other than dying, because you've allocated some extra stuff for caching or whatever, and you can reclaim that memory.
However, in those instances where you can try to recover from a failed `malloc()` that you're doing something tricky and error prone in a code path that's pretty unusual, making testing especially important. How do you actually go about doing this? | 2009/11/10 | [
"https://Stackoverflow.com/questions/1711170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85467/"
]
| I saw a cool solution to this problem which was presented to me by S. Paavolainen. The idea is to override the standard `malloc()`, which you can do just in the linker, by a custom allocator which
1. reads the current execution stack of the thread calling `malloc()`
2. checks if the stack exists in a database that is stored on hard disk
1. if the stack does not exist, adds the stack to the database and returns `NULL`
2. if the stack did exist already, allocates memory normally and returns
Then you just run your unit test many times: this system automatically enumerates through different control paths to `malloc()` failure and is much more efficient and reliable than e.g. random testing. | write your own library that implements malloc by randomly failing or calling the real malloc (either staticly linked or explicitly dlopened)
then LD\_PRELOAD it |
1,711,170 | What is the best way for unit testing code paths involving a failed `malloc()`? In most instances, it probably doesn't matter because you're doing something like
```
thingy *my_thingy = malloc(sizeof(thingy));
if (my_thingy == NULL) {
fprintf(stderr, "We're so screwed!\n");
exit(EXIT_FAILURE);
}
```
but in some instances you have choices other than dying, because you've allocated some extra stuff for caching or whatever, and you can reclaim that memory.
However, in those instances where you can try to recover from a failed `malloc()` that you're doing something tricky and error prone in a code path that's pretty unusual, making testing especially important. How do you actually go about doing this? | 2009/11/10 | [
"https://Stackoverflow.com/questions/1711170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85467/"
]
| write your own library that implements malloc by randomly failing or calling the real malloc (either staticly linked or explicitly dlopened)
then LD\_PRELOAD it | You could hijack malloc by using some defines and global parameter to control it... It's a bit hackish but seems to work.
```
#include <stdio.h>
#include <stdlib.h>
#define malloc(x) fake_malloc(x)
struct {
size_t last_request;
int should_fail;
void *(*real_malloc)(size_t);
} fake_malloc_params;
void *fake_malloc(size_t size) {
fake_malloc_params.last_request = size;
if (fake_malloc_params.should_fail) {
return NULL;
}
return (fake_malloc_params.real_malloc)(size);;
}
int main(void) {
fake_malloc_params.real_malloc = malloc;
void *ptr = NULL;
ptr = malloc(1);
printf("last: %d\n", (int) fake_malloc_params.last_request);
printf("ptr: 0x%p\n", ptr);
return 0;
}
``` |
1,711,170 | What is the best way for unit testing code paths involving a failed `malloc()`? In most instances, it probably doesn't matter because you're doing something like
```
thingy *my_thingy = malloc(sizeof(thingy));
if (my_thingy == NULL) {
fprintf(stderr, "We're so screwed!\n");
exit(EXIT_FAILURE);
}
```
but in some instances you have choices other than dying, because you've allocated some extra stuff for caching or whatever, and you can reclaim that memory.
However, in those instances where you can try to recover from a failed `malloc()` that you're doing something tricky and error prone in a code path that's pretty unusual, making testing especially important. How do you actually go about doing this? | 2009/11/10 | [
"https://Stackoverflow.com/questions/1711170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85467/"
]
| I saw a cool solution to this problem which was presented to me by S. Paavolainen. The idea is to override the standard `malloc()`, which you can do just in the linker, by a custom allocator which
1. reads the current execution stack of the thread calling `malloc()`
2. checks if the stack exists in a database that is stored on hard disk
1. if the stack does not exist, adds the stack to the database and returns `NULL`
2. if the stack did exist already, allocates memory normally and returns
Then you just run your unit test many times: this system automatically enumerates through different control paths to `malloc()` failure and is much more efficient and reliable than e.g. random testing. | You could hijack malloc by using some defines and global parameter to control it... It's a bit hackish but seems to work.
```
#include <stdio.h>
#include <stdlib.h>
#define malloc(x) fake_malloc(x)
struct {
size_t last_request;
int should_fail;
void *(*real_malloc)(size_t);
} fake_malloc_params;
void *fake_malloc(size_t size) {
fake_malloc_params.last_request = size;
if (fake_malloc_params.should_fail) {
return NULL;
}
return (fake_malloc_params.real_malloc)(size);;
}
int main(void) {
fake_malloc_params.real_malloc = malloc;
void *ptr = NULL;
ptr = malloc(1);
printf("last: %d\n", (int) fake_malloc_params.last_request);
printf("ptr: 0x%p\n", ptr);
return 0;
}
``` |
21,948,545 | I want to iterate the entries above the main diagonal of a square matrix of size n without using nested loops.
For example if the matrix M is of size n=3, then there are choose(3,2)=3 entries above the diagonal. where choose is the binomial coefficient.
```
for(i=1 to choose(n,2))
row = getRow(i)
col = getCol(i)
M[row,col] = some value
```
I have not been able to come up with a formula for getting row and col based on index i.
For example:
for a matrix of size = 3 and indexes starting at 1,
i=1 corresponds to row = 1 and col = 2
i=2 corresponds to row = 1 and col = 3
i=3 corresponds to row = 2 and col = 3 | 2014/02/22 | [
"https://Stackoverflow.com/questions/21948545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/176291/"
]
| You can use `triu` command of MATLAB as follows:
```
n=5; %user input
mat=magic(n);
nRows=size(mat,1);
nCols=size(mat,2);
%extract the elements above the main diagonal
u=triu(mat).*(~eye(n));
uT=u.'; %transpose to get the indices in the order you mentioned
%arrange it in a vector
u_ind=uT(uT~=0);
```
`u_ind` will contain the elements above the upper triangle in the desired format i.e. u\_ind(3) will contain the element at row=1 and col=4.
To get these row and column indices, you can get them as follows:
```
%You can easily get this if you make simple observations. For a matrix of size 5x5
%the number of total elements above main diagonal are: (4+3+2+1)
%i.e. sum of first n-1 elements -> hence the formula below
totalIndices=0.5*n*(n-1);
%number of elements per row you get
indicesPerRow=n-1:-1:1
%I observed that there is some relation between its index and its (row,col) subscript.
%If the index is 5 in a 5x5 matrix, then you can imagine that it is the first non-zero
%element in the second row -> because first row has 4 elements. If the index was 8,
%similarly, it would have been first non-zero element in the third row in the upper
%triangular matrix we have formed. This is what I have translated into code below.
ind1=cumsum(indicesPerRow);
ind2=ind1;
%Enter the number whose (row,col) index you want to find.
myInd=9;
ind2(ind1<myInd)=[];
pos=find(ind1<myInd,1,'last');
ind2=ind2(1);
ind3=rem(ind2,myInd);
detRow=pos+1;
detCol=nCols-ind3;
fprintf('Index %d corresponds to (row,col)=(%d,%d)\n',myInd,detRow,detCol);
``` | You can try:
```
n = 3;
for(int i = 1; i <= n; i++)
{
for(int j=i+1; j<=n; j++)
{
row = i;
col = j;
}
}
```
result:
1,2
1,3
2,3 |
21,948,545 | I want to iterate the entries above the main diagonal of a square matrix of size n without using nested loops.
For example if the matrix M is of size n=3, then there are choose(3,2)=3 entries above the diagonal. where choose is the binomial coefficient.
```
for(i=1 to choose(n,2))
row = getRow(i)
col = getCol(i)
M[row,col] = some value
```
I have not been able to come up with a formula for getting row and col based on index i.
For example:
for a matrix of size = 3 and indexes starting at 1,
i=1 corresponds to row = 1 and col = 2
i=2 corresponds to row = 1 and col = 3
i=3 corresponds to row = 2 and col = 3 | 2014/02/22 | [
"https://Stackoverflow.com/questions/21948545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/176291/"
]
| So *you* want a formula ! Ok ! Lets go for some simple maths:
The number of entry of the r first rows is `r*(r+1)/2`. Therefore `row` is the largest integer number such that `row*(row+1)/2 <= i`. So row is the integer part of the positive solution of the equation
```
row*(row+1)/2 = i
```
it rewrites as
```
row^2 + row - 2*i = 0
```
This is a 2nd degree equation so you can solve it using square roots. The positive solution is `(sqrt(1+8*i) - 1)/2`.
So you have:
```
row(i) = floor((sqrt(1+8*i) - 1)/2)
col(i) = i - row*(row+1)/2
```
Demo in Python:
```
def rc(i):
r = floor((-1 + sqrt(1+8*i))/2)
return (r, i-r*(r+1)/2)
```
Test:
```
print [rc(i) for i in range(20)]
[(0, 0), (1, 0), (1, 1), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2), (3, 3),
(4, 0), (4, 1), (4, 2), (4, 3), (4, 4), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4)]
```
With the correct presentation
```
(0, 0),
(1, 0), (1, 1),
(2, 0), (2, 1), (2, 2),
(3, 0), (3, 1), (3, 2), (3, 3),
(4, 0), (4, 1), (4, 2), (4, 3), (4, 4),
...
```
**Note:** I'm starting all my indices with 0. You have to shift i, r and c by one if you want to stick with the usual numbering. | You can try:
```
n = 3;
for(int i = 1; i <= n; i++)
{
for(int j=i+1; j<=n; j++)
{
row = i;
col = j;
}
}
```
result:
1,2
1,3
2,3 |
21,948,545 | I want to iterate the entries above the main diagonal of a square matrix of size n without using nested loops.
For example if the matrix M is of size n=3, then there are choose(3,2)=3 entries above the diagonal. where choose is the binomial coefficient.
```
for(i=1 to choose(n,2))
row = getRow(i)
col = getCol(i)
M[row,col] = some value
```
I have not been able to come up with a formula for getting row and col based on index i.
For example:
for a matrix of size = 3 and indexes starting at 1,
i=1 corresponds to row = 1 and col = 2
i=2 corresponds to row = 1 and col = 3
i=3 corresponds to row = 2 and col = 3 | 2014/02/22 | [
"https://Stackoverflow.com/questions/21948545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/176291/"
]
| You can use `triu` command of MATLAB as follows:
```
n=5; %user input
mat=magic(n);
nRows=size(mat,1);
nCols=size(mat,2);
%extract the elements above the main diagonal
u=triu(mat).*(~eye(n));
uT=u.'; %transpose to get the indices in the order you mentioned
%arrange it in a vector
u_ind=uT(uT~=0);
```
`u_ind` will contain the elements above the upper triangle in the desired format i.e. u\_ind(3) will contain the element at row=1 and col=4.
To get these row and column indices, you can get them as follows:
```
%You can easily get this if you make simple observations. For a matrix of size 5x5
%the number of total elements above main diagonal are: (4+3+2+1)
%i.e. sum of first n-1 elements -> hence the formula below
totalIndices=0.5*n*(n-1);
%number of elements per row you get
indicesPerRow=n-1:-1:1
%I observed that there is some relation between its index and its (row,col) subscript.
%If the index is 5 in a 5x5 matrix, then you can imagine that it is the first non-zero
%element in the second row -> because first row has 4 elements. If the index was 8,
%similarly, it would have been first non-zero element in the third row in the upper
%triangular matrix we have formed. This is what I have translated into code below.
ind1=cumsum(indicesPerRow);
ind2=ind1;
%Enter the number whose (row,col) index you want to find.
myInd=9;
ind2(ind1<myInd)=[];
pos=find(ind1<myInd,1,'last');
ind2=ind2(1);
ind3=rem(ind2,myInd);
detRow=pos+1;
detCol=nCols-ind3;
fprintf('Index %d corresponds to (row,col)=(%d,%d)\n',myInd,detRow,detCol);
``` | So *you* want a formula ! Ok ! Lets go for some simple maths:
The number of entry of the r first rows is `r*(r+1)/2`. Therefore `row` is the largest integer number such that `row*(row+1)/2 <= i`. So row is the integer part of the positive solution of the equation
```
row*(row+1)/2 = i
```
it rewrites as
```
row^2 + row - 2*i = 0
```
This is a 2nd degree equation so you can solve it using square roots. The positive solution is `(sqrt(1+8*i) - 1)/2`.
So you have:
```
row(i) = floor((sqrt(1+8*i) - 1)/2)
col(i) = i - row*(row+1)/2
```
Demo in Python:
```
def rc(i):
r = floor((-1 + sqrt(1+8*i))/2)
return (r, i-r*(r+1)/2)
```
Test:
```
print [rc(i) for i in range(20)]
[(0, 0), (1, 0), (1, 1), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2), (3, 3),
(4, 0), (4, 1), (4, 2), (4, 3), (4, 4), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4)]
```
With the correct presentation
```
(0, 0),
(1, 0), (1, 1),
(2, 0), (2, 1), (2, 2),
(3, 0), (3, 1), (3, 2), (3, 3),
(4, 0), (4, 1), (4, 2), (4, 3), (4, 4),
...
```
**Note:** I'm starting all my indices with 0. You have to shift i, r and c by one if you want to stick with the usual numbering. |
72,832,063 | I'm trying to create a new column in the below sample data frame that combines the data from the customer\_response and the bot\_response into a list shown in the combined column of the second table shown below.
One thing to note is that there will always be the same number of delimiters for the customer and bot column for each row.
df
| conv\_id | customer\_response | bot\_response |
| --- | --- | --- |
| 1 | Make a payment; Credit Card; $1000; Thanks! | I can help with that. Which account?; What amount?; Payment successful; You're Welcome! |
| 2 | Replace a card; Ending in 4352; overnight; thanks | I can help replace your card, which account?; How soon do you need it; The replacement card will arrive in 3-5 business days; No problem |
| 3 | What is my due date?; Am I past due?; thanks | Hello, your due date is the 3rd of each month; No, your account is current; you're welcome! |
Desired output:
| conv\_id | customer\_response | bot\_response | combined |
| --- | --- | --- | --- |
| 1 | Make a payment; Credit Card; $1000; Thanks! | I can help with that. Which account?; What amount?; Payment successful; You're Welcome! | ["Customer: Make a payment", "Bot: I can help with that. Which account?", "Customer: Credit Card", "Bot: What amount?", "Customer: $1000", "Bot: Payment successful", "Customer: Thanks!", "Bot: You're Welcome!"] |
| 2 | ... | ... | ... |
| 3 | ... | ... | ... |
Here is my code so far but for some reason I'm drawing a blank on how to create a column to combine the two as shown in the combined column in the second table above.
```
df['cust_dil'] = [x for x in df['customer_response'].str.split(';')]
df['bot_dil'] = [x for x in df['bot_response'].str.split(';')]
```
At a high level, I know I need to loop through the elements in each row after splitting them and add the the respective text "Bot" or "Customer" before each element in the list and then combine the 2 columns in order.
I'm really stumped on this so any help that can be given is greatly appreciated. | 2022/07/01 | [
"https://Stackoverflow.com/questions/72832063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7572119/"
]
| When you want to create a column whose value depends on more than one other column, `DataFrame.apply` is a good way to do it. You might try something like this
```
def combine_responses(row):
cust_dil = [x for x in row.customer_response.str.split(';')]
bot_dil = [x for x in row.bot_response.str.split(';')]
## Write some code to interleave these.
## https://stackoverflow.com/questions/7946798/interleave-multiple-lists-of-the-same-length-in-python
return [val for pair in zip(cust_dil, bot_dil) for val in pair]
df['combined'] = df.apply(combine_responses, axis=1)
``` | Here is a more `pandaic` approach to your problem with no `loops`, `comprehension list` and `apply` logic.
```
import pandas as pd
import numpy as np
data_dict= {
'conv_id': [1, 2, 3],
'customer_response': ['Make a payment; Credit Card; $1000; Thanks!', 'Replace a card; Ending in 4352; overnight; thanks', 'What is my due date?; Am I past due?; thanks'],
'bot_response': ['I can help with that. Which account?; What amount?; Payment successful; You\'re Welcome!', 'I can help replace your card, which account?; How soon do you need it; The replacement card will arrive in 3-5 business days; No problem', 'Hello, your due date is the 3rd of each month; No, your account is current; you\'re welcome!']}
df = pd.DataFrame(data_dict)
bot_response_split = df["bot_response"].str.split(';', expand=True).fillna("").applymap('Bot : {}'.format).replace('Bot : $', '',regex=True)
customer_response_split = df["customer_response"].str.split(';', expand=True).fillna("").applymap('Customer : {}'.format).replace('Customer : $', '',regex=True)
bot_response_split.columns = np.arange(len(customer_response_split.columns), len(customer_response_split.columns) + len(bot_response_split.columns))
new_columns = list(customer_response_split.columns) + list(bot_response_split.columns)
new_columns[::2] = list(customer_response_split.columns)
new_columns[1::2] = list(bot_response_split.columns)
df['combined'] = pd.concat([customer_response_split, bot_response_split], axis=1).reindex(columns=new_columns).values.tolist()
```
**Code explanation :**
* We first split the column on the delimiter `;`, those many columns will be created as the number of chats for each cell in the column, then we fill all our `None` values with `empty string`, then based on regex we prepend the appropriate third person in the chat eg `Bot and customer` here. After that we agin apply regex to replace those cells by `empty string` for which applymap added 'Customer : ' but the cell was empty.
```
bot_response_split = df["bot_response"].str.split(';', expand=True).fillna("").applymap('Bot : {}'.format).replace('Bot : $', '',regex=True)
customer_response_split = df["customer_response"].str.split(';', expand=True).fillna("").applymap('Customer : {}'.format).replace('Customer : $', '',regex=True)
```
* Secondly we rename the column names for the `bot_response_datframe` as this will help in interleaving.
```
bot_response_split.columns = np.arange(len(customer_response_split.columns), len(customer_response_split.columns) + len(bot_response_split.columns))
```
* Next we join the column list from `customer` and `bot` dataframe to a third column list which will help us in interleaving `new_columns`
```
new_columns = list(customer_response_split.columns) + list(bot_response_split.columns)
```
* From the `customer` dataframe we take the column list and insert it to `new_columns` alternatively. We are doing the same for `bot` dataframe column as well.
```
new_columns[::2] = list(customer_response_split.columns)
new_columns[1::2] = list(bot_response_split.columns)
```
* In the end, we concat our `customer` and `bot` dataframe and re order our indexes such that the columns are interleaved, then we join all the columns so that the values are interleaved and insert it to a third column in `df` called `combined`
```
df['combined'] = pd.concat([customer_response_split, bot_response_split], axis=1).reindex(columns=new_columns).values.tolist()
```
**Output :**
[](https://i.stack.imgur.com/jqvXr.png) |
1,782,044 | How can I use linqpad with code only in ef 4.
I mean how to reference metadata when there is no edmx file? | 2009/11/23 | [
"https://Stackoverflow.com/questions/1782044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/216874/"
]
| I believe you want to `unset($arr['addtocart']);` | ```
$vars = array('name' => super, 'price' => 65.87, 'quantity' => 25, 'addtocart' => 1);
unset($vars['addtocart']);
``` |
59,671,638 | I am trying to assert a text that's seen on a media gallery overlay page. All I want is for the code to verify if the text is present and if so, assets it matches the expected text.
For some reason, I keep getting failed tests. Below is the code I have written in Visual Code:
```
let expSuccessARMessage = "See it in Your Space (Augmented Reality) is currently only available using an AR compatible Apple device (iOS 12 or above)."
let successARMessage = browser.getText(page.pageElements.arMessage);
console.log(successARMessage);
assert(successARMessage === expSuccessARMessage, 'Success message');
```
What am I missing here? | 2020/01/09 | [
"https://Stackoverflow.com/questions/59671638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7437599/"
]
| Not a magician, but you should be getting `browser.getText is not a function` error in the console, because the `getText()` method is defined inside the `element` object, not the `browser` object. Read the complete API log **[here](https://webdriver.io/docs/api/element/getText.html)**.
So your code should be:
```
let expectedText = "Your long text here"
let foundText = $(page.pageElements.arMessage).getText();
// Considering 'page.pageElements.arMessage' is a valid selector for targeted element
console.log(`Found the following text: ${foundText}`);
assert.equal(expectedText, foundText, 'This is actually the ERROR message');
```
---
I want to add to the answer that there can also be a `browser` object centric approach, using the **[webdriver](https://webdriver.io/docs/api/webdriver.html)** protocol API. Thus, our code becomes:
```
let expectedText = "Your long text here"
let elementObject = browser.findElement('css selector', page.pageElements.arMessage);
// Considering 'page.pageElements.arMessage' is a valid selector for targeted element
let foundText = browser.getElementText(elementObject.ELEMENT);
console.log(`Found the following text: ${foundText}`);
assert.equal(expectedText, foundText, 'This is actually the ERROR message');
```
---
The latter approach is obsolete IMHO, and the recommended approach for WebdriverIO v5 would be using **[$](https://webdriver.io/docs/api/browser/$.html)**, respectively **[$$](https://webdriver.io/docs/api/browser/$$.html)** (*element & elements*). But wanted to give you a broader perspective. | If you defined the element into object repository like:
```
get OtpDescriptionText () { return '//div[@class="otp-description"]'; }
```
In order to **console** or **assert/expect** that element you need to use like:
```
let elem1 = await $(RegistratonPage.OtpDescriptionText);
console.log(await elem1.getText());
```
or
```
await expect($(RegistratonPage.OtpDescriptionText)).toHaveTextContaining('We just need to check this phone number belongs to you.')
```
If you don't use $, error is thrown |
72,849 | Kann man Absendeadresse sagen?
Wenn ich nach "Absendeadresse vs Absenderadresse" [google](https://www.google.com/search?q=Absendeadresse%20vs%20Absenderadresse), bekomme ich Ergebnisse für "Absenderadresse vs Absenderadresse" vorgeschlagen, woraus ich schließe, dass Google meint, "Absendeadresse" sei kein richtiges deutsches Wort. Deswegen die Frage. | 2023/01/28 | [
"https://german.stackexchange.com/questions/72849",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/536/"
]
| Du kannst im Deutschen Wörter zusammensetzen, wie es dir gefällt, die Frage ist eigentlich nur, ob das Ergebnis für andere verständlich ist. Das ist bei "Absendeadresse" sicherlich der Fall. Etablierte gegenderte Formen existieren für sehr viele Wörter (noch?) nicht, und es gibt auch keine Instanz, die diese festlegen kann. Wenn man das Gendern grundsätzlich für sinnvoll hält, darf und muss man halt kreativ werden.
Absendeadresse, Absender[\*\_:/][Ii]nnenAdresse, Absendendenadresse ... -- alles möglich (zumindest wenn man nicht für eine Entität schreibt, die den Regeln des Rechtschreibrates unterliegt, der die Formen mit Stern, Doppelpunkt oder Unterstrich nicht zulässt). Da die Mehrheit der Sprachgemeinschaft bekanntlich das Gendern ablehnt, zum Teil sehr vehement, stellt sich auch die Frage, wie man sich selbst in dieser Frage seinen Lesern darstellen möchte, und je nachdem werden unterschiedliche Autoren jeweils unauffälligere oder auffälligere Formen bevorzugen, oder das generische Maskulinum. Das gehört zur persönlichen Freiheit, sich auszudrücken. | Ein richtiges (wenn auch nicht notwendigerweise gängiges) deutsches Wort ist "Absendeadresse" durchaus.
Neben der hohen Wahrscheinlichkeit, dass man es als unbeabsichtigtes Resultat aus einem Tippfehler einstuft, da es sehr nahe an einem tatsächlich gängigen Wort ("Absenderadresse") liegt, sehe ich das Hauptproblem darin, dass die zwei Begriffe inhaltlich nicht synonym zu sein scheinen:
Die "Absenderadresse", ganz gleich, wie man zur Inklusivität des Wortes "Absender" stehen mag, bezieht sich auf den Absender, also die Entität, von welcher die Sendung stammt. Unter einer "Absenderadresse" erwarte ich den Namen einer Person oder Organisation, sowie Straße, Stadt und ggf. Land.
Eine "Absendeadresse" klingt hingegen vielmehr danach, als gehe es um die Handlung des Absendens. Wer die Sendung veranlasst, bleibt dabei außen vor. Würde mich jemand explizit nach einer "Absendeadresse" fragen, würde ich intuitiv nur Straße, Stadt und ggf. Land angeben. |
63,984,884 | I have a text string, and have identified a set of words which I want to wrap with []. I have stored these words in an array, and have also stored the index position of their first and last characters in each object as well.
How can I append [] to either side of these words in Python?
Here is an example of a text string I am extracting words from:
`"The SARs were leaked to the Buzzfeed website and shared with the International Consortium of Investigative Journalists (ICIJ). Panorama led the research for the BBC as part of a global probe. The ICIJ led the reporting of the Panama Papers and Paradise Papers leaks - secret files detailing the offshore activities of the wealthy and the famous. Fergus Shiel, from the consortium, said the FinCEN Files are an insight into what banks know about the vast flows of dirty money across the globe… [The] system that is meant to regulate the flows of tainted money is broken. The leaked SARs had been submitted to the US Financial Crimes Enforcement Network, or FinCEN between 2000 and 2017 and cover transactions worth about $2 trillion. FinCEN said the leak could impact US national security, risk investigations, and threaten the safety of those who file the reports. But last week it announced proposals to overhaul its anti-money laundering programmes. The UK also unveiled plans to reform its register of company information to clamp down on fraud and money laundering.The investment scam that HSBC was warned about was called WCM777. It led to the death of investor Reynaldo Pacheco, who was found under water on a wine estate in Napa, California, in April 2014. Police say he had been bludgeoned with rocks. He signed up to the scheme and was expected to recruit other investors. The promise was everyone would get rich. A woman Mr Pacheco, 44, introduced lost about $3,000. That led to the killing by men hired to kidnap him. He literally was trying to… make people's lives better, and he himself was scammed, and conned, and he unfortunately paid for it with his life,said Sgt Chris Pacheco (no relation), one of the officers who investigated the killing. Reynaldo, he said, was murdered for being a victim in a Ponzi scheme."`
Here is an example of what the array of words I am looking to append square brackets to looks like:
`[('Buzzfeed', 28, 36, 'ORG'), ('International Consortium of Investigative Journalists', 61, 118, 'ORG'), ('Panorama', 127, 135, 'ORG'), ('BBC', 161, 164, 'ORG'), ('Panama Papers', 222, 239, 'ORG'), ('Fergus Shiel', 346, 358, 'PERSON'), ('Files', 397, 402, 'PRODUCT'), ('US Financial Crimes Enforcement Network', 608, 651, 'ORG'), ('FinCEN', 733, 739, 'ORG'), ('US', 767, 769, 'GPE'), ('last week', 869, 878, 'DATE'), ('UK', 956, 958, 'GPE'), ('HSBC', 1094, 1098, 'ORG'), ('Reynaldo Pacheco', 1167, 1183, 'PERSON'), ('Napa', 1231, 1235, 'GPE'), ('California', 1237, 1247, 'GPE'), ('April 2014', 1252, 1262, 'DATE'), ('Mr Pacheco', 1431, 1441, 'PERSON'), ('44', 1443, 1445, 'DATE'), ('Sgt Chris Pacheco', 1677, 1694, 'PERSON')]` | 2020/09/21 | [
"https://Stackoverflow.com/questions/63984884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13444628/"
]
| If you sort your list of phrases (I've called it `words`) in reverse order, you can insert the `[` and `]` around each phrase in a loop. The reason you need to do it backwards is because the insertion will change the indexes of subsequent characters in the string:
```
for w in sorted(words, key=lambda x:-x[1]):
text = text[:w[1]] + '[' + text[w[1]:w[2]] + ']' + text[w[2]:]
print(text)
```
Output:
The SARs were leaked to the [Buzzfeed] website and shared with [the International Consortium of Investigative Journalists] (ICIJ). [Panorama] led the research for the [BBC] as part of a global probe. The ICIJ led the reporting of [the Panama Papers] and Paradise Papers leaks - secret files detailing the offshore activities of the wealthy and the famous. [Fergus Shiel], from the consortium, said the FinCEN [Files] are an insight into what banks know about the vast flows of dirty money across the globe… [The] system that is meant to regulate the flows of tainted money is broken. The leaked SARs had been submitted to [the US Financial Crimes Enforcement Network], or FinCEN between 2000 and 2017 and cover transactions worth about $2 trillion. [FinCEN] said the leak could impact [US] national security, risk investigations, and threaten the safety of those who file the reports. But [last week] it announced proposals to overhaul its anti-money laundering programmes. The [UK] also unveiled plans to reform its register of company information to clamp down on fraud and money laundering.The investment scam that [HSBC] was warned about was called WCM777. It led to the death of investor [Reynaldo Pacheco], who was found under water on a wine estate in [Napa], [California], in [April 2014]. Police say he had been bludgeoned with rocks. He signed up to the scheme and was expected to recruit other investors. The promise was everyone would get rich. A woman [Mr Pacheco], [44], introduced lost about $3,000. That led to the killing by men hired to kidnap him. He literally was trying to… make people's lives better, and he himself was scammed, and conned, and he unfortunately paid for it with his life,said [Sgt Chris Pacheco] (no relation), one of the officers who investigated the killing. Reynaldo, he said, was murdered for being a victim in a Ponzi scheme.
[Demo on ideone](https://ideone.com/KWjP7E) | The following should work: l is your original list and t is yout text:
```
l=[list(i) for i in l]
for i in range(len(l)):
x1, x2=l[i][1], l[i][2]
t=t[:x1]+ '[' + t[x1:x2] + ']' +t[x2:]
for k in range(i+1, len(l)):
l[k][1]+=2
l[k][2]+=2
```
This gives the following Output:
```
"The SARs were leaked to the [Buzzfeed] website and shared with [the International Consortium of Investigative Journalists] (ICIJ). [Panorama] led the research for the [BBC] as part of a global probe. The ICIJ led the reporting of [the Panama Papers] and Paradise Papers leaks - secret files detailing the offshore activities of the wealthy and the famous. [Fergus Shiel], from the consortium, said the FinCEN [Files] are an insight into what banks know about the vast flows of dirty money across the globe… [The] system that is meant to regulate the flows of tainted money is broken. The leaked SARs had been submitted to [the US Financial Crimes Enforcement Network], or FinCEN between 2000 and 2017 and cover transactions worth about $2 trillion. [FinCEN] said the leak could impact [US] national security, risk investigations, and threaten the safety of those who file the reports. But [last week] it announced proposals to overhaul its anti-money laundering programmes. The [UK] also unveiled plans to reform its register of company information to clamp down on fraud and money laundering.The investment scam that [HSBC] was warned about was called WCM777. It led to the death of investor [Reynaldo Pacheco], who was found under water on a wine estate in [Napa], [California], in [April 2014]. Police say he had been bludgeoned with rocks. He signed up to the scheme and was expected to recruit other investors. The promise was everyone would get rich. A woman [Mr Pacheco], [44], introduced lost about $3,000. That led to the killing by men hired to kidnap him. He literally was trying to… make people's lives better, and he himself was scammed, and conned, and he unfortunately paid for it with his life,said [Sgt Chris Pacheco] (no relation), one of the officers who investigated the killing. Reynaldo, he said, was murdered for being a victim in a Ponzi scheme."
``` |
63,984,884 | I have a text string, and have identified a set of words which I want to wrap with []. I have stored these words in an array, and have also stored the index position of their first and last characters in each object as well.
How can I append [] to either side of these words in Python?
Here is an example of a text string I am extracting words from:
`"The SARs were leaked to the Buzzfeed website and shared with the International Consortium of Investigative Journalists (ICIJ). Panorama led the research for the BBC as part of a global probe. The ICIJ led the reporting of the Panama Papers and Paradise Papers leaks - secret files detailing the offshore activities of the wealthy and the famous. Fergus Shiel, from the consortium, said the FinCEN Files are an insight into what banks know about the vast flows of dirty money across the globe… [The] system that is meant to regulate the flows of tainted money is broken. The leaked SARs had been submitted to the US Financial Crimes Enforcement Network, or FinCEN between 2000 and 2017 and cover transactions worth about $2 trillion. FinCEN said the leak could impact US national security, risk investigations, and threaten the safety of those who file the reports. But last week it announced proposals to overhaul its anti-money laundering programmes. The UK also unveiled plans to reform its register of company information to clamp down on fraud and money laundering.The investment scam that HSBC was warned about was called WCM777. It led to the death of investor Reynaldo Pacheco, who was found under water on a wine estate in Napa, California, in April 2014. Police say he had been bludgeoned with rocks. He signed up to the scheme and was expected to recruit other investors. The promise was everyone would get rich. A woman Mr Pacheco, 44, introduced lost about $3,000. That led to the killing by men hired to kidnap him. He literally was trying to… make people's lives better, and he himself was scammed, and conned, and he unfortunately paid for it with his life,said Sgt Chris Pacheco (no relation), one of the officers who investigated the killing. Reynaldo, he said, was murdered for being a victim in a Ponzi scheme."`
Here is an example of what the array of words I am looking to append square brackets to looks like:
`[('Buzzfeed', 28, 36, 'ORG'), ('International Consortium of Investigative Journalists', 61, 118, 'ORG'), ('Panorama', 127, 135, 'ORG'), ('BBC', 161, 164, 'ORG'), ('Panama Papers', 222, 239, 'ORG'), ('Fergus Shiel', 346, 358, 'PERSON'), ('Files', 397, 402, 'PRODUCT'), ('US Financial Crimes Enforcement Network', 608, 651, 'ORG'), ('FinCEN', 733, 739, 'ORG'), ('US', 767, 769, 'GPE'), ('last week', 869, 878, 'DATE'), ('UK', 956, 958, 'GPE'), ('HSBC', 1094, 1098, 'ORG'), ('Reynaldo Pacheco', 1167, 1183, 'PERSON'), ('Napa', 1231, 1235, 'GPE'), ('California', 1237, 1247, 'GPE'), ('April 2014', 1252, 1262, 'DATE'), ('Mr Pacheco', 1431, 1441, 'PERSON'), ('44', 1443, 1445, 'DATE'), ('Sgt Chris Pacheco', 1677, 1694, 'PERSON')]` | 2020/09/21 | [
"https://Stackoverflow.com/questions/63984884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13444628/"
]
| If you sort your list of phrases (I've called it `words`) in reverse order, you can insert the `[` and `]` around each phrase in a loop. The reason you need to do it backwards is because the insertion will change the indexes of subsequent characters in the string:
```
for w in sorted(words, key=lambda x:-x[1]):
text = text[:w[1]] + '[' + text[w[1]:w[2]] + ']' + text[w[2]:]
print(text)
```
Output:
The SARs were leaked to the [Buzzfeed] website and shared with [the International Consortium of Investigative Journalists] (ICIJ). [Panorama] led the research for the [BBC] as part of a global probe. The ICIJ led the reporting of [the Panama Papers] and Paradise Papers leaks - secret files detailing the offshore activities of the wealthy and the famous. [Fergus Shiel], from the consortium, said the FinCEN [Files] are an insight into what banks know about the vast flows of dirty money across the globe… [The] system that is meant to regulate the flows of tainted money is broken. The leaked SARs had been submitted to [the US Financial Crimes Enforcement Network], or FinCEN between 2000 and 2017 and cover transactions worth about $2 trillion. [FinCEN] said the leak could impact [US] national security, risk investigations, and threaten the safety of those who file the reports. But [last week] it announced proposals to overhaul its anti-money laundering programmes. The [UK] also unveiled plans to reform its register of company information to clamp down on fraud and money laundering.The investment scam that [HSBC] was warned about was called WCM777. It led to the death of investor [Reynaldo Pacheco], who was found under water on a wine estate in [Napa], [California], in [April 2014]. Police say he had been bludgeoned with rocks. He signed up to the scheme and was expected to recruit other investors. The promise was everyone would get rich. A woman [Mr Pacheco], [44], introduced lost about $3,000. That led to the killing by men hired to kidnap him. He literally was trying to… make people's lives better, and he himself was scammed, and conned, and he unfortunately paid for it with his life,said [Sgt Chris Pacheco] (no relation), one of the officers who investigated the killing. Reynaldo, he said, was murdered for being a victim in a Ponzi scheme.
[Demo on ideone](https://ideone.com/KWjP7E) | If you can make certain assumptions about your data, then here's a very simple version which is probably what my first attempt would look like:
```
text = "The SARs were leaked..."
keywords_indexed = [('Buzzfeed', 28, 36, 'ORG'), ...]
# Construct a set of keywords that we want to bracket
words_to_bracket = set(k[0] for k in keywords_indexed)
# Replace every instance of a word-to-be-bracketed
bracketed_text = text
for word in words_to_bracket:
bracketed_text = bracketed_text.replace(word, "[{}]".format(word))
print(bracketed_text)
```
**Pros**: It's simple, easy to understand, maintainable.
**Cons**: It's quite inefficient, but that may not matter unless you're handling very large chunks of text and have to do it fast.
Only you can decide which tradeoffs to make. Just wanted to offer you a nice, clean version to choose from!
---
Output of above code on the OP's sample input:
>
> The SARs were leaked to the [Buzzfeed] website and shared with the [International Consortium of Investigative Journalists] (ICIJ). [Panorama] led the research for the [BBC] as part of a global probe. The ICIJ led the reporting of the [Panama Papers] and Paradise Papers leaks - secret files detailing the offshore activities of the wealthy and the famous. [Fergus Shiel], from the consortium, said the [FinCEN] [Files] are an insight into what banks know about the vast flows of dirty money across the globe… [The] system that is meant to regulate the flows of tainted money is broken. The leaked SARs had been submitted to the [US] Financial Crimes Enforcement Network, or [FinCEN] between 2000 and 2017 and cover transactions worth about $2 trillion. [FinCEN] said the leak could impact [US] national security, risk investigations, and threaten the safety of those who file the reports. But [last week] it announced proposals to overhaul its anti-money laundering programmes. The [UK] also unveiled plans to reform its register of company information to clamp down on fraud and money laundering.The investment scam that [HSBC] was warned about was called WCM777. It led to the death of investor [Reynaldo Pacheco], who was found under water on a wine estate in [Napa], [California], in [April 2014]. Police say he had been bludgeoned with rocks. He signed up to the scheme and was expected to recruit other investors. The promise was everyone would get rich. A woman [Mr Pacheco], [44], introduced lost about $3,000. That led to the killing by men hired to kidnap him. He literally was trying to… make people's lives better, and he himself was scammed, and conned, and he unfortunately paid for it with his life,said [Sgt Chris Pacheco] (no relation), one of the officers who investigated the killing. Reynaldo, he said, was murdered for being a victim in a Ponzi scheme.
>
>
> |
17,684,201 | I am a beginner of JavaScript and want to display an array of objects in HTML.
The format of the data is like this:
```
[
{"key":"apple","value":1.90},
{"key":"berry","value":1.7},
{"key":"banana","value":1.5},
{"key":"cherry","value":1.2}
]
```
I want to use a list with three columns (id, name, relevance) to display them. And the id can increase from 1 automatically.
Could anyone tell me how to write a javascript code to display it?
Please give me some materials or examples to learn. | 2013/07/16 | [
"https://Stackoverflow.com/questions/17684201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2557815/"
]
| Explanation
-----------
What you want is to fill a table (or another DOMElement) in HTML, with your JavaScript, which is executed dynamically once the page is loaded and your JSON object is received.
You want to loop through the object. The best way to do so would be with a `for` loop, and making sure our *looping variable* remains valid for the length of our object (all its attributes).
The best way to get the length of a JSON object is through `myJSONObject.length`: You select the keys of **myJSONObject** and return their count.
You can access the values stored in your JSON Object the following way, in your `for` loop (assuming the looping variable defined is named `i`): `myJSONObject[i].theAttributeIWantToGet`
---
Price formatting breakdown
--------------------------
Now, those prices need to have a proper format, don't they? So we'll check if any of the `value` attribute has **less than 2** characters after the `.` within them. If they do, we add another decimal `0`. We also add a `$` before writing the formatted value. Here is a breakdown of how it works:
* `obj[i].value.toString().substring(startIndex, length)`
+ We want to check the length after the `.` sign, so our startIndex will be the position of this dot within our string.
+ `obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'),length)`
+ We now need to set the length. We want to find the length of all what's after the dot, so we'll take the length of the whole string just to be safe.
+ Final result: `obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2`
- This will return true or false. If it's true: There's less than 2 digits after the dot !
+ We add the `if` statement and the last zero:
+ `if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2)
obj[i].value += "0";`
---
**Also:** [Why I use `innerHTML` instead of `appendChild()`](http://jsperf.com/html-innerhtml-vs-appendchild).
---
Solution
========
[JSFiddle](http://jsfiddle.net/mjE7R/)
--------------------------------------
HTML
----
```html
<table>
<tbody id="tbody"></tbody>
</table>
```
JSON
----
```json
[{
"key": "apple",
"value": 1.90
}, {
"key": "berry",
"value": 1.7
}, {
"key": "banana",
"value": 1.5
}, {
"key": "cherry",
"value": 1.2
}]
```
JavaScript
----------
**Note:** The JSON object will be named `obj` in this instance.
```js
var tbody = document.getElementById('tbody');
for (var i = 0; i < obj.length; i++) {
var tr = "<tr>";
/* Verification to add the last decimal 0 */
if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2)
obj[i].value += "0";
/* Must not forget the $ sign */
tr += "<td>" + obj[i].key + "</td>" + "<td>$" + obj[i].value.toString() + "</td></tr>";
/* We add the table row to the table body */
tbody.innerHTML += tr;
}
```
[JSFiddle](http://jsfiddle.net/mjE7R/)
-------------------------------------- | I am not totally sure what you are asking for. The title of you post seems like you are looking for JSON.stringfy like mentioned in the previous answer but apparently you are not.
Are you trying to create and HTML list, ? Can you please try to explain your need again? I doubt what you are trying to do is complicated and I sure we can help you if you give a little more detail and purpose of what you are trying to do.
I am going to guess that you are trying to display HMTL by looping over you JSON object. Try this pure JavaScript example:
```
var fruits = JSON.parse('[{"key":"apple","value":1.90}, {"key":"berry","value":1.7}, {"key":"banana","value":1.5}, {"key":"cherry","value":1.2} ]');
var tbl = document.createElement('table');
var thead = document.createElement("thead");
var tbody = document.createElement("tbody")
var tr_head = document.createElement("tr");
var th_id = document.createElement("th");
var th_name = document.createElement("th");
var th_price = document.createElement("th");
th_id.textContent = "Id";
th_name.textContent = "Name";
th_price.textContent = "Price";
tr_head.appendChild(th_id);
tr_head.appendChild(th_name);
tr_head.appendChild(th_price);
thead.appendChild(tr_head);
for(var i = 0, j = fruits.length; i < j; i++) {
var tr_body = document.createElement("tr");
var td_id = document.createElement("td");
var td_name = document.createElement("td");
var td_value = document.createElement("td");
td_id.textContent = i;
td_name.textContent = fruits[i].key;
td_value.textContent = fruits[i].value;
tr_body.appendChild(td_id);
tr_body.appendChild(td_name);
tr_body.appendChild(td_value);
tbody.appendChild(tr_body);
}
tbl.appendChild(thead);
tbl.appendChild(tbody);
console.log(tbl);
``` |
17,684,201 | I am a beginner of JavaScript and want to display an array of objects in HTML.
The format of the data is like this:
```
[
{"key":"apple","value":1.90},
{"key":"berry","value":1.7},
{"key":"banana","value":1.5},
{"key":"cherry","value":1.2}
]
```
I want to use a list with three columns (id, name, relevance) to display them. And the id can increase from 1 automatically.
Could anyone tell me how to write a javascript code to display it?
Please give me some materials or examples to learn. | 2013/07/16 | [
"https://Stackoverflow.com/questions/17684201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2557815/"
]
| You can do something like this:
```
var table = document.createElement("table");
//Add a header
var header = document.createElement("tr");
var idHeaderCell = document.createElement("th");
var nameHeaderCell = document.createElement("th");
var relevanceHeaderCell = document.createElement("th");
header.appendChild(idHeaderCell);
header.appendChild(nameHeaderCell);
header.appendChild(relevanceHeaderCell);
table.appendChild(header);
//Add the rest of the data to the table
for(var i = 0; i < data.length; i++) {
var id = (i + 1);
var name = data[i].key;
var relevance = data[i].value;
var tr = document.createElement("tr");
var idCell = document.createElement("td");
var nameCell = document.createElement("td");
var relevanceCell = document.createElement("td");
idCell.appendChild(document.createTextNode(id));
nameCell.appendChild(document.createTextNode(name));
relevanceCell.appendChild(document.createTextNode(relevance));
tr.appendChild(idCell);
tr.appendChild(nameCell);
tr.appendChild(relevanceCell);
table.appendChild(tr);
}
``` | Maybe like this:
```
function obj2htmltable(obj) {
var html = '<table>';
for (var key in obj) {
var value = obj[key].toString();
html += '<tr><td>' + key + '</td><td>' + value + '</tr>';
}
html += '</table>';
return html;
}
```
If case of nested structure (objects inside object) obj2htmltable() could call itself recursively:
```
function obj2htmltable(obj) {
var html = '<table>';
for (var key in obj) {
var item = obj[key];
var value = (typeof(item) === 'object') ? obj2htmltable(item) : item.toString();
html += '<tr><td>' + key + '</td><td>' + value + '</tr>';
}
html += '</table>';
return html;
}
``` |
17,684,201 | I am a beginner of JavaScript and want to display an array of objects in HTML.
The format of the data is like this:
```
[
{"key":"apple","value":1.90},
{"key":"berry","value":1.7},
{"key":"banana","value":1.5},
{"key":"cherry","value":1.2}
]
```
I want to use a list with three columns (id, name, relevance) to display them. And the id can increase from 1 automatically.
Could anyone tell me how to write a javascript code to display it?
Please give me some materials or examples to learn. | 2013/07/16 | [
"https://Stackoverflow.com/questions/17684201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2557815/"
]
| Explanation
-----------
What you want is to fill a table (or another DOMElement) in HTML, with your JavaScript, which is executed dynamically once the page is loaded and your JSON object is received.
You want to loop through the object. The best way to do so would be with a `for` loop, and making sure our *looping variable* remains valid for the length of our object (all its attributes).
The best way to get the length of a JSON object is through `myJSONObject.length`: You select the keys of **myJSONObject** and return their count.
You can access the values stored in your JSON Object the following way, in your `for` loop (assuming the looping variable defined is named `i`): `myJSONObject[i].theAttributeIWantToGet`
---
Price formatting breakdown
--------------------------
Now, those prices need to have a proper format, don't they? So we'll check if any of the `value` attribute has **less than 2** characters after the `.` within them. If they do, we add another decimal `0`. We also add a `$` before writing the formatted value. Here is a breakdown of how it works:
* `obj[i].value.toString().substring(startIndex, length)`
+ We want to check the length after the `.` sign, so our startIndex will be the position of this dot within our string.
+ `obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'),length)`
+ We now need to set the length. We want to find the length of all what's after the dot, so we'll take the length of the whole string just to be safe.
+ Final result: `obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2`
- This will return true or false. If it's true: There's less than 2 digits after the dot !
+ We add the `if` statement and the last zero:
+ `if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2)
obj[i].value += "0";`
---
**Also:** [Why I use `innerHTML` instead of `appendChild()`](http://jsperf.com/html-innerhtml-vs-appendchild).
---
Solution
========
[JSFiddle](http://jsfiddle.net/mjE7R/)
--------------------------------------
HTML
----
```html
<table>
<tbody id="tbody"></tbody>
</table>
```
JSON
----
```json
[{
"key": "apple",
"value": 1.90
}, {
"key": "berry",
"value": 1.7
}, {
"key": "banana",
"value": 1.5
}, {
"key": "cherry",
"value": 1.2
}]
```
JavaScript
----------
**Note:** The JSON object will be named `obj` in this instance.
```js
var tbody = document.getElementById('tbody');
for (var i = 0; i < obj.length; i++) {
var tr = "<tr>";
/* Verification to add the last decimal 0 */
if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2)
obj[i].value += "0";
/* Must not forget the $ sign */
tr += "<td>" + obj[i].key + "</td>" + "<td>$" + obj[i].value.toString() + "</td></tr>";
/* We add the table row to the table body */
tbody.innerHTML += tr;
}
```
[JSFiddle](http://jsfiddle.net/mjE7R/)
-------------------------------------- | Iterate through the list and retrieve the data for each item this way (assuming your data is in a var called data):
```
for (var i = 0; i < data.length; i++) {
var id = i + 1;
var name = data[i].key;
var relevance = data[i].value;
}
```
Then, do something with the variables in each loop, print them out however you want. |
17,684,201 | I am a beginner of JavaScript and want to display an array of objects in HTML.
The format of the data is like this:
```
[
{"key":"apple","value":1.90},
{"key":"berry","value":1.7},
{"key":"banana","value":1.5},
{"key":"cherry","value":1.2}
]
```
I want to use a list with three columns (id, name, relevance) to display them. And the id can increase from 1 automatically.
Could anyone tell me how to write a javascript code to display it?
Please give me some materials or examples to learn. | 2013/07/16 | [
"https://Stackoverflow.com/questions/17684201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2557815/"
]
| It can be simply done by a small & smart process:
```
<table cellpadding="2" cellspacing="2" border="0" bgcolor="#dfdfdf" width="40%" align="center">
<thead>
<tr>
<th>Name</th>
<th width="20%">Age</th>
<th width="12%">Status</th>
</tr>
</thead>
<tbody id="tableData"></tbody>
</table>
<script type="text/javascript">
var mainObj = [
{
name: "Kapil",
age: 21,
status: "Active"
},
{
name: "John",
age: 28,
status: "Inactive"
},
{
name: "Deos",
age: 18,
status: "Active"
}
];
var k = '<tbody>'
for(i = 0;i < mainObj.length; i++){
k+= '<tr>';
k+= '<td>' + mainObj[i].name + '</td>';
k+= '<td>' + mainObj[i].age + '</td>';
k+= '<td>' + mainObj[i].status + '</td>';
k+= '</tr>';
}
k+='</tbody>';
document.getElementById('tableData').innerHTML = k;
</script>
``` | Array.map() combined with template literals comes in really handy for rendering HTML markup within Javascript for large objects in a scalable manner:
```
function tableMarkupFromObjectArray(obj) {
let headers = `
<th>Index</th>
${Object.keys(obj[0]).map((col) =>`
<th>${col}</th>`
).join('')}`
let content = obj.map((row, idx) => `
<tr>
<td>${idx}</td>
${Object.values(row).map((datum) => `
<td>${datum}</td>`
).join('')}
</tr>
`).join('')
let tablemarkup = `
<table>
${headers}
${content}
</table>
`
return tablemarkup
}
let myobj =[
{ "name": "apple", "rel": 1.90 },
{ "name": "berry", "rel": 1.7 },
{ "name": "banana", "rel": 1.5 },
{ "name": "cherry", "rel": 1.2 }
]
document.querySelector("#mydiv").innerHTML = tableMarkupFromObjectArray(myobj)
```
<http://jsfiddle.net/4L7c5vad/> |
17,684,201 | I am a beginner of JavaScript and want to display an array of objects in HTML.
The format of the data is like this:
```
[
{"key":"apple","value":1.90},
{"key":"berry","value":1.7},
{"key":"banana","value":1.5},
{"key":"cherry","value":1.2}
]
```
I want to use a list with three columns (id, name, relevance) to display them. And the id can increase from 1 automatically.
Could anyone tell me how to write a javascript code to display it?
Please give me some materials or examples to learn. | 2013/07/16 | [
"https://Stackoverflow.com/questions/17684201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2557815/"
]
| It can be simply done by a small & smart process:
```
<table cellpadding="2" cellspacing="2" border="0" bgcolor="#dfdfdf" width="40%" align="center">
<thead>
<tr>
<th>Name</th>
<th width="20%">Age</th>
<th width="12%">Status</th>
</tr>
</thead>
<tbody id="tableData"></tbody>
</table>
<script type="text/javascript">
var mainObj = [
{
name: "Kapil",
age: 21,
status: "Active"
},
{
name: "John",
age: 28,
status: "Inactive"
},
{
name: "Deos",
age: 18,
status: "Active"
}
];
var k = '<tbody>'
for(i = 0;i < mainObj.length; i++){
k+= '<tr>';
k+= '<td>' + mainObj[i].name + '</td>';
k+= '<td>' + mainObj[i].age + '</td>';
k+= '<td>' + mainObj[i].status + '</td>';
k+= '</tr>';
}
k+='</tbody>';
document.getElementById('tableData').innerHTML = k;
</script>
``` | Here a function for build a table from any collection (array of objects)
[Table creator](https://codepen.io/anon/pen/KZjVaZ?editors=0010)
```
const data=[
{
name: "Kapil",
age: 21,
status: "Active"
},
{
name: "John",
age: 28,
status: "Inactive"
},
{
name: "Deos",
age: 18,
status: "Active",
testing: 'Gooo!!'
}
]
const createTable=function(data){
const table = document.createElement("table");
const header = document.createElement("tr");
const keys=Object.keys(data[0])
console.log(keys)
for(const key of keys){
const th=document.createElement("th");
th.appendChild(document.createTextNode(key));
header.appendChild(th);
}
table.appendChild(header);
const len=data.length
for(const row of data) {
const tr = document.createElement("tr");
for(const key of keys){
const td = document.createElement("td");
const content=row[key] ||''
td.appendChild(document.createTextNode(content));
tr.appendChild(td);
delete row[key]
}
/****
you can omit next cycle if all object have the same structor or if the first element of collection have all fields
****/
for(const key in row){
const th=document.createElement("th");
th.appendChild(document.createTextNode(key))
keys.push(key)
header.appendChild(th);
const td = document.createElement("td");
const content=row[key] ||''
td.appendChild(document.createTextNode(content));
tr.appendChild(td);
}
table.appendChild(tr);
}
return table
```
} |
17,684,201 | I am a beginner of JavaScript and want to display an array of objects in HTML.
The format of the data is like this:
```
[
{"key":"apple","value":1.90},
{"key":"berry","value":1.7},
{"key":"banana","value":1.5},
{"key":"cherry","value":1.2}
]
```
I want to use a list with three columns (id, name, relevance) to display them. And the id can increase from 1 automatically.
Could anyone tell me how to write a javascript code to display it?
Please give me some materials or examples to learn. | 2013/07/16 | [
"https://Stackoverflow.com/questions/17684201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2557815/"
]
| Array.map() combined with template literals comes in really handy for rendering HTML markup within Javascript for large objects in a scalable manner:
```
function tableMarkupFromObjectArray(obj) {
let headers = `
<th>Index</th>
${Object.keys(obj[0]).map((col) =>`
<th>${col}</th>`
).join('')}`
let content = obj.map((row, idx) => `
<tr>
<td>${idx}</td>
${Object.values(row).map((datum) => `
<td>${datum}</td>`
).join('')}
</tr>
`).join('')
let tablemarkup = `
<table>
${headers}
${content}
</table>
`
return tablemarkup
}
let myobj =[
{ "name": "apple", "rel": 1.90 },
{ "name": "berry", "rel": 1.7 },
{ "name": "banana", "rel": 1.5 },
{ "name": "cherry", "rel": 1.2 }
]
document.querySelector("#mydiv").innerHTML = tableMarkupFromObjectArray(myobj)
```
<http://jsfiddle.net/4L7c5vad/> | Maybe like this:
```
function obj2htmltable(obj) {
var html = '<table>';
for (var key in obj) {
var value = obj[key].toString();
html += '<tr><td>' + key + '</td><td>' + value + '</tr>';
}
html += '</table>';
return html;
}
```
If case of nested structure (objects inside object) obj2htmltable() could call itself recursively:
```
function obj2htmltable(obj) {
var html = '<table>';
for (var key in obj) {
var item = obj[key];
var value = (typeof(item) === 'object') ? obj2htmltable(item) : item.toString();
html += '<tr><td>' + key + '</td><td>' + value + '</tr>';
}
html += '</table>';
return html;
}
``` |
17,684,201 | I am a beginner of JavaScript and want to display an array of objects in HTML.
The format of the data is like this:
```
[
{"key":"apple","value":1.90},
{"key":"berry","value":1.7},
{"key":"banana","value":1.5},
{"key":"cherry","value":1.2}
]
```
I want to use a list with three columns (id, name, relevance) to display them. And the id can increase from 1 automatically.
Could anyone tell me how to write a javascript code to display it?
Please give me some materials or examples to learn. | 2013/07/16 | [
"https://Stackoverflow.com/questions/17684201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2557815/"
]
| It can be simply done by a small & smart process:
```
<table cellpadding="2" cellspacing="2" border="0" bgcolor="#dfdfdf" width="40%" align="center">
<thead>
<tr>
<th>Name</th>
<th width="20%">Age</th>
<th width="12%">Status</th>
</tr>
</thead>
<tbody id="tableData"></tbody>
</table>
<script type="text/javascript">
var mainObj = [
{
name: "Kapil",
age: 21,
status: "Active"
},
{
name: "John",
age: 28,
status: "Inactive"
},
{
name: "Deos",
age: 18,
status: "Active"
}
];
var k = '<tbody>'
for(i = 0;i < mainObj.length; i++){
k+= '<tr>';
k+= '<td>' + mainObj[i].name + '</td>';
k+= '<td>' + mainObj[i].age + '</td>';
k+= '<td>' + mainObj[i].status + '</td>';
k+= '</tr>';
}
k+='</tbody>';
document.getElementById('tableData').innerHTML = k;
</script>
``` | Maybe like this:
```
function obj2htmltable(obj) {
var html = '<table>';
for (var key in obj) {
var value = obj[key].toString();
html += '<tr><td>' + key + '</td><td>' + value + '</tr>';
}
html += '</table>';
return html;
}
```
If case of nested structure (objects inside object) obj2htmltable() could call itself recursively:
```
function obj2htmltable(obj) {
var html = '<table>';
for (var key in obj) {
var item = obj[key];
var value = (typeof(item) === 'object') ? obj2htmltable(item) : item.toString();
html += '<tr><td>' + key + '</td><td>' + value + '</tr>';
}
html += '</table>';
return html;
}
``` |
17,684,201 | I am a beginner of JavaScript and want to display an array of objects in HTML.
The format of the data is like this:
```
[
{"key":"apple","value":1.90},
{"key":"berry","value":1.7},
{"key":"banana","value":1.5},
{"key":"cherry","value":1.2}
]
```
I want to use a list with three columns (id, name, relevance) to display them. And the id can increase from 1 automatically.
Could anyone tell me how to write a javascript code to display it?
Please give me some materials or examples to learn. | 2013/07/16 | [
"https://Stackoverflow.com/questions/17684201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2557815/"
]
| It can be simply done by a small & smart process:
```
<table cellpadding="2" cellspacing="2" border="0" bgcolor="#dfdfdf" width="40%" align="center">
<thead>
<tr>
<th>Name</th>
<th width="20%">Age</th>
<th width="12%">Status</th>
</tr>
</thead>
<tbody id="tableData"></tbody>
</table>
<script type="text/javascript">
var mainObj = [
{
name: "Kapil",
age: 21,
status: "Active"
},
{
name: "John",
age: 28,
status: "Inactive"
},
{
name: "Deos",
age: 18,
status: "Active"
}
];
var k = '<tbody>'
for(i = 0;i < mainObj.length; i++){
k+= '<tr>';
k+= '<td>' + mainObj[i].name + '</td>';
k+= '<td>' + mainObj[i].age + '</td>';
k+= '<td>' + mainObj[i].status + '</td>';
k+= '</tr>';
}
k+='</tbody>';
document.getElementById('tableData').innerHTML = k;
</script>
``` | I am not totally sure what you are asking for. The title of you post seems like you are looking for JSON.stringfy like mentioned in the previous answer but apparently you are not.
Are you trying to create and HTML list, ? Can you please try to explain your need again? I doubt what you are trying to do is complicated and I sure we can help you if you give a little more detail and purpose of what you are trying to do.
I am going to guess that you are trying to display HMTL by looping over you JSON object. Try this pure JavaScript example:
```
var fruits = JSON.parse('[{"key":"apple","value":1.90}, {"key":"berry","value":1.7}, {"key":"banana","value":1.5}, {"key":"cherry","value":1.2} ]');
var tbl = document.createElement('table');
var thead = document.createElement("thead");
var tbody = document.createElement("tbody")
var tr_head = document.createElement("tr");
var th_id = document.createElement("th");
var th_name = document.createElement("th");
var th_price = document.createElement("th");
th_id.textContent = "Id";
th_name.textContent = "Name";
th_price.textContent = "Price";
tr_head.appendChild(th_id);
tr_head.appendChild(th_name);
tr_head.appendChild(th_price);
thead.appendChild(tr_head);
for(var i = 0, j = fruits.length; i < j; i++) {
var tr_body = document.createElement("tr");
var td_id = document.createElement("td");
var td_name = document.createElement("td");
var td_value = document.createElement("td");
td_id.textContent = i;
td_name.textContent = fruits[i].key;
td_value.textContent = fruits[i].value;
tr_body.appendChild(td_id);
tr_body.appendChild(td_name);
tr_body.appendChild(td_value);
tbody.appendChild(tr_body);
}
tbl.appendChild(thead);
tbl.appendChild(tbody);
console.log(tbl);
``` |
17,684,201 | I am a beginner of JavaScript and want to display an array of objects in HTML.
The format of the data is like this:
```
[
{"key":"apple","value":1.90},
{"key":"berry","value":1.7},
{"key":"banana","value":1.5},
{"key":"cherry","value":1.2}
]
```
I want to use a list with three columns (id, name, relevance) to display them. And the id can increase from 1 automatically.
Could anyone tell me how to write a javascript code to display it?
Please give me some materials or examples to learn. | 2013/07/16 | [
"https://Stackoverflow.com/questions/17684201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2557815/"
]
| Explanation
-----------
What you want is to fill a table (or another DOMElement) in HTML, with your JavaScript, which is executed dynamically once the page is loaded and your JSON object is received.
You want to loop through the object. The best way to do so would be with a `for` loop, and making sure our *looping variable* remains valid for the length of our object (all its attributes).
The best way to get the length of a JSON object is through `myJSONObject.length`: You select the keys of **myJSONObject** and return their count.
You can access the values stored in your JSON Object the following way, in your `for` loop (assuming the looping variable defined is named `i`): `myJSONObject[i].theAttributeIWantToGet`
---
Price formatting breakdown
--------------------------
Now, those prices need to have a proper format, don't they? So we'll check if any of the `value` attribute has **less than 2** characters after the `.` within them. If they do, we add another decimal `0`. We also add a `$` before writing the formatted value. Here is a breakdown of how it works:
* `obj[i].value.toString().substring(startIndex, length)`
+ We want to check the length after the `.` sign, so our startIndex will be the position of this dot within our string.
+ `obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'),length)`
+ We now need to set the length. We want to find the length of all what's after the dot, so we'll take the length of the whole string just to be safe.
+ Final result: `obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2`
- This will return true or false. If it's true: There's less than 2 digits after the dot !
+ We add the `if` statement and the last zero:
+ `if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2)
obj[i].value += "0";`
---
**Also:** [Why I use `innerHTML` instead of `appendChild()`](http://jsperf.com/html-innerhtml-vs-appendchild).
---
Solution
========
[JSFiddle](http://jsfiddle.net/mjE7R/)
--------------------------------------
HTML
----
```html
<table>
<tbody id="tbody"></tbody>
</table>
```
JSON
----
```json
[{
"key": "apple",
"value": 1.90
}, {
"key": "berry",
"value": 1.7
}, {
"key": "banana",
"value": 1.5
}, {
"key": "cherry",
"value": 1.2
}]
```
JavaScript
----------
**Note:** The JSON object will be named `obj` in this instance.
```js
var tbody = document.getElementById('tbody');
for (var i = 0; i < obj.length; i++) {
var tr = "<tr>";
/* Verification to add the last decimal 0 */
if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2)
obj[i].value += "0";
/* Must not forget the $ sign */
tr += "<td>" + obj[i].key + "</td>" + "<td>$" + obj[i].value.toString() + "</td></tr>";
/* We add the table row to the table body */
tbody.innerHTML += tr;
}
```
[JSFiddle](http://jsfiddle.net/mjE7R/)
-------------------------------------- | You can do something like this:
```
var table = document.createElement("table");
//Add a header
var header = document.createElement("tr");
var idHeaderCell = document.createElement("th");
var nameHeaderCell = document.createElement("th");
var relevanceHeaderCell = document.createElement("th");
header.appendChild(idHeaderCell);
header.appendChild(nameHeaderCell);
header.appendChild(relevanceHeaderCell);
table.appendChild(header);
//Add the rest of the data to the table
for(var i = 0; i < data.length; i++) {
var id = (i + 1);
var name = data[i].key;
var relevance = data[i].value;
var tr = document.createElement("tr");
var idCell = document.createElement("td");
var nameCell = document.createElement("td");
var relevanceCell = document.createElement("td");
idCell.appendChild(document.createTextNode(id));
nameCell.appendChild(document.createTextNode(name));
relevanceCell.appendChild(document.createTextNode(relevance));
tr.appendChild(idCell);
tr.appendChild(nameCell);
tr.appendChild(relevanceCell);
table.appendChild(tr);
}
``` |
17,684,201 | I am a beginner of JavaScript and want to display an array of objects in HTML.
The format of the data is like this:
```
[
{"key":"apple","value":1.90},
{"key":"berry","value":1.7},
{"key":"banana","value":1.5},
{"key":"cherry","value":1.2}
]
```
I want to use a list with three columns (id, name, relevance) to display them. And the id can increase from 1 automatically.
Could anyone tell me how to write a javascript code to display it?
Please give me some materials or examples to learn. | 2013/07/16 | [
"https://Stackoverflow.com/questions/17684201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2557815/"
]
| It can be simply done by a small & smart process:
```
<table cellpadding="2" cellspacing="2" border="0" bgcolor="#dfdfdf" width="40%" align="center">
<thead>
<tr>
<th>Name</th>
<th width="20%">Age</th>
<th width="12%">Status</th>
</tr>
</thead>
<tbody id="tableData"></tbody>
</table>
<script type="text/javascript">
var mainObj = [
{
name: "Kapil",
age: 21,
status: "Active"
},
{
name: "John",
age: 28,
status: "Inactive"
},
{
name: "Deos",
age: 18,
status: "Active"
}
];
var k = '<tbody>'
for(i = 0;i < mainObj.length; i++){
k+= '<tr>';
k+= '<td>' + mainObj[i].name + '</td>';
k+= '<td>' + mainObj[i].age + '</td>';
k+= '<td>' + mainObj[i].status + '</td>';
k+= '</tr>';
}
k+='</tbody>';
document.getElementById('tableData').innerHTML = k;
</script>
``` | Here is my ES6 solution.
I have used the `reduce` operation to construct a `Set` storing the keys from all objects in the array:
```
function arrayToTable(data) {
const keys = [...data.reduce((all, obj)=>{
Object.keys(obj).forEach(key => all.add(key));
return all;
}, new Set())];
const header = keys.map(key => `<th>${key}</th>`).join('')
const tbody = data.map(row => keys.map(key => `<td>${row[key]}</td>`).join('')).map(row => `<tr>${row}</tr>`)
return `<table>
<thead><tr>${header}</tr></thead>
<tbody>${tbody}</body>
</table>`;
}
``` |
70,114,905 | I currently have a JSON string I am deserializing with `serde_json`.
```
{
"foo": "<val>" // val can contain "SI" or "NO"
}
```
I would like to deserialize this to a bool using `serde` and a custom lookup that turns "SI" -> true and vice-versa.
```
#[derive(Deserialize)]
pub struct Entry {
pub foo: bool, // How to express string to bool deserialization ?
}
```
How can I do that simply ? | 2021/11/25 | [
"https://Stackoverflow.com/questions/70114905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4218017/"
]
| You could use `deserialize_with` like so:
```rust
#[derive(Deserialize)]
pub struct Entry {
#[serde(deserialize_with = "deserialize_bool")]
pub foo: bool,
}
fn deserialize_bool<'de, D>(deserializer: D) -> Result<bool, D::Error>
where
D: de::Deserializer<'de>,
{
let s: &str = de::Deserialize::deserialize(deserializer)?;
match s {
"SI" => Ok(true),
"NO" => Ok(false),
_ => Err(de::Error::unknown_variant(s, &["SI", "NO"])),
}
}
```
See: <https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=0ac9e89f97afc893197d37bc55dba188> | I would use a custom deserializer with ability to convert from different concrete types.
```rust
use serde::{de, Deserialize, Deserializer};
use serde_json::Value;
#[derive(Deserialize)]
pub struct Entry {
#[serde(deserialize_with = "boolean")]
pub foo: bool,
}
fn boolean<'de, D: Deserializer<'de>>(deserializer: D) -> Result<bool, D::Error> {
Ok(match Value::deserialize(deserializer)? {
Value::Bool(b) => b,
Value::String(s) => s == "yes",
Value::Number(num) => num.as_i64().ok_or(de::Error::custom("Invalid number"))? != 0,
Value::Null => false,
_ => return Err(de::Error::custom("Wrong type, expected boolean")),
})
}
``` |
20,735,389 | My JLabel and JTextField are not appearing overtop the image and I'm not sure why. I've put the image on a JLabel and setOpaque(false) but no luck. Any advice? Thanks for the help in advance.
```
private JTextField tf;
private JLabel jl2;
private JLabel jl3;
public void window() {
ImageIcon ic = new ImageIcon("hangman.png");
JFrame gameFrame = new JFrame();
JPanel jp = new JPanel();
jp.setOpaque(false); //!!
jp.setBorder(BorderFactory.createTitledBorder(""));
JLabel img = new JLabel(ic, JLabel.CENTER);
img.setOpaque(false);
JLabel jl = new JLabel("Enter a Letter:");
jl.setFont(new Font("Rockwell", Font.PLAIN, 20));
tf = new JTextField(1);
jl2 = new JLabel("Letters Used: ");
jl3 = new JLabel();//blank spaces
tf.setFont(new Font("Rockwell", Font.PLAIN, 20));
jl2.setFont(new Font("Rockwell", Font.PLAIN, 20));
jp.add(jl);
jp.add(tf);
jp.add(jl2);
jp.add(jl3);
gameFrame.add(img);
img.add(jp);
gameFrame.setTitle("Hangman");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setIconImage(
new ImageIcon("Hangman-Game-grey.png").getImage());
gameFrame.setResizable(false);
gameFrame.pack();
gameFrame.setLocationRelativeTo(null);
gameFrame.setVisible(true);
``` | 2013/12/22 | [
"https://Stackoverflow.com/questions/20735389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3123422/"
]
| It's slightly annoying when you're just trying to build something quickly, but in the long run it forces good code organization practice (by making it harder to shove all business logic into a controller). | You can do something like this:
```
//ArticleController
module.exports = {
findStore: async () => {
return await findStoreFunc(req.param('id'));
},
index: async () => {
...
return await findStoreFunc(id);
}
};
const findStoreFunc = async (id) => {...}
```
And to use the function from another controller:
```
const ArticleController = require('./ArticleController');
//CustomerController
module.exports = {
index: async () => {
...
let article = await ArticleController.findStore(id);
...
}
};
``` |
20,735,389 | My JLabel and JTextField are not appearing overtop the image and I'm not sure why. I've put the image on a JLabel and setOpaque(false) but no luck. Any advice? Thanks for the help in advance.
```
private JTextField tf;
private JLabel jl2;
private JLabel jl3;
public void window() {
ImageIcon ic = new ImageIcon("hangman.png");
JFrame gameFrame = new JFrame();
JPanel jp = new JPanel();
jp.setOpaque(false); //!!
jp.setBorder(BorderFactory.createTitledBorder(""));
JLabel img = new JLabel(ic, JLabel.CENTER);
img.setOpaque(false);
JLabel jl = new JLabel("Enter a Letter:");
jl.setFont(new Font("Rockwell", Font.PLAIN, 20));
tf = new JTextField(1);
jl2 = new JLabel("Letters Used: ");
jl3 = new JLabel();//blank spaces
tf.setFont(new Font("Rockwell", Font.PLAIN, 20));
jl2.setFont(new Font("Rockwell", Font.PLAIN, 20));
jp.add(jl);
jp.add(tf);
jp.add(jl2);
jp.add(jl3);
gameFrame.add(img);
img.add(jp);
gameFrame.setTitle("Hangman");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setIconImage(
new ImageIcon("Hangman-Game-grey.png").getImage());
gameFrame.setResizable(false);
gameFrame.pack();
gameFrame.setLocationRelativeTo(null);
gameFrame.setVisible(true);
``` | 2013/12/22 | [
"https://Stackoverflow.com/questions/20735389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3123422/"
]
| You can use `sails.controllers.yourControllerName.findStore()`
the `sails` global object has references to almost everything. | I would like to suggest a solution that works but not the best possible way to do it. We can use bind function to bind the context with the calling source as shown below :
generateUrl is present in the Controller A
```
function generateUrl(){
return 'www.google.com';
}
```
get URL is another method in Controller A
```
getURL(){
A.generateURL.bind(A.generateURL) //func call with optional arg
}
```
I hope this helps! |
20,735,389 | My JLabel and JTextField are not appearing overtop the image and I'm not sure why. I've put the image on a JLabel and setOpaque(false) but no luck. Any advice? Thanks for the help in advance.
```
private JTextField tf;
private JLabel jl2;
private JLabel jl3;
public void window() {
ImageIcon ic = new ImageIcon("hangman.png");
JFrame gameFrame = new JFrame();
JPanel jp = new JPanel();
jp.setOpaque(false); //!!
jp.setBorder(BorderFactory.createTitledBorder(""));
JLabel img = new JLabel(ic, JLabel.CENTER);
img.setOpaque(false);
JLabel jl = new JLabel("Enter a Letter:");
jl.setFont(new Font("Rockwell", Font.PLAIN, 20));
tf = new JTextField(1);
jl2 = new JLabel("Letters Used: ");
jl3 = new JLabel();//blank spaces
tf.setFont(new Font("Rockwell", Font.PLAIN, 20));
jl2.setFont(new Font("Rockwell", Font.PLAIN, 20));
jp.add(jl);
jp.add(tf);
jp.add(jl2);
jp.add(jl3);
gameFrame.add(img);
img.add(jp);
gameFrame.setTitle("Hangman");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setIconImage(
new ImageIcon("Hangman-Game-grey.png").getImage());
gameFrame.setResizable(false);
gameFrame.pack();
gameFrame.setLocationRelativeTo(null);
gameFrame.setVisible(true);
``` | 2013/12/22 | [
"https://Stackoverflow.com/questions/20735389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3123422/"
]
| You can use `sails.controllers.yourControllerName.findStore()`
the `sails` global object has references to almost everything. | One of the best ways to organize your code in Sails, at least for me and my team, has been to have all the real business logic in Services (/api/services). Those objects can be accessed globally from any controller.
Also, a good practice is working with promises in services (as Sails use them on the model methods)
Just create a Store service (StoreService.js), with your code:
```
module.exports = {
findStore: function(storeId) {
// here you call your models, add object security validation, etc...
return Store.findOne(storeId);
}
};
```
Your Controllers should handle all that is related to requests, calling services, and returning apropriate responses.
For example, in you example, the controller could have this:
```
module.exports = {
index: function(req, res) {
if(req.param('id')) {
StoreService.findStore(req.param('id'))
.then(res.ok)
.catch(res.serverError);
} else {
res.badRequest('Missing Store id');
}
},
findStore: function(req, res) {
if(req.param('id')) {
StoreService.findStore(req.param('id'))
.then(res.ok)
.catch(res.serverError);
} else {
res.badRequest('Missing Store id');
}
},
};
```
That way, you have really simple controllers, and all business logic is managed by services. |
20,735,389 | My JLabel and JTextField are not appearing overtop the image and I'm not sure why. I've put the image on a JLabel and setOpaque(false) but no luck. Any advice? Thanks for the help in advance.
```
private JTextField tf;
private JLabel jl2;
private JLabel jl3;
public void window() {
ImageIcon ic = new ImageIcon("hangman.png");
JFrame gameFrame = new JFrame();
JPanel jp = new JPanel();
jp.setOpaque(false); //!!
jp.setBorder(BorderFactory.createTitledBorder(""));
JLabel img = new JLabel(ic, JLabel.CENTER);
img.setOpaque(false);
JLabel jl = new JLabel("Enter a Letter:");
jl.setFont(new Font("Rockwell", Font.PLAIN, 20));
tf = new JTextField(1);
jl2 = new JLabel("Letters Used: ");
jl3 = new JLabel();//blank spaces
tf.setFont(new Font("Rockwell", Font.PLAIN, 20));
jl2.setFont(new Font("Rockwell", Font.PLAIN, 20));
jp.add(jl);
jp.add(tf);
jp.add(jl2);
jp.add(jl3);
gameFrame.add(img);
img.add(jp);
gameFrame.setTitle("Hangman");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setIconImage(
new ImageIcon("Hangman-Game-grey.png").getImage());
gameFrame.setResizable(false);
gameFrame.pack();
gameFrame.setLocationRelativeTo(null);
gameFrame.setVisible(true);
``` | 2013/12/22 | [
"https://Stackoverflow.com/questions/20735389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3123422/"
]
| You can use `sails.controllers.yourControllerName.findStore()`
the `sails` global object has references to almost everything. | Having the same problem for last few hours. I used the api/services folder.
It may not be exactly what you need but it is an option.
A good explanation is here. [What services would one add to the api/services folder in sails.js](https://stackoverflow.com/questions/18447434/what-services-would-one-add-to-the-api-services-folder-in-sailsjs) |
20,735,389 | My JLabel and JTextField are not appearing overtop the image and I'm not sure why. I've put the image on a JLabel and setOpaque(false) but no luck. Any advice? Thanks for the help in advance.
```
private JTextField tf;
private JLabel jl2;
private JLabel jl3;
public void window() {
ImageIcon ic = new ImageIcon("hangman.png");
JFrame gameFrame = new JFrame();
JPanel jp = new JPanel();
jp.setOpaque(false); //!!
jp.setBorder(BorderFactory.createTitledBorder(""));
JLabel img = new JLabel(ic, JLabel.CENTER);
img.setOpaque(false);
JLabel jl = new JLabel("Enter a Letter:");
jl.setFont(new Font("Rockwell", Font.PLAIN, 20));
tf = new JTextField(1);
jl2 = new JLabel("Letters Used: ");
jl3 = new JLabel();//blank spaces
tf.setFont(new Font("Rockwell", Font.PLAIN, 20));
jl2.setFont(new Font("Rockwell", Font.PLAIN, 20));
jp.add(jl);
jp.add(tf);
jp.add(jl2);
jp.add(jl3);
gameFrame.add(img);
img.add(jp);
gameFrame.setTitle("Hangman");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setIconImage(
new ImageIcon("Hangman-Game-grey.png").getImage());
gameFrame.setResizable(false);
gameFrame.pack();
gameFrame.setLocationRelativeTo(null);
gameFrame.setVisible(true);
``` | 2013/12/22 | [
"https://Stackoverflow.com/questions/20735389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3123422/"
]
| Having the same problem for last few hours. I used the api/services folder.
It may not be exactly what you need but it is an option.
A good explanation is here. [What services would one add to the api/services folder in sails.js](https://stackoverflow.com/questions/18447434/what-services-would-one-add-to-the-api-services-folder-in-sailsjs) | A more elegant way to solve this problem is using the keyword `this` before the function name.
Example:
```
one: function() {
console.log('First Function');
},
two: function() {
// call the function one in the same controller
this.one();
}
``` |
20,735,389 | My JLabel and JTextField are not appearing overtop the image and I'm not sure why. I've put the image on a JLabel and setOpaque(false) but no luck. Any advice? Thanks for the help in advance.
```
private JTextField tf;
private JLabel jl2;
private JLabel jl3;
public void window() {
ImageIcon ic = new ImageIcon("hangman.png");
JFrame gameFrame = new JFrame();
JPanel jp = new JPanel();
jp.setOpaque(false); //!!
jp.setBorder(BorderFactory.createTitledBorder(""));
JLabel img = new JLabel(ic, JLabel.CENTER);
img.setOpaque(false);
JLabel jl = new JLabel("Enter a Letter:");
jl.setFont(new Font("Rockwell", Font.PLAIN, 20));
tf = new JTextField(1);
jl2 = new JLabel("Letters Used: ");
jl3 = new JLabel();//blank spaces
tf.setFont(new Font("Rockwell", Font.PLAIN, 20));
jl2.setFont(new Font("Rockwell", Font.PLAIN, 20));
jp.add(jl);
jp.add(tf);
jp.add(jl2);
jp.add(jl3);
gameFrame.add(img);
img.add(jp);
gameFrame.setTitle("Hangman");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setIconImage(
new ImageIcon("Hangman-Game-grey.png").getImage());
gameFrame.setResizable(false);
gameFrame.pack();
gameFrame.setLocationRelativeTo(null);
gameFrame.setVisible(true);
``` | 2013/12/22 | [
"https://Stackoverflow.com/questions/20735389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3123422/"
]
| I would like to suggest a solution that works but not the best possible way to do it. We can use bind function to bind the context with the calling source as shown below :
generateUrl is present in the Controller A
```
function generateUrl(){
return 'www.google.com';
}
```
get URL is another method in Controller A
```
getURL(){
A.generateURL.bind(A.generateURL) //func call with optional arg
}
```
I hope this helps! | A more elegant way to solve this problem is using the keyword `this` before the function name.
Example:
```
one: function() {
console.log('First Function');
},
two: function() {
// call the function one in the same controller
this.one();
}
``` |
20,735,389 | My JLabel and JTextField are not appearing overtop the image and I'm not sure why. I've put the image on a JLabel and setOpaque(false) but no luck. Any advice? Thanks for the help in advance.
```
private JTextField tf;
private JLabel jl2;
private JLabel jl3;
public void window() {
ImageIcon ic = new ImageIcon("hangman.png");
JFrame gameFrame = new JFrame();
JPanel jp = new JPanel();
jp.setOpaque(false); //!!
jp.setBorder(BorderFactory.createTitledBorder(""));
JLabel img = new JLabel(ic, JLabel.CENTER);
img.setOpaque(false);
JLabel jl = new JLabel("Enter a Letter:");
jl.setFont(new Font("Rockwell", Font.PLAIN, 20));
tf = new JTextField(1);
jl2 = new JLabel("Letters Used: ");
jl3 = new JLabel();//blank spaces
tf.setFont(new Font("Rockwell", Font.PLAIN, 20));
jl2.setFont(new Font("Rockwell", Font.PLAIN, 20));
jp.add(jl);
jp.add(tf);
jp.add(jl2);
jp.add(jl3);
gameFrame.add(img);
img.add(jp);
gameFrame.setTitle("Hangman");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setIconImage(
new ImageIcon("Hangman-Game-grey.png").getImage());
gameFrame.setResizable(false);
gameFrame.pack();
gameFrame.setLocationRelativeTo(null);
gameFrame.setVisible(true);
``` | 2013/12/22 | [
"https://Stackoverflow.com/questions/20735389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3123422/"
]
| You can use `sails.controllers.yourControllerName.findStore()`
the `sails` global object has references to almost everything. | You can do something like this:
```
//ArticleController
module.exports = {
findStore: async () => {
return await findStoreFunc(req.param('id'));
},
index: async () => {
...
return await findStoreFunc(id);
}
};
const findStoreFunc = async (id) => {...}
```
And to use the function from another controller:
```
const ArticleController = require('./ArticleController');
//CustomerController
module.exports = {
index: async () => {
...
let article = await ArticleController.findStore(id);
...
}
};
``` |
20,735,389 | My JLabel and JTextField are not appearing overtop the image and I'm not sure why. I've put the image on a JLabel and setOpaque(false) but no luck. Any advice? Thanks for the help in advance.
```
private JTextField tf;
private JLabel jl2;
private JLabel jl3;
public void window() {
ImageIcon ic = new ImageIcon("hangman.png");
JFrame gameFrame = new JFrame();
JPanel jp = new JPanel();
jp.setOpaque(false); //!!
jp.setBorder(BorderFactory.createTitledBorder(""));
JLabel img = new JLabel(ic, JLabel.CENTER);
img.setOpaque(false);
JLabel jl = new JLabel("Enter a Letter:");
jl.setFont(new Font("Rockwell", Font.PLAIN, 20));
tf = new JTextField(1);
jl2 = new JLabel("Letters Used: ");
jl3 = new JLabel();//blank spaces
tf.setFont(new Font("Rockwell", Font.PLAIN, 20));
jl2.setFont(new Font("Rockwell", Font.PLAIN, 20));
jp.add(jl);
jp.add(tf);
jp.add(jl2);
jp.add(jl3);
gameFrame.add(img);
img.add(jp);
gameFrame.setTitle("Hangman");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setIconImage(
new ImageIcon("Hangman-Game-grey.png").getImage());
gameFrame.setResizable(false);
gameFrame.pack();
gameFrame.setLocationRelativeTo(null);
gameFrame.setVisible(true);
``` | 2013/12/22 | [
"https://Stackoverflow.com/questions/20735389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3123422/"
]
| I would like to suggest a solution that works but not the best possible way to do it. We can use bind function to bind the context with the calling source as shown below :
generateUrl is present in the Controller A
```
function generateUrl(){
return 'www.google.com';
}
```
get URL is another method in Controller A
```
getURL(){
A.generateURL.bind(A.generateURL) //func call with optional arg
}
```
I hope this helps! | You can do something like this:
```
//ArticleController
module.exports = {
findStore: async () => {
return await findStoreFunc(req.param('id'));
},
index: async () => {
...
return await findStoreFunc(id);
}
};
const findStoreFunc = async (id) => {...}
```
And to use the function from another controller:
```
const ArticleController = require('./ArticleController');
//CustomerController
module.exports = {
index: async () => {
...
let article = await ArticleController.findStore(id);
...
}
};
``` |
20,735,389 | My JLabel and JTextField are not appearing overtop the image and I'm not sure why. I've put the image on a JLabel and setOpaque(false) but no luck. Any advice? Thanks for the help in advance.
```
private JTextField tf;
private JLabel jl2;
private JLabel jl3;
public void window() {
ImageIcon ic = new ImageIcon("hangman.png");
JFrame gameFrame = new JFrame();
JPanel jp = new JPanel();
jp.setOpaque(false); //!!
jp.setBorder(BorderFactory.createTitledBorder(""));
JLabel img = new JLabel(ic, JLabel.CENTER);
img.setOpaque(false);
JLabel jl = new JLabel("Enter a Letter:");
jl.setFont(new Font("Rockwell", Font.PLAIN, 20));
tf = new JTextField(1);
jl2 = new JLabel("Letters Used: ");
jl3 = new JLabel();//blank spaces
tf.setFont(new Font("Rockwell", Font.PLAIN, 20));
jl2.setFont(new Font("Rockwell", Font.PLAIN, 20));
jp.add(jl);
jp.add(tf);
jp.add(jl2);
jp.add(jl3);
gameFrame.add(img);
img.add(jp);
gameFrame.setTitle("Hangman");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setIconImage(
new ImageIcon("Hangman-Game-grey.png").getImage());
gameFrame.setResizable(false);
gameFrame.pack();
gameFrame.setLocationRelativeTo(null);
gameFrame.setVisible(true);
``` | 2013/12/22 | [
"https://Stackoverflow.com/questions/20735389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3123422/"
]
| It's slightly annoying when you're just trying to build something quickly, but in the long run it forces good code organization practice (by making it harder to shove all business logic into a controller). | I would like to suggest a solution that works but not the best possible way to do it. We can use bind function to bind the context with the calling source as shown below :
generateUrl is present in the Controller A
```
function generateUrl(){
return 'www.google.com';
}
```
get URL is another method in Controller A
```
getURL(){
A.generateURL.bind(A.generateURL) //func call with optional arg
}
```
I hope this helps! |
20,735,389 | My JLabel and JTextField are not appearing overtop the image and I'm not sure why. I've put the image on a JLabel and setOpaque(false) but no luck. Any advice? Thanks for the help in advance.
```
private JTextField tf;
private JLabel jl2;
private JLabel jl3;
public void window() {
ImageIcon ic = new ImageIcon("hangman.png");
JFrame gameFrame = new JFrame();
JPanel jp = new JPanel();
jp.setOpaque(false); //!!
jp.setBorder(BorderFactory.createTitledBorder(""));
JLabel img = new JLabel(ic, JLabel.CENTER);
img.setOpaque(false);
JLabel jl = new JLabel("Enter a Letter:");
jl.setFont(new Font("Rockwell", Font.PLAIN, 20));
tf = new JTextField(1);
jl2 = new JLabel("Letters Used: ");
jl3 = new JLabel();//blank spaces
tf.setFont(new Font("Rockwell", Font.PLAIN, 20));
jl2.setFont(new Font("Rockwell", Font.PLAIN, 20));
jp.add(jl);
jp.add(tf);
jp.add(jl2);
jp.add(jl3);
gameFrame.add(img);
img.add(jp);
gameFrame.setTitle("Hangman");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setIconImage(
new ImageIcon("Hangman-Game-grey.png").getImage());
gameFrame.setResizable(false);
gameFrame.pack();
gameFrame.setLocationRelativeTo(null);
gameFrame.setVisible(true);
``` | 2013/12/22 | [
"https://Stackoverflow.com/questions/20735389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3123422/"
]
| Having the same problem for last few hours. I used the api/services folder.
It may not be exactly what you need but it is an option.
A good explanation is here. [What services would one add to the api/services folder in sails.js](https://stackoverflow.com/questions/18447434/what-services-would-one-add-to-the-api-services-folder-in-sailsjs) | I would like to suggest a solution that works but not the best possible way to do it. We can use bind function to bind the context with the calling source as shown below :
generateUrl is present in the Controller A
```
function generateUrl(){
return 'www.google.com';
}
```
get URL is another method in Controller A
```
getURL(){
A.generateURL.bind(A.generateURL) //func call with optional arg
}
```
I hope this helps! |
22,536,630 | I'm having the following table layout: four different tables, each containing around 10 to 15 million entries. Three string attributes of each table are the same (let's call them Id, Name1, Name2). Now we want to read all entries having the same Id column but different (Name1,Name2) tuples. It is estimated that less than 0.5 % of all entries are matching.
We've created a view AllEntries (basically a UNION ALL of the relevant attributes over all four tables) and our query looks like this:
```
SELECT *
FROM AllEntries
GROUP BY Id
HAVING COUNT(DISTINCT(Name1)) > 1 OR COUNT(DISTINCT(Name2)) > 1
```
Executing the query in our test database with 2 million entries in each table (i.e. 8 million entries in the view) already takes around 2 to 3 minutes (nice server).
**Q:** Is there any performance improvement possible to improve the performance? | 2014/03/20 | [
"https://Stackoverflow.com/questions/22536630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1400869/"
]
| `count(distinct)` is more resource intensive than other aggregation functions. You could try:
```
SELECT *
FROM AllEntries
GROUP BY Id
HAVING min(Name1) <> max(Name1) or min(Name2) <> max(Name2);
```
If you build indexes on `id, Name1` and `id, Name2` in each of the subtables, the following should show a significant performance improvement:
```
select ae.*
from AllEntries ae
where exists (select 1 from subtable1 ae2 where ae.id = ae2.id and ae.Name1 <> ae2.Name1) or
exists (select 1 from subtable2 ae2 where ae.id = ae2.id and ae.Name1 <> ae2.Name1) or
. . .
```
These are split into subqueries to encourage the optimizer to use a different index on each one. | This will largely depend on your indices, but the last statement with the OR condition is certainly not ideal for a table of this size. Also, I'm not sure why you need a SELECT \* for this... extra IO. Avoid it if you can.
Try something like this....
```
SELECT id, COUNT(name1)
FROM {table}
GROUP BY id
HAVING COUNT(*) > 1
UNION ALL
SELECT id, COUNT(name2)
FROM {table}
GROUP BY id
HAVING COUNT(*) > 1
UNION ALL
```
etc
This will let you leverage the index on ID and also avoid COUNT DISTINCT, which is a very expensive function as a rule.
If you want to get those specific records, I'd recommend writing a CTE and joining the result of the query above with the data itself.... return all the ids and the names for which count(\*) is higher.
For as few records as you expect to be duplicated in some way, another option is just
```
SELECT id, COUNT(*)
FROM {table}
GROUP BY id
HAVING COUNT(*) > 1
```
and then join that with your datatable using id.... that'd avoid the extra work with the union all stuff, and would show you every record for which ID is duplicated. To me that would be preferable anyway... you probably don't want duplicate ID's :-) |
22,536,630 | I'm having the following table layout: four different tables, each containing around 10 to 15 million entries. Three string attributes of each table are the same (let's call them Id, Name1, Name2). Now we want to read all entries having the same Id column but different (Name1,Name2) tuples. It is estimated that less than 0.5 % of all entries are matching.
We've created a view AllEntries (basically a UNION ALL of the relevant attributes over all four tables) and our query looks like this:
```
SELECT *
FROM AllEntries
GROUP BY Id
HAVING COUNT(DISTINCT(Name1)) > 1 OR COUNT(DISTINCT(Name2)) > 1
```
Executing the query in our test database with 2 million entries in each table (i.e. 8 million entries in the view) already takes around 2 to 3 minutes (nice server).
**Q:** Is there any performance improvement possible to improve the performance? | 2014/03/20 | [
"https://Stackoverflow.com/questions/22536630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1400869/"
]
| Try a CTE with `ROW_NUMBER()` instead of the traditional `GROUP BY/HAVING` approach:
```
;with cteDups as
(
Select *
,ROW_NUMBER() Over(Partition By Name1 Order By Id) rn1
,ROW_NUMBER() Over(Partition By Name2 Order By Id) rn2
From AllEntries
)
Select *
From cteDups
Where rn1 > 1
Or rn2 > 1
``` | `count(distinct)` is more resource intensive than other aggregation functions. You could try:
```
SELECT *
FROM AllEntries
GROUP BY Id
HAVING min(Name1) <> max(Name1) or min(Name2) <> max(Name2);
```
If you build indexes on `id, Name1` and `id, Name2` in each of the subtables, the following should show a significant performance improvement:
```
select ae.*
from AllEntries ae
where exists (select 1 from subtable1 ae2 where ae.id = ae2.id and ae.Name1 <> ae2.Name1) or
exists (select 1 from subtable2 ae2 where ae.id = ae2.id and ae.Name1 <> ae2.Name1) or
. . .
```
These are split into subqueries to encourage the optimizer to use a different index on each one. |
22,536,630 | I'm having the following table layout: four different tables, each containing around 10 to 15 million entries. Three string attributes of each table are the same (let's call them Id, Name1, Name2). Now we want to read all entries having the same Id column but different (Name1,Name2) tuples. It is estimated that less than 0.5 % of all entries are matching.
We've created a view AllEntries (basically a UNION ALL of the relevant attributes over all four tables) and our query looks like this:
```
SELECT *
FROM AllEntries
GROUP BY Id
HAVING COUNT(DISTINCT(Name1)) > 1 OR COUNT(DISTINCT(Name2)) > 1
```
Executing the query in our test database with 2 million entries in each table (i.e. 8 million entries in the view) already takes around 2 to 3 minutes (nice server).
**Q:** Is there any performance improvement possible to improve the performance? | 2014/03/20 | [
"https://Stackoverflow.com/questions/22536630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1400869/"
]
| `count(distinct)` is more resource intensive than other aggregation functions. You could try:
```
SELECT *
FROM AllEntries
GROUP BY Id
HAVING min(Name1) <> max(Name1) or min(Name2) <> max(Name2);
```
If you build indexes on `id, Name1` and `id, Name2` in each of the subtables, the following should show a significant performance improvement:
```
select ae.*
from AllEntries ae
where exists (select 1 from subtable1 ae2 where ae.id = ae2.id and ae.Name1 <> ae2.Name1) or
exists (select 1 from subtable2 ae2 where ae.id = ae2.id and ae.Name1 <> ae2.Name1) or
. . .
```
These are split into subqueries to encourage the optimizer to use a different index on each one. | That UNION is killing it
There is no use of indexes on name1 or name2 after a union
Cannot create an index on a view with UNION
You are going to think this is whacked out but give it a try
It uses indexes and favors a small number of matches
If you don't have indexes on word1 and word2 then do so
```
select distinct ta.ID
from t1 as ta
join t1 as tb
on ta.ID = tb.ID
and ( (ta.word1 <> tb.word1) or (ta.word2 <> tb.word2) )
union
select distinct ta.ID
from t1 as ta
join t2 as tb
on ta.ID = tb.ID
and ( (ta.word1 <> tb.word1) or (ta.word2 <> tb.word2) )
union
t1 t3
union
t1 t4
union
t2 t2
union
t2 t3
union
t2 t4
union
t3 t3
union
t3 t4
union
t4 t4
``` |
22,536,630 | I'm having the following table layout: four different tables, each containing around 10 to 15 million entries. Three string attributes of each table are the same (let's call them Id, Name1, Name2). Now we want to read all entries having the same Id column but different (Name1,Name2) tuples. It is estimated that less than 0.5 % of all entries are matching.
We've created a view AllEntries (basically a UNION ALL of the relevant attributes over all four tables) and our query looks like this:
```
SELECT *
FROM AllEntries
GROUP BY Id
HAVING COUNT(DISTINCT(Name1)) > 1 OR COUNT(DISTINCT(Name2)) > 1
```
Executing the query in our test database with 2 million entries in each table (i.e. 8 million entries in the view) already takes around 2 to 3 minutes (nice server).
**Q:** Is there any performance improvement possible to improve the performance? | 2014/03/20 | [
"https://Stackoverflow.com/questions/22536630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1400869/"
]
| Try a CTE with `ROW_NUMBER()` instead of the traditional `GROUP BY/HAVING` approach:
```
;with cteDups as
(
Select *
,ROW_NUMBER() Over(Partition By Name1 Order By Id) rn1
,ROW_NUMBER() Over(Partition By Name2 Order By Id) rn2
From AllEntries
)
Select *
From cteDups
Where rn1 > 1
Or rn2 > 1
``` | This will largely depend on your indices, but the last statement with the OR condition is certainly not ideal for a table of this size. Also, I'm not sure why you need a SELECT \* for this... extra IO. Avoid it if you can.
Try something like this....
```
SELECT id, COUNT(name1)
FROM {table}
GROUP BY id
HAVING COUNT(*) > 1
UNION ALL
SELECT id, COUNT(name2)
FROM {table}
GROUP BY id
HAVING COUNT(*) > 1
UNION ALL
```
etc
This will let you leverage the index on ID and also avoid COUNT DISTINCT, which is a very expensive function as a rule.
If you want to get those specific records, I'd recommend writing a CTE and joining the result of the query above with the data itself.... return all the ids and the names for which count(\*) is higher.
For as few records as you expect to be duplicated in some way, another option is just
```
SELECT id, COUNT(*)
FROM {table}
GROUP BY id
HAVING COUNT(*) > 1
```
and then join that with your datatable using id.... that'd avoid the extra work with the union all stuff, and would show you every record for which ID is duplicated. To me that would be preferable anyway... you probably don't want duplicate ID's :-) |
22,536,630 | I'm having the following table layout: four different tables, each containing around 10 to 15 million entries. Three string attributes of each table are the same (let's call them Id, Name1, Name2). Now we want to read all entries having the same Id column but different (Name1,Name2) tuples. It is estimated that less than 0.5 % of all entries are matching.
We've created a view AllEntries (basically a UNION ALL of the relevant attributes over all four tables) and our query looks like this:
```
SELECT *
FROM AllEntries
GROUP BY Id
HAVING COUNT(DISTINCT(Name1)) > 1 OR COUNT(DISTINCT(Name2)) > 1
```
Executing the query in our test database with 2 million entries in each table (i.e. 8 million entries in the view) already takes around 2 to 3 minutes (nice server).
**Q:** Is there any performance improvement possible to improve the performance? | 2014/03/20 | [
"https://Stackoverflow.com/questions/22536630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1400869/"
]
| Try a CTE with `ROW_NUMBER()` instead of the traditional `GROUP BY/HAVING` approach:
```
;with cteDups as
(
Select *
,ROW_NUMBER() Over(Partition By Name1 Order By Id) rn1
,ROW_NUMBER() Over(Partition By Name2 Order By Id) rn2
From AllEntries
)
Select *
From cteDups
Where rn1 > 1
Or rn2 > 1
``` | That UNION is killing it
There is no use of indexes on name1 or name2 after a union
Cannot create an index on a view with UNION
You are going to think this is whacked out but give it a try
It uses indexes and favors a small number of matches
If you don't have indexes on word1 and word2 then do so
```
select distinct ta.ID
from t1 as ta
join t1 as tb
on ta.ID = tb.ID
and ( (ta.word1 <> tb.word1) or (ta.word2 <> tb.word2) )
union
select distinct ta.ID
from t1 as ta
join t2 as tb
on ta.ID = tb.ID
and ( (ta.word1 <> tb.word1) or (ta.word2 <> tb.word2) )
union
t1 t3
union
t1 t4
union
t2 t2
union
t2 t3
union
t2 t4
union
t3 t3
union
t3 t4
union
t4 t4
``` |
31,795,169 | I am making an ajax call for a like/dislike on a video and I found out that I need to pass the CSRF token when I submit the data.
I have to calls one to when the user clicks like and one when the user clicks dislike. My issue is if the user clicks like and realizes they made a mistake and click on dislike they will receive an error:
`403 Forbidden`
`The action you have requested is not allowed.`
If the user refreshes the page first and changes their selection everything is ok. it's only when they try to switch from one to the other without refresh.
Here is my code:
```
<script>
// like btn
$('.like-btn').click(function() {
$('.dislike-btn').removeClass('text-danger');
$(this).addClass('liked-video');
$.ajax({
type:"POST",
url: '<?=base_url("videos/like_video")?>',
data: {video_id: <?=$video_id?>, user_id: <?=$logged_in_userid?>, value: "like", '<?=$this->security->get_csrf_token_name()?>':'<?=$this->security->get_csrf_hash()?>'},
success: function() {}
});
});
// dislike btn
$('.dislike-btn').click(function() {
$('.like-btn').removeClass('text-success');
$(this).addClass('disliked-video');
$.ajax({
type:"POST",
url: '<?=base_url("videos/dislike_video")?>',
data: {video_id: <?=$video_id?>, user_id: <?=$logged_in_userid?>, value: "dislike", '<?=$this->security->get_csrf_token_name()?>':'<?=$this->security->get_csrf_hash()?>'},
success: function() {}
});
});
</script>
```
Why does it give the user an error when they make changes to their selection? | 2015/08/03 | [
"https://Stackoverflow.com/questions/31795169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1739465/"
]
| So I copied this paragraph from the user guide.
"Tokens may be either regenerated on every submission (default) or kept the same throughout the life of the CSRF cookie. The default regeneration of tokens provides stricter security, but may result in usability concerns as other tokens become invalid (back/forward navigation, multiple tabs/windows, asynchronous actions, etc). You may alter this behavior by editing the following config parameter. "
Try to add/edit this line in your config file:
$config['csrf\_regeneration'] = TRUE; | There's another way to do this that doesn't require disabling csrf regeneration. you can send the new csrf token back to the calling ajax script.
In your CodeIgniter Controller:
```
$data = array('data'=> 'data to send back to browser');
$csrf = $this->security->get_csrf_hash();
$this->output
->set_content_type('application/json')
->set_output(json_encode(array('data' => $data, 'csrf' => $csrf)));
```
$data = the data to return to the browser
$csrf = new csrf token to be used by the browser for next ajax post request
Obviously you can output this in other ways but JSON is used mostly with ajax calls. Also include this token in every post response to be used for the next post request
Then in your next ajax request (javascript):
```
var token = data.csrf;
$.ajax({
url: '/next/ajax/request/url',
type: 'POST',
data: { new_data: 'new data to send via post', csrf_token:token },
cache: false,
success: function(data, textStatus, jqXHR) {
// Get new csrf token for next ajax post
var new_csrf_token = data.csrf
//Do something with data returned from post request
},
error: function(jqXHR, textStatus, errorThrown) {
// Handle errors here
console.log('ERRORS: ' + textStatus + ' - ' + errorThrown );
}
});
```
Also remember that where I've got `csrf_token:token` replace `crf_token` with the name of your token found in application/config/config.php on line that states `$config['csrf_token_name'] = 'csrf_token';` |
35,333,630 | i'm learning and trying to use laravel 5.2, i'm confusing how to add field in a table.
I create a migration file called 2016\_01\_29\_093417\_create\_thread\_table.php, everytime i want to add a field, i add a code inside the file e.g
```
$table->string('content');
```
and then run the command
```
php artisan migrate:refresh
```
the new field will appear in the table but the testing data (e.g a user in user table will be truncated)
The questions are:
1) what is the right way (best practice) to add new field to a table?
2) how to keep the testing data all the tables, e.g user in users table?
Anyone know how to do? | 2016/02/11 | [
"https://Stackoverflow.com/questions/35333630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/925552/"
]
| There are two ways to do this.
**Your application is already live** with people using it and you don't want to lose their data: you simply make a new migration and supply `up()` and `down()` with corresponding operations. For example:
```
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class UsersNewField extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function ($table) {
$table->string('email');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function ($table) {
$table->dropColumn('email');
});
}
}
```
After you run `php artisan migrate` it will simply run the latest migration.
**Your application is still in development** and nobody is using it yet: you use seeds to populate your database with testing data and edit your initial migration as necessary. For example:
```
<?php
use Illuminate\Database\Seeder;
class UsersSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('users')->insert([
'name' => 'First User',
'email' => '[email protected]',
'password' => bcrypt('somepass9019'),
]);
DB::table('users')->insert([
'name' => 'Second User',
'email' => '[email protected]',
'password' => bcrypt('somepass2039'),
]);
DB::table('users')->insert([
'name' => 'Third User',
'email' => '[email protected]',
'password' => bcrypt('somepass0534'),
]);
}
}
```
After you run `php artisan migrate:refresh --seed` it will reset the database and seed it with initial/testing data. | well you need to create a new migration for each column changes
you need to use `migrate`
`migration:refresh` will reset and seed the database again
I would suggest make use of seeders and model factories if you wish to preserve your testing data and save time entering data again
<https://laravel.com/docs/5.1/seeding#using-model-factories> |
88,777 | I can't seem to get into the Views administration panel from any place in Commerce Kickstart 7.x-2.9. There is no menu entry even with Administration menu installed. Trying to configure via the link for Views on the modules admin page simply sends the page to the Administration menu with no "Views" option. Likewise directly entering siteurl/admin/views goes to the same place.
I guess the Views access is overridden by the Kickstart configuration.
Does anyone know a way around this? | 2013/10/13 | [
"https://drupal.stackexchange.com/questions/88777",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/19314/"
]
| I eventually figured this out. With Administration Menu Module installed, views is not available - it seems like the menu links do not get built.
There is a big problem with simply uninstalling the Administration Menu and re-enabling the Commerce Kickstart Menu module. According to <https://drupal.org/node/1877594#comment-7500586>. "When Commerce Kickstart Menus gets disabled, due to #550254: Menu links are sometimes not properly re-parented Management menu is not being properly rebuilt, hence it will look broken."
In order to get to views I had to uninstall Commerce Kickstart Menu module, apply the patch discussed, then reinstall and re-enable it. | If you have not made any changes and are logged in as admin then the menu link should be under `Site Settings -> Visual and Layout -> Views`
 |
88,777 | I can't seem to get into the Views administration panel from any place in Commerce Kickstart 7.x-2.9. There is no menu entry even with Administration menu installed. Trying to configure via the link for Views on the modules admin page simply sends the page to the Administration menu with no "Views" option. Likewise directly entering siteurl/admin/views goes to the same place.
I guess the Views access is overridden by the Kickstart configuration.
Does anyone know a way around this? | 2013/10/13 | [
"https://drupal.stackexchange.com/questions/88777",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/19314/"
]
| If you have not made any changes and are logged in as admin then the menu link should be under `Site Settings -> Visual and Layout -> Views`
 | The original chosen solution is old and now outdated it seems. All I had to do was go to modules page and disable Commerce Kickstart Menus (if not already disabled) then go to modules uninstall page and uninstall Commerce Kickstart Menus. Now from the `/admin/structure/menu/manage/management` I can just re-adjust any menus that seem out of place and all control has been relinquished to the UI as would be expected. |
88,777 | I can't seem to get into the Views administration panel from any place in Commerce Kickstart 7.x-2.9. There is no menu entry even with Administration menu installed. Trying to configure via the link for Views on the modules admin page simply sends the page to the Administration menu with no "Views" option. Likewise directly entering siteurl/admin/views goes to the same place.
I guess the Views access is overridden by the Kickstart configuration.
Does anyone know a way around this? | 2013/10/13 | [
"https://drupal.stackexchange.com/questions/88777",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/19314/"
]
| I eventually figured this out. With Administration Menu Module installed, views is not available - it seems like the menu links do not get built.
There is a big problem with simply uninstalling the Administration Menu and re-enabling the Commerce Kickstart Menu module. According to <https://drupal.org/node/1877594#comment-7500586>. "When Commerce Kickstart Menus gets disabled, due to #550254: Menu links are sometimes not properly re-parented Management menu is not being properly rebuilt, hence it will look broken."
In order to get to views I had to uninstall Commerce Kickstart Menu module, apply the patch discussed, then reinstall and re-enable it. | The original chosen solution is old and now outdated it seems. All I had to do was go to modules page and disable Commerce Kickstart Menus (if not already disabled) then go to modules uninstall page and uninstall Commerce Kickstart Menus. Now from the `/admin/structure/menu/manage/management` I can just re-adjust any menus that seem out of place and all control has been relinquished to the UI as would be expected. |
52,305,586 | I am new to MySQL trigger. I want to make a trigger that before the update is made from my `emp_audit` table will check first if the `empno` from my employees table already exists. If it exists then do the update otherwise do nothing.
I encounter the following error:
>
> Error 1064
>
>
>
The code is:
```
DELIMITER $$
CREATE TRIGGER before_emp_audit_update
BEFORE UPDATE ON emp_audit
FOR EACH ROW BEGIN
IF (SELECT COUNT(*) FROM employees WHERE empno = NEW.empno) = 1
THEN
UPDATE INTO emp_audit
SET ACTION = 'update',
empno = NEW.empno,
lastname = NEW.lastname,
changedat = NOW();
END IF;
END$$
DELIMITER;
``` | 2018/09/13 | [
"https://Stackoverflow.com/questions/52305586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10356066/"
]
| I had the same problem. It seems that SIRF and SURF are [no longer available in opencv > 3.4.2.16](https://github.com/DynaSlum/satsense/issues/13). I chose an older opencv-python and opencv-contrib-python versions and solved this problem. Here is the [history version](https://pypi.org/project/opencv-python/#history) about opencv-python, and I use the following code :
```
pip install opencv-python==3.4.2.16
pip install opencv-contrib-python==3.4.2.16
```
**Edit**
For Anaconda User just this instead of pip
```
conda install -c menpo opencv
```
this will install cv2 3.4.1 and everything you need to run SIFT
good luck~ | It may be due to a mismatch of opencv version and opencv-contrib version.
If you installed opencv from the source using CMake, and the source version is different from the version of opencv-contrib-python, uninstall the current opencv-contrib-python and do `pip install opencv-contrib-python==<version of the source>.X` or an another compatible version.
One version setup that I have running is opencv source (3.2), opencv-python (3.4.0.14) and opencv-contrib-python (3.4.2.17) |
52,305,586 | I am new to MySQL trigger. I want to make a trigger that before the update is made from my `emp_audit` table will check first if the `empno` from my employees table already exists. If it exists then do the update otherwise do nothing.
I encounter the following error:
>
> Error 1064
>
>
>
The code is:
```
DELIMITER $$
CREATE TRIGGER before_emp_audit_update
BEFORE UPDATE ON emp_audit
FOR EACH ROW BEGIN
IF (SELECT COUNT(*) FROM employees WHERE empno = NEW.empno) = 1
THEN
UPDATE INTO emp_audit
SET ACTION = 'update',
empno = NEW.empno,
lastname = NEW.lastname,
changedat = NOW();
END IF;
END$$
DELIMITER;
``` | 2018/09/13 | [
"https://Stackoverflow.com/questions/52305586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10356066/"
]
| Edit: The `opencv-contrib-python-nonfree` was removed from pypi.
**On Linux/ MacOS**, I've found a better solution! To access nonfree detectors use:
`pip install opencv-contrib-python-nonfree` | It may be due to a mismatch of opencv version and opencv-contrib version.
If you installed opencv from the source using CMake, and the source version is different from the version of opencv-contrib-python, uninstall the current opencv-contrib-python and do `pip install opencv-contrib-python==<version of the source>.X` or an another compatible version.
One version setup that I have running is opencv source (3.2), opencv-python (3.4.0.14) and opencv-contrib-python (3.4.2.17) |
52,305,586 | I am new to MySQL trigger. I want to make a trigger that before the update is made from my `emp_audit` table will check first if the `empno` from my employees table already exists. If it exists then do the update otherwise do nothing.
I encounter the following error:
>
> Error 1064
>
>
>
The code is:
```
DELIMITER $$
CREATE TRIGGER before_emp_audit_update
BEFORE UPDATE ON emp_audit
FOR EACH ROW BEGIN
IF (SELECT COUNT(*) FROM employees WHERE empno = NEW.empno) = 1
THEN
UPDATE INTO emp_audit
SET ACTION = 'update',
empno = NEW.empno,
lastname = NEW.lastname,
changedat = NOW();
END IF;
END$$
DELIMITER;
``` | 2018/09/13 | [
"https://Stackoverflow.com/questions/52305586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10356066/"
]
| Since SIFT patent expired, SIFT has been moved to the main repo.
To use SIFT in Opencv, You should use cv2.SIFT\_create() instead of cv2.xfeatures2d.SIFT\_create() now. (xfeatures2d only exists in the contrib package, but sift is part of the main package now.)
Below link will be helpful.
<https://github.com/opencv/opencv/issues/16736> | It may be due to a mismatch of opencv version and opencv-contrib version.
If you installed opencv from the source using CMake, and the source version is different from the version of opencv-contrib-python, uninstall the current opencv-contrib-python and do `pip install opencv-contrib-python==<version of the source>.X` or an another compatible version.
One version setup that I have running is opencv source (3.2), opencv-python (3.4.0.14) and opencv-contrib-python (3.4.2.17) |
52,305,586 | I am new to MySQL trigger. I want to make a trigger that before the update is made from my `emp_audit` table will check first if the `empno` from my employees table already exists. If it exists then do the update otherwise do nothing.
I encounter the following error:
>
> Error 1064
>
>
>
The code is:
```
DELIMITER $$
CREATE TRIGGER before_emp_audit_update
BEFORE UPDATE ON emp_audit
FOR EACH ROW BEGIN
IF (SELECT COUNT(*) FROM employees WHERE empno = NEW.empno) = 1
THEN
UPDATE INTO emp_audit
SET ACTION = 'update',
empno = NEW.empno,
lastname = NEW.lastname,
changedat = NOW();
END IF;
END$$
DELIMITER;
``` | 2018/09/13 | [
"https://Stackoverflow.com/questions/52305586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10356066/"
]
| I had the same problem. It seems that SIRF and SURF are [no longer available in opencv > 3.4.2.16](https://github.com/DynaSlum/satsense/issues/13). I chose an older opencv-python and opencv-contrib-python versions and solved this problem. Here is the [history version](https://pypi.org/project/opencv-python/#history) about opencv-python, and I use the following code :
```
pip install opencv-python==3.4.2.16
pip install opencv-contrib-python==3.4.2.16
```
**Edit**
For Anaconda User just this instead of pip
```
conda install -c menpo opencv
```
this will install cv2 3.4.1 and everything you need to run SIFT
good luck~ | Edit: The `opencv-contrib-python-nonfree` was removed from pypi.
**On Linux/ MacOS**, I've found a better solution! To access nonfree detectors use:
`pip install opencv-contrib-python-nonfree` |
52,305,586 | I am new to MySQL trigger. I want to make a trigger that before the update is made from my `emp_audit` table will check first if the `empno` from my employees table already exists. If it exists then do the update otherwise do nothing.
I encounter the following error:
>
> Error 1064
>
>
>
The code is:
```
DELIMITER $$
CREATE TRIGGER before_emp_audit_update
BEFORE UPDATE ON emp_audit
FOR EACH ROW BEGIN
IF (SELECT COUNT(*) FROM employees WHERE empno = NEW.empno) = 1
THEN
UPDATE INTO emp_audit
SET ACTION = 'update',
empno = NEW.empno,
lastname = NEW.lastname,
changedat = NOW();
END IF;
END$$
DELIMITER;
``` | 2018/09/13 | [
"https://Stackoverflow.com/questions/52305586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10356066/"
]
| I had the same problem. It seems that SIRF and SURF are [no longer available in opencv > 3.4.2.16](https://github.com/DynaSlum/satsense/issues/13). I chose an older opencv-python and opencv-contrib-python versions and solved this problem. Here is the [history version](https://pypi.org/project/opencv-python/#history) about opencv-python, and I use the following code :
```
pip install opencv-python==3.4.2.16
pip install opencv-contrib-python==3.4.2.16
```
**Edit**
For Anaconda User just this instead of pip
```
conda install -c menpo opencv
```
this will install cv2 3.4.1 and everything you need to run SIFT
good luck~ | Since SIFT patent expired, SIFT has been moved to the main repo.
To use SIFT in Opencv, You should use cv2.SIFT\_create() instead of cv2.xfeatures2d.SIFT\_create() now. (xfeatures2d only exists in the contrib package, but sift is part of the main package now.)
Below link will be helpful.
<https://github.com/opencv/opencv/issues/16736> |
7,852,466 | How do I change `width` value assigned in `#center`? (I don't want to switch between CSS files just because 1 changed `width` value.) How do I dynamically change the value using Javascript?
```html
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style type="text/css">
#main #center {
width: 600px; // change width to 700 on click
float: left;
}
#main #center .send {
background: #fff;
padding: 10px;
position: relative;
}
#main #center .send .music {
text-align: center;
margin-bottom: 10px;
}
#main #center .send .write {
font-family: georgia, serif;
font-size: 150px;
opacity: 0.2;
}
//....etc.
</style>
</head>
<body>
// change #center width to 700
<a href="#go2" onclick="how to change width of #center ???" ></a>
</body>
</html>
``` | 2011/10/21 | [
"https://Stackoverflow.com/questions/7852466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1007481/"
]
| Two possible ways:
1. Give the element "center" a class value that matches another CSS rule
2. Alter the "style" property of the element | Call a javascript function in the onclick which takes the dom element and sets the new width OR changes the class of the element
```
function changeWidth(){
document.getElementById('center');
div.style.width="1270px";
}
``` |
7,852,466 | How do I change `width` value assigned in `#center`? (I don't want to switch between CSS files just because 1 changed `width` value.) How do I dynamically change the value using Javascript?
```html
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style type="text/css">
#main #center {
width: 600px; // change width to 700 on click
float: left;
}
#main #center .send {
background: #fff;
padding: 10px;
position: relative;
}
#main #center .send .music {
text-align: center;
margin-bottom: 10px;
}
#main #center .send .write {
font-family: georgia, serif;
font-size: 150px;
opacity: 0.2;
}
//....etc.
</style>
</head>
<body>
// change #center width to 700
<a href="#go2" onclick="how to change width of #center ???" ></a>
</body>
</html>
``` | 2011/10/21 | [
"https://Stackoverflow.com/questions/7852466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1007481/"
]
| ```
document.getElementById('center').style.width = "599px";
``` | Two possible ways:
1. Give the element "center" a class value that matches another CSS rule
2. Alter the "style" property of the element |
7,852,466 | How do I change `width` value assigned in `#center`? (I don't want to switch between CSS files just because 1 changed `width` value.) How do I dynamically change the value using Javascript?
```html
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style type="text/css">
#main #center {
width: 600px; // change width to 700 on click
float: left;
}
#main #center .send {
background: #fff;
padding: 10px;
position: relative;
}
#main #center .send .music {
text-align: center;
margin-bottom: 10px;
}
#main #center .send .write {
font-family: georgia, serif;
font-size: 150px;
opacity: 0.2;
}
//....etc.
</style>
</head>
<body>
// change #center width to 700
<a href="#go2" onclick="how to change width of #center ???" ></a>
</body>
</html>
``` | 2011/10/21 | [
"https://Stackoverflow.com/questions/7852466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1007481/"
]
| Two possible ways:
1. Give the element "center" a class value that matches another CSS rule
2. Alter the "style" property of the element | ```
<div onclick="changeWidth()" id="main">
Stuff
</div>
<div onclick="changeWidth()" id="center">
More Stuff
</div>
function changeWidth(){
this.style.width = "700px";
}
``` |
7,852,466 | How do I change `width` value assigned in `#center`? (I don't want to switch between CSS files just because 1 changed `width` value.) How do I dynamically change the value using Javascript?
```html
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style type="text/css">
#main #center {
width: 600px; // change width to 700 on click
float: left;
}
#main #center .send {
background: #fff;
padding: 10px;
position: relative;
}
#main #center .send .music {
text-align: center;
margin-bottom: 10px;
}
#main #center .send .write {
font-family: georgia, serif;
font-size: 150px;
opacity: 0.2;
}
//....etc.
</style>
</head>
<body>
// change #center width to 700
<a href="#go2" onclick="how to change width of #center ???" ></a>
</body>
</html>
``` | 2011/10/21 | [
"https://Stackoverflow.com/questions/7852466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1007481/"
]
| Two possible ways:
1. Give the element "center" a class value that matches another CSS rule
2. Alter the "style" property of the element | ```
document.getElementById( 'center' ).style.width = "700px";
``` |
7,852,466 | How do I change `width` value assigned in `#center`? (I don't want to switch between CSS files just because 1 changed `width` value.) How do I dynamically change the value using Javascript?
```html
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style type="text/css">
#main #center {
width: 600px; // change width to 700 on click
float: left;
}
#main #center .send {
background: #fff;
padding: 10px;
position: relative;
}
#main #center .send .music {
text-align: center;
margin-bottom: 10px;
}
#main #center .send .write {
font-family: georgia, serif;
font-size: 150px;
opacity: 0.2;
}
//....etc.
</style>
</head>
<body>
// change #center width to 700
<a href="#go2" onclick="how to change width of #center ???" ></a>
</body>
</html>
``` | 2011/10/21 | [
"https://Stackoverflow.com/questions/7852466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1007481/"
]
| ```
document.getElementById('center').style.width = "599px";
``` | Call a javascript function in the onclick which takes the dom element and sets the new width OR changes the class of the element
```
function changeWidth(){
document.getElementById('center');
div.style.width="1270px";
}
``` |
7,852,466 | How do I change `width` value assigned in `#center`? (I don't want to switch between CSS files just because 1 changed `width` value.) How do I dynamically change the value using Javascript?
```html
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style type="text/css">
#main #center {
width: 600px; // change width to 700 on click
float: left;
}
#main #center .send {
background: #fff;
padding: 10px;
position: relative;
}
#main #center .send .music {
text-align: center;
margin-bottom: 10px;
}
#main #center .send .write {
font-family: georgia, serif;
font-size: 150px;
opacity: 0.2;
}
//....etc.
</style>
</head>
<body>
// change #center width to 700
<a href="#go2" onclick="how to change width of #center ???" ></a>
</body>
</html>
``` | 2011/10/21 | [
"https://Stackoverflow.com/questions/7852466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1007481/"
]
| ```
document.getElementById( 'center' ).style.width = "700px";
``` | Call a javascript function in the onclick which takes the dom element and sets the new width OR changes the class of the element
```
function changeWidth(){
document.getElementById('center');
div.style.width="1270px";
}
``` |
7,852,466 | How do I change `width` value assigned in `#center`? (I don't want to switch between CSS files just because 1 changed `width` value.) How do I dynamically change the value using Javascript?
```html
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style type="text/css">
#main #center {
width: 600px; // change width to 700 on click
float: left;
}
#main #center .send {
background: #fff;
padding: 10px;
position: relative;
}
#main #center .send .music {
text-align: center;
margin-bottom: 10px;
}
#main #center .send .write {
font-family: georgia, serif;
font-size: 150px;
opacity: 0.2;
}
//....etc.
</style>
</head>
<body>
// change #center width to 700
<a href="#go2" onclick="how to change width of #center ???" ></a>
</body>
</html>
``` | 2011/10/21 | [
"https://Stackoverflow.com/questions/7852466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1007481/"
]
| ```
document.getElementById('center').style.width = "599px";
``` | ```
<div onclick="changeWidth()" id="main">
Stuff
</div>
<div onclick="changeWidth()" id="center">
More Stuff
</div>
function changeWidth(){
this.style.width = "700px";
}
``` |
7,852,466 | How do I change `width` value assigned in `#center`? (I don't want to switch between CSS files just because 1 changed `width` value.) How do I dynamically change the value using Javascript?
```html
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style type="text/css">
#main #center {
width: 600px; // change width to 700 on click
float: left;
}
#main #center .send {
background: #fff;
padding: 10px;
position: relative;
}
#main #center .send .music {
text-align: center;
margin-bottom: 10px;
}
#main #center .send .write {
font-family: georgia, serif;
font-size: 150px;
opacity: 0.2;
}
//....etc.
</style>
</head>
<body>
// change #center width to 700
<a href="#go2" onclick="how to change width of #center ???" ></a>
</body>
</html>
``` | 2011/10/21 | [
"https://Stackoverflow.com/questions/7852466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1007481/"
]
| ```
document.getElementById('center').style.width = "599px";
``` | ```
document.getElementById( 'center' ).style.width = "700px";
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.