date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/20 | 1,094 | 3,243 | <issue_start>username_0: I have a custom array object. It has two main variables:
m\_array = Pointer to dynamic array.
m\_size - The size of the array. The size for this array is 10.
When I rotate to the left, this works fine:
```
std::rotate(m_array + 0, m_array + 1, m_array + m_size);
```
This is equivalent to:
```
// simple rotation to the left
std::rotate(v.begin(), v.begin() + 1, v.end());
```
When I try rotating to the right, I'm getting a runtime error.
I need the equivalent of this:
```
// simple rotation to the right
std::rotate(v.rbegin(), v.rbegin() + 1, v.rend());
```
I tried this:
```
std::rotate(m_array + m_size, m_array + m_size + 1, m_array + 0);
```
I get the error: Invalid iterator range
So, I thought this was m\_size, so I tried this:
```
std::rotate(m_array + m_size - 1, m_array + (m_size - 1) + 1, m_array + 0);
```
And I get the same error.
Thoughts are welcomed.
The source I tried to follow:
<http://en.cppreference.com/w/cpp/algorithm/rotate><issue_comment>username_1: To do a right rotation (to borrow your phrase), you want the range to be everything *but* the last element in the array. I'll leave it to you to adapt this code to work on variable-sized arrays.
```
#include
#include
int main() {
int data[10] = { 0, 1, 2, 3, 4,
5, 6, 7, 8, 9 };
auto print\_all = [&data]() {
for(auto v: data) {
std::cout << v << ' ';
}
std::cout << '\n';
};
print\_all();
// rotate elements to the left
std::rotate(data, data + 1, data + 10);
print\_all();
// rotate element to the right, back to the original position
std::rotate(data, data + 9, data + 10);
print\_all();
return 0;
}
```
My output looks like this:
```
./rotate
0 1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 0
0 1 2 3 4 5 6 7 8 9
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: The reason `std::rotate(v.rbegin(), v.rbegin() + 1, v.rend())` works is that it uses reverse iterators. That means that `v.rbegin() + 1` is actually decrementing the position in the array and is equal to `v.begin() + v.size() - 1`.
When using raw pointer arithmetic, there is no way to get the same reverse iterating behavior. You will have to manually translate the left rotation to a right rotation. This can easily be done by flipping the rotate position about the center of the array and performing a left rotate.
Left or right rotation can be boiled down to dividing an array into 2 sections and then swapping them. Whether it is a left rotation or right rotation just dictates where the division is made. For a left rotate by `k`, the rotation point is at `k mod N`. For a right rotate, the rotation point is at `-k mod N` where `N` is the total length of the array. This selects the index in the original array you would like to be at index `0` of the newly rotated array.
So the following right rotate by 1,
```
std::rotate(v.rbegin(), v.rbegin() + 1, v.rend())
```
is equivalent to using raw pointers in the following way:
```
int* p = &v[0];
int n = v.size();
int k = -1;
std::rotate(p, p + mod(k, n), p + n);
```
where `mod()` is the modulo operation (basically the `%` operator that always wraps to a positive number):
```
int mod(int x, int y) { return ((x % y) + y) % y; }
```
Upvotes: 2 |
2018/03/20 | 344 | 1,386 | <issue_start>username_0: Folks:
I have recently begun working with xPages. I have a view of documents that needs to present data from other related documents in six separated columns. What I am trying is to use a Computed column that does a lookup to a view with a concatenated string. My intention was to parse this into the 6 columns of data. It isn't working and it may be silly of me to try referring to a computed column in another computed column.
Another alternative was to have the underlying view present the UNID of the other document and then do a @GetDocField on the xPages view.
So I have two questions:
1) May I programmatically refer to a Computed column in a view from another Computed column?
2) For efficiency, what would be the best way to present data like a 'join' in a view?
I appreciate your attention and help.
Cheers,
<NAME><issue_comment>username_1: Can you try to “go native” ? You build one view that contains both documents arranged to be in that view after each other. So you have Type1,Type2,Type1,Type2 etc.
Then use a repeat control to render a table or list “joining” the two rows.
This would save you doing tons of lookups.
Eventually you use that view as Json Rest source to do the joining in Json
Upvotes: 2 <issue_comment>username_2: I would create a Java bean that returns a list of Java objects that contain your data.
Upvotes: 1 |
2018/03/20 | 677 | 2,479 | <issue_start>username_0: I have a paragraph, the content is automatically generated, I cannot edit the HTML directly. The paragraph will always end in an email address then a question mark. I want to bold the email address. Here is the HTML:
```
Do you want to stop receiving emails from us to the email address <EMAIL>?
```
I would like to bold the email address only. I tried the following:
```
$('.unsub-main:contains').html(function(){
// separate the text by spaces
var text= $(this).text().split(' ');
// drop the last word and store it in a variable
var last = text.pop();
// join the text back and if it has more than 1 word add the span tag
// to the last word
return text.join(" ") + (text.length > 0 ? ' '+last+'' : last);
});
```
Can I wrap the last string before the question mark in the paragraph in a span tag?<issue_comment>username_1: You don't need javascript for this, you don't even need CSS. Any reason you can't just wrap it in strong tags like this?
```
Do you want to stop receiving emails from us to the email address **<EMAIL>**?
```
or better yet make the email clickable with a mailto: href and also bold:
```
Do you want to stop receiving emails from us to the email address **[<EMAIL>](mailto:<EMAIL>)**?
```
Simple jquery way:
```
var boldLink = 'Do you want to stop receiving emails from us to the email address **[<EMAIL>](mailto:<EMAIL>)**?
'
$('.unsub-main').html(boldLink)
```
Upvotes: 0 <issue_comment>username_2: Your code almost works. All you need is to remove the `:contains` selector, which is used to filter only those elements that contain something. Its syntax is `$(":contains(text)")`, but you didn't define the text to find in the brackets, so `$('.unsub-main:contains')` matches nothing. Either remove `:contains` or use it with text in brackets
```js
$('.unsub-main').html(function(){
// separate the text by spaces
var text = $(this).text().split(' ');
// drop the last word and store it in a variable
var last = text.pop();
// join the text back and if it has more than 1 word add the span tag
// to the last word
return text.join(" ") + (text.length > 0 ? ' '+last+'' : last);
});
```
```css
.last {
font-weight: bold;
}
```
```html
Do you want to stop receiving emails from us to the email address <EMAIL>?
```
Upvotes: 3 [selected_answer] |
2018/03/20 | 606 | 2,080 | <issue_start>username_0: I developed a Spring Boot REST API and the URL is: `http://localhost:8080/greeting`
However, when I'm trying to access it, it says
>
> Whitelabel Error Page This application has no explicit mapping for
> /error, so you are seeing this as a fallback. Mon Mar 19 22:06:54 EDT
> 2018 There was an unexpected error (type=Not Found, status=404). No
> message available
>
>
>
Here is the example that I used: <https://spring.io/guides/gs/rest-service/><issue_comment>username_1: You don't need javascript for this, you don't even need CSS. Any reason you can't just wrap it in strong tags like this?
```
Do you want to stop receiving emails from us to the email address **<EMAIL>**?
```
or better yet make the email clickable with a mailto: href and also bold:
```
Do you want to stop receiving emails from us to the email address **[<EMAIL>](mailto:<EMAIL>)**?
```
Simple jquery way:
```
var boldLink = 'Do you want to stop receiving emails from us to the email address **[<EMAIL>](mailto:<EMAIL>)**?
'
$('.unsub-main').html(boldLink)
```
Upvotes: 0 <issue_comment>username_2: Your code almost works. All you need is to remove the `:contains` selector, which is used to filter only those elements that contain something. Its syntax is `$(":contains(text)")`, but you didn't define the text to find in the brackets, so `$('.unsub-main:contains')` matches nothing. Either remove `:contains` or use it with text in brackets
```js
$('.unsub-main').html(function(){
// separate the text by spaces
var text = $(this).text().split(' ');
// drop the last word and store it in a variable
var last = text.pop();
// join the text back and if it has more than 1 word add the span tag
// to the last word
return text.join(" ") + (text.length > 0 ? ' '+last+'' : last);
});
```
```css
.last {
font-weight: bold;
}
```
```html
Do you want to stop receiving emails from us to the email address <EMAIL>?
```
Upvotes: 3 [selected_answer] |
2018/03/20 | 1,000 | 3,545 | <issue_start>username_0: I'm attempting to set a global variable equal to a JSON element being returned from a Promise with Axios, within my React Native application. I've followed the advice from [this question](https://stackoverflow.com/questions/44231366/how-to-set-variable-outside-axios-get#), but still am unable to set the variable's value.
Here is my method using an Axios call:
```
temp_high = null;
_getForecast(zipcode)
{
const request = "http://api.wunderground.com/api/" + API_KEY + "/forecast/q/" + zipcode + ".json";
return axios.get(request).then( (response) => {
if(response.status == 200) {
this.response = response.data;
return this.response;
}
});
}
```
And my render:
```
render() {
this._getForecast(49306).then(data => {
this.temp_high = parseInt(data.forecast.simpleforecast.forecastday[0].high.fahrenheit);
});
return (
Weather for Belmont, MI
High: {this.temp\_high}
);
}
}
```
If I log `data.forecast.simpleforecast.forecastday[0].high.fahrenheit` to the console, or create an alert calling that, the value is indeed correct. I just cannot seem to set it equal to temp\_high.<issue_comment>username_1: If you want to assign to a standalone variable (even if it happens to be in the global scope), don't prefix it with `this`. Just
```
temp_high = Number(data.forecast.simpleforecast.forecastday[0].high.fahrenheit);
```
`this` resolves to the calling context of the current function you're in.
Upvotes: 1 <issue_comment>username_2: **This answer is wrong, the arrow allows for <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions>**) be carefull with the keyword "this".
It is currently setting the this.temp\_high to the \_getForecast function. What you might want to do is have
```
render() {
var self = this;
this._getForecast(49306).then(data => {
self.temp_high
=parseInt(data.forecast.simpleforecast.forecastday[0].high.fahrenheit);
});
return (
Weather for Belmont, MI
High: {this.temp\_high}
);
}
}
```
Upvotes: -1 <issue_comment>username_3: 1. If you want your component's view to update in response to the new data, you need to use setState, to tell React to re-render. React doesn't react (hue) to regular class properties.
2. Async functions shouldn't be called from render. You should instead use [lifecycle hooks](https://reactjs.org/docs/state-and-lifecycle.html#adding-lifecycle-methods-to-a-class), and `componentDidMount` would work best for this situation, to fetch the information once on mount.
With that in mind, you'd end up with something like this:
```
class Example extends React.Component {
state = {
data: null
}
componentDidMount() {
// fetch forecast data when the component mounts
this._getForecast(49306)
}
_getForecast(zipcode) {
const request =
"http://api.wunderground.com/api/" +
API_KEY +
"/forecast/q/" +
zipcode +
".json"
return axios.get(request).then(response => {
if (response.status == 200) {
this.setState({ data: response.data })
}
})
}
render() {
if (this.state.data === null) {
// don't render if we haven't received data yet
// otherwise we'll get an error trying to calculate temp_high
return
}
const temp_high = Number(
this.state.data.forecast.simpleforecast.forecastday[0].high.fahrenheit
)
return (
Weather for Belmont, MI
High: {temp\_high}
)
}
}
```
Upvotes: 3 [selected_answer] |
2018/03/20 | 623 | 2,344 | <issue_start>username_0: Consider I want to download only 10 files from the bucket, how do we pass 10 as an argument.<issue_comment>username_1: Your use case appears to be:
* Every 30 minutes
* Download 10 random files from Amazon S3
Presumably, these 10 files should not be files previously downloaded.
There is no in-built S3 functionality to download a random selection of files. Instead, you will need to:
* Obtain a listing of files from your desired S3 bucket and optional path
* Randomly select which files you want to download
* Download the selected files
This would be easily done via a programming language (eg Python), where you could obtain an array of filenames, randomize it, then loop through the list and download each file.
You can also do it in a shell script by calling the [AWS Command-Line Interface (CLI)](http://aws.amazon.com/cli/) to obtain the listing (`aws s3 ls`) and to copy the files (`aws s3 cp`).
Alternatively, you could choose to synchronize *ALL* the files to your local machine (`aws s3 sync`) and then select random local files to process.
Try the above steps. If you experience difficulties, post your code and the error/problem you are experiencing and we can assist.
Upvotes: 0 <issue_comment>username_2: The easiest way to do so is to make a python script that you can run every 30 minutes.I have written the python code that will do your work :
```
import boto3
import random
s3 = boto3.client('s3')
source=boto3.resource('s3')
keys = []
resp = s3.list_objects_v2(Bucket='bucket_name')
for obj in resp['Contents']:
keys.append(obj['Key'])
length = len(keys);
for x in range(10):
hello=random.randint(0,length)
source.meta.client.download_file('bucket_name', keys[hello] , keys[hello])
```
In line 12 you can pass a number as an argument that will define the number of random files you want to download. Further if you want your script to execute the task automatically every 30 minutes, then you can define above code as a separate method and then can use "sched" module of python to call this method repeatedly for which you can find the code in the link here:
[What is the best way to repeatedly execute a function every x seconds in Python?](https://stackoverflow.com/questions/474528/what-is-the-best-way-to-repeatedly-execute-a-function-every-x-seconds-in-python)
Upvotes: 1 |
2018/03/20 | 975 | 3,400 | <issue_start>username_0: I'm struggling with figuring out how to transform a table from from one layout to another:
```
Table1
DEP_NO POSITION_CATEGORY NAME
177 CLERICAL <NAME>
177 MANAGER <NAME>
177 EXECUTIVE DAVID GREEN
200 CLERICAL <NAME>SS
200 MANAGER GEORGE EAST
200 EXECUTIVE MORRIS SMITH
300 CLERICAL PHIL ORANGE
300 MANAGER <NAME>RE
300 EXECUTIVE MARISOL BERN
400 CLERICAL LISA HEAD
400 MANAGER <NAME>
400 EXECUTIVE NICE GUY
Table2
DEP_NO CLERICAL MANAGER EXECUTIVE
177 <NAME> <NAME> DAVID GREEN
200 <NAME> GEORGE EAST MORRIS SMITH
300 PHIL ORANGE <NAME> MARISOL BERN
400 LISA HEAD LINDA TELLER NICE GUY
```
As you can see contents of `tables1` column two are column names in `table2`,
and the names in `table1` become the contents in `table2`
My pandas knowledge is a bit rudimentary, and I cant figure out what the easiest way to get the transform accomplished is.<issue_comment>username_1: Your use case appears to be:
* Every 30 minutes
* Download 10 random files from Amazon S3
Presumably, these 10 files should not be files previously downloaded.
There is no in-built S3 functionality to download a random selection of files. Instead, you will need to:
* Obtain a listing of files from your desired S3 bucket and optional path
* Randomly select which files you want to download
* Download the selected files
This would be easily done via a programming language (eg Python), where you could obtain an array of filenames, randomize it, then loop through the list and download each file.
You can also do it in a shell script by calling the [AWS Command-Line Interface (CLI)](http://aws.amazon.com/cli/) to obtain the listing (`aws s3 ls`) and to copy the files (`aws s3 cp`).
Alternatively, you could choose to synchronize *ALL* the files to your local machine (`aws s3 sync`) and then select random local files to process.
Try the above steps. If you experience difficulties, post your code and the error/problem you are experiencing and we can assist.
Upvotes: 0 <issue_comment>username_2: The easiest way to do so is to make a python script that you can run every 30 minutes.I have written the python code that will do your work :
```
import boto3
import random
s3 = boto3.client('s3')
source=boto3.resource('s3')
keys = []
resp = s3.list_objects_v2(Bucket='bucket_name')
for obj in resp['Contents']:
keys.append(obj['Key'])
length = len(keys);
for x in range(10):
hello=random.randint(0,length)
source.meta.client.download_file('bucket_name', keys[hello] , keys[hello])
```
In line 12 you can pass a number as an argument that will define the number of random files you want to download. Further if you want your script to execute the task automatically every 30 minutes, then you can define above code as a separate method and then can use "sched" module of python to call this method repeatedly for which you can find the code in the link here:
[What is the best way to repeatedly execute a function every x seconds in Python?](https://stackoverflow.com/questions/474528/what-is-the-best-way-to-repeatedly-execute-a-function-every-x-seconds-in-python)
Upvotes: 1 |
2018/03/20 | 838 | 3,215 | <issue_start>username_0: I am unable to debug an api developed in ASP.NET core.
API is hosted in IIS and if I execute the request through fiddler,
I do get the response back. However, if I wish to debug the api for some reason, it's not working because symbols have not been loaded.
I tried following options.
1) Running VS in ADMIN mode.
2) verified this setting @
Tools -> Options -> Debugging -> General -> Enable Just My Code (Managed Only)
3) Added IIS\_USERS and IUSER @ IIS Virtual directory security section and granted full rights.
4) Project is built in debug mode.
5 ) debugging information is set to Portable (Project properties->Build->Advanced)
6) Ran Regiis utility..
Following modules did not get loaded when verified the modules and not sure if this is causing any issue?
aspnetcore.dll, rewrite.dll, iisres.dll
NOTE: If I create a normal application i.e. any windows app and attach a debugger. all modules get loaded and I am able to debug.
Please advise.<issue_comment>username_1: Your use case appears to be:
* Every 30 minutes
* Download 10 random files from Amazon S3
Presumably, these 10 files should not be files previously downloaded.
There is no in-built S3 functionality to download a random selection of files. Instead, you will need to:
* Obtain a listing of files from your desired S3 bucket and optional path
* Randomly select which files you want to download
* Download the selected files
This would be easily done via a programming language (eg Python), where you could obtain an array of filenames, randomize it, then loop through the list and download each file.
You can also do it in a shell script by calling the [AWS Command-Line Interface (CLI)](http://aws.amazon.com/cli/) to obtain the listing (`aws s3 ls`) and to copy the files (`aws s3 cp`).
Alternatively, you could choose to synchronize *ALL* the files to your local machine (`aws s3 sync`) and then select random local files to process.
Try the above steps. If you experience difficulties, post your code and the error/problem you are experiencing and we can assist.
Upvotes: 0 <issue_comment>username_2: The easiest way to do so is to make a python script that you can run every 30 minutes.I have written the python code that will do your work :
```
import boto3
import random
s3 = boto3.client('s3')
source=boto3.resource('s3')
keys = []
resp = s3.list_objects_v2(Bucket='bucket_name')
for obj in resp['Contents']:
keys.append(obj['Key'])
length = len(keys);
for x in range(10):
hello=random.randint(0,length)
source.meta.client.download_file('bucket_name', keys[hello] , keys[hello])
```
In line 12 you can pass a number as an argument that will define the number of random files you want to download. Further if you want your script to execute the task automatically every 30 minutes, then you can define above code as a separate method and then can use "sched" module of python to call this method repeatedly for which you can find the code in the link here:
[What is the best way to repeatedly execute a function every x seconds in Python?](https://stackoverflow.com/questions/474528/what-is-the-best-way-to-repeatedly-execute-a-function-every-x-seconds-in-python)
Upvotes: 1 |
2018/03/20 | 345 | 937 | <issue_start>username_0: I want to direct error\_log and access\_log in php.ini to stdout. My OS is windows 10. Is it possible?<issue_comment>username_1: To output logs in docker, write them to `/dev` IE:
```
error_log /dev/stderr
```
Cheers!
Upvotes: 2 <issue_comment>username_2: Note that, when it comes to the [official `php` Docker image](https://hub.docker.com/_/php), action is no longer required:
* For `php:-apache`, error logs are [automatically redirected to `/dev/stderr`](https://github.com/docker-library/php/blob/3074b80a38201143a7938fb355c918ca109062d7/8.1/buster/apache/Dockerfile#L85).
* For `php:-fpm`, error logs are [automatically redirected to `/proc/self/fd/2`](https://github.com/docker-library/php/blob/3074b80a38201143a7938fb355c918ca109062d7/8.1/buster/fpm/Dockerfile#L245). This has the same effect as above, but [with a few less layers of indirection](https://unix.stackexchange.com/a/564084).
Upvotes: 0 |
2018/03/20 | 466 | 1,456 | <issue_start>username_0: Here is the code :
```
#include
using namespace std;
int a, b;
int f(int c)
{
int n = 1;
for (int i = 0; i < c, i++;)
{
int a = n + i;
}
return a;
}
void main()
{
int i = 3;
int b = f(i);
cout << a << b << i;
}
```
The output is 0,0,3
I understand the a = 0 because it is a global variable and defaults to 0, and i = 3, but I can't figure out how or why b = 0<issue_comment>username_1: In your program, `f()` always returns `0`. The `a` inside the `for` loop is a different `a` from the global variable (it "shadows" it). Therefore, local variable `b` in `main()` (which shadows global `b`) is initialized to `0` by the call to `f()`.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Because in for loop of function f, a is a local varaible. Its scople is effective only in for loop. So return value is global a; So return 0;
Upvotes: 1 <issue_comment>username_3: While others have already pointed out that you write to a local `a` in your loop, but return the global `a`, it's also worth nothing that even if you fix that, your loop will actually never enter it's body, because `i < c, i++` evaluates to `0`, which will be interpreted as `false`. (See [What does the comma operator , do?](https://stackoverflow.com/questions/52550/what-does-the-comma-operator-do).)
You need to fix your entire loop to this:
```
for (int i = 0; i < c; i++)
{
a = n + i;
}
```
Upvotes: 0 |
2018/03/20 | 351 | 1,454 | <issue_start>username_0: I'm pretty new to Typescript, and I'm trying to understand the parts that go into it. Is the DefinitelyTyped Project the same at the @types project?, and is @types the latest way to add type definitions to a project.<issue_comment>username_1: The DefinitelyTyped project predates the @types module scope. Before Typescript 2.1 type definitions had to be maintained manually or via a 3rd party package manager like [typings](https://www.npmjs.com/package/typings). To simplify type management the @types module scope was introduced so that NPM could be used to manage type definitions. Typescript 2.1+ automatically checks for installed @types modules includes them during compilation.
[This article answers this question and others related to typescript and the @types module scope.](https://blog.angular-university.io/typescript-2-type-system-how-do-type-definitions-work-in-npm-when-to-use-types-and-why-what-are-compiler-opt-in-types/)
Upvotes: 1 <issue_comment>username_2: >
> Is the DefinitelyTyped Project the same at the @types project?
>
>
>
You could say that. A better statement : The NPM modules under @types are automatically published from the type definitions present in the DefinitelyTyped Project.
* The @types org Packages : <https://www.npmjs.com/~types>
* Definitely Typed files used to generate / publish the packages : <https://github.com/DefinitelyTyped/DefinitelyTyped>
Upvotes: 3 [selected_answer] |
2018/03/20 | 429 | 1,636 | <issue_start>username_0: I have looked at a few posts on here but haven't had success with making my div change background color when the mouse hovers. It's a little messy, but bear with me. Here is the html/php code:
```
[php=
echo "Section Two - Unknown";
?](https:/doltesting.000webhostapp.com/pageTwo.php)
```
And here is the CSS:
```
a.hoverTwo a:hover a:visited a:link {
background: yellow;
color: black; }
```<issue_comment>username_1: The DefinitelyTyped project predates the @types module scope. Before Typescript 2.1 type definitions had to be maintained manually or via a 3rd party package manager like [typings](https://www.npmjs.com/package/typings). To simplify type management the @types module scope was introduced so that NPM could be used to manage type definitions. Typescript 2.1+ automatically checks for installed @types modules includes them during compilation.
[This article answers this question and others related to typescript and the @types module scope.](https://blog.angular-university.io/typescript-2-type-system-how-do-type-definitions-work-in-npm-when-to-use-types-and-why-what-are-compiler-opt-in-types/)
Upvotes: 1 <issue_comment>username_2: >
> Is the DefinitelyTyped Project the same at the @types project?
>
>
>
You could say that. A better statement : The NPM modules under @types are automatically published from the type definitions present in the DefinitelyTyped Project.
* The @types org Packages : <https://www.npmjs.com/~types>
* Definitely Typed files used to generate / publish the packages : <https://github.com/DefinitelyTyped/DefinitelyTyped>
Upvotes: 3 [selected_answer] |
2018/03/20 | 1,049 | 3,421 | <issue_start>username_0: ```
private:
struct info{
int size = 0;
int key = 0;
int capacity = 1;
std::vector \*value = new std::vector(capacity);
};
int keyCapacity\_;
int size\_;
std::vector \*keys\_;
```
within a function...
```
//some code
keys_ = new std::vector(keyCapacity\_);
//some code
(\*keys\_)[size\_] = new info;
(\*keys\_)[size\_]->(\*value)[size] = inputValue; //getting error on this line
(\*keys\_)[size\_]->size += 1;
(\*keys\_)[size\_]->key = key;
```
I have a pointer to a vector of struct info. Then within info there is a pointer to a vector that will hold values. Very large amounts of data may be input and the program resizes the vectors if needed. The current input value is added to the first open spot on the vector which is size\_. On the line I've identified above I am getting an error:
```
a3.hpp:67:20: error: expected unqualified-id before ‘(’ token
(*keys_)[size_]->(*value)[size] = value;
^
a3.hpp:67:22: error: invalid type argument of unary ‘*’ (have ‘int’)
(*keys_)[size_]->(*value)[size] = value;
```
How can I access this vector to change the value?<issue_comment>username_1: `(*keys_)[size_]`
this one is right
`(*keys_)[size_]->(*value)[size]`
but this one is not. it will look like you are calling (\*value)[size] which doesnt make any sense. its a syntax error.
so you have to call the value first and then dereference it as a whole. like this `(*keys_)`
```
int size = yourSize;
(*((*keys_)[size_]->value))
```
after that you will can now access its index and object inside it.
`(*((*keys_)[size_]->value))[size] = &value`
Upvotes: 1 <issue_comment>username_2: Well, `*value` is not in scope in this context. It's in parentheses, so it will be evaluated separately. To get to value, you need:
```
(*keys_)[size_]->value
```
And then you want to dereference that:
```
*((*keys_)[size_]->value)
```
The extra set of parens probably isn't necessary, but it makes things clear. Then you want to index that:
```
(*((*keys_)[size_]->value))[size]
```
And I am assuming that `size_` and `size` are correct, different indices. Be careful with your naming. That similarity could trip you up very easily.
As a side note, do realize that using `new` is almost never what you want to do in modern C++. You probably want to be using smart pointers instead.
Upvotes: 2 <issue_comment>username_3: The quick fix for your line is this: `(*((*keys_)[size_]->value))[size] = inputValue;`
But seriously, don't use C style pointers. Change your code to this instead:
```
private:
struct info {
int size = 0;
int key = 0;
int capacity = 1;
std::vector value;
}
int keyCapacity\_;
int size\_;
std::vector> keys\_;
```
And in that function:
```
//some code
keys_.resize(keyCapacity_);
//some code
keys_[size_] = std::make_unique();
keys\_[size\_]->value[size] = inputValue;
keys\_[size\_]->size += 1;
keys\_[size\_]->key = key;
```
Since you haven't given a complete example, I can't be entirely sure, but the code still looks wrong to me, because it seems you try to write to a vector that has size 0. From what I can see this should work, but take it was a grain of salt:
```
//some code
keys_.resize(keyCapacity_);
//some code
keys_[size_] = std::make_unique();
keys\_[size\_]->value.push\_back(inputValue);
keys\_[size\_]->size += 1;
keys\_[size\_]->key = key;
```
Upvotes: 0 |
2018/03/20 | 1,143 | 4,583 | <issue_start>username_0: What is the best way to **async call** to load a **UIImage to a textView** as a NSTextAttachment in a tableView? So far this is working very badly.
I am using a URL string to load a single image inside multiple tableView cells.
```
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
//Transform Data From ^ to load at the bottom
tableView.transform = CGAffineTransform (scaleX: 1,y: -1);
cell?.contentView.transform = CGAffineTransform (scaleX: 1,y: -1);
cell?.accessoryView?.transform = CGAffineTransform (scaleX: 1,y: -1);
let username = cell?.viewWithTag(1) as! UITextView
username.text = messageArray[indexPath.row].username
let message = cell?.viewWithTag(2) as! UITextView
//message.text = messageArray[indexPath.row].message // delete later
var test = messageArray[indexPath.row].uploadedPhotoUrl
print(test ?? String.self)
if(test != ""){
// create an NSMutableAttributedString that we'll append everything to
let fullString = NSMutableAttributedString(string: "")
// create our NSTextAttachment
let image1Attachment = NSTextAttachment()
URLSession.shared.dataTask(with: NSURL(string: messageArray[indexPath.row].uploadedPhotoUrl)! as URL, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error ?? String())
return
}
DispatchQueue.main.async(execute: { () -> Void in
let image = UIImage(data: data!)
image1Attachment.image = image
//calculate new size. (-20 because I want to have a litle space on the right of picture)
let newImageWidth = (message.bounds.size.width - 20 )
//resize this
image1Attachment.bounds = CGRect.init(x: 0, y: 0, width: newImageWidth, height: 200)
// wrap the attachment in its own attributed string so we can append it
let image1String = NSAttributedString(attachment: image1Attachment)
// add the NSTextAttachment wrapper to our full string, then add some more text.
fullString.append(image1String)
fullString.append(NSAttributedString(string: message.text))
// draw the result in a label
message.attributedText = fullString
//message.textStorage.insert(image1String, at: message.selectedRange.location)
message.textColor = .white
test = ""
})
}).resume()
}else {
message.text = messageArray[indexPath.row].message
}
let timeStamp = cell?.viewWithTag(3) as! UILabel
timeStamp.text = messageArray[indexPath.row].timeStamp
let imageView = cell?.viewWithTag(4) as! UIImageView
imageView.image = nil
let urlString = messageArray[indexPath.row].photoUrl
imageView.layer.cornerRadius = 10
imageView.clipsToBounds = true
//Load profile image(on cell) with URL & Alamofire Library
let downloadURL = NSURL(string: urlString!)
imageView.af_setImage(withURL: downloadURL! as URL)
return cell!
}
```
Images are still lagging when index is scrolling(appearing and disappearing) and are also not loading completely
[](https://i.stack.imgur.com/ATHmw.png)<issue_comment>username_1: You are loading an image at a time while the tableviewcell is scrolling. There is some time to call the service and then wait for the response to be returned, thus affecting the scrolling although it is on another thread.
You can try calling the images in batches of maybe 10 or 20 at a time.
Upvotes: 1 [selected_answer]<issue_comment>username_2: **TL/DR:**
Learn to write better code.
For starters, there's no way `tableView(:cellForRowAt:)` can accomplish all that work in under 16 milliseconds. I think you should reconsider your app structure and architecture for starters. It would serve your app better to abstract the networking calls to an API that can run on a background thread(s).
One way would be to abstract away a lot of the implementation to an`OperationQueue` [Ray Wenderlich](https://www.raywenderlich.com/76341/use-nsoperation-nsoperationqueue-swift) has a couple tutorials on how this works. This particular one was written for Swift 1.2, however the principles for `Operation` are there.
Upvotes: -1 |
2018/03/20 | 474 | 1,667 | <issue_start>username_0: I have two dataframes, called Old and New. Old has 96 rows, and New has 48 rows. I want to take one column of Old, say `['Values']` and split it into two columns in New, say `['First']` and `['Second']`. Thus, for a simple example with 6 rows to start; from:
```
Values
1 10
2 20
3 30
4 40
5 50
6 60
```
to
```
First Second
1 10 40
2 20 50
3 30 60
```
I have a notion that this should be trivially easy, and yet I can't do it because the indices need to be changed. I simply want to copy values, as you see.
How is this best done?<issue_comment>username_1: You are loading an image at a time while the tableviewcell is scrolling. There is some time to call the service and then wait for the response to be returned, thus affecting the scrolling although it is on another thread.
You can try calling the images in batches of maybe 10 or 20 at a time.
Upvotes: 1 [selected_answer]<issue_comment>username_2: **TL/DR:**
Learn to write better code.
For starters, there's no way `tableView(:cellForRowAt:)` can accomplish all that work in under 16 milliseconds. I think you should reconsider your app structure and architecture for starters. It would serve your app better to abstract the networking calls to an API that can run on a background thread(s).
One way would be to abstract away a lot of the implementation to an`OperationQueue` [Ray Wenderlich](https://www.raywenderlich.com/76341/use-nsoperation-nsoperationqueue-swift) has a couple tutorials on how this works. This particular one was written for Swift 1.2, however the principles for `Operation` are there.
Upvotes: -1 |
2018/03/20 | 871 | 3,218 | <issue_start>username_0: **The TL;DR version**
I'd like to know:
* Where does the specification for the use of ECDHE get defined (in a cert parameter or a server configuration of SSL contexts, or elsewhere)?
* In a non-home-rolled certificate setup, who's responsibility is it to define the ECDHE public and private information (the end user or cert provider)?
* Can an existing Certificate which does not appear to use ECDHE be made to without causing issues with the Certificate?
* Are there any examples of someone using SSL in Boost::ASIO with an ECDHE setup?
**The Longer Version**
We've been building an application which is using a proper-paid-for certificate from an external Cert Authority. The application uses a home-rolled server setup based off of Boost ASIO and Boost Beast, and we only recently noticed it doesn't play nice with iOS - ASIO says there is no shared cipher.
Reading into how TLS works has led me to the fact that some part of our server was preventing us from serving TLS using the ECDHE-\* suite of ciphers (which iOS seems to want) - but I'm having difficulty in figuring out how to wrangle ASIO and our current cert/key into serving ECDHE.
What I've tried:
* Using the same cert and key, adding in the results of `openssl dhparam` into ASIO using [set\_tmp\_dh](http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference/ssl__context/use_tmp_dh.html), then specifying ciphers. Curl reports that this allows a connection using `DHE` but not `ECDHE`. Specifying ciphers that only use `ECDHE` causes errors when connecting.
* Trying to pass the output of `openssl ecparam` to ASIO using a similar method to the above. I've not been able to format something that ASIO accepts.
* Trying to see if there is a way you can use the output of `openssl ecparam` with another combining function to modify the original cert into one that uses `ECDHE`. I clued onto this one from [the OpenSSL wiki](https://wiki.openssl.org/index.php/Elliptic_Curve_Diffie_Hellman) suggesting that if the cert does not contain the line `ASN1 OID: prime256v1` (or a similar named curve), then it is not suitable for ECDHE usage.
At this point I'm unsure as to where the issue truly lies (in ASIO, in the certificates or in how I'm putting it all together) and most of the information on the internet I can find relates to home-rolling everything from scratch, rather than working with existing certs.<issue_comment>username_1: **Update 11/05/19**
<https://github.com/chriskohlhoff/asio/pull/117> pulled in changes for ASIO with ECDHE. Will need to wait a while to see which Boost lib version it makes it into.
*Original Answer*
I seem to have found an answer for any googlers - ASIO does not appear to support ECDHE natively at the time of writing. [This issue](https://github.com/chriskohlhoff/asio/issues/116) from the main repo suggests that ECDHE is on the cards for support but is not yet implemented.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Here is a link to the ECDHE implementation that's been waiting to be merged since 2016: <https://github.com/chriskohlhoff/asio/pull/117>.
+1 to get the attention of the Boost ASIO maintainer; he's been pretty slow with it.
Upvotes: 0 |
2018/03/20 | 673 | 2,726 | <issue_start>username_0: I have a spark streaming job with a batch interval of 2 mins(configurable).
This job reads from a Kafka topic and creates a Dataset and applies a schema on top of it and inserts these records into the Hive table.
The Spark Job creates one file per batch interval in the Hive partition like below:
dataset.coalesce(1).write().mode(SaveMode.Append).insertInto(targetEntityName);
Now the data that comes in is not that big, and if I increase the batch duration to maybe 10mins or so, then even I might end up getting only 2-3mb of data, which is way less than the block size.
This is the expected behaviour in Spark Streaming.
I am looking for efficient ways to do a post processing to merge all these small files and create one big file.
If anyone's done it before, please share your ideas.<issue_comment>username_1: I would encourage you to not use Spark to stream data from Kafka to HDFS.
[Kafka Connect HDFS](https://docs.confluent.io/kafka-connectors/hdfs/current/overview.html) Plugin by Confluent (or Apache Gobblin by LinkedIn) exist for this very purpose. Both offer Hive integration.
Find my comments about compaction of small files in [this Github issue](https://github.com/confluentinc/kafka-connect-hdfs/issues/271)
If you need to write Spark code to process Kafka data into a schema, then you can still do that, and write into another topic in (preferably) Avro format, which Hive can easily read without a predefined table schema
I personally have written a "compaction" process that actually grabs a bunch of hourly Avro data partitions from a Hive table, then converts into daily Parquet partitioned table for analytics. It's been working great so far.
If you want to batch the records before they land on HDFS, that's where Kafka Connect or Apache Nifi (mentioned in the link) can help, given that you have enough memory to store records before they are flushed to HDFS
Upvotes: 3 <issue_comment>username_2: I have exactly the same situation as you. I solved it by:
Lets assume that your new coming data are stored in a dataset: dataset1
1- Partition the table with a good partition key, in my case I have found that I can partition using a combination of keys to have around 100MB per partition.
2- Save using spark core not using spark sql:
a- load the whole partition in you memory (inside a dataset: dataset2) when you want to save
b- Then apply dataset union function: `dataset3 = dataset1.union(dataset2)`
c- make sure that the resulted dataset is partitioned as you wish e.g: `dataset3.repartition(1)`
d - save the resulting dataset in "OverWrite" mode to replace the existing file
If you need more details about any step please reach out.
Upvotes: 1 |
2018/03/20 | 821 | 3,137 | <issue_start>username_0: I am trying to determine if a MTLTexture (in bgra8Unorm format) is blank by calculating the sum of all the R G B and A components of each of its pixels.
This function intends to do this by adding adjacent floats in memory after a texture has been copied to a pointer. However I have determined that this function ends up returning false nomatter the MTLTexture given.
What is wrong with this function?
```
func anythingHere(_ texture: MTLTexture) -> Bool {
let width = texture.width
let height = texture.height
let bytesPerRow = width * 4
let data = UnsafeMutableRawPointer.allocate(bytes: bytesPerRow * height, alignedTo: 4)
defer {
data.deallocate(bytes: bytesPerRow * height, alignedTo: 4)
}
let region = MTLRegionMake2D(0, 0, width, height)
texture.getBytes(data, bytesPerRow: bytesPerRow, from: region, mipmapLevel: 0)
var bind = data.assumingMemoryBound(to: UInt8.self)
var sum:UInt8 = 0;
for i in 0..
```<issue_comment>username_1: Didn't look in detail at the rest of the code, but I think this,
```
bind.advanced(by: 1)
```
should be:
```
bind = bind.advanced(by: 1)
```
Upvotes: 1 <issue_comment>username_2: Matthijs' change is necessary, but there are also a couple of other issues with the correctness of this method.
You're actually only iterating over 1/4 of the pixels, since you're stepping byte-wise and the upper bound of your loop is `width * height` rather than `bytesPerRow * height`.
Additionally, computing the sum of the pixels doesn't really seem like what you want. You can save some work by returning true as soon as you encounter a non-zero value (`if bind.pointee != 0`).
(Incidentally, Swift's integer overflow protection will actually raise an exception if you accumulate a value greater than 255 into a `UInt8`. I suppose you could use a bigger integer, or disable overflow checking with `sum = sum &+ bind.pointee`, but again, breaking the loop on the first non-clear pixel will save some time and prevent false positives when the accumulator "rolls over" to exactly 0.)
Here's a version of your function that worked for me:
```
func anythingHere(_ texture: MTLTexture) -> Bool {
let width = texture.width
let height = texture.height
let bytesPerRow = width * 4
let data = UnsafeMutableRawPointer.allocate(byteCount: bytesPerRow * height, alignment: 4)
defer {
data.deallocate()
}
let region = MTLRegionMake2D(0, 0, width, height)
texture.getBytes(data, bytesPerRow: bytesPerRow, from: region, mipmapLevel: 0)
var bind = data.assumingMemoryBound(to: UInt8.self)
for _ in 0..
```
Keep in mind that on macOS, the default `storageMode` for textures is `managed`, which means their contents aren't automatically synchronized back to main memory when they're modified on the GPU. You must explicitly use a blit command encoder to sync the contents yourself:
```
let syncEncoder = buffer.makeBlitCommandEncoder()!
syncEncoder.synchronize(resource: texture)
syncEncoder.endEncoding()
```
Upvotes: 4 [selected_answer] |
2018/03/20 | 608 | 2,380 | <issue_start>username_0: In Python3.6, I use threading.local() to store some status for thread.
Here is a simple example to explain my question:
```
import threading
class Test(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.local = threading.local()
self.local.test = 123
def run(self):
print(self.local.test)
```
When I start this thread:
```
t = Test()
t.start()
```
Python gives me an error:
```
AttributeError: '_thread._local' object has no attribute 'test'
```
It seems the **test** atrribute can not access out of the **\_\_init\_\_** function scope, because I can print the value in the **\_\_init\_\_** function after local set attribute **test=123**.
Is it necessary to use threading.local object inside in a Thread subclass? I think the instance attributes of a Thread instance could keep the attributes thread safe.
Anyway, **why the threading.local object not work as expected between instance function?**<issue_comment>username_1: When you constructed your thread you were using a DIFFERENT thread. when you execute the run method on the thread you are starting a NEW thread. that thread does not yet have a thread local variable set. this is why you do not have your attribute it was set on the thread constructing the thread object and not the thread running the object.
Upvotes: 2 <issue_comment>username_2: As stated in <https://docs.python.org/3.6/library/threading.html#thread-local-data>:
>
> The instance’s values will be different for separate threads.
>
>
>
`Test.__init__` executes in the caller's thread (e.g. the thread where `t = Test()` executes). Yes, it's good place to *create* thread-local storage (TLS).
But when `t.run` executes, it will have completely diffferent contents -- *the contents accessible only within the thread `t`*.
TLS is good when You need to share data in scope of current thread. It like just a local variable inside a function -- but for threads. When the thread finishes execution -- TLS disappears.
For inter-thread communication [Futures](https://docs.python.org/3/library/concurrent.futures.html) can be a good choice. Some others are *Conditional variables*, *events*, etc. See [threading](https://docs.python.org/3.6/library/threading.html#event-objects) docs page.
Upvotes: 3 [selected_answer] |
2018/03/20 | 418 | 1,561 | <issue_start>username_0: I want to use recursion to calculate the sum of the list values, but there is an error when using the sum2 function: TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
```
def sum(list):
if list == []:
return 0
else:
return list[0] + sum(list[1:])
print(sum([1,2,3]))
def sum2(list):
if list == []:
return 0
else:
print(list[0] + sum(list[1:]))
sum([1,2,3])
```<issue_comment>username_1: `print()` sends output to your console via standard output. `return` sends output to whatever called your function. If you want to use recursion, you need to use a return statement, not `print()`.
Here's an example:
```
def sum2(l):
if l == []:
return 0
else:
return l[0] + sum2(l[1:])
sum2([1, 2, 3])
# 6
```
This is recursive because the return statement contains a call to the function itself. Generally, a good thing to learn about in a computer science class but a bad thing to do in production code.
Upvotes: 2 [selected_answer]<issue_comment>username_2: I didn't understand what's your requirement by looking in to your code, but as I understood you need to know the difference between **print** and **return** .
`print` is a function which requires a print description and printing variables or object. This function will helps the developer to debug and check the console output. Where as `return` is a keyword and this will be used in any function or method to return some value from that function or method to it's caller .
Upvotes: 0 |
2018/03/20 | 458 | 1,753 | <issue_start>username_0: I am going to implement the validation in angular 4.
I've already have a solution but need simple and clean code.
Here is my code.
* mobile-auth.component.ts
```
this.appForm = fb.group({
'otp': ['', Validators.compose([Validators.required, ValidationService.digit4Validator])],
});
```
* validation.service.ts
```
...
static digit4Validator(control) {
if (control.value) {
if (control.value.match(/^\d+/) && control.value.length === 4) {
return null;
} else {
return {'invalid4DigitCode': true};
}
}
}
...
```
If you have any good solution please let me know.<issue_comment>username_1: `print()` sends output to your console via standard output. `return` sends output to whatever called your function. If you want to use recursion, you need to use a return statement, not `print()`.
Here's an example:
```
def sum2(l):
if l == []:
return 0
else:
return l[0] + sum2(l[1:])
sum2([1, 2, 3])
# 6
```
This is recursive because the return statement contains a call to the function itself. Generally, a good thing to learn about in a computer science class but a bad thing to do in production code.
Upvotes: 2 [selected_answer]<issue_comment>username_2: I didn't understand what's your requirement by looking in to your code, but as I understood you need to know the difference between **print** and **return** .
`print` is a function which requires a print description and printing variables or object. This function will helps the developer to debug and check the console output. Where as `return` is a keyword and this will be used in any function or method to return some value from that function or method to it's caller .
Upvotes: 0 |
2018/03/20 | 549 | 2,072 | <issue_start>username_0: I've been stuck on this for a while. Does anyone have an idea on why I keep on getting a Signal Abort (SIGABRT) in Xcode with the following code? I'm using Fuse Tools to create my app and what this block does is re-size an image before uploading. The error is on the third line down where `imageFileURL` is. I also included a screenshot. Any help is appreciated.
```
+(NSArray*) getImageSize:(NSString*)path {
CGFloat width = 0.0f, height = 0.0f;
NSURL *imageFileURL = [NSURL fileURLWithPath:path];
CFURLRef url = (__bridge CFURLRef) imageFileURL;
CGImageSourceRef imageSource = CGImageSourceCreateWithURL(url, nil);
if (imageSource == nil) {
return @[ @( 0 ), @( 0 )];
}
CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil);
CFRelease(imageSource);
```
[](https://i.stack.imgur.com/Xzq5l.png)<issue_comment>username_1: `print()` sends output to your console via standard output. `return` sends output to whatever called your function. If you want to use recursion, you need to use a return statement, not `print()`.
Here's an example:
```
def sum2(l):
if l == []:
return 0
else:
return l[0] + sum2(l[1:])
sum2([1, 2, 3])
# 6
```
This is recursive because the return statement contains a call to the function itself. Generally, a good thing to learn about in a computer science class but a bad thing to do in production code.
Upvotes: 2 [selected_answer]<issue_comment>username_2: I didn't understand what's your requirement by looking in to your code, but as I understood you need to know the difference between **print** and **return** .
`print` is a function which requires a print description and printing variables or object. This function will helps the developer to debug and check the console output. Where as `return` is a keyword and this will be used in any function or method to return some value from that function or method to it's caller .
Upvotes: 0 |
2018/03/20 | 1,322 | 5,649 | <issue_start>username_0: We're moving all of our infrastructure to Google Kubernetes Engine (GKE) - we currently have 50+ AWS machines with lots of APIs, Services, Webapps, Database servers and more.
As we have already dockerized everything, it's time to start moving everything to GKE.
I have a question that may sound too basic, but I've been searching the Internet for a week and did not found any reasonable post about this
Straight to the point, which of the following approaches is better and why:
1. Having multiple node pools with multiple machine types and always specify in which pool each deployment should be done; or
2. Having a single pool with lots of machines and let Kubernetes scheduler do the job without worrying about where my deployments will be done; or
3. Having BIG machines (in multiple zones to improve clusters' availability and resilience) and let Kubernetes deploy everything there.<issue_comment>username_1: 1) makes a lot of sense as if you want, you can still allow kube deployments treat it as one large pool (by not adding nodeSelector/NodeAffinity) but you can have different machines of different sizes, you can think about having a pool of spot instances, etc. And, after all, you can have pools that are tainted and so forth excluded from normal scheduling and available to only a particular set of workloads. It is in my opinion preferred to have some proficiency with this approach from the very beginning, yet in case of many provisioners it should be very easy to migrate from 2) to 1) anyway.
2) As explained above, it's effectively a subset of 1) so better to build up exp with 1) approach from day 1, but if you ensure your provisioning solution supports easy extension to 1) model then you can get away with starting with this simplified approach.
3) Big is nice, but "big" is relative. It depends on the requirements and amount of your workloads. Remember that while you need to plan for loss of a whole AZ anyway, it will be much more frequent to loose single nodes (reboots, decommissions of underlying hardware, updates etc.) so if you have more hosts, impact of loosing one will be smaller. Bottom line is that you need to find your own balance, that makes sense for your particular scale. Maybe 50 nodes is too much, would 15 cut it? Who knows but you :)
Upvotes: 2 <issue_comment>username_2: List of consideration to be taken merely as hints, I do not pretend to describe best practice.
----------------------------------------------------------------------------------------------
* Each pod you add brings with it some **overhead**, but you increase in terms of flexibility and availability making failure and maintenance of nodes to be less impacting the production.
* Nodes too small would cause a big waste of resources since sometimes will be not possible to schedule a pod even if the total amount of free RAM or CPU across the nodes would be enough, you can see this issue similar to memory **fragmentation**.
* I guess that the sizes of PODs and their memory and CPU request are not similar, but I do not see this as a big issue in principle and a reason to go for 1). I do not see why a big POD should run merely on big machines and a small one should be scheduled on small nodes. **I would rather use 1) if you need a different memoryGB/CPUcores ratio to support different workloads.**
I would advise you to run some test in the initial phase to understand which is the size of the biggest POD and the average size of the workload in order to properly chose the machine types. Consider that having 1 POD that exactly fit in one node and assign to it is not the right to proceed(virtual machine exist for this kind of scenario). Since fragmentation of resources would easily cause to impossibility to schedule a large node.
* Consider that their size will likely increase in the future and to [scale vertically](https://stackoverflow.com/questions/45037213/how-to-vertically-scale-google-cloud-instance-without-stopping-running-app) is not always this immediate and you need to switch off machine and terminate pods, I would **oversize a bit** taking this issue into account and since scaling horizontally is way easier.
* Talking about the machine type you can decide to go for a machine 5xsize the biggest POD you have (or 3x? or 10x?). **Oversize a bit** as well the numebr of nodes of the cluster to take into account overheads, fragmentation and in order to still have free resources.
1. >
> Remember that you have an hard limit of 100 pods each node and 5000 nodes.
>
>
>
2. >
> [Remember](https://cloud.google.com/compute/docs/networks-and-firewalls#egress_throughput_caps) that in GCP the network egress throughput cap is dependent on the number of vCPUs that a virtual machine instance has. Each vCPU has a 2 Gbps egress cap for peak performance. However each additional vCPU increases the network cap, up to a theoretical maximum of 16 Gbps for each virtual machine.
>
>
>
3. >
> Regarding the prices of the virtual machines notice that there is no difference in price buying two machines with size x or one with size 2x. Avoid to customise the size of machines because rarely is convenient, if you feel like your workload needs more cpu or mem go for HighMem or HighCpu machine type.
>
>
>
P.S. Since you are going to build a pretty big Cluster, check the [size of the DNS](https://kubernetes.io/docs/tasks/administer-cluster/dns-horizontal-autoscaling/)
I will add any consideration that it comes to my mind, consider in the future to update your question with the description of the path you chose and the issue you faced.
Upvotes: 3 |
2018/03/20 | 539 | 1,909 | <issue_start>username_0: I am trying to upload an image to be stored in a database on mysql however I keep receiving an error:
>
> Notice: Undefined index: profilepic in >[php-path]/tuto>rsignupsubmit.php on line 17
>
>
>
There is a simple button upload of type file on a form:
```
Profile Picture
```
I then have this code on another submit page, I am quite new to PHP however I have searched and searched and cannot find a solution anywhere.
```
//File upload
$target_dir = "../img/";
$newprofilepic = $target_dir . basename($_FILES ["profilepic"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($newprofilepic,PATHINFO_EXTENSION));
$newlocation = mysqli_real_escape_string($conn,$_POST['location']);
$insertquery = "INSERT INTO tutors(name, username, password, email, mobile,
profilepic, location,
message)"."VALUES('$newname','$newusername','$newpassword','$newemail',
'$newmobile', '$newprofilepic', '$newlocation', '$newmessage')";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
mysqli_close($conn);
```
Thanks in advance.<issue_comment>username_1: I've tried to reproduce this error. Here is my code
```
Profile Picture
$target_dir = "../img/";
$newprofilepic = $target_dir . basename($_FILES["profilepic"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($newprofilepic, PATHINFO_EXTENSION));
```
And this error doesn't appear for me. Are you using `enctype="multipar/form-data"` in your form tag?
This error can appear if this key doesn't exist in your `$_FILES` array. Please check it using `var_dump($_FILES);`
Upvotes: 1 <issue_comment>username_2: Undefined index: is a common error when you are calling an element of an array or object but that element does not exist. For example if in the below $\_FILES array there is no "profilepic" element you would get this error.
$\_FILES ["profilepic"]["name"]
Upvotes: 0 |
2018/03/20 | 1,033 | 3,471 | <issue_start>username_0: I managed to apply swagger ui on Spring boot application and was able to open the page using <http://localhost:8181/swagger-ui.html>
After some time i kept working on my application and now its gone. i did not remove any jars. i added an Application Startup class which is used to load some things at startup as i was deploying on Wildfly 10.
Even if i try to run it as Spring boot app with tomcat it does not work. I am not sure what I changed that this stopped coming all of a sudden.
I can open /swagger-resources/configuration/ui and /swagger-resources/configuration/security and /swagger/api-docs ( i put my springfox.documenation.swagger.v2.path as /myapp/swagger/api-docs)
when i hit
i get this in logs
```
2018-03-20 13:01:22.130 DEBUG 9928 --- [0.1-8181-exec-5] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/swagger-ui.html]
2018-03-20 13:01:22.131 DEBUG 9928 --- [0.1-8181-exec-5] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /swagger-ui.html
2018-03-20 13:01:22.131 DEBUG 9928 --- [0.1-8181-exec-5] .m.m.a.ExceptionHandlerExceptionResolver : Resolving exception from handler [null]: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
2018-03-20 13:01:22.131 DEBUG 9928 --- [0.1-8181-exec-5] .w.s.m.a.ResponseStatusExceptionResolver : Resolving exception from handler [null]: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
2018-03-20 13:01:22.132 DEBUG 9928 --- [0.1-8181-exec-5] .w.s.m.s.DefaultHandlerExceptionResolver : Resolving exception from handler [null]: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
2018-03-20 13:01:22.132 DEBUG 9928 --- [0.1-8181-exec-5] o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2018-03-20 13:01:22.132 DEBUG 9928 --- [0.1-8181-exec-5] o.s.web.servlet.DispatcherServlet : Successfully completed request
```<issue_comment>username_1: the issue was that I had a Controller with a RequestMapping("/myapp") on class
as this was also a Wildfly application I have a jboss-web.xml with the same value in contextroot
now when i deployed on WF 10 . my context root became /myapp/myapp in order to hit the controller otherwise it wont hit the controller. So i removed it from the Controller and whenever I goto swagger-ui.html it would go through the controller and ( as the logs said) not find any handler for /swagger-ui.html)
Upvotes: 0 <issue_comment>username_2: * It might be the swagger-UI dependency is not present that's why it is
not able to load the Swagger UI.
Please Add the dependency in pom.xml
```
io.springfox
springfox-swagger-ui
2.5.0
```
After that use the swagger configuration so that it can enable swagger.
```
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
```
Upvotes: 1 |
2018/03/20 | 377 | 1,584 | <issue_start>username_0: In the cmdb\_rel\_ci table, I want to retrieve the value and total count of all the unique parent.sys\_class\_name values for Type(cmdb\_rel\_type) "Depends on::Used by".
I was trying to use with GlideAggregate, but classname is showing empty.
Can anyone offer some advice?<issue_comment>username_1: the issue was that I had a Controller with a RequestMapping("/myapp") on class
as this was also a Wildfly application I have a jboss-web.xml with the same value in contextroot
now when i deployed on WF 10 . my context root became /myapp/myapp in order to hit the controller otherwise it wont hit the controller. So i removed it from the Controller and whenever I goto swagger-ui.html it would go through the controller and ( as the logs said) not find any handler for /swagger-ui.html)
Upvotes: 0 <issue_comment>username_2: * It might be the swagger-UI dependency is not present that's why it is
not able to load the Swagger UI.
Please Add the dependency in pom.xml
```
io.springfox
springfox-swagger-ui
2.5.0
```
After that use the swagger configuration so that it can enable swagger.
```
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
```
Upvotes: 1 |
2018/03/20 | 1,013 | 2,708 | <issue_start>username_0: Yet another problem.
This time I think because the tag is used twice in the same message, nested.
I have no issue retrieving other items with unique labels (like `requestDateTime`, `statusDateTime` and `completedStateEnteredDate`), but I can't successfully grab the reference number, or the status (which is inside status) or the type (again, inside another tag).
So I know my namespace works, just can't work out how to get the data I need.
Specifically, I need to capture that numeric value in the `6000526` part. The data does return multiple SOM numbers, so the bonus would be how do I capture more than one (like the first 2 or 5 would be cool).
```
true
26
11
57
22
7
57
true
11567
11657
11667
11657
098453520
2017-04-11T10:08:01+12:00
6000526
GC and LC Complete
2017-04-11T10:09:09+12:00
Port
2017-04-11T10:09:09+12:00
```<issue_comment>username_1: Use this XPath expression to get the result desired:
```
/return/networkUpdateList/som/som
```
**Result:**
```
6000526
```
This even works for multiple element children of different `networkUpdateList` nodes.
Upvotes: 2 <issue_comment>username_2: I staggered upon the solution, works for all duplicated names:
//som/som does the job.
As does //status/status and //type/type so I am a happy camper.
I just don't know how to pick up the next occurrence within the response, but I don't desperately need that, I can just loop.
Edit: Also discovered that
`(//som/som) [2]`
Returns the second occurence, and that (//som/som) [1] returns the first, etc. Very simple and good to know.
Discovered here: <https://msdn.microsoft.com/en-us/library/ms256086(v=vs.110).aspx>
Upvotes: 1 [selected_answer]<issue_comment>username_3: Create a Script assertion and use the following code:
```
// create groovyUtils and XmlHolder for response of Request 1 request
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def holder = groovyUtils.getXmlHolder( "SOAP Request#Response" )
// loop item nodes in response message
for( item in holder.getNodeValues( "//som/som" ))
log.info "Item : [$item]"
```
This should print out all the values for each node that that follows the XPath. In the script Assertion Log should output in the following format:
>
> Wed Mar 21 14:46:14 GMT 2018:INFO:Item : [0.69]
>
>
> Wed Mar 21 14:46:14 GMT 2018:INFO:Item : [4.14]
>
>
> Wed Mar 21 14:46:14 GMT 2018:INFO:Item : [0.69]
>
>
> Wed Mar 21 14:46:14 GMT 2018:INFO:Item : [0.69]
>
>
> Wed Mar 21 14:46:14 GMT 2018:INFO:Item : [1.6]
>
>
> Wed Mar 21 14:46:14 GMT 2018:INFO:Item : [3.45]
>
>
> Wed Mar 21 14:46:14 GMT 2018:INFO:Item : [1.85]
>
>
>
Upvotes: 0 |
2018/03/20 | 735 | 2,006 | <issue_start>username_0: I need to construct an instance of SAMLObject from a SAML message string. After having a look at the OpenSAML APIs, I can't figure how it can be done.
Any advice?<issue_comment>username_1: Use this XPath expression to get the result desired:
```
/return/networkUpdateList/som/som
```
**Result:**
```
6000526
```
This even works for multiple element children of different `networkUpdateList` nodes.
Upvotes: 2 <issue_comment>username_2: I staggered upon the solution, works for all duplicated names:
//som/som does the job.
As does //status/status and //type/type so I am a happy camper.
I just don't know how to pick up the next occurrence within the response, but I don't desperately need that, I can just loop.
Edit: Also discovered that
`(//som/som) [2]`
Returns the second occurence, and that (//som/som) [1] returns the first, etc. Very simple and good to know.
Discovered here: <https://msdn.microsoft.com/en-us/library/ms256086(v=vs.110).aspx>
Upvotes: 1 [selected_answer]<issue_comment>username_3: Create a Script assertion and use the following code:
```
// create groovyUtils and XmlHolder for response of Request 1 request
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def holder = groovyUtils.getXmlHolder( "SOAP Request#Response" )
// loop item nodes in response message
for( item in holder.getNodeValues( "//som/som" ))
log.info "Item : [$item]"
```
This should print out all the values for each node that that follows the XPath. In the script Assertion Log should output in the following format:
>
> Wed Mar 21 14:46:14 GMT 2018:INFO:Item : [0.69]
>
>
> Wed Mar 21 14:46:14 GMT 2018:INFO:Item : [4.14]
>
>
> Wed Mar 21 14:46:14 GMT 2018:INFO:Item : [0.69]
>
>
> Wed Mar 21 14:46:14 GMT 2018:INFO:Item : [0.69]
>
>
> Wed Mar 21 14:46:14 GMT 2018:INFO:Item : [1.6]
>
>
> Wed Mar 21 14:46:14 GMT 2018:INFO:Item : [3.45]
>
>
> Wed Mar 21 14:46:14 GMT 2018:INFO:Item : [1.85]
>
>
>
Upvotes: 0 |
2018/03/20 | 8,016 | 27,783 | <issue_start>username_0: I'm writing some software that analyzes registered domain names and looks for trends. I'm experimenting with some machine learning to help predict what domain names will be purchased in the future based on what types of domains are being registered.
I've been looking around searching for a way to download "all" of the registered domains that exist, but I haven't been able to find a way to do so.
It's easy for me to query individual domain names using the `whois` command line tool, for example:
```
$ whois google.com
Domain Name: GOOGLE.COM
Registry Domain ID: 2138514_DOMAIN_COM-VRSN
Registrar WHOIS Server: whois.markmonitor.com
Registrar URL: http://www.markmonitor.com
Updated Date: 2018-02-21T18:36:40Z
Creation Date: 1997-09-15T04:00:00Z
Registry Expiry Date: 2020-09-14T04:00:00Z
Registrar: MarkMonitor Inc.
Registrar IANA ID: 292
Registrar Abuse Contact Email: <EMAIL>
Registrar Abuse Contact Phone: +1.2083895740
Domain Status: clientDeleteProhibited https://icann.org/epp#clientDeleteProhibited
Domain Status: clientTransferProhibited https://icann.org/epp#clientTransferProhibited
Domain Status: clientUpdateProhibited https://icann.org/epp#clientUpdateProhibited
Domain Status: serverDeleteProhibited https://icann.org/epp#serverDeleteProhibited
Domain Status: serverTransferProhibited https://icann.org/epp#serverTransferProhibited
Domain Status: serverUpdateProhibited https://icann.org/epp#serverUpdateProhibited
Name Server: NS1.GOOGLE.COM
Name Server: NS2.GOOGLE.COM
Name Server: NS3.GOOGLE.COM
Name Server: NS4.GOOGLE.COM
DNSSEC: unsigned
URL of the ICANN Whois Inaccuracy Complaint Form: https://www.icann.org/wicf/
>>> Last update of whois database: 2018-03-20T03:16:59Z <<<
For more information on Whois status codes, please visit https://icann.org/epp
NOTICE: The expiration date displayed in this record is the date the
registrar's sponsorship of the domain name registration in the registry is
currently set to expire. This date does not necessarily reflect the expiration
date of the domain name registrant's agreement with the sponsoring
registrar. Users may consult the sponsoring registrar's Whois database to
view the registrar's reported date of expiration for this registration.
TERMS OF USE: You are not authorized to access or query our Whois
database through the use of electronic processes that are high-volume and
automated except as reasonably necessary to register domain names or
modify existing registrations; the Data in VeriSign Global Registry
Services' ("VeriSign") Whois database is provided by VeriSign for
information purposes only, and to assist persons in obtaining information
about or related to a domain name registration record. VeriSign does not
guarantee its accuracy. By submitting a Whois query, you agree to abide
by the following terms of use: You agree that you may use this Data only
for lawful purposes and that under no circumstances will you use this Data
to: (1) allow, enable, or otherwise support the transmission of mass
unsolicited, commercial advertising or solicitations via e-mail, telephone,
or facsimile; or (2) enable high volume, automated, electronic processes
that apply to VeriSign (or its computer systems). The compilation,
repackaging, dissemination or other use of this Data is expressly
prohibited without the prior written consent of VeriSign. You agree not to
use electronic processes that are automated and high-volume to access or
query the Whois database except as reasonably necessary to register
domain names or modify existing registrations. VeriSign reserves the right
to restrict your access to the Whois database in its sole discretion to ensure
operational stability. VeriSign may restrict or terminate your access to the
Whois database for failure to abide by these terms of use. VeriSign
reserves the right to modify these terms at any time.
The Registry database contains ONLY .COM, .NET, .EDU domains and
Registrars.
Domain Name: google.com
Registry Domain ID: 2138514_DOMAIN_COM-VRSN
Registrar WHOIS Server: whois.markmonitor.com
Registrar URL: http://www.markmonitor.com
Updated Date: 2018-02-21T10:45:07-0800
Creation Date: 1997-09-15T00:00:00-0700
Registrar Registration Expiration Date: 2020-09-13T21:00:00-0700
Registrar: MarkMonitor, Inc.
Registrar IANA ID: 292
Registrar Abuse Contact Email: <EMAIL>
Registrar Abuse Contact Phone: +1.2083895740
Domain Status: clientUpdateProhibited (https://www.icann.org/epp#clientUpdateProhibited)
Domain Status: clientTransferProhibited (https://www.icann.org/epp#clientTransferProhibited)
Domain Status: clientDeleteProhibited (https://www.icann.org/epp#clientDeleteProhibited)
Domain Status: serverUpdateProhibited (https://www.icann.org/epp#serverUpdateProhibited)
Domain Status: serverTransferProhibited (https://www.icann.org/epp#serverTransferProhibited)
Domain Status: serverDeleteProhibited (https://www.icann.org/epp#serverDeleteProhibited)
Registry Registrant ID:
Registrant Name: Domain Administrator
Registrant Organization: Google LLC
Registrant Street: 1600 Amphitheatre Parkway,
Registrant City: Mountain View
Registrant State/Province: CA
Registrant Postal Code: 94043
Registrant Country: US
Registrant Phone: +1.6502530000
Registrant Phone Ext:
Registrant Fax: +1.6502530001
Registrant Fax Ext:
Registrant Email: <EMAIL>
Registry Admin ID:
Admin Name: Domain Administrator
Admin Organization: Google LLC
Admin Street: 1600 Amphitheatre Parkway,
Admin City: Mountain View
Admin State/Province: CA
Admin Postal Code: 94043
Admin Country: US
Admin Phone: +1.6502530000
Admin Phone Ext:
Admin Fax: +1.6502530001
Admin Fax Ext:
Admin Email: <EMAIL>
Registry Tech ID:
Tech Name: Domain Administrator
Tech Organization: Google LLC
Tech Street: 1600 Amphitheatre Parkway,
Tech City: Mountain View
Tech State/Province: CA
Tech Postal Code: 94043
Tech Country: US
Tech Phone: +1.6502530000
Tech Phone Ext:
Tech Fax: +1.6502530001
Tech Fax Ext:
Tech Email: <EMAIL>
Name Server: ns1.google.com
Name Server: ns4.google.com
Name Server: ns2.google.com
Name Server: ns3.google.com
DNSSEC: unsigned
URL of the ICANN WHOIS Data Problem Reporting System: http://wdprs.internic.net/
>>> Last update of WHOIS database: 2018-03-19T20:13:36-0700 <<<
The Data in MarkMonitor.com's WHOIS database is provided by MarkMonitor.com for
information purposes, and to assist persons in obtaining information about or
related to a domain name registration record. MarkMonitor.com does not guarantee
its accuracy. By submitting a WHOIS query, you agree that you will use this Data
only for lawful purposes and that, under no circumstances will you use this Data to:
(1) allow, enable, or otherwise support the transmission of mass unsolicited,
commercial advertising or solicitations via e-mail (spam); or
(2) enable high volume, automated, electronic processes that apply to
MarkMonitor.com (or its systems).
MarkMonitor.com reserves the right to modify these terms at any time.
By submitting this query, you agree to abide by this policy.
MarkMonitor is the Global Leader in Online Brand Protection.
MarkMonitor Domain Management(TM)
MarkMonitor Brand Protection(TM)
MarkMonitor AntiPiracy(TM)
MarkMonitor AntiFraud(TM)
Professional and Managed Services
Visit MarkMonitor at http://www.markmonitor.com
Contact us at +1.8007459229
In Europe, at +44.02032062220
For more information on Whois status codes, please visit
https://www.icann.org/resources/pages/epp-status-codes-2014-06-16-en
--
```
The WHOIS data contains everything I need, but I can't find a way to download the WHOIS data for *all* currently registered domains.
Is there some way for me to get this data? I feel like it must be publicly available somewhere since the `whois` CLI tool can so easily query the info.
What am I missing here?<issue_comment>username_1: TL;DR: You can not (download all "whois" data).
(side preliminary note: "whois data", while often used is kind of incorrect. You use the whois protocol with a whois client to query a whois server at a registry, and more specifically here a domain name registry, that stores contact data about domain names it sponsors. For the same reason there is no "whois database".)
Now for the long sad story:
It is not possible for many obvious technical and non technical reasons. And you are **deeply** mistaken if you think the `whois` CLI command is simple (see my other answer here: <https://unix.stackexchange.com/a/407030/211833> for details on that point)
First your question makes no sense for all TLDs at once. You have at least to separate ccTLDs from gTLDs.
1) **ccTLDs**
ccTLDs have often stricter rules about privacy on personal data and this ought to be even stricter with ongoing European regulations such as GDPR.
Basically some of them already forbid to have access to the complete list of domain names (which is often refered as the "zonefile") which has no personal data, so there is no way you will get access to all the content and the personal data.
You may try to approach some and ask if there is anything possible like for research studies, but I doubt you will be successful and you will need to deal with each ccTLD registry separately as they each deal with their own content (all data on the domain names in the TLD they manage)
2) **gTLDs**
For them, the situation is quite different.
First, since things are by default more liberal (no protection of personal data), you will see that many registrars/companies provide proxy/privacy services which means that even in a whois query output you will not see much useful data.
But still due to GDPR and assimilated, things are changing. Do a whois on `godaddy.com` for example and watch all these stars for contact names and emails, and hence the need to go to a website.
However registrars and registries are under contract with ICANN. Which means they both have some requirements, and they are uniform.
First, all registries are mandated to give access to their zonefiles. It is often done throught the CZDA, for which you can find details on ICANN website. Note that it is in fact the list of all domain names publishes, not exactly the list of all domain names registered as you can register a domain name and not put it visible on the DNS.
As for the contact data, that is the rest of the information visible in whois, there are other points not wellknown.
See the registrar agreement at <https://www.icann.org/resources/pages/approved-with-specs-2013-09-17-en> and specially section 3.3.6 that provide bulk acces to registrar "whois" data. Note how it is tied to some money (USD$10 000) and comes with various limitations on what you can do with it.
Remember that you would need to do it **per registrar**, so in the gTLDs world that is more than 1000 of them.
There is no equivalent provisions in the registry agreements for public bulk access (see <https://newgtlds.icann.org/sites/default/files/agreements/agreement-approved-31jul17-en.html>).
Things are complicated because as up today and for some months yet, `.COM/.NET` remains a thin registry that is one without the contact data stored at registry level, only at registrars.
Also all the above will change in the coming months/years because of the new regulations and also because RDAP, a new protocol, is slated to replace whois at one point. RDAP will allow far greater level of granularity on the access given and the amount of data returned.
Of course, in all cases above, nothing technically forbids anyone to just do regular whois queries and store the results locally. As you can see in a whois output your use of the data is constrained by various limits and bulk querying whois servers always expose you to the risk of being blacklisted or at least heavily rate limited.
Note that for the input (which names to query the whois server for), it is easy to start with zonefiles, even cross TLDs (if `site.example` exists you can try also `site.test` even if you do not have `.test` zonefile), or search engines queries, or dictionaries, etc.
Multiple companies do that and provide tools to search their data, like to do reverse queries and things like that. Maybe some could deliver you bulk results, but certainly not for free.
Upvotes: 4 [selected_answer]<issue_comment>username_2: This website allows to download lists of registered domain names: <https://networksdb.io> .
Some are free, some are paid for. It allows also to access aggregates WHOIS data for IP blocks to find which companies own what address blocks and the other way around.
Upvotes: -1 <issue_comment>username_3: You can get the Whois record for millions of the registered domains (Active & Inactive) by using WhoisFreaks Database. <https://whoisfreaks.com/>. It provides well-parsed Whois domain information such as domain registration details, domain registrar details, registrant details, administrative contact, technical contact, server names, domain status, registry data, etc.
* WhoisFreaks Database is One of the biggest whois databases with whois
information for 1000+ TLDs (gTLDs & ccTLDs), 422M+ tracked domains,
555M+ whois records.
* Well parsed and normalized whois data records which are available in
CSV file format easy to read and integrate into any business system.
* Accurate and updated, the WhoisFreaks database is updated on the
daily basis.
* WhoisFreaks database provides whois records from 1986.
* Custom whois domain data is also available on the basis of Registrant
Specific Domains, Country-Specific Domains, and TLDs Specific
Domains.
* Over 4.5 Million domains are registered each month.
* WhoisFreaks database contains only unique Whois records of the
domains.
**WhoisFreaks JSON response looks like this:**
```
{
"status": true,
"domain_name": "google.com",
"query_time": "2021-03-12 08:03:53",
"whois_server": "whois.markmonitor.com",
"domain_registered": "yes",
"create_date": "1997-09-15",
"update_date": "2019-09-09",
"expiry_date": "2028-09-13",
"domain_registrar": {
"iana_id": "292",
"registrar_name": "MarkMonitor, Inc.",
"whois_server": "whois.markmonitor.com",
"website_url": "http://www.markmonitor.com",
"email_address": "<EMAIL>",
"phone_number": "+1.2083895770"
},
"registrant_contact": {
"company": "Google LLC",
"state": "CA",
"country_name": "United States",
"country_code": "US",
"email_address": "Select Request Email Form at https://domains.markmonitor.com/whois/google.com"
},
"administrative_contact": {
"company": "Google LLC",
"state": "CA",
"country_name": "United States",
"country_code": "US",
"email_address": "Select Request Email Form at https://domains.markmonitor.com/whois/google.com"
},
"technical_contact": {
"company": "Google LLC",
"state": "CA",
"country_name": "United States",
"country_code": "US",
"email_address": "Select Request Email Form at https://domains.markmonitor.com/whois/google.com"
},
"name_servers": [
"ns1.google.com",
"ns2.google.com",
"ns3.google.com",
"ns4.google.com"
],
"domain_status": [
"clientTransferProhibited",
"clientDeleteProhibited",
"serverDeleteProhibited",
"serverTransferProhibited",
"serverUpdateProhibited",
"clientUpdateProhibited"
],
"whois_raw_domain": "\nDomain Name: google.com\nRegistry Domain ID: 2138514_DOMAIN_COM-VRSN\nRegistrar WHOIS Server: whois.markmonitor.com\nRegistrar URL: http://www.markmonitor.com\nUpdated Date: 2019-09-09T08:39:04-0700\nCreation Date: 1997-09-15T00:00:00-0700\nRegistrar Registration Expiration Date: 2028-09-13T00:00:00-0700\nRegistrar: MarkMonitor, Inc.\nRegistrar IANA ID: 292\nRegistrar Abuse Contact Email: <EMAIL>\nRegistrar Abuse Contact Phone: +1.2083895770\nDomain Status: clientUpdateProhibited (https://www.icann.org/epp#clientUpdateProhibited)\nDomain Status: clientTransferProhibited (https://www.icann.org/epp#clientTransferProhibited)\nDomain Status: clientDeleteProhibited (https://www.icann.org/epp#clientDeleteProhibited)\nDomain Status: serverUpdateProhibited (https://www.icann.org/epp#serverUpdateProhibited)\nDomain Status: serverTransferProhibited (https://www.icann.org/epp#serverTransferProhibited)\nDomain Status: serverDeleteProhibited (https://www.icann.org/epp#serverDeleteProhibited)\nRegistrant Organization: Google LLC\nRegistrant State/Province: CA\nRegistrant Country: US\nRegistrant Email: Select Request Email Form at https://domains.markmonitor.com/whois/google.com\nAdmin Organization: Google LLC\nAdmin State/Province: CA\nAdmin Country: US\nAdmin Email: Select Request Email Form at https://domains.markmonitor.com/whois/google.com\nTech Organization: Google LLC\nTech State/Province: CA\nTech Country: US\nTech Email: Select Request Email Form at https://domains.markmonitor.com/whois/google.com\nName Server: ns3.google.com\nName Server: ns2.google.com\nName Server: ns1.google.com\nName Server: ns4.google.com\nDNSSEC: unsigned\nURL of the ICANN WHOIS Data Problem Reporting System: http://wdprs.internic.net/\n>>> Last update of WHOIS database: 2021-03-11T22:57:36-0800 <<<\n\nFor more information on WHOIS status codes, please visit:\n https://www.icann.org/resources/pages/epp-status-codes\n\nIf you wish to contact this domainâs Registrant, Administrative, or Technical\ncontact, and such email address is not visible above, you may do so via our web\nform, pursuant to ICANNâs Temporary Specification. To verify that you are not a\nrobot, please enter your email address to receive a link to a page that\nfacilitates email communication with the relevant contact(s).\n\nWeb-based WHOIS:\n https://domains.markmonitor.com/whois\n\nIf you have a legitimate interest in viewing the non-public WHOIS details, send\nyour request and the reasons for your request to <EMAIL>\nand specify the domain name in the subject line. We will review that request and\nmay ask for supporting documentation and explanation.\n\nThe data in MarkMonitorâs WHOIS database is provided for information purposes,\nand to assist persons in obtaining information about or related to a domain\nnameâs registration record. While MarkMonitor believes the data to be accurate,\nthe data is provided \"as is\" with no guarantee or warranties regarding its\naccuracy.\n\nBy submitting a WHOIS query, you agree that you will use this data only for\nlawful purposes and that, under no circumstances will you use this data to:\n (1) allow, enable, or otherwise support the transmission by email, telephone,\nor facsimile of mass, unsolicited, commercial advertising, or spam; or\n (2) enable high volume, automated, or electronic processes that send queries,\ndata, or email to MarkMonitor (or its systems) or the domain name contacts (or\nits systems).\n\nMarkMonitor reserves the right to modify these terms at any time.\n\nBy submitting this query, you agree to abide by this policy.\n\nMarkMonitor Domain Management(TM)\nProtecting companies and consumers in a digital world.\n\nVisit MarkMonitor at https://www.markmonitor.com\nContact us at +1.8007459229\nIn Europe, at +44.02032062220\n--",
"registry_data": {
"domain_name": "GOOGLE.COM",
"query_time": "2021-03-12 08:03:52",
"whois_server": "whois.verisign-grs.com",
"domain_registered": "yes",
"create_date": "1997-09-15",
"update_date": "2019-09-09",
"expiry_date": "2028-09-14",
"domain_registrar": {
"iana_id": "292",
"registrar_name": "MarkMonitor Inc.",
"whois_server": "whois.markmonitor.com",
"website_url": "http://www.markmonitor.com",
"email_address": "<EMAIL>",
"phone_number": "+1.2083895740"
},
"name_servers": [
"NS2.GOOGLE.COM",
"NS1.GOOGLE.COM",
"NS4.GOOGLE.COM",
"NS3.GOOGLE.COM"
],
"domain_status": [
"clientDeleteProhibited",
"clientTransferProhibited",
"serverDeleteProhibited",
"serverTransferProhibited",
"serverUpdateProhibited",
"clientUpdateProhibited"
],
"whois_raw_registery": "\n Domain Name: GOOGLE.COM\n Registry Domain ID: 2138514_DOMAIN_COM-VRSN\n Registrar WHOIS Server: whois.markmonitor.com\n Registrar URL: http://www.markmonitor.com\n Updated Date: 2019-09-09T15:39:04Z\n Creation Date: 1997-09-15T04:00:00Z\n Registry Expiry Date: 2028-09-14T04:00:00Z\n Registrar: MarkMonitor Inc.\n Registrar IANA ID: 292\n Registrar Abuse Contact Email: <EMAIL>\n Registrar Abuse Contact Phone: +1.2083895740\n Domain Status: clientDeleteProhibited https://icann.org/epp#clientDeleteProhibited\n Domain Status: clientTransferProhibited https://icann.org/epp#clientTransferProhibited\n Domain Status: clientUpdateProhibited https://icann.org/epp#clientUpdateProhibited\n Domain Status: serverDeleteProhibited https://icann.org/epp#serverDeleteProhibited\n Domain Status: serverTransferProhibited https://icann.org/epp#serverTransferProhibited\n Domain Status: serverUpdateProhibited https://icann.org/epp#serverUpdateProhibited\n Name Server: NS1.GOOGLE.COM\n Name Server: NS2.GOOGLE.COM\n Name Server: NS3.GOOGLE.COM\n Name Server: NS4.GOOGLE.COM\n DNSSEC: unsigned\n URL of the ICANN Whois Inaccuracy Complaint Form: https://www.icann.org/wicf/\n>>> Last update of whois database: 2021-03-12T07:03:38Z <<<\n\nFor more information on Whois status codes, please visit https://icann.org/epp\n\nNOTICE: The expiration date displayed in this record is the date the\nregistrar's sponsorship of the domain name registration in the registry is\ncurrently set to expire. This date does not necessarily reflect the expiration\ndate of the domain name registrant's agreement with the sponsoring\nregistrar. Users may consult the sponsoring registrar's Whois database to\nview the registrar's reported date of expiration for this registration.\n\nTERMS OF USE: You are not authorized to access or query our Whois\ndatabase through the use of electronic processes that are high-volume and\nautomated except as reasonably necessary to register domain names or\nmodify existing registrations; the Data in VeriSign Global Registry\nServices' (\"VeriSign\") Whois database is provided by VeriSign for\ninformation purposes only, and to assist persons in obtaining information\nabout or related to a domain name registration record. VeriSign does not\nguarantee its accuracy. By submitting a Whois query, you agree to abide\nby the following terms of use: You agree that you may use this Data only\nfor lawful purposes and that under no circumstances will you use this Data\nto: (1) allow, enable, or otherwise support the transmission of mass\nunsolicited, commercial advertising or solicitations via e-mail, telephone,\nor facsimile; or (2) enable high volume, automated, electronic processes\nthat apply to VeriSign (or its computer systems). The compilation,\nrepackaging, dissemination or other use of this Data is expressly\nprohibited without the prior written consent of VeriSign. You agree not to\nuse electronic processes that are automated and high-volume to access or\nquery the Whois database except as reasonably necessary to register\ndomain names or modify existing registrations. VeriSign reserves the right\nto restrict your access to the Whois database in its sole discretion to ensure\noperational stability. VeriSign may restrict or terminate your access to the\nWhois database for failure to abide by these terms of use. VeriSign\nreserves the right to modify these terms at any time.\n\nThe Registry database contains ONLY .COM, .NET, .EDU domains and\nRegistrars."
}
}
```
I hope it would be the best solution that will help you in purchasing the domain names.
Disclaimer: I work for [WhoisFreaks API & Database](http://whoisfreaks.com).
Upvotes: 1 <issue_comment>username_4: For this you can also try the website [www.whoisdb.co](https://whoisdb.co), Here you will get instant access to a 100M+ whois database. You will get whois information like
```
"num","domain_name","query_time","create_date","update_date","expiry_date","domain_registrar_id","domain_registrar_name","domain_registrar_whois","domain_registrar_url","registrant_name","registrant_company","registrant_address","registrant_city","registrant_state","registrant_zip","registrant_country","registrant_email","registrant_phone","registrant_fax","administrative_name","administrative_company","administrative_address","administrative_city","administrative_state","administrative_zip","administrative_country","administrative_email","administrative_phone","administrative_fax","technical_name","technical_company","technical_address","technical_city","technical_state","technical_zip","technical_country","technical_email","technical_phone","technical_fax","billing_name","billing_company","billing_address","billing_city","billing_state","billing_zip","billing_country","billing_email","billing_phone","billing_fax","name_server_1","name_server_2","name_server_3","name_server_4","domain_status_1","domain_status_2","domain_status_3","domain_status_4"
```
Some key hights
* Download more than 50000 whois leads of newly registered domains everyday
* Every day, more than 100,000 domains are added to the list created with whois leads information.
* You can even use their API or Webhooks to get the databse
* All database can also be downloaded in the form of xls file or zip file
OUTGOING WEBHOOK
When the event below is triggered inside the software, send and POST a JSON to the provided URL.
**Preview of JSON**
```
{
"webhook_event": "new_domain_registered",
"num": "value",
"domain_name": "value",
"query_time": "value",
"create_date": "value",
"update_date": "value",
"expiry_date": "value",
"domain_registrar_id": "value",
"domain_registrar_name": "value",
"domain_registrar_whois": "value",
"domain_registrar_url": "value",
"registrant_name": "value",
"registrant_company": "value",
"registrant_address": "value",
"registrant_city": "value",
"registrant_state": "value",
"registrant_zip": "value",
"registrant_country": "value",
"registrant_email": "value",
"registrant_phone": "value",
"registrant_fax": "value",
"administrative_name": "value",
"administrative_company": "value",
"administrative_address": "value",
"administrative_city": "value",
"administrative_state": "value",
"administrative_zip": "value",
"administrative_country": "value",
"administrative_email": "value",
"administrative_phone": "value",
"administrative_fax": "value",
"technical_name": "value",
"technical_company": "value",
"technical_address": "value",
"technical_city": "value",
"technical_state": "value",
"technical_zip": "value",
"technical_country": "value",
"technical_email": "value",
"technical_phone": "value",
"technical_fax": "value",
"billing_name": "value",
"billing_company": "value",
"billing_address": "value",
"billing_city": "value",
"billing_state": "value",
"billing_zip": "value",
"billing_country": "value",
"billing_email": "value",
"billing_phone": "value",
"billing_fax": "value",
"name_server_1": "value",
"name_server_2": "value",
"name_server_3": "value",
"name_server_4": "value",
"domain_status_1": "value",
"domain_status_2": "value",
"domain_status_3": "value",
"domain_status_4": "value"
}
```
Upvotes: 0 |
2018/03/20 | 291 | 944 | <issue_start>username_0: Please could someone help. I have used this formula in my Tableau Desktop so that in the tooltip (when I hover on the bar chart) it can display figures with 0 Decimal Places.
```
int(IIF((ZN(round(SUM([Rental Area])),0) - LOOKUP(ZN(round(SUM([Rental Area])),0), -1)) / ABS(LOOKUP(ZN(round(SUM([Rental Area])),0), -1))
=-1,null,ZN(round(SUM(Rental Area])),0) - LOOKUP(ZN(round(SUM([Rental Area])),0), -1)))
```
What it is displaying is...example 349.0 or 45.0 and NOT 349 or 45<issue_comment>username_1: You can put your IIF statement inside INT. Hope that will help. Refer to [Tableau community link.](https://community.tableau.com/thread/157952)
Upvotes: 0 <issue_comment>username_2: Right-click your calculated field in the Measures pane and choose "Default Properties -> Number Format". In the Number Format window that opens, choose "Number (Custom)" and set to zero decimal places.
Upvotes: 3 [selected_answer] |
2018/03/20 | 612 | 1,613 | <issue_start>username_0: Let me present a simplified version of the data I have:
```
declare @cctbl table ([cc] [int]);
insert into @cctbl ([cc]) values (1),(2),(3);
declare @datetbl table ([dte] [date]);
insert into @datetbl ([dte]) values ('20180320'),('20180321'),('20180322');
declare @outtbl table ([cc] [int],[dte] [date]);
insert into @outtbl ([cc],[dte])
select [c].[cc],[d].[dte]
from @cctbl [c]
full outer join @datetbl [d] on ...?
```
I've got these two lists and the output I need from the above example will be:
```
[cc] [dte]
1 2018-03-20
1 2018-03-21
1 2018-03-22
2 2018-03-20
2 2018-03-21
2 2018-03-22
3 2018-03-20
3 2018-03-21
3 2018-03-22
```
How do I get there from my 2 separated columns?<issue_comment>username_1: You can use [`CROSS or OUTER APPLY`](https://technet.microsoft.com/en-us/library/ms175156(v=sql.105).aspx) for this.
Using your example data, the result is the same no matter which you use.
```
SELECT *
FROM @cctbl c
CROSS APPLY @datetbl d
ORDER BY c.cc
```
[](https://i.stack.imgur.com/rkjTS.png)
>
> CROSS APPLY returns only rows from the outer table that produce a
> result set from the table-valued function. OUTER APPLY returns both
> rows that produce a result set, and rows that do not, with NULL values
> in the columns produced by the table-valued function.
>
>
>
[[DEMO]](http://rextester.com/FMWZ61940)
Upvotes: 1 <issue_comment>username_2: Cross join is what you're after I think
Upvotes: 3 [selected_answer] |
2018/03/20 | 353 | 1,398 | <issue_start>username_0: I follow the guideline .
* Install composer-wallet-redis image and start the container.
* export NODE\_CONFIG={"composer":{"wallet":{"type":"@ampretia/composer-wallet-redis","desc":"Uses a local redis instance","options":{}}}}
* composer card import <EMAIL>
I found the card still store in my local machine at path ~/.composer/card/
How can I check whether the card exist in the redis server?
How to import the business network cards into the cloud custom wallet?<issue_comment>username_1: The primary issue (which I will correct in the README) is that the module name should the `composer-wallet-redis` The @ampretia was a temporary repo.
Assuming that redis is started on the default port, you can run the redis CLI like this
```
docker run -it --link composer-wallet-redis:redis --rm redis redis-cli -h redis -p 6379
```
You can then issue redis cli commands to look at the data. Though it is not recommended to view the data or modify it. Useful to confirm to yourself it's working. The `KEYS *` command will display everything but this should only be used in a development context. See the warnings on the redis docs pages.
Upvotes: 1 <issue_comment>username_2: 1. export NODE\_ENVIRONMENT
2. start the docker container
3. composer card import
4. execute `docker run ***` command followed by `KEYS *` ,empty list or set.
@username_1
Upvotes: 0 |
2018/03/20 | 1,137 | 4,051 | <issue_start>username_0: I have a react app and am using dotenv-webpack to manage my API keys.
I have:
- created a .env with the API keys and gitignored it.
- required and added dotenv as a plugin in webpack.config.js.
After that, I've been able to reference one of the keys in a .js file by using process.env.api\_key. But I am having problems trying to reference it in index.html in the script tag.
index.html:
```
```
How do I reference the process.env.API\_key here?
```
```
I have tried using backquotes that work in .js file, like so `${API_KEY}`, but that does not work in the .html file.<issue_comment>username_1: Solution
========
You can't reference the `process.env` variable directly inside `html`.
Create your own template from `index.html` and replace the api url with a parameter.
HtmlWebpackPlugin
=================
>
> Simplifies creation of HTML files to serve your webpack bundles.
>
>
>
You can either let the plugin generate an HTML file for you, supply your own template using lodash templates or use your own loader.
### Webpack.config.js
[HtmlWebpackPlugin](https://github.com/jantimon/html-webpack-plugin#writing-your-own-templates) allows you to create and pass parameters to your template:
```
const api_key = process.env.api_key;
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: 'index.js',
plugins: [
new HtmlWebpackPlugin({
inject: false,
template: './template.html',
// Pass the full url with the key!
apiUrl: `https://maps.googleapis.com/maps/api/js?key=${api_key}`,
});
]
}
```
### template.html
Inside the template you can access to the parameter:
```
```
See: [Writing Your Own Templates](https://github.com/jantimon/html-webpack-plugin#writing-your-own-templates)
Notes
=====
>
> This is a modified answer from this [comment](https://github.com/webpack/webpack/issues/3105#issuecomment-252312656), please read the full conversation.
>
>
>
Upvotes: 4 <issue_comment>username_2: >
> I put the following code in componentWillMount where the map renders
> and it worked (at least in development: const API\_KEY =
> process.env.GOOGLEMAP\_API\_KEY; const script =
> document.createElement('script'); script.src =
> <https://maps.googleapis.com/maps/api/js?key=>${API\_KEY};
> document.head.append(script);
>
>
>
I was able to get this to work using the code posted by bigmugcup in the comments above. I did not modify the webpack.config.js file.
Upvotes: 3 [selected_answer]<issue_comment>username_3: If you're already using create-react-app, this is already available by updating to
```
```
as it says in [the docs](https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables#referencing-environment-variables-in-the-html)
>
> You can also access the environment variables starting with REACT\_APP\_ in the public/index.html.
>
>
>
Upvotes: 5 <issue_comment>username_4: The simple way you can use
in HTML
```
%NODE\_ENV%
```
and in script
```
if('%NODE\_ENV%' === 'production') {
.... some code
}
```
Upvotes: 4 <issue_comment>username_5: I was looking for the issue how to set attribute value conditionally, after a couple of minutes, I actually found a way to handle this case, which I am listing below. And its handled by **HtmlWebpackPlugin**. This snippet will also help you referencing environment variable in HTML file.
**Environment setup**
* I am using Create React App, which has HtmlWebpackPlugin within modules, will be visible upon ejecting the application.
* My App is in default state i-e not ejected
**Environment Variable Definition**
I am setting environment variable [**APP\_ENV**] in scripts property of **Package.json** file., which looks like
```js
"scripts": {
"start": "set APP_ENV=development&& react-scripts start",
"build:prod": "set APP_ENV=production&& react-scripts build",
"eject": "react-scripts eject"
}
```
**Referencing varialble in HTML file**
Upvotes: 1 |
2018/03/20 | 1,190 | 4,291 | <issue_start>username_0: On MacOS, I installed homebrew, then installed pip.
Trying to use a Python scraper that uses "BeautifulSoup" package.
Ran: `pip install -r requirements.txt`
requirements.txt includes:
```
BeautifulSoup
ipython
```
BeautifulSoup gives an error, after googling I realized that there is a new version. so I ran:
```
pip install beautifulsoup4
```
seems to have installed correctly. Then I ran the scraping script and I got the following error:
```
Traceback (most recent call last):
File "scrape.py", line 3, in
from BeautifulSoup import BeautifulSoup
ImportError: No module named BeautifulSoup
```
I tried changing BeautifulSoup to BeautifulSoup4 in the script, but it is the same error.
Anything else I can try?
This is the script I am trying to use: <https://github.com/jojurajan/wp-content-scraper><issue_comment>username_1: Solution
========
You can't reference the `process.env` variable directly inside `html`.
Create your own template from `index.html` and replace the api url with a parameter.
HtmlWebpackPlugin
=================
>
> Simplifies creation of HTML files to serve your webpack bundles.
>
>
>
You can either let the plugin generate an HTML file for you, supply your own template using lodash templates or use your own loader.
### Webpack.config.js
[HtmlWebpackPlugin](https://github.com/jantimon/html-webpack-plugin#writing-your-own-templates) allows you to create and pass parameters to your template:
```
const api_key = process.env.api_key;
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: 'index.js',
plugins: [
new HtmlWebpackPlugin({
inject: false,
template: './template.html',
// Pass the full url with the key!
apiUrl: `https://maps.googleapis.com/maps/api/js?key=${api_key}`,
});
]
}
```
### template.html
Inside the template you can access to the parameter:
```
```
See: [Writing Your Own Templates](https://github.com/jantimon/html-webpack-plugin#writing-your-own-templates)
Notes
=====
>
> This is a modified answer from this [comment](https://github.com/webpack/webpack/issues/3105#issuecomment-252312656), please read the full conversation.
>
>
>
Upvotes: 4 <issue_comment>username_2: >
> I put the following code in componentWillMount where the map renders
> and it worked (at least in development: const API\_KEY =
> process.env.GOOGLEMAP\_API\_KEY; const script =
> document.createElement('script'); script.src =
> <https://maps.googleapis.com/maps/api/js?key=>${API\_KEY};
> document.head.append(script);
>
>
>
I was able to get this to work using the code posted by bigmugcup in the comments above. I did not modify the webpack.config.js file.
Upvotes: 3 [selected_answer]<issue_comment>username_3: If you're already using create-react-app, this is already available by updating to
```
```
as it says in [the docs](https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables#referencing-environment-variables-in-the-html)
>
> You can also access the environment variables starting with REACT\_APP\_ in the public/index.html.
>
>
>
Upvotes: 5 <issue_comment>username_4: The simple way you can use
in HTML
```
%NODE\_ENV%
```
and in script
```
if('%NODE\_ENV%' === 'production') {
.... some code
}
```
Upvotes: 4 <issue_comment>username_5: I was looking for the issue how to set attribute value conditionally, after a couple of minutes, I actually found a way to handle this case, which I am listing below. And its handled by **HtmlWebpackPlugin**. This snippet will also help you referencing environment variable in HTML file.
**Environment setup**
* I am using Create React App, which has HtmlWebpackPlugin within modules, will be visible upon ejecting the application.
* My App is in default state i-e not ejected
**Environment Variable Definition**
I am setting environment variable [**APP\_ENV**] in scripts property of **Package.json** file., which looks like
```js
"scripts": {
"start": "set APP_ENV=development&& react-scripts start",
"build:prod": "set APP_ENV=production&& react-scripts build",
"eject": "react-scripts eject"
}
```
**Referencing varialble in HTML file**
Upvotes: 1 |
2018/03/20 | 417 | 1,634 | <issue_start>username_0: The idea is how to build an android game that contains inside it many small games like Snake, draw letters, Sudoku...(Elevate as an example)
Should I use Android native, ionic, unity…?
Note that Elevate has incredible animations.
[Elevate in Play Store](https://play.google.com/store/apps/details?id=com.wonder&hl=en)<issue_comment>username_1: Sorry.. To Say that. It doesn't looks like a real game. Unity 3D is a heavy engine which is highly recommended for big games. But still if you want to build it in Unity the i suggest you the following tools:
Game Engine: Unity 3D.
Database: Firebase.
Animations: Adobe Illustrator.
Upvotes: -1 <issue_comment>username_2: I'm almost certain it's a native app based on the standard UI widgets (e.g. [RecyclerView](https://developer.android.com/guide/topics/ui/layout/recyclerview.html), [CardView](https://developer.android.com/reference/android/support/v7/widget/CardView.html), [CoordinatorLayout](https://developer.android.com/reference/android/support/design/widget/CoordinatorLayout.html)) it uses.
With that being said, you can surely build such an app with other tools like Unity or even Game Maker Studio. However, implementing UI widgets that mimic native Android functionality can prove difficult and time-consuming.
My recommendation would be to use an IDE such as Android Studio and utilize Google's vast UI libraries to build the menu sections of the app.
As for the mini-games, it all comes down to managing resources and memory (making sure that resources for a particular game are loaded in/out of memory as needed).
Upvotes: 2 [selected_answer] |
2018/03/20 | 441 | 1,783 | <issue_start>username_0: Hadoop `copyToLocal` is creating `.crc` files in the destination directory along with the actual data files which is unnecessary for me and fiddle with my further data processing. Is there a way to avoid that from being created instead of deleting it later?
```
val config = new Configuration()
val fs = FileSystem.get(config)
fs.copyToLocalFile(new Path(src),new Path(dest))
```
Maven dependency:
```
org.apache.hadoop
hadoop-common
3.0.0
provided
```<issue_comment>username_1: Sorry.. To Say that. It doesn't looks like a real game. Unity 3D is a heavy engine which is highly recommended for big games. But still if you want to build it in Unity the i suggest you the following tools:
Game Engine: Unity 3D.
Database: Firebase.
Animations: Adobe Illustrator.
Upvotes: -1 <issue_comment>username_2: I'm almost certain it's a native app based on the standard UI widgets (e.g. [RecyclerView](https://developer.android.com/guide/topics/ui/layout/recyclerview.html), [CardView](https://developer.android.com/reference/android/support/v7/widget/CardView.html), [CoordinatorLayout](https://developer.android.com/reference/android/support/design/widget/CoordinatorLayout.html)) it uses.
With that being said, you can surely build such an app with other tools like Unity or even Game Maker Studio. However, implementing UI widgets that mimic native Android functionality can prove difficult and time-consuming.
My recommendation would be to use an IDE such as Android Studio and utilize Google's vast UI libraries to build the menu sections of the app.
As for the mini-games, it all comes down to managing resources and memory (making sure that resources for a particular game are loaded in/out of memory as needed).
Upvotes: 2 [selected_answer] |
2018/03/20 | 906 | 3,110 | <issue_start>username_0: I'm trying to create a linked list from user input but it's not printing anything when i try to print it. Not even the head. Also note, it is intentionally backwards.
Here is my function for getting user input, it returns the list. I know it is wrong but i've spent hours on it and can't get it to work...
```
#include
#include
#include
struct Node {
int value;
Node \*next;
}
Node\* getInput() {
Node\* head = nullptr;
Node\* tmp;
while (true) {
int x;
if (!(cin >> x)) {
break;
} else if ( head == nullptr) {
head = new Node{x, nullptr);
} else {
tmp = new Node{x , nullptr};
tmp->next = head;
head = head->next;
}
}
return tmp;
}
int main() {
cout << getInput()->value;
}
```<issue_comment>username_1: `head = head->next;` is the problem. You're allocating a `Node` correctly, but you immediately leak that `Node` and `head` is pointing to `nullptr`.
The simplest solution is to keep `head` pointed at the most recent `Node`. You'll need a special case for the first insertion since `head` will be uninitialized (fix that by the way), but that way you're always pointing at the most recent `Node`.
If you have trouble, draw your `Node`s out on paper with arrows. Watch how the arrows change at each insertion, and you'll see what's happening.
Upvotes: 0 <issue_comment>username_2: The return value of get input() is not the actual head/start of the list. Head will always point to null the moment you insert any node. Head value can be stored in a temporary pointer during first insert and return temporary pointer instead of head.
Upvotes: 1 <issue_comment>username_3: If you are trying to print the linked list in reverse order, here's a working version:
```
#include
#include
#include
using namespace std;
struct Node {
int value;
Node \*next;
Node(int val, Node \*nextPtr) {
value = val;
next = nextPtr;
}
};
Node \*getInput() {
Node \*head = nullptr;
Node \*tmp;
while (true) {
int x;
if (!(cin >> x)) {
break;
} else if (head == nullptr) {
head = new Node(x, nullptr);
} else {
tmp = new Node(x, nullptr);
tmp->next = head;
head = tmp;
}
}
return head;
}
int main() {
Node \*head = getInput();
Node \*tmp;
while (head != nullptr) {
cout << head->value << ", ";
tmp = head;
head = head->next;
delete tmp;
}
cout << endl;
return 0;
}
```
Upvotes: 1 <issue_comment>username_4: A couple of good solutions up, but because the request was for a backward list, this can be really, really simple.
```
Node* getInput()
{
Node* head = nullptr;
int x;
while (std::cin >> x) // keep going until we can't get a good x.
{
head = new Node{x, head}; // point node at current head, assign new head
// head always points at the beginning of list because items are
// always inserted at the start of the list.
}
return head;
}
```
So to prove this list prints backward, here's a simple tester
```
int main()
{
Node* cur = getInput();
while (cur)
{
std::cout << cur->value << '\n';
cur = cur->next;
}
}
```
Upvotes: 2 [selected_answer] |
2018/03/20 | 946 | 2,966 | <issue_start>username_0: I have an Excel file and am trying to create a bar chart that groups categories and shows the average rating of the category. Because there are a lot of categories, I'd also like to only show either the top 10 or bottom 10 in the resulting horizontal bar chart.
```
category rating
A 10
A 8
A 9
B 1
B 4
B 9
C 6
C 7
D 9
```
Something like this (representative bar instead of the numbers):
```
A 9
D 9
...
C 6.5
B 4.66
```
I know this seems super simple to do, but I can't seem to be able to get anything working after trying various answers around here. Using ggplot2 seems to be the most promising so far. Closest I've gotten is showing the number of ratings for each category...
Edit: didn't save the work I did earlier as it wasn't the result I wanted, but it was something like this (didn't use ggplot)
```
dat[,c(1,12)]
category = dat[,1] //selecting column from sheet
rating = dat[,12] //selecting column from sheet
rating<-as.numeric(unlist(dat[,12]))
dat<-table(dat$rating,dat$category)
barplot(dat, main="Overall Ratings",
xlab="Ratings", col=c("skyblue","red"), horiz=TRUE,
legend = rownames(dat))
```<issue_comment>username_1: This solution uses data.table to summarize the data, then delivers the result to ggplot:
```
library(data.table);library(ggplot2)
category=c("A","A","A","B","B","B","C","C","D")
rating=c(10,9,8,1,4,9,6,7,9)
dt=as.data.table(cbind(category,rating))
ggplot(dt[,mean(as.numeric(rating)),by=category],aes(category,V1))+geom_col()+ylab("Mean")
```
Upvotes: 0 <issue_comment>username_2: Here's a chaining solution using `dplyr` and `tidyr`. First, we need to load the data.
```
library(dplyr)
library(tidyr)
library(ggplot2)
df <- read.table(text="category,rating
A,10
A,8
A,9
B,1
B,4
B,9
C,6
C,7
D,9
", sep=",", header=TRUE)
```
Now to the solution. After grouping the data by `category`, we calculate each category's mean rating.
```
means.df <-
df %>%
group_by(category) %>%
summarise(mean = mean(rating))
```
`top_n` selects the top (positive number) or bottom (negative number) n rows from a dataset. We apply this to our dataset with means. In your real data, adjust the 2 to 10 for the top and to -10 for the bottom 10 categories.
```
means.df %>%
top_n(2, mean) %>%
ggplot(aes(x = category, y = mean)) +
geom_bar(stat = 'identity')
```
The following code plots the top/bottom `cutoff_number` categories into one plot. Adjust the variable `cutoff_number` as needed.
```
cutoff_number <- 2
means.df %>%
arrange(-mean) %>%
mutate(
topbottom = ifelse(row_number() <= cutoff_number, "top", NA),
topbottom = ifelse(row_number() > nrow(.) - cutoff_number, "bottom", topbottom)
) %>%
ggplot(aes(x = category, y = mean)) +
geom_bar(stat = 'identity') +
facet_wrap(~topbottom, scales = 'free_x')
```
Upvotes: 3 [selected_answer] |
2018/03/20 | 504 | 1,771 | <issue_start>username_0: My app is built on rails and the web server is puma.
I need to load data from database and it takes more than 60 seconds to load all of them. Every time I send a get request to the server, I have to wait more than 60 seconds.
The timeout of request get is 60 seconds, so I always get 504 gateway timeout. I can't find the place to change the request timeout in puma configuration.
How can I set the request timeout longer than 60 seconds?
Thanks!<issue_comment>username_1: Preferably, you should be optimizing your code and queries to respond in faster duration of time so that in production environment there is no bottleneck with large traffic coming on your application.
If you really want to increase the response time then you can use rack timeout to do this:
<https://github.com/kch/rack-timeout>
Upvotes: -1 <issue_comment>username_2: ****UPDATE**: Apparently worker\_timeout is NOT the answer, as it relates to the whole process hanging, not just an individual request. So it seems to be something Puma doesn't support, and the developers are expecting you to implement it with whatever is fronting Puma, such as Nginx.**
*ORIGINAL: Rails itself doesn't time out, but use [worker\_timeout](https://github.com/puma/puma/blob/2668597ec1dd9546d83db9f2ec5ad092add483e6/examples/config.rb#L179) in `config/puma.rb` if you're running Puma. Example:*
*worker\_timeout (24*60*60) if ENV['RAILS\_ENV']=='development'*
[Source](https://github.com/puma/puma/issues/1024)
Upvotes: 3 <issue_comment>username_3: The 504 error here is with the gateway in front of the rails server, for example it could be Cloudflare, or nginx etc.
So the settings would be there. You'd have to increase the timeout there, as well as in rails/puma.
Upvotes: 0 |
2018/03/20 | 1,472 | 5,089 | <issue_start>username_0: I'm trying to create dynamic checkbox with the name fetching from json, [this issue](https://github.com/react-native-training/react-native-elements/issues/603) looks same as I need, but without the code explaining, I can't archieve my goal,
I have a json example like this :
```
this.state = {
data : [
{
"name": "ALL",
},
{
"name": "Android",
},
{
"name": "iOS",
},
{
"name": "React Native",
}
]}
```
and with this code below:
```
{this.setState({checked: !this.state.checked})}}
checked={this.state.checked}
/>
```
the checkbox running well but it's just showing 2nd value of json
**My Goal** is to displaying all of json value into flatlist and makes checkbox running well,
For now I just can displaying those json into FlatList, but the checkbox is not works
```
import React, { Component } from 'react';
import {
Text, View, StyleSheet, Alert, FlatList
} from 'react-native';
import Dimensions from 'Dimensions';
import { CheckBox } from 'react-native-elements'
const DeviceWidth = Dimensions.get('window').width;
const DeviceHeight = Dimensions.get('window').height;
class MedicalClearlance extends React.Component {
constructor(props){
super(props);
this.state = {
checked:[],
data : [
{
"name": "ALL",
},
{
"name": "Android",
},
{
"name": "iOS",
},
{
"name": "React Native",
}
]}
}
render() {
return (
{this.setState({checked: !this.state.checked}), console.log(this.state.checked +' '+ index)}}
checked={this.state.checked}/>
}
/>
);
}
}
```
anyone can help me how to archieve my goal?<issue_comment>username_1: You need to fill up the `checked` array in order to manipulate it after.
```
constructor() {
super();
this.state = {
data: [
{
"name": "ALL",
},
{
"name": "Android",
},
{
"name": "iOS",
},
{
"name": "React Native",
}
],
checked: []
}
}
componentWillMount() {
let { data, checked } = this.state;
let intialCheck = data.map(x => false);
this.setState({ checked: intialCheck })
}
```
and pass the `index` of the selected checkbox to update it
```
handleChange = (index) => {
let checked = [...this.state.checked];
checked[index] = !checked[index];
this.setState({ checked });
}
render() {
let { data, checked } = this.state;
return (
this.handleChange(index)}
checked={checked[index]} />
}
/>
);
}
```
I hope it helps!
Upvotes: 3 <issue_comment>username_2: The answer that [username_1](https://stackoverflow.com/users/6153188/ahsan-ali) provided will work. ***However it is missing a very vital line of code.***
* Within the component, be sure to add this `extraData
={this.state}`. This will allow the FlatList component to re-render whenever the state is changed.
The **render method** will then look like this:
```
handleChange = (index) => {
let checked = [...this.state.checked];
checked[index] = !checked[index];
this.setState({ checked });
}
render() {
let { data, checked } = this.state;
return (
this.handleChange(index)}
checked={checked[index]} />
}
/>
);
}
```
>
> By passing extraData={this.state} to FlatList we make sure FlatList
> itself will re-render when the state.selected changes. Without setting
> this prop, FlatList would not know it needs to re-render any items
> because it is also a PureComponent and the prop comparison will not
> show any changes.
>
>
>
More information can be found at React-Native Flat-List documentation [here](https://facebook.github.io/react-native/docs/flatlist.html).
---
If you're using the code from [<NAME>'s](https://stackoverflow.com/users/6153188/ahsan-ali) post, there may be another error you come across.
* A warning error displays that the `componentWillMount()` method is
deprecated. In which case be sure to use the `componentDidMount()`
instead.
Hope this helps people!
Upvotes: 3 <issue_comment>username_3: **you could try this for multiple selection, ref link-> <https://facebook.github.io/react-native/docs/flatlist>**
```
class MyListItem extends React.PureComponent
{
_onPress = () => {
this.props.onPressItem(this.props.id);
};
render() {
const textColor = this.props.selected ? 'red' : 'black';
return (
{this.props.title}
);
}
}
class MultiSelectList extends React.PureComponent {
state = {selected: (new Map(): Map)};
\_keyExtractor = (item, index) => item.id;
\_onPressItem = (id: string) => {
// updater functions are preferred for transactional updates
this.setState((state) => {
// copy the map rather than modifying state.
const selected = new Map(state.selected);
selected.set(id, !selected.get(id)); // toggle
return {selected};
});
};
\_renderItem = ({item}) => (
);
render() {
return (
);
}
}
for(const ele of this.state.selected.keys())
console.log(ele);
//\*\*after that you could get all the selected keys or values from something like this\*\*
```
Upvotes: 0 |
2018/03/20 | 1,642 | 7,007 | <issue_start>username_0: Is it possible to remote update or patch only certain piece of code to an embedded device (microcontroller)?
I am writing a bare metal C program on a microcontroller. Lets say I have main program which comprises of function `A()`, `B()`, `C()` and `D()` each in their own .c file.
I would like to do a remote update (patching) of only `B()` which has its own custom section in the main program so that the address is fixed and known.
The thing that puzzles me is how do I produce an updated executable of `B()`? Given that it relies on standard C library or other global variables from the main program. I need to resolve all the symbols from the main program.
Would appreciate any suggestions or reference to other thread if this question has been asked before (I tried to search but couldn't find any)
Solutions:
* from <NAME>: Compile the new `B()`, and link it with the symbol file previously generated from the main program using gcc `--just-symbols` option. The resultant elf will contain just `B()` that assumes all these other symbols are there. (I haven't tried it but this is the concept that I was looking for)
* Compile the whole program with the new `B()`, and manually take only the `B()` part binary from the main program (because its section address and size are known). Send `B()` binary to the device for remote update (not efficient as it involves many manual works).<issue_comment>username_1: Some approach like this requires that the programmer manually manages all code allocation with their own custom segments. You'd have to know the fixed address of the function and it can't be allowed to grow beyond a certain size.
The flash memory used will dictate the restrictions, namely how large an area do you need to erase before programming. If you can execute code from eeprom/data flash then that's the obvious choice.
Library calls etc are irrelevant as the library functions are most likely stored elsewhere. Or in the rare case where they are inlined, they'll be small. But you might have to write the function in assembler, since C compiler-generated machine code may screw up the calling convention or unexpectedly overwrite registers if taken out of the expected context.
Because all of the above is fairly complex, the normal approach is to only modify const variables, rather than code, and keep those in eeprom/data flash, then have your program act based on those values.
Upvotes: 0 <issue_comment>username_2: Dynamic loading and linking requires run-time support - normally provided by an OS. VxWorks for example includes support for that (although the code is normally loaded into RAM over a network or mass-storage file-system rather then Flash or other re-writable ROM).
You could in theory write your own run-time linker/loader. However for it to work, the embedded firmware must contain a symbol table in order to complete the link. The way it works in VxWorks, is the object code to be loaded is *partially linked* and contains unresolved symbols that are completed by the run-time linker/loader by reference to the embedded symbol table.
Other embedded operating systems that support dynamic loading are:
* [Precise/MQX](http://www.electronicdesign.com/embedded/rtos-includes-support-dynamic-task-loading)
* [Nucleus](https://www.mentor.com/embedded-software/nucleus/kernel)
Another approach that does not require a symbol table is to provide services via a *software interrupt* API (as used in PC-BIOS and MS-DOS). The loaded module will necessarily have a restricted access to services provided by the API, but because they are interrupts, the actual location of such services does not need to be known to the loadable module, not explicitly linked at run-time.
There is an article on dynamically loading modules in small RTOS systems on Embedded.com:
* [Bring big system features to small RTOS devices with downloadable app modules](https://www.embedded.com/design/operating-systems/4216903/1/Bring-big-system-features-to-small-RTOS-devices-with-downloadable-app-modules).
The author <NAME> works for Express Logic who produce ThreadX RTOS, which gives you an idea of the kind of system it is expected to work on, although the article and method described is not specific to ThreadX.
Upvotes: 1 <issue_comment>username_3: I'm assuming you're talking about bare metal with my answer.
First off, linking a new function `B()` with the original program is relatively simple, particularly with GCC. LD can take a 'symbol file' as input using the `--just-symbols` option. So, scrape your map file, create the symbol file and use it as an input to your new link. Your resultant elf will contain just your code that assumes all these other symbols are there.
At that point, compile your new function `B()`, which should be a different name than `B()` (so we'll choose `B_()`). It should have the exact same signature as `B()` or things won't work right. You have to compile with the same headers, etc. that your original code was compiled with or it likely won't work.
Now, depending on how you've architected your original program, life can be easy or a real mess.
If you make your original program with the idea of patching in mind, then the prep is relatively trivial. Identify which functions you might want to patch and then call them through function pointers, e.g.:
```
void OriginalB(void)
{
//Original implementation of B goes here
}
void (B*)(void) = OriginalB;
void main(void)
{
B(); //this calls OriginalB() through the function pointer B. Once you
//patch the global function pointer B to point to B_(), then this
//code will call your new function.
}
```
Now your patch program is the original program linked with your `B_()`, but you somehow have to update the global function pointer `B` to point to `B_()` (rather than `OriginalB()`)
Assuming you can use your new elf (or hex file) to update your device, it's pretty easy to just go modify those to change the value of `B` or assign the new function pointer directly in your code.
If not, then whatever method of injection you need to do also needs to inject a change to the global pointer.
If you didn't prep your original program, then it can be a real bear (but doable) to go modify references to `B()` to instead jump to your new `B_()`. It might get super tricky if your new function is too far away for a relative jump, but still doable in theory. I've never actually done it. ;)
If you're trying to patch a ROM, you almost have to have prepped the original ROMmed program to use function points for potential patch points. Or have some support in the ROM hardware to allow limited patching (usually it's just a few locations it will let you patch).
Some of the details may be incorrect for GCC (I use the Keil tools in my professional flow), but the concept is the same. It's doable. It's fragile. There's no standard way of doing this and it's highly tool and application dependent.
Upvotes: 0 |
2018/03/20 | 799 | 2,753 | <issue_start>username_0: Is there a more efficient way to write the below if statements & preserve the exact same effect?
Let's say this dataRequest function runs from within in an interval that triggers it every 5 seconds.
There is fresh data in dataRequest each time it is requested.
As it exists right now, this code assigns a value to the latest data.item\_1 - then (after each iteration) passes the value from the current result to a history variable before reassigning the current. This creates a history of the results, up to 6.
It feels inefficient & redundant to do it like this, but I wasn't able to come up with another way. Seems unsustainable, esp if you have something like 100 history states...
```
let result_current,
result_prev_1,
result_prev_2,
result_prev_3,
result_prev_4,
result_prev_5,
result_prev_6,
result_prev_7;
//
const dataRequest = function() {
let request;
request = new XMLHttpRequest();
request.open('GET', 'https://somedatafeed.com', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
data = JSON.parse(request.response)
// ...
if (result_prev_6) { result_prev_7 = result_prev_6; }
if (result_prev_5) { result_prev_6 = result_prev_5; }
if (result_prev_4) { result_prev_5 = result_prev_4; }
if (result_prev_3) { result_prev_4 = result_prev_3; }
if (result_prev_2) { result_prev_3 = result_prev_2; }
if (result_prev_1) { result_prev_2 = result_prev_1; }
if (result_current) { result_prev_1 = result_current; }
result_current = data.item_1.result;
} else {
// error
}
};
request.send();
}
```
Any thoughts?<issue_comment>username_1: Add to an array instead.
```
const resultArr = [];
const dataRequest = function() {
// ...
const data = JSON.parse(request.response);
resultArr.unshift(data.item_1.result); // or use push
}
// ...
```
Then you can access the most recent result via `resultArr[0]`, and the older results in the other indicies.
Upvotes: 2 <issue_comment>username_2: storing results in an array might be easier
```
let result = new Array(8);
//
const dataRequest = function() {
let request;
request = new XMLHttpRequest();
request.open('GET', 'https://somedatafeed.com', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
data = JSON.parse(request.response)
// ...
for(var i = result.length; i > 0; i--){
if(result[i]) { result[i] = result[i-1]}
}
result[0] = data.item_1.result;
} else {
// error
}
};
request.send();
}
```
Upvotes: 0 |
2018/03/20 | 308 | 1,161 | <issue_start>username_0: I would like Vim to send the name of the currently open file to macOS Terminal.
It is possible to tell the macOS terminal the filename of a currently open document by sending the escape sequence `\e]6;FILENAME\a`. This can be seen be executing the command `printf "\e]6;FileName.txt\a"`
I would like Vim to send the filename of the currently open document to Terminal. It seems like this should be easy, but `:echo "\e]6;FileName.txt\007"` will turn the escape sequences into printable characters and add some color to them, so it instead outputs `^[]6;FileName.txt^G` which is not recognized by Terminal.
How can I configure `:echo` not to mangle my escape sequences?<issue_comment>username_1: Thank you @romainl; this was as simple as adding `set title` to my `~/.vimrc` file.
Upvotes: 5 [selected_answer]<issue_comment>username_2: ```
set title
```
to the ~/.vimrc file does put the file being edited
onto the terminal heading, very useful if several tabs are open.
You can also add
```
oldtitle=
```
which will retore the terminals original title.
Otherwise VIM wites a "thanks for flying VIM" message on
exit.
Upvotes: 0 |
2018/03/20 | 639 | 2,492 | <issue_start>username_0: This does not work
When I don't have a blank constructor in my class the code will not run causing an error saying no default constructor exists for class.
```
#include
class myClass
{
public:
myClass(int val)
:x(val)
{}
private:
int x;
};
int main()
{
myClass random;
return 0;
}
```
This works
```
#include
class myClass
{
public:
myClass(int val)
:x(val)
{}
myClass()
{}
private:
int x;
};
int main()
{
myClass random;
return 0;
}
```<issue_comment>username_1: This is because when you try to instantiate the object `myClass random`, you are trying to invoke the default constructor which you do not have.
If you changed it to `myClass random(3)`( basically trying to invoke the constructor that you have), you would see that the compiler would have no problems.
If you want `myClass random` to compile fine, then you must have a default constructor in your class.
Upvotes: 2 [selected_answer]<issue_comment>username_2: Once you declare a constructor in a `class` (any constructor), the compiler won't automatically generate a default constructor for you (this is what you're calling the blank constructor).
If you don't want to implement the default constructor (generally a good idea if you just want the default behavior), you can tell the compiler to generate it for you as of C++11.
```
class myClass {
public:
myClass(int val)
:x(val)
{}
myClass() = default; // the compiler handles the implementation
private:
int x;
};
```
Upvotes: 0 <issue_comment>username_3: In the first case you have defined a parameterized constructor. When a constructor is defined the compiler now does not automatically define a default constructor like before.
If no constructor is defined the compiler automatically defines a default constructor but if another constructor is defined the compiler will not do so.
i.e. in first case a default constructor does not exist. In the second case you have defined one and hence has no errors.
Upvotes: 0 <issue_comment>username_4: See [default constructor](http://en.cppreference.com/w/cpp/language/default_constructor).
>
> If no user-declared constructors of any kind are provided for a class type, the compiler will always declare a default constructor as an inline public member of its class.
>
>
>
However, there's a constuctor declared in your class, thus the compiler won't declare a default constructor. You have to explicitly declare one yourself.
Upvotes: 0 |
2018/03/20 | 632 | 2,623 | <issue_start>username_0: hey so im trying to display a graph based on selected from and to from user.
the column that it will call is from `created_at` column but when i write my code like
```html
$email = count(DiraResponses::where('company_id', $companyID)->where('created_at', '>=', $request->from)->where('created_at', '<=', $request->to)->where('type', 'email')->where('format', 'email')->get());
```
it returns an error
`FatalThrowableError in FileSessionHandler.php line 70:
Call to undefined method Carbon\Carbon::getTimestamp()`
how should i solve this? this error comes only when i call the created\_at column.<issue_comment>username_1: This is because when you try to instantiate the object `myClass random`, you are trying to invoke the default constructor which you do not have.
If you changed it to `myClass random(3)`( basically trying to invoke the constructor that you have), you would see that the compiler would have no problems.
If you want `myClass random` to compile fine, then you must have a default constructor in your class.
Upvotes: 2 [selected_answer]<issue_comment>username_2: Once you declare a constructor in a `class` (any constructor), the compiler won't automatically generate a default constructor for you (this is what you're calling the blank constructor).
If you don't want to implement the default constructor (generally a good idea if you just want the default behavior), you can tell the compiler to generate it for you as of C++11.
```
class myClass {
public:
myClass(int val)
:x(val)
{}
myClass() = default; // the compiler handles the implementation
private:
int x;
};
```
Upvotes: 0 <issue_comment>username_3: In the first case you have defined a parameterized constructor. When a constructor is defined the compiler now does not automatically define a default constructor like before.
If no constructor is defined the compiler automatically defines a default constructor but if another constructor is defined the compiler will not do so.
i.e. in first case a default constructor does not exist. In the second case you have defined one and hence has no errors.
Upvotes: 0 <issue_comment>username_4: See [default constructor](http://en.cppreference.com/w/cpp/language/default_constructor).
>
> If no user-declared constructors of any kind are provided for a class type, the compiler will always declare a default constructor as an inline public member of its class.
>
>
>
However, there's a constuctor declared in your class, thus the compiler won't declare a default constructor. You have to explicitly declare one yourself.
Upvotes: 0 |
2018/03/20 | 602 | 2,274 | <issue_start>username_0: If I understand correctly the binary form of Java 10 is 100% identical to Java 9 so it shouldn't make any problems.
Is my assumption correct?<issue_comment>username_1: `javac` has supported a [`--release`](https://docs.oracle.com/javase/9/tools/javac.htm#JSWOR627) argument for a while. As long as you aren't using features from a newer release (in this case Java 10), you can do:
```
javac --release 9
```
And everything should work fine. Even better, the Java compiler will complain if there are issues that need to be addressed.
Note that without doing this you will get an [`UnsupportedClassVersionError`](https://docs.oracle.com/javase/9/docs/api/java/lang/UnsupportedClassVersionError.html) even if the code is technically valid because the minimum Java version required is [included in the compiled bytecode](https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.1), and this defaults to the current version of the java compiler.
Nowadays you can also use [multirelease jars](http://openjdk.java.net/jeps/238) if you want to use newer java language features but also include code supporting older JVMs.
Upvotes: 3 <issue_comment>username_2: This has nothing to do with Java 10; the rules are the same as they've always been.
In every version of Java, the classfile version number has been incremented. You can run *older* classfiles on a newer Java runtime (you can run files compiled twenty years ago under Java 1.0 on Java 10!), but it has never been true that you can run *newer* classfiles on an older runtime. This hasn't changed with Java 10.
However, you can compile classes such that they run on older versions, if you don't use newer features introduced since that version. This used to be accomplished by the `-source` and `-target` switches:
```
// Run this on Java 8
javac -source 6 -target 6 Foo.java
```
and you'll get classfiles that will run on Java 6 and later. (The source version cannot be greater than the target version.) This was recently replaced with the more comprehensive `--release` option:
```
javac --release 9
```
which implies not only `-source 9` and `-target 9`, but the compiler will also prevent you from using JDK functionality introduced after 9.
Upvotes: 5 [selected_answer] |
2018/03/20 | 607 | 2,127 | <issue_start>username_0: I have a html file as follows.
```
* Teachers
```
In this html file i.e in teacher.component.ts i am redirecting to all teachers component as shown abouve.
In my app.routing.ts my routes are as follows.
```
const routes: Routes = [
{ path: '', component: LoginComponentComponent },
{
path: 'Dashboard', component: SidebarComponent, canActivate: [OnlyLoggedInGuard],
children: [
{ path: 'Teachers/AllTeachers', component: AllTeachersComponent},
{ path: 'Teachers/AddTeacher', component: AddTeacherComponent},
]
},
```
now i have to navigate from all teachers to add teacher from all teachers component .I am doing it by clicking another button. But on doing this the routerlink active is not working it is not applying the active class to html.I need to keep the li active as long as it is there in teachers.<issue_comment>username_1: Here is a sample that I created for you:
<https://stackblitz.com/edit/angular-gx5ovm>
I think the trick is moving routerLinkActive="active" to the parent ul instead of li. If you want to have it on the li elements then you have to put routerLinkActive="active" on each one of the li elements.
This is from Angular documentation:
>
> you can apply the RouterLinkActive directive to an ancestor of a
> RouterLink.
>
>
>
> ```
>
> Jim
> Bob
>
>
> ```
>
>
<https://angular.io/api/router/RouterLinkActive#description>
**UPDATE**:
Is this what you are after?
<https://stackblitz.com/edit/angular-hvnczx>
Upvotes: 2 <issue_comment>username_2: [Code example](https://stackblitz.com/edit/angular-hhxgdu) Updated @username_1 code example. Just simply add `routerLinkActive="active"` to routerLink directives.
```
* All Teachers
...
```
`routerLinkActive` directive shoulde be together with `routerLink`:
```
* All Teachers
* Add Teachers
```
[CODE EXAMPLE 3](https://stackblitz.com/edit/angular-jqgojl)
Upvotes: 1 <issue_comment>username_3: You should use relative path, to let Angular know it's a relative path, as shown in the code below :
```
```
Upvotes: 0 |
2018/03/20 | 522 | 1,864 | <issue_start>username_0: I am attempting to write an enzyme test for a react component. I want to test that, when I give this component a prop of "items," the component contains a "ToDoItem" as shown mapped below. I can't figure out how to test the presence of the ToDoItem component.
Here is the component:
```
import React from 'react';
import ToDoItem from '../ToDoItem/ToDoItem';
export default class ToDos extends React.Component {
render() {
const toDoItems = this.props.items.map((item, key) => (
this.props.onDelete(value)}
onCheck={value => this.props.onCheck(value)}
/>
));
return (
### Tasks
{ toDoItems }
)
}
}
```
Here is the enzyme test. This fails:
```
it('contains to ToDoItem when passed props', () => {
const toDos = mount();
expect(toDos.find()).toEqual(true)
});
```
I've tried adding the full mapped item in the expect statement:
this.props.onDelete(value)} onCheck={value => this.props.onCheck(value)} />
This does not work either. Help!<issue_comment>username_1: **You should never add key as the index of the array**. I'm writing that in bold because it causes mistakes when you remove an item from the array and react doesn't have track of that and hence your test fails.
There's even a [youtube video](https://www.youtube.com/watch?v=MYdNmD3GJ1E) about it.
Instead of using the index, you can use an identifier / id like this:
```
const toDoItems = this.props.items.map((item, index) => (
this.props.onDelete(value)}
onCheck={value => this.props.onCheck(value)}
/>
));
```
Which will help react keep track of the component.
Upvotes: 1 <issue_comment>username_2: This worked:
```
it('displays ToDoItem if passed props', () => {
const wrapper = shallow();
expect(wrapper.find('ToDoItem').exists()).toEqual(true);
});
```
Upvotes: 2 |
2018/03/20 | 417 | 1,421 | <issue_start>username_0: Okay so I'm trying to select innertext from a tag which is 2 below the a tag containing specified string
Example of html:
```
[Example String](#) |
132 |
89 |
123 |
```
I want second TD below " Example String within the ahref tag:
```
89 |
```
I know if i do:
```
//a[contains(., 'Example String')]
```
this will successfully identify the a href containing Example String using SelectNode but then I want to grab the inner text from the 2nd td tag below that
I tried,
```
//a[contains(., 'Example String')]/td[2]
```
but I had no luck..<issue_comment>username_1: **You should never add key as the index of the array**. I'm writing that in bold because it causes mistakes when you remove an item from the array and react doesn't have track of that and hence your test fails.
There's even a [youtube video](https://www.youtube.com/watch?v=MYdNmD3GJ1E) about it.
Instead of using the index, you can use an identifier / id like this:
```
const toDoItems = this.props.items.map((item, index) => (
this.props.onDelete(value)}
onCheck={value => this.props.onCheck(value)}
/>
));
```
Which will help react keep track of the component.
Upvotes: 1 <issue_comment>username_2: This worked:
```
it('displays ToDoItem if passed props', () => {
const wrapper = shallow();
expect(wrapper.find('ToDoItem').exists()).toEqual(true);
});
```
Upvotes: 2 |
2018/03/20 | 512 | 1,662 | <issue_start>username_0: This is my code:
```js
function person(name, age) {
this.name = name;
this.age = age;
this.changeName = changeName;
function changeName(name) {
this.name = name;
}
}
my = new person("Ying", 21);
for (i in my) {
document.write(my[i] + " ");
}
```
Result:
>
> Ying 21 function changeName(name) { this.name = name; }
>
>
>
why does it output the changeName() method?<issue_comment>username_1: When it comes to the changeName property, you're using the + operator on a function, so it gets implicitly converted to a string. You might want something like this instead:
```
if (typeof my[i] !== 'function') document.write(my[i] + " ");
```
Upvotes: 1 <issue_comment>username_2: In javascript methods aren't special. They are members of the object like any other. If you want to ignore them you can do this:
```
my = new person("Ying", 21);
for (i in my) {
if (typeof my[i] !== 'function') document.write(my[i] + " ");
}
```
This skips over keys whose members are functions.
Upvotes: 0 <issue_comment>username_3: When you create a constructor function every thing that you define within the function gets attached to the constructed object because of javascript being function scoped. So your function is associated with the **this**. Hence the problem that you face.
Upvotes: 0 <issue_comment>username_4: ```js
function person(name, age) {
this.name = name;
this.age = age;
this.changeName = changeName;
function changeName(name) {
this.name = name;
}
}
my = new person("Ying", 21);
for (i in my) {
if (typeof my[i] !== 'function') document.write(my[i] + " ");
}
```
Upvotes: 0 |
2018/03/20 | 879 | 2,730 | <issue_start>username_0: Say for example I have a paragraph of text, and when I click on a certain word in a span, I'd like a picture to appear while the word is STILL visible (position the picture right below the word). I know how to do this easily if the the img tag follows the span directly, with relative positioning, but because I have an entire paragraph of text following that one span, I can't put the in there. Example: (hover over the bold)
```js
function showCat(){
var y = document.getElementsByClassName("popupImage");
y[0].style.visibility = "visible";
//this or something else?
y[0].style.top = "-2em";
}
```
```css
.popupImage{
width: 40%;
visibility: hidden;
position: relative;
top: 4em;
}
.moreInfo{
font-weight: bold;
}
```
```html
I'm <NAME>, a HTML and CSS Student
I chose the HTML/CSS dual degree and moved here in 2016 to get a taste of both disciplines from the University of NoWhere.

```
The image cannot fall directly after the span in bold.
I don't do much work at all with frontend design and my instincts tell me there is someway to make the image relative to the span even though they are not one after another in the html.<issue_comment>username_1: Your code already showcases the image below the ext in question, but if you want it to appear **next** to the text in question, why not simply move the `![]()` tag to directly after your tag? That way you also don't have to worry about `top` positioning:
```js
function showCat() {
var y = document.getElementsByClassName("popupImage");
y[0].style.visibility = "visible";
}
```
```css
.popupImage {
width: 40%;
visibility: hidden;
position: relative;
}
.moreInfo {
font-weight: bold;
}
```
```html
I'm <NAME>, a
HTML and CSS Student

```
Upvotes: 1 <issue_comment>username_2: In addition to @Obsidian , Instead of using `visibility`, you should use `display`
```js
function showCat() {
var y = document.getElementsByClassName("popupImage");
y[0].style.display = "block";}
```
```css
.popupImage {
width: 40%;
display: none;
position: relative;
}
.moreInfo {
font-weight: bold;
}
```
```html
I'm <NAME>, a
HTML and CSS Student

I chose the HTML/CSS dual degree and moved here in 2016 to get a taste of both disciplines from the
University of NoWhere.
```
Upvotes: 0 |
2018/03/20 | 1,403 | 5,188 | <issue_start>username_0: I have two connected components, they both need the same parent so that they can talk to each other. However I would like to be able to render them anywhere, 100% separate. I have a [jsfiddle](https://jsfiddle.net/69z2wepo/142067/) example to show the idea, it is a terrible solution to my problem since I'm creating a new Img component whenever I need to change the props passed in. But it shows the idea. I feel like I'm probably going about this wrong but maybe there is a way to pass props to the Img without just making a new instance. Having a non React class be the parent is not ideal for sure.
Fiddle explanation:
make an Img component that takes in a prop telling it if it should render or not
make a Switch component that will change the prop passed into Img component when clicked
They can be rendered anywhere separately and are controlled by a parent class.
The forceUpdate is just to make the example work, I know that is not a good use of it.
The code:
```
const Img = (props) => {
return (

);
};
const Switch = (props) => {
return (
props.toggleImg()}>
click me
);
};
class MasterComponent {
constructor(outerThis) {
this.outerThis = outerThis;
this.toggleState = true;
this.img = ![]();
this.switch = this.toggleImg() } />;
}
toggleImg() {
this.toggleState = !this.toggleState;
this.img = ![]();
this.outerThis.forceUpdate();
}
}
class Example extends React.Component {
constructor(props) {
super(props);
this.masterComponent = new MasterComponent(this);
}
render() {
return
{this.masterComponent.img}
{this.masterComponent.switch}
;
}
}
```
edit:
So the question is basically this. I want the 'MasterComponent' to be some sort of parent that gives you two children that interact with each other in the realm of state/props but are rendered separately like in the Example's render. So imagine importing MasterComponent and then using it like I did in the Example component without knowing what is going on behind the scenes. That is the design pattern I hoped for, but it doesn't seem achievable with React alone maybe.
My version of the MasterComponent is bad because I'm replacing the Img component with a new instance of Img with different props when I really just want to update the props it had. Using forceUpdate over setState is bad too but I'm less concerned about that.
I think since MasterComponent isn't a react component with state that can cause a rerender and Img and Switch aren't inside a render function where they can organically receive that state, maybe my idea doesn't work.<issue_comment>username_1: So i think it's pretty dang good, however to make it more "React tm" like:
```
const Img = (props) => {
return (

);
};
const Switch = (props) => {
return (
click me
);
};
class MasterComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
showImg: true,
};
this.toggleImg = this.toggleImg.bind(this);
}
toggleImg() {
this.setState({showImg: !this.state.showImg});
}
render() {
return
![]()
;
}
}
class Example extends React.Component {
render() {
return
;
}
}
ReactDOM.render(
,
document.getElementById('container')
);
```
like this is more composable and using react Components classes
also you maybe interested in something like:
```
{this.state.showImg && ![]()}
```
Upvotes: 0 <issue_comment>username_2: So... I don't know that this is a *good* pattern... it's not super React-y, but I *think* it would achieve what you are looking for. I haven't tested it, but I'm thinking something like this:
```
function getImgSwitchPair() {
const state = {
isShowing: true
};
const toggleImg = () => {
state.isShowing = !state.isShowing;
};
const Img = () => {
return (

);
};
const Switch = () => {
return (
click me
);
};
return {
Img,
Switch,
toggleImg
};
}
class Example extends React.Component {
constructor(props) {
super(props);
const {Img, Switch} = getImgSwitchPair();
this.Img = Img;
this.Switch = Switch;
}
render() {
return (
![]()
);
}
}
```
`getImgSwitchPair` generates and returns a coupled `Img` and `Switch` component, as well as the `toggleImg` function if you want to call it manually. We use a `state` object to mutate to change `isShowing` state.
I *think* this would work. However, it would exist and update state completely outside of the React lifecycle, which I think would be problematic. So while this may work, I'm not positive it is a good pattern.
I'm hesitant to post this w/o testing and knowing it may be a problematic pattern, but I'm hoping perhaps it gets you down the path of what you're looking for...
Upvotes: 2 [selected_answer] |
2018/03/20 | 700 | 1,888 | <issue_start>username_0: It is my first using rabbitmq,I download erlang 9.3 and rabbitmq 3.7.4,and also configure my path with erl and rabbitmq,It seems well as I enter commend line and use `rabbitmq-plugins enable rabbitmq_management`,but when i use `rabbitmqctl start_app`,it occur to an argument error,like this:
>
> Starting node rabbit@DESKTOP-0T1B7S8 ...
> \*\* (ArgumentError) argument error
> (stdlib) io\_lib.erl:170: :io\_lib.format(' \* effective user\'s home directory: ~s~n', [[67, 58, 92, 85, 115, 101, 114, 115, 92, 19975, 23480, 26827]])
> src/rabbit\_misc.erl:670: :rabbit\_misc."-format\_many/1-lc$^0/1-0-"/1
> src/rabbit\_misc.erl:670: :rabbit\_misc."-format\_many/1-lc$^0/1-0-"/1
> src/rabbit\_misc.erl:670: :rabbit\_misc.format\_many/1
> (rabbitmqctl) lib/rabbitmqctl.ex:349: RabbitMQCtl.get\_node\_diagnostics/1
> (rabbitmqctl) lib/rabbitmqctl.ex:307: RabbitMQCtl.format\_error/3
> (rabbitmqctl) lib/rabbitmqctl.ex:43: RabbitMQCtl.main/1
> (elixir) lib/kernel/cli.ex:76: anonymous fn/3 in Kernel.CLI.exec\_fun/2
>
>
>
I use win10 and my path is
erl: `D:\RabbitMQ\erl9.3\bin`
rabbitmq: `D:\RabbitMQ\rabbitMQ\rabbitmq_server-3.7.4\sbin`
Actually,my computer's username used to be chinese and now I change it to english,it also doesn't work.Now I think my path hasn't non-ASCII charactor.
I have no idea with this problem,can anyone help me? Thanks!<issue_comment>username_1: You can see your 'C:\Users\username' is not English . change it to English.
Upvotes: 0 <issue_comment>username_2: ```
'C:\Users\username'
```
My computer 'username' is Chinese, so we need stop RebbitMQ service, then execute the following 3 statements:
```
rabbitmq-service.bat remove
set RABBITMQ_BASE=D:\install3\rabbitmq\rabbitmq_server-3.7.8\data
rabbitmq-service.bat install
```
RABBITMQ\_BASE is my storage path of db and log, now it works very well.
Upvotes: -1 |
2018/03/20 | 1,679 | 5,010 | <issue_start>username_0: I am trying to include a file with functions in another Julia file. I can do it with
```
include("ImpurityChainLibrary.jl")
```
However, when I do
```
@everywhere include("ImpurityChainLibrary.jl")
```
I get an error (shortened):
```
ERROR: On worker 3: SystemError: opening file /Users/alex/Documents/Julia/Graphene_Adsorbant_Lattice/ImpurityChainLibrary.jl: No such file or directory ...
```
I am running
```
Julia Version 0.6.2
Commit <PASSWORD> (2017-12-13 18:08 UTC)
Platform Info:
OS: macOS (x86_64-apple-darwin14.5.0)
CPU: Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz
WORD_SIZE: 64
BLAS: libopenblas (USE64BITINT DYNAMIC_ARCH NO_AFFINITY Haswell)
LAPACK: libopenblas64_
LIBM: libopenlibm
LLVM: libLLVM-3.9.1 (ORCJIT, skylake)
```
I use Atom.
Following the minimal example given below, I ran the code and it worked. Then, I created a second file in the same folder as dummy.jl and put in a single line `@everywhere include("dummy.jl")`.
Then I launch Julia in Atom. I check nprocs() and get 1. When I do addprocs(3), the function call goes through and nprocs() shows 4. When I try to run the `@everywhere include("dummy.jl")` line, I get the error that I described above.
What am I doing wrong?
Thank you<issue_comment>username_1: **DISCLAIMER.** Because the comment field is too short for this, I have compiled an answer instead:
Please include your Julia version as printed in `versioninfo()`. For instance, I am running
```
julia> versioninfo()
Julia Version 0.6.2
Commit <PASSWORD>0c17 (2017-12-13 18:08 UTC)
Platform Info:
OS: Linux (x86_64-pc-linux-gnu)
CPU: Intel(R) Core(TM) i7-3720QM CPU @ 2.60GHz
WORD_SIZE: 64
BLAS: libopenblas (SANDYBRIDGE)
LAPACK: liblapack
LIBM: libopenlibm
LLVM: libLLVM-3.9.1 (ORCJIT, ivybridge)
```
Then, please make sure to provide an [MCVE](https://stackoverflow.com/help/mcve). With the information you have provided in your question, it is *not* possible for us to reproduce your error. The reason is simple. Check the minimal working example below on my machine:
```sh
~> mkdir dummy
~> cd dummy/
~/dummy> echo "f(x) = 5x" > dummy.jl
~/dummy> julia --procs 4 --eval '@everywhere include("dummy.jl"); @everywhere @show myid(), f(myid())'
(myid(), f(myid())) = (1, 5)
From worker 4: (myid(), f(myid())) = (4, 20)
From worker 3: (myid(), f(myid())) = (3, 15)
From worker 5: (myid(), f(myid())) = (5, 25)
From worker 2: (myid(), f(myid())) = (2, 10)
```
Most likely, you have some code that changes directory before calling `@everywhere`. Make sure the error can be reproduced easily on other computers.
**EDIT.** I have added the minimal working example based on OP's modified question below:
```
shell> ls
anotherfile.jl dummy.jl
shell> cat dummy.jl
f(x) = 5x
shell> cat anotherfile.jl
@everywhere include("dummy.jl")
julia> addprocs(3)
3-element Array{Int64,1}:
2
3
4
julia> nprocs()
4
julia> include("anotherfile.jl")
julia> @everywhere @show myid(), f(myid())
(myid(), f(myid())) = (1, 5)
From worker 2: (myid(), f(myid())) = (2, 10)
From worker 3: (myid(), f(myid())) = (3, 15)
From worker 4: (myid(), f(myid())) = (4, 20)
```
As can be seen, the setting you have tried, *i.e.*, adding `anotherfile` and putting `@everywhere include("dummy.jl")` line in it, works as expected, too. Then, you should try opening [an issue](https://github.com/JunoLab/Atom.jl/issues) to let the developers for Atom know about it, if that is the problem, at all.
Upvotes: 2 <issue_comment>username_2: I think this question was dismissed too quickly. The behavior can be reproduced outside of the Atom environment. (I'm using Julia 0.6.3 on OSX)
Suppose you have a repository structure:
```
repo/
src/
-MyMod.jl
-script.jl
```
with “MyMod.jl” containing:
```
module MyMod
export f
f(x) = 5 * x
end
```
and “script.jl” containing:
```
@everywhere include("MyMod.jl")
using MyMod
for p in workers()
@show remotecall_fetch(f, p, p)
end
```
From within `repo/src/` you can run `julia -p 4 script.jl` successfully, but from `repo/` you cannot run Julia with multiple processes (i.e. call `julia -p 4 src/script.jl`), since the worker processes attempt to load `repo/MyMod.jl` which doesn’t exist.
This seems to be because `include` interprets relative paths differently from the main process than it does from worker processes. On main "relative" seems to be relative to the script/file, on workers it is relative to the current working directory.
As a workaround I've been using (\*\*edited to handle precompiling):
```
function include_everywhere(filepath)
include(filepath) # Load on Node 1 first, triggering any precompile
if nprocs() > 1
fullpath = joinpath(@__DIR__, filepath)
@sync for p in workers()
@async remotecall_wait(include, p, fullpath)
end
end
end
include_everywhere("MyMod.jl")
using MyMod
```
I hope this helps.
Upvotes: 3 [selected_answer] |
2018/03/20 | 2,426 | 7,832 | <issue_start>username_0: I have trouble to simplify the code in AJAX.
I use AJAX like below, and it's work perfectly, but the code looks dirty.
```
$.ajax({
url: "api/indexMajorNewsGroup.json",
dataType:'json',
type: 'GET',
cache: false,
ifModified: true,
success: function getData(result){
// =======other function=======
if(window.innerWidth>1280) {
textEllipsis('.biggestNews .majorNews h2',0,30);
textEllipsis('.otherNews #news2 h2',1,30);
textEllipsis('.otherNews #news3 h2',2,30);
textEllipsis('.otherNews #news4 h2',3,30);
textEllipsis('.otherNews #news5 h2',4,30);
}else if(window.innerWidth>980 && window.innerWidth<1280){
textEllipsis('.biggestNews .majorNews h2',0,15);
textEllipsis('.otherNews #news2 h2',1,10);
textEllipsis('.otherNews #news3 h2',2,10);
textEllipsis('.otherNews #news4 h2',3,10);
textEllipsis('.otherNews #news5 h2',4,10);
}else{
//mb
textEllipsis('#newsMb1 h2',0,15);
textEllipsis('.otherNews #news2 h2',1,15);
textEllipsis('.otherNews #news3 h2',2,15);
textEllipsis('.otherNews #news4 h2',3,15);
textEllipsis('.otherNews #news5 h2',4,15);
textEllipsis('#newsMb2 h2',5,15);
}
// =======other function=======
function NewsSlideRule(){
// =======other function=======
if(window.innerWidth>1280) {
textEllipsis('.biggestNews .majorNews h2',0,30);
textEllipsis('.otherNews #news2 h2',1,30);
textEllipsis('.otherNews #news3 h2',2,30);
textEllipsis('.otherNews #news4 h2',3,30);
textEllipsis('.otherNews #news5 h2',4,30);
}else if(window.innerWidth>980 && window.innerWidth<1280){
textEllipsis('.biggestNews .majorNews h2',0,15);
textEllipsis('.otherNews #news2 h2',1,10);
textEllipsis('.otherNews #news3 h2',2,10);
textEllipsis('.otherNews #news4 h2',3,10);
textEllipsis('.otherNews #news5 h2',4,10);
}else{
//mb
textEllipsis('#newsMb1 h2',0,15);
textEllipsis('.otherNews #news2 h2',1,15);
textEllipsis('.otherNews #news3 h2',2,15);
textEllipsis('.otherNews #news4 h2',3,15);
textEllipsis('.otherNews #news5 h2',4,15);
textEllipsis('#newsMb2 h2',0,15);
}
}
}
```
I try to put `if` in function, like this:
```
function RWDtextEllipsis(){
if(window.innerWidth>1280) {
textEllipsis('.biggestNews .majorNews h2',0,30);
textEllipsis('.otherNews #news2 h2',1,30);
textEllipsis('.otherNews #news3 h2',2,30);
textEllipsis('.otherNews #news4 h2',3,30);
textEllipsis('.otherNews #news5 h2',4,30);
}else if(window.innerWidth>980 && window.innerWidth<1280){
textEllipsis('.biggestNews .majorNews h2',0,15);
textEllipsis('.otherNews #news2 h2',1,10);
textEllipsis('.otherNews #news3 h2',2,10);
textEllipsis('.otherNews #news4 h2',3,10);
textEllipsis('.otherNews #news5 h2',4,10);
}else{
//mb
textEllipsis('#newsMb1 h2',0,15);
textEllipsis('.otherNews #news2 h2',1,15);
textEllipsis('.otherNews #news3 h2',2,15);
textEllipsis('.otherNews #news4 h2',3,15);
textEllipsis('.otherNews #news5 h2',4,15);
textEllipsis('#newsMb2 h2',0,15);
}
}
```
Call `RWDtextEllipsis()` in `NewsSlideRule()` and the out of `NewsSlideRule()`, but it's broken.
What's wrong with it?
Is there any advice to simplify my code?<issue_comment>username_1: **DISCLAIMER.** Because the comment field is too short for this, I have compiled an answer instead:
Please include your Julia version as printed in `versioninfo()`. For instance, I am running
```
julia> versioninfo()
Julia Version 0.6.2
Commit <PASSWORD> (2017-12-13 18:08 UTC)
Platform Info:
OS: Linux (x86_64-pc-linux-gnu)
CPU: Intel(R) Core(TM) i7-3720QM CPU @ 2.60GHz
WORD_SIZE: 64
BLAS: libopenblas (SANDYBRIDGE)
LAPACK: liblapack
LIBM: libopenlibm
LLVM: libLLVM-3.9.1 (ORCJIT, ivybridge)
```
Then, please make sure to provide an [MCVE](https://stackoverflow.com/help/mcve). With the information you have provided in your question, it is *not* possible for us to reproduce your error. The reason is simple. Check the minimal working example below on my machine:
```sh
~> mkdir dummy
~> cd dummy/
~/dummy> echo "f(x) = 5x" > dummy.jl
~/dummy> julia --procs 4 --eval '@everywhere include("dummy.jl"); @everywhere @show myid(), f(myid())'
(myid(), f(myid())) = (1, 5)
From worker 4: (myid(), f(myid())) = (4, 20)
From worker 3: (myid(), f(myid())) = (3, 15)
From worker 5: (myid(), f(myid())) = (5, 25)
From worker 2: (myid(), f(myid())) = (2, 10)
```
Most likely, you have some code that changes directory before calling `@everywhere`. Make sure the error can be reproduced easily on other computers.
**EDIT.** I have added the minimal working example based on OP's modified question below:
```
shell> ls
anotherfile.jl dummy.jl
shell> cat dummy.jl
f(x) = 5x
shell> cat anotherfile.jl
@everywhere include("dummy.jl")
julia> addprocs(3)
3-element Array{Int64,1}:
2
3
4
julia> nprocs()
4
julia> include("anotherfile.jl")
julia> @everywhere @show myid(), f(myid())
(myid(), f(myid())) = (1, 5)
From worker 2: (myid(), f(myid())) = (2, 10)
From worker 3: (myid(), f(myid())) = (3, 15)
From worker 4: (myid(), f(myid())) = (4, 20)
```
As can be seen, the setting you have tried, *i.e.*, adding `anotherfile` and putting `@everywhere include("dummy.jl")` line in it, works as expected, too. Then, you should try opening [an issue](https://github.com/JunoLab/Atom.jl/issues) to let the developers for Atom know about it, if that is the problem, at all.
Upvotes: 2 <issue_comment>username_2: I think this question was dismissed too quickly. The behavior can be reproduced outside of the Atom environment. (I'm using Julia 0.6.3 on OSX)
Suppose you have a repository structure:
```
repo/
src/
-MyMod.jl
-script.jl
```
with “MyMod.jl” containing:
```
module MyMod
export f
f(x) = 5 * x
end
```
and “script.jl” containing:
```
@everywhere include("MyMod.jl")
using MyMod
for p in workers()
@show remotecall_fetch(f, p, p)
end
```
From within `repo/src/` you can run `julia -p 4 script.jl` successfully, but from `repo/` you cannot run Julia with multiple processes (i.e. call `julia -p 4 src/script.jl`), since the worker processes attempt to load `repo/MyMod.jl` which doesn’t exist.
This seems to be because `include` interprets relative paths differently from the main process than it does from worker processes. On main "relative" seems to be relative to the script/file, on workers it is relative to the current working directory.
As a workaround I've been using (\*\*edited to handle precompiling):
```
function include_everywhere(filepath)
include(filepath) # Load on Node 1 first, triggering any precompile
if nprocs() > 1
fullpath = joinpath(@__DIR__, filepath)
@sync for p in workers()
@async remotecall_wait(include, p, fullpath)
end
end
end
include_everywhere("MyMod.jl")
using MyMod
```
I hope this helps.
Upvotes: 3 [selected_answer] |
2018/03/20 | 363 | 1,142 | <issue_start>username_0: I am using JedisCluster, and I need to set a key with 1-hour expiry, now I am doing something like
```
getJedisCluster().set(key,value);
getJedisCluster().expire(key, 60 * 60);
```
But I hope I can using a single command to reduce the round trip to send commands
With Redis cli , I can write this:
```
set key value ex 3600
```
But in JedisCluster, I can only find a interface:
```
public String set(final String key, final String value, final String nxxx, final String expx, final long time) {
```
which means I either should use setex or setnx.
But I hope my set command applies both to update or insert.
How can I do this?
Ps: Jedis-Client's version is 2.9.0<issue_comment>username_1: You can use setex method directly. It does exactly this
```
set key value ex 3600
```
Upvotes: 1 <issue_comment>username_2: If you are using jedis client version 2.9.1
```
jedis.setex(sid, 86400,String.valueOf(version));
```
In the latest versions, we have something like this
[](https://i.stack.imgur.com/IsyZK.png)
Upvotes: 2 |
2018/03/20 | 484 | 1,581 | <issue_start>username_0: I recently upgrade my aframe from 0.5.0 directly to 0.8.1 due to Chrome v65 compatibility issue. One of the changes, as documented is that Aframe no longer controls camera pose, which will be controlled directly by three.js.
There is a recent PR here about the change: <https://github.com/aframevr/aframe/pull/3327>
This change removes the userHeight parameter support for camera position. In my application, I would need the camera to be at (0, 0, 0) in both VR and non-VR mode.
I tried to use:
```
```
or
```
```
but the result of both of them is that the camera is position at (0, 0, 0) before entering VR. After entering VR, the it is at (0, 1.6, 0) and after exiting VR, it remains at (0, 1.6, 0).
The question is: how do I set the camera postion to (0, 0, 0) in both VR and non-VR mode in [email protected]?
Also, this [answer](https://stackoverflow.com/questions/41624558/how-to-reset-camera-position-on-enter-vr) is no longer valid right?<issue_comment>username_1: Does wrapping your camera in an entity help?
<https://aframe.io/docs/0.8.0/primitives/a-camera.html#manually-positioning-the-camera>
```
```
Upvotes: 1 <issue_comment>username_2: I had a similar issue to this with camera rotation when I updated to 0.8.
From what I understand, the latest version has now moved the position and rotation management to threejs.
In order to resolve this, you should use a "rig" around the camera and set your position on the rig.
The rig is simply a parent entity, that the children will get the relative settings from.
```
```
Upvotes: 2 |
2018/03/20 | 643 | 2,833 | <issue_start>username_0: I just downloaded an `Ionic` project from internet.
On the file: `src/pages/home/home.ts` I have the following fragment of code:
```
...
addTodo() {
let prompt = this.alertCtrl.create({
title: 'Add Todo',
message: 'Describe your todo below:',
inputs: [
{
name: 'title'
}
],
buttons: [
{
text: 'Cancel'
},
{
text: 'Save',
handler: todo => {
if (todo) {
this.showLoader();
this.todoService.createTodo(todo).then(
result => {
this.loading.dismiss();
this.todos = result;
console.log("todo created");
},
err => {
this.loading.dismiss();
console.log("not allowed");
}
);
}
}
}
]
});
prompt.present();
}
...
```
On the file: `src/providers/todos.ts` I have the following fragment of code:
```
...
createTodo(todo) {
return new Promise((resolve, reject) => {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', this.authService.token);
this.http
.post(
'http://1172.16.58.3:8080/api/todos',
JSON.stringify(todo),
{ headers: headers }
)
.map(res => res.json())
.subscribe(
res => {
resolve(res);
},
err => {
reject(err);
}
);
});
}
...
```
**My question is:**
On the file: `home.ts` where we have: `handler: todo => { ... }` what's the content of the parameter: `todo`?, is it an object?, is it a string with the title of the todo?
What happens inside...
```
this.todoService.createTodo(todo)
```<issue_comment>username_1: Does wrapping your camera in an entity help?
<https://aframe.io/docs/0.8.0/primitives/a-camera.html#manually-positioning-the-camera>
```
```
Upvotes: 1 <issue_comment>username_2: I had a similar issue to this with camera rotation when I updated to 0.8.
From what I understand, the latest version has now moved the position and rotation management to threejs.
In order to resolve this, you should use a "rig" around the camera and set your position on the rig.
The rig is simply a parent entity, that the children will get the relative settings from.
```
```
Upvotes: 2 |
2018/03/20 | 775 | 2,695 | <issue_start>username_0: I'm using `DispatchGroup` to perform a task, but `group.notify` is being called before the task is completed.
My code:
```
let group = DispatchGroup()
let queueImage = DispatchQueue(label: "com.image")
let queueVideo = DispatchQueue(label: "com.video")
queueImage.async(group: group) {
sleep(2)
print("image")
}
queueVideo.async(group: group) {
sleep(3)
print("video")
}
group.notify(queue: .main) {
print("all finished.")
}
```
Logs:
```
all finish.
image
video
```<issue_comment>username_1: **Update:** The question above actually runs correctly as is (as rmaddy pointed out!)
I'm saving this wrong answer below in case others get confused about DispatchQueue's async(group:) methods behavior, since [Apple's swift doc on it](https://developer.apple.com/documentation/dispatch/dispatchqueue/2016098-async) is currently lousy.
---
The group's enter() needs to be called before each call to async(), and then the group's leave() needs to be called at end of each async() block, but *within* the block. It's basically like a refcount that when it reaches zero (no enters remaining), then the notify block is called.
```
let group = DispatchGroup()
let queueImage = DispatchQueue(label: "com.image")
let queueVideo = DispatchQueue(label: "com.video")
group.enter()
queueImage.async(group: group) {
sleep(2)
print("image")
group.leave()
}
group.enter()
queueVideo.async(group: group) {
sleep(3)
print("video")
group.leave()
}
group.notify(queue: .main) {
print("all finished.")
}
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: Generic answer : (Swift 5)
```
let yourDispatchGroup = DispatchGroup()
yourDispatchGroup.enter()
task1FunctionCall {
yourDispatchGroup.leave() //task 1 complete
}
yourDispatchGroup.enter()
task2FunctionCall {
yourDispatchGroup.leave() //task 2 complete
}
.. ..
yourDispatchGroup.enter()
tasknFunctionCall {
yourDispatchGroup.leave() //task n complete
}
dispatchGroup.notify(queue: .main) {
//This is invoked when all the tasks in the group is completed.
}
```
Upvotes: 1 <issue_comment>username_3: If your `DispatchGroup` is a `lazy var`, try to not call the `notify` method inside the initialization code block.
```swift
lazy var dispatchGroup: DispatchGroup = {
let dispatchGroup = DispatchGroup()
// not call here dispatchGroup.notify(...
return dispatchGroup
}()
```
You need to call all the `enter` methods before the `notify` method:
```
dispatchGroup.enter()
dispatchQueue.async(group: dispatchGroup) {
// ...
self.dispatchGroup.leave()
}
dispatchGroup.notify(queue: .main) {
print("all finished.")
}
```
Upvotes: 1 |
2018/03/20 | 435 | 1,370 | <issue_start>username_0: I m testing Azure function locally using cli.
I have noticed 2 issues:
1. Sometimes CLI do not shows correct time when function will be executing. For example I have cron to execute function every two mins but it shows function will be executed after a difference of seconds ? weird.
2. Often it do not starts execution as per time shown in CLI, few times it took much time and then respond.
Is is normal ? Please guide how I can fix these.
[](https://i.stack.imgur.com/W9B6x.png)
[](https://i.stack.imgur.com/Plzyw.png)<issue_comment>username_1: try `[TimerTrigger("0 */2 * * * *")]` see examples [here](https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-timer)
Upvotes: 1 <issue_comment>username_2: `* */2 * * * *` cron expression means that you want to execute it every second (the first `*`) of every 2nd minute, so
```
2:50:00
2:50:01
2:50:02
...
2:50:59
2:52:00
2:52:01
etc
```
The correct expression is `0 */2 * * * *`: execute every 2nd minute when seconds are 0, which should give
```
2:50:00
2:52:00
```
Please check if you still have delays after this change, and it so, post it as a new question with exact description of the problem.
Upvotes: 1 [selected_answer] |
2018/03/20 | 357 | 1,152 | <issue_start>username_0: I am following [vue.js tutorial - method event handlers](https://v2.vuejs.org/v2/guide/events.html#Method-Event-Handlers)
```
handle this
.
.
.
methods: {
handler: function (event) {
console.log(JSON.stringify(event));
}}
```
However when I try to display the event all i get is `{"isTrusted":true}`
When I tried `console.log(event.target.tagName)` I get an empty string.
I think I am supposed to get Button.<issue_comment>username_1: Try it like this
```
v-on:click="handler($event)"
```
Upvotes: -1 <issue_comment>username_2: Here's a [codepen](https://codepen.io/DakshMiglani/pen/pLRdyy?editors=1010) which I created.
My Vue Instance looks like:
```
new Vue({
el: '#app',
methods: {
greet: (e) => {
console.log(e.target.tagName);
}
},
})
```
and my html looks like this:
```
Yo, I'm a button
```
and when i see the console, it looks like this:
[](https://i.stack.imgur.com/jDmdq.png)
Upvotes: 3 [selected_answer] |
2018/03/20 | 1,147 | 3,719 | <issue_start>username_0: I'm just curious on which of these methods is better (or if there's an even better one that I'm missing). I'm trying to determine if the first letter and last letter of a word are the same, and there are two obvious solutions to me.
```
if word[:1] == word[len(word)-1:]
```
or
```
if word[0] == word[len(word)-1]
```
As I understand it, the first is just pulling slices of the string and doing a string comparison, while the second is pulling the character from either end and comparing as bytes.
I'm curious if there's a performance difference between the two, and if there's any "preferable" way to do this?<issue_comment>username_1: In Go, `string`s are UTF-8 encoded. UTF-8 is a variable-length encoding.
```
package main
import "fmt"
func main() {
word := "世界世"
fmt.Println(word[:1] == word[len(word)-1:])
fmt.Println(word[0] == word[len(word)-1])
}
```
Output:
```
false
false
```
---
If you really want to compare a byte, not a character, then be as precise as possible for the compiler. Obviously, compare a byte, not a slice.
```
BenchmarkSlice-4 200000000 7.55 ns/op
BenchmarkByte-4 2000000000 1.08 ns/op
package main
import "testing"
var word = "word"
func BenchmarkSlice(b *testing.B) {
for i := 0; i < b.N; i++ {
if word[:1] == word[len(word)-1:] {
}
}
}
func BenchmarkByte(b *testing.B) {
for i := 0; i < b.N; i++ {
if word[0] == word[len(word)-1] {
}
}
}
```
Upvotes: 3 <issue_comment>username_2: If by letter you mean [rune](https://golang.org/ref/spec#Rune_literals), then use:
```
func eqRune(s string) bool {
if s == "" {
return false // or true if that makes more sense for the app
}
f, _ := utf8.DecodeRuneInString(s) // 2nd return value is rune size. ignore it.
l, _ := utf8.DecodeLastRuneInString(s) // 2nd return value is rune size. ignore it.
if f != l {
return false
}
if f == unicode.ReplacementChar {
// First and last are invalid UTF-8. Fallback to
// comparing bytes.
return s[0] == s[len(s)-1]
}
return true
}
```
If you mean byte, then use:
```
func eqByte(s string) bool {
if s == "" {
return false // or true if that makes more sense for the app
}
return s[0] == s[len(s)-1]
}
```
Comparing individual bytes is faster than comparing string slices as shown by the benchmark in another answer.
[playground example](https://play.golang.org/p/phizJQhd92g)
Upvotes: 3 [selected_answer]<issue_comment>username_3: A string is a sequence of bytes. Your method works if you know the string contains only ASCII characters. Otherwise, you should use a method that handles multibyte characters instead of string indexing. You can convert it to a rune slice to process code points or characters, like this:
```
r := []rune(s)
return r[0] == r[len(r) - 1]
```
You can read more about strings, byte slices, runes, and code points in [the official Go Blog post on the subject](https://blog.golang.org/strings).
To answer your question, there's no significant performance difference between the two index expressions you posted.
Here's a runnable example:
```
package main
import "fmt"
func EndsMatch(s string) bool {
r := []rune(s)
return r[0] == r[len(r) - 1]
}
func main() {
tests := []struct{
s string
e bool
}{
{"foo", false},
{"eve", true},
{"世界世", true},
}
for _, t := range tests {
r := EndsMatch(t.s)
if r != t.e {
fmt.Printf("EndsMatch(%s) failed: expected %t, got %t\n", t.s, t.e, r)
}
}
}
```
Prints nothing.
Upvotes: 0 |
2018/03/20 | 1,487 | 5,036 | <issue_start>username_0: I have some JSON like this:
```
{
"a": { "text": "text", "index": 5 },
"b": { "text": "text", "index": 3 },
"c": { "text": "text", "index": 1 },
}
```
Now I need to interate this object and call a function on every property of the first level (a, b and c), but I have to do it on order using the "index" property, like "c" first, then "b" and last "a".
However I read that I shouldn't use a for in loop:
>
> A for...in loop iterates over the properties of an object in an arbitrary order (see the delete operator for more on why one cannot depend on the seeming orderliness of iteration, at least in a cross-browser setting).
>
>
>
then how I can do this?
Thanks<issue_comment>username_1: Probably you should use `Object.keys` to get a list of all the properties, sort that list, then iterate over it.
Upvotes: -1 <issue_comment>username_2: You could,
1. Get the properties of the object as an array using [`Object.keys()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys).
2. Sort the properties of the object using [`sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort).
3. Use [`forEach()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) to iterate through the sorted items (which is executed in ascending order of the array).
```js
var items = {
"a": {
"text": "text",
"index": 5
},
"b": {
"text": "text",
"index": 3
},
"c": {
"text": "text",
"index": 1,
}
};
Object.keys(items).sort(function(a, b) {
return items[a].index - items[b].index;
}).forEach(doStuff);
function doStuff(key) {
console.log(items[key]);
}
```
Upvotes: 4 [selected_answer]<issue_comment>username_3: You can use [getOwnPropertyNames](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames)
```js
let obj = {
"a": { "text": "text", "index": 5 },
"b": { "text": "text", "index": 3 },
"c": { "text": "text", "index": 1 }
};
function test(p) {
console.log(p);
}
Object.getOwnPropertyNames(obj)
.reverse()
.forEach(function(p){
test(obj[p]);
});
```
Upvotes: 2 <issue_comment>username_4: The another solution is store the object keys and reverse it, then iterate with the object keys.
```js
var obj = {
"a": { "text": "text", "index": 5 },
"b": { "text": "text", "index": 3 },
"c": { "text": "text", "index": 1 }
};
var yourFunction = console.log;
var keys = Object.keys(obj);
keys.reverse();
for (var i = 0; i < keys.length; i++) {
yourFunction(obj[keys[i]]);
}
```
Upvotes: 0 <issue_comment>username_5: You can try the following:
1. Covert the object to an array with elements in sorted order based on the index.
2. Than simply forEach() on the sorted properties.
Sort function can be implemented as :
```js
var obj = {
"a": { "text": "text", "index": 5 },
"b": { "text": "text", "index": 3 },
"c": { "text": "text", "index": 1},
}
function sortProperties(obj, sortedBy, isNumericSort, reverse) {
sortedBy = sortedBy || 1; // by default first key
isNumericSort = isNumericSort || false; // by default text sort
reverse = reverse || false; // by default no reverse
var reversed = (reverse) ? -1 : 1;
var sortable = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
sortable.push([key, obj[key]]);
}
}
if (isNumericSort)
sortable.sort(function (a, b) {
return reversed * (a[1][sortedBy] - b[1][sortedBy]);
});
else
sortable.sort(function (a, b) {
var x = a[1][sortedBy].toLowerCase(),
y = b[1][sortedBy].toLowerCase();
return x < y ? reversed * -1 : x > y ? reversed : 0;
});
return sortable; // array in format [ [ key1, val1 ], [ key2, val2 ], ... ]
}
sortProperties(obj, 'index', true, false);
```
Upvotes: 1 <issue_comment>username_6: you can also make use of `reverse()` method of javascript if you want to access the json items in reverse order.
get the array of all the keys of json using `Object.keys()`
reverse the array using `reverse()` method
and finally you can make use of javascript `forEach()` method to work on the items of the json. Sample code is shown below
```
let obj = {
"a": { "text": "text", "index": 5 },
"b": { "text": "text", "index": 3 },
"c": { "text": "text", "index": 1 },
}
Object.keys(obj)
.reverse()
.forEach(ele => {
console.log(obj[ele]);
});
```
visit **[This link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse)** to know more about `reverse()` method
Upvotes: 0 |
2018/03/20 | 472 | 1,754 | <issue_start>username_0: We are using react-native-google-signIn for android in our project. We have created a project in google developer console and downloaded the google-services.json file. The google-services.json file is placed in android/apps folder.
When we configure the googleSignIn in code , am getting error: 10 code from google.
```
GoogleSignin.configure({
webClientId:'***********************.apps.googleusercontent.com'
})
```
If i don't pass the `webClientId` , the sign-in is successful but `idToken` is returned as null in the user object.
I made sure that the `webClientId` value is correct by following [[1]](https://www.npmjs.com/package/react-native-google-signin) and [[2]](https://github.com/devfd/react-native-google-signin/issues/263).
Any suggestions in this regard will be appreciated.<issue_comment>username_1: Your SHA-1 key may be incorrect. The comment of @mtt87 did help me:
<https://github.com/devfd/react-native-google-signin/issues/224>
Upvotes: 2 [selected_answer]<issue_comment>username_2: I am using firebase and kept getting the same issue until I passed the web client\_id from the firebase google-services file into the GoogleSignin.configure method.
```
await GoogleSignin.configure({
webClientId: '.apps.googleusercontent.com',
});
const userInfo = await GoogleSignin.signIn();
```
Upvotes: 1 <issue_comment>username_3: May be there is a problem related to SHA1 key.
Make sure you have placed both debug and release SHA1 key to your firebase project.
for finding SHA1 key:
go to your android folder and hit below command
For debug mode :
```
keytool -keystore app/debug.keystore -list -v
```
For release mode:
```
keytool -keystore app/release.keystore -list -v
```
Upvotes: 0 |
2018/03/20 | 1,009 | 2,704 | <issue_start>username_0: I have array like this :
```
Array (
[2018-03-12] => Array (
[United States] => 4
[Australia] => 15
[United Kingdom] => 0
[New Zealand] => 0
)
[2018-03-13] => Array (
[United States] => 0
[Australia] => 8
[United Kingdom] => 2
[New Zealand] => 0
)
)
```
I want to make an array like this:
```
[
["2018-03-12", 4, 15, 0, 0],
["2018-03-13", 0, 8, 0, 2]
]
```
How can this be done?<issue_comment>username_1: Try:
```
$arr = [
'2018-03-12' => [
'United States' => 4,
'Australia' => 15,
'United Kingdom' => 0,
'New Zealand' => 0,
],
'2018-03-13' => [
'United States' => 0,
'Australia' => 8,
'United Kingdom' => 2,
'New Zealand' => 0,
]
];
return array_map(function ($item, $key) {
return array_merge([$key], array_values($item));
},$arr, array_keys($arr));
```
Demo <https://implode.io/K8yHG0>
Upvotes: 4 [selected_answer]<issue_comment>username_2: You only need to iterate each top level element, then merge/store the key as an element and the subarray values.
Code: ([Demo](https://3v4l.org/FqrUX))
```
$array = [
'2018-03-12' => [
'United States' => 4,
'Australia' => 15,
'United Kingdom' => 0,
'New Zealand' => 0,
],
'2018-03-13' => [
'United States' => 0,
'Australia' => 8,
'United Kingdom' => 2,
'New Zealand' => 0,
]
];
foreach ($array as $key => $subarray) {
$result[] = array_merge([$key], array_values($subarray));
}
var_export($result);
```
Output:
```
array (
0 =>
array (
0 => '2018-03-12',
1 => 4,
2 => 15,
3 => 0,
4 => 0,
),
1 =>
array (
0 => '2018-03-13',
1 => 0,
2 => 8,
3 => 2,
4 => 0,
),
)
```
Or you can unshift the key into subarray and reindex both levels.
```
foreach ($array as $key => $subarray) {
array_unshift($subarray, $key);
$result[] = array_values($subarray);
}
```
Or you can use the Union Operator to merge the key with the subarray elements and then reindex.
```
foreach ($array as $key => $subarray) {
$result[] = array_values([$key] + $subarray);
}
```
You can even unpack the subarray into an array\_push call if your php version allows variadics.
```
foreach ($array as $key => $subarray) {
$temp = [];
array_push($temp, $key, ...array_values($subarray));
$result[] = $temp;
}
```
Or ([Demo](https://3v4l.org/9RJR4))
```
var_export(
array_map(
fn($k) => array_merge([$k], array_values($array[$k])),
array_keys($array)
)
);
```
Upvotes: 0 |
2018/03/20 | 1,013 | 2,773 | <issue_start>username_0: I want to create a nested list by a repetition of a simple list, say
```
x = ['a','b','c']
y = [x] * 3
```
Which results in
```
[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
```
When I change an element of one of the nested lists, the corresponding elements in all other lists also change:
```
y[0][0] = 'z'
[['z', 'b', 'c'], ['z', 'b', 'c'], ['z', 'b', 'c']]
```
What should I do in order to get the following list instead of the above change in all list items?
```
[['z', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
```<issue_comment>username_1: Try:
```
$arr = [
'2018-03-12' => [
'United States' => 4,
'Australia' => 15,
'United Kingdom' => 0,
'New Zealand' => 0,
],
'2018-03-13' => [
'United States' => 0,
'Australia' => 8,
'United Kingdom' => 2,
'New Zealand' => 0,
]
];
return array_map(function ($item, $key) {
return array_merge([$key], array_values($item));
},$arr, array_keys($arr));
```
Demo <https://implode.io/K8yHG0>
Upvotes: 4 [selected_answer]<issue_comment>username_2: You only need to iterate each top level element, then merge/store the key as an element and the subarray values.
Code: ([Demo](https://3v4l.org/FqrUX))
```
$array = [
'2018-03-12' => [
'United States' => 4,
'Australia' => 15,
'United Kingdom' => 0,
'New Zealand' => 0,
],
'2018-03-13' => [
'United States' => 0,
'Australia' => 8,
'United Kingdom' => 2,
'New Zealand' => 0,
]
];
foreach ($array as $key => $subarray) {
$result[] = array_merge([$key], array_values($subarray));
}
var_export($result);
```
Output:
```
array (
0 =>
array (
0 => '2018-03-12',
1 => 4,
2 => 15,
3 => 0,
4 => 0,
),
1 =>
array (
0 => '2018-03-13',
1 => 0,
2 => 8,
3 => 2,
4 => 0,
),
)
```
Or you can unshift the key into subarray and reindex both levels.
```
foreach ($array as $key => $subarray) {
array_unshift($subarray, $key);
$result[] = array_values($subarray);
}
```
Or you can use the Union Operator to merge the key with the subarray elements and then reindex.
```
foreach ($array as $key => $subarray) {
$result[] = array_values([$key] + $subarray);
}
```
You can even unpack the subarray into an array\_push call if your php version allows variadics.
```
foreach ($array as $key => $subarray) {
$temp = [];
array_push($temp, $key, ...array_values($subarray));
$result[] = $temp;
}
```
Or ([Demo](https://3v4l.org/9RJR4))
```
var_export(
array_map(
fn($k) => array_merge([$k], array_values($array[$k])),
array_keys($array)
)
);
```
Upvotes: 0 |
2018/03/20 | 858 | 2,407 | <issue_start>username_0: When i run `heroku pg:psql` i get `--> Connecting to postgresql-cylindrical-38664`
and stalls out. Everything is looking good to go, it just gets stuck and doesn't do anything.<issue_comment>username_1: Try:
```
$arr = [
'2018-03-12' => [
'United States' => 4,
'Australia' => 15,
'United Kingdom' => 0,
'New Zealand' => 0,
],
'2018-03-13' => [
'United States' => 0,
'Australia' => 8,
'United Kingdom' => 2,
'New Zealand' => 0,
]
];
return array_map(function ($item, $key) {
return array_merge([$key], array_values($item));
},$arr, array_keys($arr));
```
Demo <https://implode.io/K8yHG0>
Upvotes: 4 [selected_answer]<issue_comment>username_2: You only need to iterate each top level element, then merge/store the key as an element and the subarray values.
Code: ([Demo](https://3v4l.org/FqrUX))
```
$array = [
'2018-03-12' => [
'United States' => 4,
'Australia' => 15,
'United Kingdom' => 0,
'New Zealand' => 0,
],
'2018-03-13' => [
'United States' => 0,
'Australia' => 8,
'United Kingdom' => 2,
'New Zealand' => 0,
]
];
foreach ($array as $key => $subarray) {
$result[] = array_merge([$key], array_values($subarray));
}
var_export($result);
```
Output:
```
array (
0 =>
array (
0 => '2018-03-12',
1 => 4,
2 => 15,
3 => 0,
4 => 0,
),
1 =>
array (
0 => '2018-03-13',
1 => 0,
2 => 8,
3 => 2,
4 => 0,
),
)
```
Or you can unshift the key into subarray and reindex both levels.
```
foreach ($array as $key => $subarray) {
array_unshift($subarray, $key);
$result[] = array_values($subarray);
}
```
Or you can use the Union Operator to merge the key with the subarray elements and then reindex.
```
foreach ($array as $key => $subarray) {
$result[] = array_values([$key] + $subarray);
}
```
You can even unpack the subarray into an array\_push call if your php version allows variadics.
```
foreach ($array as $key => $subarray) {
$temp = [];
array_push($temp, $key, ...array_values($subarray));
$result[] = $temp;
}
```
Or ([Demo](https://3v4l.org/9RJR4))
```
var_export(
array_map(
fn($k) => array_merge([$k], array_values($array[$k])),
array_keys($array)
)
);
```
Upvotes: 0 |
2018/03/20 | 203 | 588 | <issue_start>username_0: I want to search something only datewise without time stamp in Postgres DB.<issue_comment>username_1: Select The Date in query and use % after ex.
```
Select * from tble Where date LIKE '2017-01-10%'
```
Upvotes: -1 <issue_comment>username_2: select \* from table
where trunc(date) = to\_Date(;01/01/2018','mm/dd/yyyy')
Upvotes: -1 <issue_comment>username_3: ```
SELECT * FROM tble WHERE date(date) = '2017-01-10'
```
Upvotes: 1 <issue_comment>username_4: Try using the following code:
```
SELECT * FROM table WHERE date::date = '2021-02-09'
```
Upvotes: 0 |
2018/03/20 | 852 | 3,679 | <issue_start>username_0: I am making an app that using CLLocationManager, this app will be used to record the attendee of the employee. to validate the attendee of the employees, we will get GPS Coordinate.
as far as I know, in there is an app that usually used to get fake GPS. I want to prevent this mock GPS to be active when the user using my app.
If I am using Android, I can download a fake GPS app. and when let say I use tinder I can fake my location. let say actually I am in Bangkok, but because I use fake GPS app, I can set my tinder location to be in London, not in Bangkok anymore.
So Basically I want to prevent fake location that comes from that fake GPS when the user using my App. To be honest I don't really know whether iOS allow fake location or not
can I get that function in Swift?
here is the class LocationManager I use to get the coordinate
```
import UIKit
import CoreLocation
class LocationManager: NSObject {
let manager = CLLocationManager()
var didGetLocation: ((Coordinate?) -> Void)?
override init() {
super.init()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestLocation()
}
func getPermission() {
// to ask permission to the user by showing an alert (the alert message is available on info.plist)
if CLLocationManager.authorizationStatus() == .notDetermined {
manager.requestWhenInUseAuthorization()
}
}
}
extension LocationManager : CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
manager.requestLocation()
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error.localizedDescription)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.first else {
didGetLocation?(nil)
return
}
let coordinate = Coordinate(location: location)
if let didGetLocation = didGetLocation {
didGetLocation(coordinate)
}
}
}
private extension Coordinate {
init(location: CLLocation) {
latitude = location.coordinate.latitude
longitude = location.coordinate.longitude
}
}
```<issue_comment>username_1: Only thing I can tell you and I've been in a similar situation is you need to have a backup method to get the user location. Use an IP location API/service (which is not 100% reliable) and create a logic in your app to compare the data.
**PS: THIS IS NOT A SOLUTION TO YOUR PROBLEM** it's just an idea you could try to work with. But this would only work best if spoofing the location is happening using different cities/states since IP location is not a high accuracy one. If GPS says you are in San Diego but your IP say you are in San Francisco, then you could block the UI/request until user confirms something.
PS2: in iOS the only way I know a user can spoof it's location is running an app through XCode, using the location feature and then opening your app. (used to do that a lot with pokemon go #notproud :))
Upvotes: 2 <issue_comment>username_2: You can check if the app is jailbroken or not. If it already jailbroken, you can prevent the user to use the app with showing permanent dialog or something else.
If you wanna know how to detect the device is jailbroken or not, you can find it by yourself. There is so many literature that will tell you how.
Cheers :)
Upvotes: 3 [selected_answer] |
2018/03/20 | 468 | 1,760 | <issue_start>username_0: I am using Laravel 5.5 and I am unable to delete the notification using the below query. It gives the following error :
>
> SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
> error in your SQL syntax; check the manual that corresponds to your
> MariaDB server version for the right syntax to use near '>video\_id=89'
> at line 1 (SQL: delete from `notifications` where data->video\_id=89).
>
>
>
`DB::table('notifications')->WhereRaw("data->video_id=$video_id")->delete();`<issue_comment>username_1: Only thing I can tell you and I've been in a similar situation is you need to have a backup method to get the user location. Use an IP location API/service (which is not 100% reliable) and create a logic in your app to compare the data.
**PS: THIS IS NOT A SOLUTION TO YOUR PROBLEM** it's just an idea you could try to work with. But this would only work best if spoofing the location is happening using different cities/states since IP location is not a high accuracy one. If GPS says you are in San Diego but your IP say you are in San Francisco, then you could block the UI/request until user confirms something.
PS2: in iOS the only way I know a user can spoof it's location is running an app through XCode, using the location feature and then opening your app. (used to do that a lot with pokemon go #notproud :))
Upvotes: 2 <issue_comment>username_2: You can check if the app is jailbroken or not. If it already jailbroken, you can prevent the user to use the app with showing permanent dialog or something else.
If you wanna know how to detect the device is jailbroken or not, you can find it by yourself. There is so many literature that will tell you how.
Cheers :)
Upvotes: 3 [selected_answer] |
2018/03/20 | 535 | 1,931 | <issue_start>username_0: When I type an M or an F, it skips straight to the "Invalid Option" part of the loop instead of printing the specific text. Any input is appreciated.
```
#include
int main() {
int MorF; //gender choice
printf("\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\n\n");
printf("Pick a gender. Type: M for Male or F for Female\n");
scanf(" %d" , &MorF);
if ( MorF == 'm' || MorF == 'M' ) {
printf("You chose Male\n");
} else if ( MorF == 'f' || MorF == 'F' ) {
printf("You chose Female\n");
} else {
printf("Invalid Option\n");
}
printf("\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\n\n");
}
```<issue_comment>username_1: Only thing I can tell you and I've been in a similar situation is you need to have a backup method to get the user location. Use an IP location API/service (which is not 100% reliable) and create a logic in your app to compare the data.
**PS: THIS IS NOT A SOLUTION TO YOUR PROBLEM** it's just an idea you could try to work with. But this would only work best if spoofing the location is happening using different cities/states since IP location is not a high accuracy one. If GPS says you are in San Diego but your IP say you are in San Francisco, then you could block the UI/request until user confirms something.
PS2: in iOS the only way I know a user can spoof it's location is running an app through XCode, using the location feature and then opening your app. (used to do that a lot with pokemon go #notproud :))
Upvotes: 2 <issue_comment>username_2: You can check if the app is jailbroken or not. If it already jailbroken, you can prevent the user to use the app with showing permanent dialog or something else.
If you wanna know how to detect the device is jailbroken or not, you can find it by yourself. There is so many literature that will tell you how.
Cheers :)
Upvotes: 3 [selected_answer] |
2018/03/20 | 794 | 1,460 | <issue_start>username_0: ```
$dates = array('2017-03-24 01:48:09', '2017-03-24 11:48:09', '2017-04-07 01:12:19', '2017-04-14 01:49:09', '2017-04-21 01:45:09', '2017-04-28 01:38:09');
```
if given array above..
i'm making a report to monitor user growth monthly.. i want to count the no. of entries per month
sample April 2 counts<issue_comment>username_1: ```
$dates = array('2017-03-24 01:48:09', '2017-03-24 11:48:09', '2017-04-07 01:12:19', '2017-04-14 01:49:09', '2017-04-21 01:45:09', '2017-04-28 01:38:09');
$count = array();
foreach ($dates as $d) {
$count[date('m', strtotime($d))]++;
}
print_r($count);
```
Output will be:
```
Array ([03] => 2 [04] => 4 )
```
That is: `03` (March) has 2 values in given array.
If you need `03` as `March`, then use:
```
$count[date('F', strtotime($d))]++;
```
Then, output will be:
```
Array ([March] => 2 [April] => 4 )
```
Upvotes: 1 <issue_comment>username_2: ```
php
$dates = array('2017-03-24 01:48:09', '2017-03-24 11:48:09', '2017-04-07 01:12:19', '2017-04-14 01:49:09', '2017-04-21 01:45:09', '2017-04-28 01:38:09');
foreach($dates as $date)
$year_months[] = date('Y-m', strtotime($date));
var_export($year_months);
var_export(array_count_values($year_months));
</code
```
Output:
```
array (
0 => '2017-03',
1 => '2017-03',
2 => '2017-04',
3 => '2017-04',
4 => '2017-04',
5 => '2017-04',
)array (
'2017-03' => 2,
'2017-04' => 4,
)
```
Upvotes: 0 |
2018/03/20 | 536 | 2,131 | <issue_start>username_0: The following code has an error:
>
> Use of the parameter "out" without assigning 'backup'
>
>
>
```
public void StartProgram()
{
string backup = " ";
NewContact(backup: out backup);
}
void NewContact(out string backup)
{
string contact = "Bob";
backup = backup + contact; // Error here
}
```
I can't figure out where the problem is, the method `NewContact(out string backup)` is using `out` parameters.
So, when the method is finished it is supposed to set a new value to the variable storage in the `StartProgram()` method.
( the variable is used to store all the contacts that are being created)<issue_comment>username_1: The `out` keyword denotes a parameter that is used for output only and not input. As such, the first usage of a parameter declare `out` **must** be an assignment. In your `NewContact` method, the first use of the `backup` parameter is here:
```
backup = backup + contact;
```
That code concatenates `backup` and `contact` and then assigns the result to `backup`. That means that your first use of the `backup` parameter is a concatenation, which is not an assignment and is thus not allowed.
Why are you trying to concatenate something that has no useful value at that point? If you expect that `backup` could have a value at that point then the parameter must be being used as input as well as output and should thus be declared `ref` rather than `out`.
Upvotes: 2 <issue_comment>username_2: As per **Out** Keyword Uses in C# , We need to assign the variable in Called Method(`NewContact`) then use for manipulation. So You could code like below:
```
void NewContact(out string backup)
{
backup = string.Empty; // Or any value that your logic needs.
string contact = SnapsEngine.ReadString("Enter the contact name");
string address = SnapsEngine.ReadMultiLineString("Enter " + contact + " address");
string number = SnapsEngine.ReadString("Enter " + contact + " number");
Storeinfo(contact: contact, address: address, number: number);
backup = backup + contact;
SnapsEngine.WaitForButton("Continue");
}
```
Upvotes: 0 |
2018/03/20 | 815 | 2,694 | <issue_start>username_0: Let say I have this
```
* item0
* item1
* item2
* item3
* item4
* item5
* item6
* item0
* item1
* item2
* item3
* item4
* item5
* item6
```
I'm trying to display their current index ex.(134,0256), but it displays (0123456). I tried some codes but it only display the selected index.
How can I do that?
thanks.
**SAMPLE CODE**
```
$(document).ready(function(){
$('button').click(function(){
$( "ul.list li.active" ).each(function(index) {
console.log(index);
});
});
});
```<issue_comment>username_1: The first argument in the [callback](http://api.jquery.com/each/) would be the index in the jQuery object collection. To get index relative to its siblings use [`index()`](http://api.jquery.com/index) method.
```
$(document).ready(function() {
$('button').click(function() {
$("ul.list li.active").each(function(index) {
console.log($(this).index()); // get index within its parent
});
});
});
```
```js
$("ul.list li.active").each(function(index) {
console.log($(this).index());
});
```
```html
* item0
* item1
* item2
* item3
* item4
* item5
* item6
* item0
* item1
* item2
* item3
* item4
* item5
* item6
```
---
For separating each list with a comma use additional iterator for the list, it's easy to do with jQuery [`map()`](http://api.jquery.com/map/) method.
```
console.log(
$("ul.list").map(function() { // iterate over each list
return $("li.active", this).map(function() { // iterate over children li
return $(this).index(); // return the index
}).get().join(''); // get the result as array and join the values
}).get().join() // get the result as array and join the values with comma
)
```
```js
console.log(
$("ul.list").map(function() {
return $("li.active", this).map(function() {
return $(this).index();
}).get().join('');
}).get().join()
)
```
```html
* item0
* item1
* item2
* item3
* item4
* item5
* item6
* item0
* item1
* item2
* item3
* item4
* item5
* item6
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Your selection will find all the elemnts in selection. Instead you want to find elements inside other element separately. Which I believe is only possible by searching. So your code should look like
```
$(document).ready(function() {
$('button').click(function(){
var indexes = [];
$( "ul.list").each(function() {
$("li", this).each(function(index) {
if($(this).hasClass('active') {
indexes.push(index);
}
});
});
console.log(indexes);
});
});
```
Upvotes: 1 |
2018/03/20 | 1,866 | 7,076 | <issue_start>username_0: I am trying to post 2 parameters (email: and password) to get a response from the server with detailed user information, I build API to handle this and get a good response using Postman, but when I tried to implement this with Swift4 new urlsession JSON decode and encode, it keeps failing and I got error on decoding the response data.
this my JSON response when using Postman:
```
{
"error": "false",
"message": "downloaded",
"UserInfo": {
"id": 5,
"email": "<EMAIL>",
"lastname": "Bence",
"name": "Mark",
"phone": "1234567",
"add1": "333",
"add2": "444",
"city": "ott",
"postalcode": "tttttt"
}
}
```
My struct file:
```
import UIKit
struct loginPost: Encodable {
let email: String
let password: String
}
struct User: Decodable {
let error: String?
let message: String?
let UserInfo: [UserData]
}
struct UserData: Codable {
let id: Int?
let email: String?
let lastname: String?
let name: String?
let phone: String?
let add1: String?
let add2: String?
let city: String
let postalcode: String?
}
```
**My Function**
```
func downloadJson() {
let url = URL(string: http://192.168.0.10/api/login_hashed.php)
guard let downloadURL = url else { return }
//POST Req
var request = URLRequest(url: downloadURL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let newpost = loginPost(email: "<EMAIL>", password: "<PASSWORD>")
do {
let jsonBody = try JSONEncoder().encode(newpost)
request.httpBody = jsonBody
print(jsonBody)
}catch{
print("some error")
}
URLSession.shared.dataTask(with: request) { data, urlResponse, error in
guard let data = data, error == nil, urlResponse != nil else {
print("something is wrong with url")
return
}
print("downloaded..")
do
{
let decoder = JSONDecoder()
let downloaduser = try decoder.decode(User.self, from: data)
self.logmessage = downloaduser.message!
print(self.logmessage)
DispatchQueue.main.async {
// self.tableView.reloadData()
}
} catch {
print("something wrong with decode")
}
}.resume()
}
```<issue_comment>username_1: I have figured it out finally, thanks,.
I just want to mention the cause of this error and share my experience.
The main cause is the way you send JSON and receive the incoming response. you should know exactly how the data look in order to create your struct the acceptable way.
My return data is just simple 2 line of text and array of text, my struct was:
```
import UIKit
struct loginPost: Encodable {
let email: String
let password: String
}
struct User: Decodable {
let error: String?
let message: String?
let UserInfo: [UserData]
}
struct UserData: Codable {
let id: Int?
let email: String?
let lastname: String?
let name: String?
let phone: String?
let add1: String?
let add2: String?
let city: String
let postalcode: String?
}
```
my mistake on line 18
```
let UserInfo: [UserData]
```
it should be
```
let UserInfo: UserData?
```
without the square bracket.
one more important point, always try to catch the decode error and it's dicription by implementing }catch let JsonErr {, it will give you exactly why the decode not working.
in my case:
>
> downloaded.. something wrong after downloaded
> typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath:
> [h2h.User.(CodingKeys in \_E33F61CC43E102744E4EF1B7E9D7EDDE).UserInfo],
> debugDescription: "Expected to decode Array but found a
> dictionary instead.", underlyingError: nil))
>
>
>
And make sure to make your server API to accept JSON format application/json and
decode what you send in order to receive what you looking for;
php code service API
```
$UserData = json_decode(file_get_contents("php://input"), true);
```
Upvotes: 1 <issue_comment>username_2: 1. List item
This Will work Are You Creating Model Is Wrong
----------------------------------------------
```
struct loginPost: Encodable {
let email: String
let password: String
}
struct Users:Codable {
var error:String?
var message:String?
var UserInfo:UserDetails?
}
struct UserDetails:Codable {
let id: Int?
let email: String?
let lastname: String?
let name: String?
let phone: String?
let add1: String?
let add2: String?
let city: String
let postalcode: String?
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
downloadJson()
}
func downloadJson() {
let url = URL(string: "http://192.168.0.10/api/login_hashed.php")
guard let downloadURL = url else { return }
//POST Req
var request = URLRequest(url: downloadURL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let newpost = loginPost(email: "<EMAIL>", password: "<PASSWORD>")
do {
let jsonBody = try JSONEncoder().encode(newpost)
request.httpBody = jsonBody
print(jsonBody)
}catch{
print("some error")
}
URLSession.shared.dataTask(with: request) { data, urlResponse, error in
guard let data = data, error == nil, urlResponse != nil else {
print("something is wrong with url")
return
}
print("downloaded..")
do
{
let decoder = JSONDecoder()
let downloaduser = try decoder.decode(Users.self, from: data)
// self.logmessage = downloaduser.message!
// print(self.logmessage)
DispatchQueue.main.async {
// self.tableView.reloadData()
}
} catch {
print("something wrong with decode")
}
}.resume()
}
}
```
Upvotes: 0 <issue_comment>username_3: Simplest and easy way to decode the json.
**MUST TRY**
```
struct Welcome: Codable {
let error, message: String?
let userInfo: UserInfo?
enum CodingKeys: String, CodingKey {
case error, message
case userInfo = "UserInfo"
}
}
// MARK: - UserInfo
struct UserInfo: Codable {
let id: Int?
let email, lastname, name, phone: String?
let add1, add2, city, postalcode: String?
}
```
**After that in your code , when you get response from api then write**
```
let decoder = JSONDecoder()
let obj = try! decoder.decode(Welcome.self, from: jsonData!)
Print(obj)
```
Upvotes: 1 |
2018/03/20 | 1,236 | 4,713 | <issue_start>username_0: I did clustering on spatial datasets using DBSCAN algorithm and generating a lot of noise 193000 of 250000 data. is that a reasonable amount?<issue_comment>username_1: I have figured it out finally, thanks,.
I just want to mention the cause of this error and share my experience.
The main cause is the way you send JSON and receive the incoming response. you should know exactly how the data look in order to create your struct the acceptable way.
My return data is just simple 2 line of text and array of text, my struct was:
```
import UIKit
struct loginPost: Encodable {
let email: String
let password: String
}
struct User: Decodable {
let error: String?
let message: String?
let UserInfo: [UserData]
}
struct UserData: Codable {
let id: Int?
let email: String?
let lastname: String?
let name: String?
let phone: String?
let add1: String?
let add2: String?
let city: String
let postalcode: String?
}
```
my mistake on line 18
```
let UserInfo: [UserData]
```
it should be
```
let UserInfo: UserData?
```
without the square bracket.
one more important point, always try to catch the decode error and it's dicription by implementing }catch let JsonErr {, it will give you exactly why the decode not working.
in my case:
>
> downloaded.. something wrong after downloaded
> typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath:
> [h2h.User.(CodingKeys in \_E33F61CC43E102744E4EF1B7E9D7EDDE).UserInfo],
> debugDescription: "Expected to decode Array but found a
> dictionary instead.", underlyingError: nil))
>
>
>
And make sure to make your server API to accept JSON format application/json and
decode what you send in order to receive what you looking for;
php code service API
```
$UserData = json_decode(file_get_contents("php://input"), true);
```
Upvotes: 1 <issue_comment>username_2: 1. List item
This Will work Are You Creating Model Is Wrong
----------------------------------------------
```
struct loginPost: Encodable {
let email: String
let password: String
}
struct Users:Codable {
var error:String?
var message:String?
var UserInfo:UserDetails?
}
struct UserDetails:Codable {
let id: Int?
let email: String?
let lastname: String?
let name: String?
let phone: String?
let add1: String?
let add2: String?
let city: String
let postalcode: String?
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
downloadJson()
}
func downloadJson() {
let url = URL(string: "http://1172.16.17.32/api/login_hashed.php")
guard let downloadURL = url else { return }
//POST Req
var request = URLRequest(url: downloadURL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let newpost = loginPost(email: "<EMAIL>", password: "<PASSWORD>")
do {
let jsonBody = try JSONEncoder().encode(newpost)
request.httpBody = jsonBody
print(jsonBody)
}catch{
print("some error")
}
URLSession.shared.dataTask(with: request) { data, urlResponse, error in
guard let data = data, error == nil, urlResponse != nil else {
print("something is wrong with url")
return
}
print("downloaded..")
do
{
let decoder = JSONDecoder()
let downloaduser = try decoder.decode(Users.self, from: data)
// self.logmessage = downloaduser.message!
// print(self.logmessage)
DispatchQueue.main.async {
// self.tableView.reloadData()
}
} catch {
print("something wrong with decode")
}
}.resume()
}
}
```
Upvotes: 0 <issue_comment>username_3: Simplest and easy way to decode the json.
**MUST TRY**
```
struct Welcome: Codable {
let error, message: String?
let userInfo: UserInfo?
enum CodingKeys: String, CodingKey {
case error, message
case userInfo = "UserInfo"
}
}
// MARK: - UserInfo
struct UserInfo: Codable {
let id: Int?
let email, lastname, name, phone: String?
let add1, add2, city, postalcode: String?
}
```
**After that in your code , when you get response from api then write**
```
let decoder = JSONDecoder()
let obj = try! decoder.decode(Welcome.self, from: jsonData!)
Print(obj)
```
Upvotes: 1 |
2018/03/20 | 416 | 1,134 | <issue_start>username_0: I have this query to convert into the Active record
```
SELECT (SELECT image FROM bc_item_image WHERE item_id = i.id LIMIT 1) as item_image, i.description, i.condition,c.cat_name as category_name,i.id as ID FROM bc_item i,bc_category c WHERE i.cat_id = c.id and i.user_id !='$user_id' and i.status = '1' and i.is_bartered = '0' and i.is_cancel = '0' and FIND_IN_SET('$subcat_id',i.interested_cat) order by i.display_count desc
```<issue_comment>username_1: ```
$this->db->select(" i.description, i.condition,c.cat_name as category_name,i.id,(SELECT image FROM bc_item_image WHERE item_id = i.id LIMIT 1) as item_image");
$this->db->from('bc_item as i');
$this->db->join('bc_category as c', 'i.cat_id = c.id');
$this->db->where('i.status', 1);
$this->db->where('i.is_bartered', 0);
$this->db->where('i.user_id','!=', $user_id);
$this->db->where('i.is_cancel', 0);
$this->db->where("FIND_IN_SET('".$subcat_id."','i.interested_cat')");
$query = $this->db->get();
```
Upvotes: 0 <issue_comment>username_2: use
```
$this->db->query('here your SQL query');
```
Upvotes: 1 |
2018/03/20 | 1,028 | 3,636 | <issue_start>username_0: ```
char szA[256]={0};
scanf("%[^a]%s",&szA); //failed when trailing string
scanf("%[^a]|%s",&szA); //worked whatever the input
```
What does '|' mean in a format string. I cannot find official specification. Is there anyone who can give me some clue?
When I input something with several '|' ,the latter one still works(just means that the program not breakdown). Doesn't it need two buffers given after the format string. The former one crashed when input string can be divided into more than one string. So there is still other difference between them. What is it ?
So, I cannot understand why the latter one works when the buffer number less than directive number while the former one fails. Or can someone give me a input string to make the latter one crash.<issue_comment>username_1: It's not one of the format specifiers so it's a *literal* `|` character, meaning it must be present in the input stream. The *official* specification is the section entitled `The fscanf function` found in the ISO standard (e.g., `C11 7.21.6.2`) and the relevant section states:
>
> The format is composed of zero or more directives: one or more white-space characters, an ordinary multibyte character (neither % nor a white-space character), or a conversion specification.
>
>
> A directive that is an ordinary multibyte character is executed by reading the next characters of the stream. If any of those characters differ from the ones composing the directive, the directive fails and the differing and subsequent characters remain unread.
>
>
>
---
You can see the effect in the following complete program which fails to scan `"four|1"` when you're looking for the literal `_` but works fine when you're looking for `|`.
```
#include
int main(void) {
char cjunk[100];
int ijunk;
char inStr[] = "four|1";
if (sscanf(inStr, "%4s\_%d", cjunk, &ijunk) != 2)
printf ("Could not scan\n");
if (sscanf(inStr, "%4s|%d", cjunk, &ijunk) == 2)
printf ("Scanned okay\n");
return 0;
}
```
Upvotes: 2 <issue_comment>username_2: >
> What does '|' mean in a format string. I cannot find official specification. Is there anyone who can give me some clue?
>
>
>
It means that the code expects a literal `|` in the input stream.
Having said, that format specifier is not going to work.
The `%[^a]` part will capture all characters that are not `a`. That means it will capture even a `|` from the input stream. It will stop capturing when the character `a` is encountered in the stream. Of course that does not match the literal `|` in the format string. Hence, nothing after that will be processed.
If I provide the input `def|akdk` to the following program
```
#include
int main()
{
char szA[256] = {0};
char temp[100] = {0};
int n = scanf("%[^a]|%s", szA, temp);
printf("%d\n%s\n%s\n", n, szA, temp);
}
```
I get the following output
```none
1
def|
```
which makes perfect sense. BTW, the last line in the output is an empty line. I'm not sure how to show that in an answer.
When I change the `scanf` line to
```
int n = scanf("%[^a]a%s", szA, temp);
```
I get the following output
```none
2
def|
kdk
```
which makes perfect sense.
Upvotes: 2 <issue_comment>username_3: So, after some conversation, in my comprehension, the latter one requires the remaining stream starts with '|' when dealing with the '|%s' directive. While the former directive excludes 'a' and leaves the remaining stream starts with 'a'. So the trailing directive always matches nothing and doesn't need to put anything into the buffer. So it never crashes even though the buffer not given.
Upvotes: 0 |
2018/03/20 | 1,646 | 5,589 | <issue_start>username_0: I'm trying to catch my custom Error, but for some reason my catch statements where I name the error that I know is being thrown, it skips those, goes to the default catch, and then gives me a EXC\_BAD\_INSTRUCTION (code=EXC\_I386\_INVOP, subcode=0x0) when I try to do `print("Unexpected error \(error)")`
Here's some abbreviated code:
This is the error that I have declared in my file that houses the class that I'm calling the method on (the class is called CC8DB):
```
public enum CC8RSVPError: Error {
case noEventOnDate
case invalidRSVPValue
}
```
I have a method declared as:
```
public func rsvpForEvent(_ inEventDate:Date?, forUserID inUserID:String, withValue inRSVPValue:String) throws -> CC8RSVPStatus
```
In another class were I'm calling this method, I have this:
```
do {
let rsvpResponse = try self.cc8DB.rsvpForEvent(inRSVPDate, forUserID: String(inMessage.author.id.rawValue), withValue: inRSVPValue);
...(other code to do when this doesn't fail)...
} catch CC8RSVPError.invalidRSVPValue {
...(Report specific error to user)...
} catch CC8RSVPError.noEventOnDate {
...(Report specific error to user)...
} catch {
...(Report general error to user)...
print("Error doing RSVP: \(error)");
}
```
And finally, in the CC8DB.rsvpForEvent() method, I'm triggering an error that does this:
```
throw CC8RSVPError.invalidRSVPValue;
```
The germane part of this method is:
```
public func rsvpForEvent(_ inEventDate:Date?, forUserID inUserID:String, withValue inRSVPValue:String) throws -> CC8RSVPStatus
{
var retStatus = CC8RSVPStatus(eventDate: nil, previousRSVP: "", newRSVP: "");
var upperRSVPValue:String = inRSVPValue.uppercased();
if (["YES", "MAYBE", "NO"].contains(upperRSVPValue)) {
//...(Code to do things when the info is correct)...
} else {
throw CC8RSVPError.invalidRSVPValue;
}
return retStatus;
}
```
For my test case where I'm seeing this, the inRSVPValue is "bla", to test what happens when a user doesn't enter a valid status value.
What I'm seeing is that rather than going into the `catch` that's specific for the `CC8RSVPError.invalidRSVPValue` case, it's going down to the general `catch`. In addition, I'm getting the EXC\_BAD\_INSTRUCTION on the line where I try and print the `error` value.
I've stepped through it to verify that I am indeed hitting the `throw` line that I think I am, and I can see in the debugger that the value of `error` is `CC8DB.CC8RSVPError.invalidRSVPValue`, but even if I try to do `po error` from the lldb command, I get the same exception error.
Has anyone seen this or know what I could have done to make do-try-catch not work right?<issue_comment>username_1: It's not one of the format specifiers so it's a *literal* `|` character, meaning it must be present in the input stream. The *official* specification is the section entitled `The fscanf function` found in the ISO standard (e.g., `C11 7.21.6.2`) and the relevant section states:
>
> The format is composed of zero or more directives: one or more white-space characters, an ordinary multibyte character (neither % nor a white-space character), or a conversion specification.
>
>
> A directive that is an ordinary multibyte character is executed by reading the next characters of the stream. If any of those characters differ from the ones composing the directive, the directive fails and the differing and subsequent characters remain unread.
>
>
>
---
You can see the effect in the following complete program which fails to scan `"four|1"` when you're looking for the literal `_` but works fine when you're looking for `|`.
```
#include
int main(void) {
char cjunk[100];
int ijunk;
char inStr[] = "four|1";
if (sscanf(inStr, "%4s\_%d", cjunk, &ijunk) != 2)
printf ("Could not scan\n");
if (sscanf(inStr, "%4s|%d", cjunk, &ijunk) == 2)
printf ("Scanned okay\n");
return 0;
}
```
Upvotes: 2 <issue_comment>username_2: >
> What does '|' mean in a format string. I cannot find official specification. Is there anyone who can give me some clue?
>
>
>
It means that the code expects a literal `|` in the input stream.
Having said, that format specifier is not going to work.
The `%[^a]` part will capture all characters that are not `a`. That means it will capture even a `|` from the input stream. It will stop capturing when the character `a` is encountered in the stream. Of course that does not match the literal `|` in the format string. Hence, nothing after that will be processed.
If I provide the input `def|akdk` to the following program
```
#include
int main()
{
char szA[256] = {0};
char temp[100] = {0};
int n = scanf("%[^a]|%s", szA, temp);
printf("%d\n%s\n%s\n", n, szA, temp);
}
```
I get the following output
```none
1
def|
```
which makes perfect sense. BTW, the last line in the output is an empty line. I'm not sure how to show that in an answer.
When I change the `scanf` line to
```
int n = scanf("%[^a]a%s", szA, temp);
```
I get the following output
```none
2
def|
kdk
```
which makes perfect sense.
Upvotes: 2 <issue_comment>username_3: So, after some conversation, in my comprehension, the latter one requires the remaining stream starts with '|' when dealing with the '|%s' directive. While the former directive excludes 'a' and leaves the remaining stream starts with 'a'. So the trailing directive always matches nothing and doesn't need to put anything into the buffer. So it never crashes even though the buffer not given.
Upvotes: 0 |
2018/03/20 | 1,343 | 5,108 | <issue_start>username_0: Using [flutter](http://flutter.io), I have installed the [firebase-auth](https://pub.dartlang.org/packages/firebase_auth) and [firestore](https://pub.dartlang.org/packages/cloud_firestore) packages and am able to both authenticate with firebase auth and make a call into firestore as long as I don't have any rules around the user.
I have a button that calls `_handleEmailSignIn` and I do get a valid user back (since they are in the Firebase Auth DB)
```
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
final FirebaseAuth _auth = FirebaseAuth.instance;
void _handleEmailSignIn(String email, String password) async {
try {
FirebaseUser user = await _auth.signInWithEmailAndPassword(
email: email, password: <PASSWORD>);
print("Email Signed in " + user.uid); // THIS works
} catch (err) {
print("ERROR CAUGHT: " + err.toString());
}
}
```
I then have another button that calls this function to attempt to add a record into the `testing123` collection.
```
Future \_helloWorld() async {
try {
await Firestore.instance
.collection('testing123')
.document()
.setData({'message': 'Hello world!'});
print('\_initRecord2 DONE');
} catch (err) {
print("ERROR CAUGHT: " + err.toString());
}
}
```
Now this works as long as I don't have any rules around checking the request user. This works...
```
service cloud.firestore {
match /databases/{database}/documents {
match /testing123auth/{doc} {
allow read, create
}
}
}
```
This does not which gives `PERMISSION_DENIED: Missing or insufficient permissions.` when I want to make sure I have the authenticated user I did with `_handleEmailSignIn`.
```
service cloud.firestore {
match /databases/{database}/documents {
match /testing123auth/{doc} {
allow read, create: if request.auth != null;
}
}
}
```
I suspect that the firestore request is not including the firebase user. Am I meant to configure firestore to include the user or is this supposed to be automatic as part of firebase?<issue_comment>username_1: I would have suggested to make the rule like:
```
service cloud.firestore {
match /databases/{database}/documents {
match /testing123auth/{documents=**} {
allow read, create: if true;
}
}
}
```
Or, better yet, limit the scope of the user:
```
service cloud.firestore {
match /databases/{database}/documents {
match /testing123auth/{userId} {
allow read, create:
if (request.auth.uid != null &&
request.auth.uid == userId); // DOCUMENT ID == USERID
} // END RULES FOR USERID DOC
// IF YOU PLAN TO PUT SUBCOLLECTIONS INSIDE DOCUMENT:
match /{documents=**} {
// ALL DOCUMENTS/COLLECTIONS INSIDE THE DOCUMENT
allow read, write:
if (request.auth.uid != null &&
request.auth.uid == userId);
} // END DOCUMENTS=**
} // END USERID DOCUMENT
}
}
```
Upvotes: -1 <issue_comment>username_2: to check if the user is signed in you should use
```
request.auth.uid != null
```
Upvotes: -1 <issue_comment>username_3: There shouldn't be any special configuration needed for the firestore to do this.
This is all you should need.
Modified from [Basic Security Rules](https://firebase.google.com/docs/rules/basics):
```
service cloud.firestore {
match /databases/{database}/documents {
match /testing123/{document=**} {
allow read, write: if request.auth.uid != null;
}
}
}
```
It seems they check if the `uid` is `null` rather than the `auth` itself. Try this out and see if it works. Also, it seemed that your code was inconsistent as the firestore rule had `testing123auth` and flutter had `testing123`. I'm not sure if that was intentional.
Upvotes: 0 <issue_comment>username_4: One thing to note that's not well documented is that `firebase_core` is the "Glue" that connects all the services together and when you're using Firebase Authentication and other Firebase services, you need to make sure you're getting instances from the same firebase core app configuration.
```
final FirebaseAuth _auth = FirebaseAuth.instance;
```
This way above should not be used if you're using multiple firebase services.
Instead, you should always get `FirebaseAuth` from `FirebaseAuth.fromApp(app)` and use this same configuration to get all other Firebase services.
```
FirebaseApp app = await FirebaseApp.configure(
name: 'MyProject',
options: FirebaseOptions(
googleAppID: Platform.isAndroid ? 'x:xxxxxxxxxxxx:android:xxxxxxxxx' : 'x:xxxxxxxxxxxxxx:ios:xxxxxxxxxxx',
gcmSenderID: 'xxxxxxxxxxxxx',
apiKey: '<KEY>',
projectID: 'project-id',
bundleID: 'project-bundle',
),
);
FirebaseAuth _auth = FirebaseAuth.fromApp(app);
Firestore _firestore = Firestore(app: app);
FirebaseStorage _storage = FirebaseStorage(app: app, storageBucket: 'gs://myproject.appspot.com');
```
This insures that all services are using the same app configuration and Firestore will receive authentication data.
Upvotes: 2 |
2018/03/20 | 1,902 | 5,520 | <issue_start>username_0: I create a rule
```
name: Metricbeat CPU Spike Rule
type: metric_aggregation
# How often ElastAlert will query Elasticsearch
# The unit can be anything from weeks to seconds
run_every:
minutes: 1
es_host: localhost
es_port: 9200
index: metricbeat-*
buffer_time:
hours: 1
metric_agg_key: system.cpu.user.pct
metric_agg_type: avg
query_key: beat.hostname
doc_type: metricsets
bucket_interval:
minutes: 5
sync_bucket_interval: true
#allow_buffer_time_overlap: true
#use_run_every_query_size: true
min_threshold: 0.5
filter:
- range:
system.cpu.user.pct:
from: 0.05
to: 0.07
# (Required)
# The alert is use when a match is found
alert:
- "email"
# (required, email specific)
# a list of email addresses to send alerts to
email:
- "<EMAIL>"
```
I think the rule works fine because when I try to test it by running `elastalert-test-rule test.yaml`, I get this:
```
Successfully loaded Metricbeat
Got 155 hits from the last 1 day
Available terms in first hit:
beat.hostname
beat.name
beat.version
@timestamp
type
metricset.rtt
metricset.name
metricset.module
system.cpu.softirq.pct
system.cpu.iowait.pct
system.cpu.system.pct
system.cpu.idle.pct
system.cpu.user.pct
system.cpu.irq.pct
system.cpu.steal.pct
system.cpu.nice.pct
INFO:elastalert:Note: In debug mode, alerts will be logged to console but NOT actually sent.
To send them but remain verbose, use --verbose instead.
INFO:elastalert:Alert for Metricbeat, SenzoServer at 2018-03-20T03:25:00Z:
INFO:elastalert:Metricbeat
Threshold violation, avg:system.cpu.user.pct 0.053 (min: 0.5 max : None)
@timestamp: 2018-03-20T03:25:00Z
beat.hostname: SenzoServer
num_hits: 155
num_matches: 16
system.cpu.user.pct_avg: 0.053
INFO:elastalert:Ignoring match for silenced rule Metricbeat.SenzoServer
INFO:elastalert:Ignoring match for silenced rule Metricbeat.SenzoServer
INFO:elastalert:Ignoring match for silenced rule Metricbeat.SenzoServer
INFO:elastalert:Ignoring match for silenced rule Metricbeat.SenzoServer
INFO:elastalert:Ignoring match for silenced rule Metricbeat.SenzoServer
INFO:elastalert:Ignoring match for silenced rule Metricbeat.SenzoServer
INFO:elastalert:Ignoring match for silenced rule Metricbeat.SenzoServer
INFO:elastalert:Ignoring match for silenced rule Metricbeat.SenzoServer
INFO:elastalert:Ignoring match for silenced rule Metricbeat.SenzoServer
INFO:elastalert:Ignoring match for silenced rule Metricbeat.SenzoServer
INFO:elastalert:Ignoring match for silenced rule Metricbeat.SenzoServer
INFO:elastalert:Ignoring match for silenced rule Metricbeat.SenzoServer
INFO:elastalert:Ignoring match for silenced rule Metricbeat.SenzoServer
INFO:elastalert:Ignoring match for silenced rule Metricbeat.SenzoServer
INFO:elastalert:Ignoring match for silenced rule Metricbeat.SenzoServer
Would have written the following documents to writeback index (default is elastalert_status):
silence - {'rule_name': u'Metricbeat.SenzoServer', '@timestamp': datetime.datetime(2018, 3, 20, 4, 38, 38, 277518, tzinfo=tzutc()), 'exponent': 0, 'until': datetime.datetime(2018, 3, 20, 4, 39, 38, 277508, tzinfo=tzutc())}
elastalert_status - {'hits': 155, 'matches': 16, '@timestamp': datetime.datetime(2018, 3, 20, 4, 38, 38, 279438, tzinfo=tzutc()), 'rule_name': 'Metricbeat', 'starttime': datetime.datetime(2018, 3, 19, 4, 38, 38, 173884, tzinfo=tzutc()), 'endtime': datetime.datetime(2018, 3, 20, 4, 38, 38, 173884, tzinfo=tzutc()), 'time_taken': 0.09930419921875}
```
So then I try to run it using `python -m elastalert.elastalert --verbose --rule test.yaml`, and I get this :
```
Traceback (most recent call last):
File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/usr/local/lib/python2.7/dist-packages/elastalert-0.1.29-py2.7.egg/elastalert/elastalert.py", line 1856, in
sys.exit(main(sys.argv[1:]))
File "/usr/local/lib/python2.7/dist-packages/elastalert-0.1.29-py2.7.egg/elastalert/elastalert.py", line 1850, in main
client = ElastAlerter(args)
File "/usr/local/lib/python2.7/dist-packages/elastalert-0.1.29-py2.7.egg/elastalert/elastalert.py", line 130, in \_\_init\_\_
self.conf = load\_rules(self.args)
File "/usr/local/lib/python2.7/dist-packages/elastalert-0.1.29-py2.7.egg/elastalert/config.py", line 433, in load\_rules
conf = yaml\_loader(filename)
File "/usr/local/lib/python2.7/dist-packages/staticconf/loader.py", line 167, in yaml\_loader
with open(filename) as fh:
IOError: [Errno 2] No such file or directory: 'config.yaml'
```
Is it something wrong with my elastalert installation? I tried install requirements.txt already not working.<issue_comment>username_1: Mention the config file in the elasticalert `config.yaml.example`in the command i.e,
`python -m elastalert.elastalert --verbose --rule example_rules/example_frequency.yaml --config config.yaml.example` It should work.
Upvotes: 1 <issue_comment>username_2: elastalert need a config file to connect with ES and load other attributes. elastalert-Test comes with its own config file (config.yaml.example)
To solve the issue, please make a copy of config.yaml.example and rename it to config.yaml. Make necessary changes in config.yaml and things will fall into place.
Thanks
Upvotes: 0 |
2018/03/20 | 1,936 | 6,497 | <issue_start>username_0: I have been messing around to find a solution as on of my view which is created using add view from respective action in List Template is giving an exception of **System.NullReferenceException: Object reference not set to an instance of an object.**
```
Line 45:
Line 46:
Line 47: @foreach (var item in Model) {
Line 48: |
Line 49: |
```
Here is my **Controller Function**
```
public ActionResult ViewCarpets()
{
IEnumerable Qualities = context.Qualities.Select(c => new SelectListItem
{
Value = c.Quality\_Id.ToString(),
Text = c.QName
});
IEnumerable Suppliers = context.Suppliers.Select(c => new SelectListItem
{
Value = c.Supplier\_Id.ToString(),
Text = c.SName
});
IEnumerable Designs = context.Design.Select(c => new SelectListItem
{
Value = c.Design\_Id.ToString(),
Text = c.DName
});
ViewBag.Quality\_Id = Qualities;
ViewBag.Supplier\_Id = Suppliers;
ViewBag.Design\_Id = Designs;
return View("ViewCarpets");
}
```
Here is my **View**
```
@model IEnumerable
@{
ViewBag.Title = "ViewCarpets";
}
View Carpets
------------
@Html.ActionLink("Create New", "Create")
|
@Html.DisplayNameFor(model => model.Design.DName)
|
@Html.DisplayNameFor(model => model.Quality.QName)
|
@Html.DisplayNameFor(model => model.Supplier.SName)
|
@Html.DisplayNameFor(model => model.PColor)
|
@Html.DisplayNameFor(model => model.PBorder\_Color)
|
@Html.DisplayNameFor(model => model.PSKU)
|
@Html.DisplayNameFor(model => model.PLength)
|
@Html.DisplayNameFor(model => model.PWidth)
|
@Html.DisplayNameFor(model => model.PCost)
|
@Html.DisplayNameFor(model => model.IsSold)
| |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
@foreach (var item in Model) {
|
@Html.DisplayFor(modelItem => item.Design.DName)
|
@Html.DisplayFor(modelItem => item.Quality.QName)
|
@Html.DisplayFor(modelItem => item.Supplier.SName)
|
@Html.DisplayFor(modelItem => item.PColor)
|
@Html.DisplayFor(modelItem => item.PBorder\_Color)
|
@Html.DisplayFor(modelItem => item.PSKU)
|
@Html.DisplayFor(modelItem => item.PLength)
|
@Html.DisplayFor(modelItem => item.PWidth)
|
@Html.DisplayFor(modelItem => item.PCost)
|
@Html.DisplayFor(modelItem => item.IsSold)
|
@Html.ActionLink("Edit", "EditCarpet", new { id = item.Product\_Id }) |
@Html.ActionLink("Details", "CarpetDetails", new { id = item.Product\_Id }) |
@Html.ActionLink("Delete", "DeleteCarpet", new { id = item.Product\_Id })
|
}
```
and Finally **Model**
```
namespace SOC.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Product")]
public partial class Product
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Product()
{
Order_Details = new HashSet();
}
public Product(Product product)
{
this.Quality\_Id = product.Quality\_Id;
this.Design\_Id = product.Design\_Id;
this.Supplier\_Id = product.Supplier\_Id;
this.PColor = product.PColor;
this.PBorder\_Color = product.PBorder\_Color;
this.PSKU = product.PSKU;
this.PLength = product.PLength;
this.PWidth = product.PWidth;
this.IsSold = product.IsSold;
}
[Key]
public int Product\_Id { get; set; }
[Display(Name="Quality")]
public int Quality\_Id { get; set; }
[Display(Name = "Design")]
public int Design\_Id { get; set; }
[Display(Name = "Supplier")]
public int Supplier\_Id { get; set; }
[Required]
[StringLength(20)]
[Display(Name = "Color")]
public string PColor { get; set; }
[Required]
[StringLength(20)]
[Display(Name = "Border Color")]
public string PBorder\_Color { get; set; }
[Required]
[Display(Name = "Stock #")]
public string PSKU { get; set; }
[Display(Name = "Length")]
public decimal PLength { get; set; }
[Display(Name = "Width")]
public decimal PWidth { get; set; }
[Display(Name = "Cost")]
public decimal PCost { get; set; }
[Display(Name = "In Stock")]
public bool IsSold { get; set; }
public virtual Design Design { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection Order\_Details { get; set; }
public virtual Quality Quality { get; set; }
public virtual Supplier Supplier { get; set; }
}
}
```<issue_comment>username_1: You don't pass model to view:
```
return View("ViewCarpets");
```
Should be:
```
var model = new Your_model_class(); // Product for example
return View("ViewCarpets", model);
```
Upvotes: 0 <issue_comment>username_2: You are not building your model nor invoking the overload of `View()` that accepts a model, so your model is null.
```
public ActionResult ViewCarpets()
{
IEnumerable Qualities = context.Qualities.Select(c => new SelectListItem
{
Value = c.Quality\_Id.ToString(),
Text = c.QName
});
IEnumerable Suppliers = context.Suppliers.Select(c => new SelectListItem
{
Value = c.Supplier\_Id.ToString(),
Text = c.SName
});
IEnumerable Designs = context.Design.Select(c => new SelectListItem
{
Value = c.Design\_Id.ToString(),
Text = c.DName
});
ViewBag.Quality\_Id = Qualities;
ViewBag.Supplier\_Id = Suppliers;
ViewBag.Design\_Id = Designs;
var products = GetProducts(); // whatever you need to do to get a list of products, database call etc.
return View("ViewCarpets", model: products);
}
```
Upvotes: 1 <issue_comment>username_3: Thank you so much for the help guys, I got a hint from @username_2 so I changed my action method like below and the problem is solved
```
public ActionResult ViewCarpets()
{
//TODO: Implement View Carpets Logic
IEnumerable Qualities = context.Qualities.Select(c => new SelectListItem
{
Value = c.Quality\_Id.ToString(),
Text = c.QName
});
IEnumerable Suppliers = context.Suppliers.Select(c => new SelectListItem
{
Value = c.Supplier\_Id.ToString(),
Text = c.SName
});
IEnumerable Designs = context.Design.Select(c => new SelectListItem
{
Value = c.Design\_Id.ToString(),
Text = c.DName
});
var model = new Product();
ViewBag.Quality\_Id = Qualities;
ViewBag.Supplier\_Id = Suppliers;
ViewBag.Design\_Id = Designs;
List product = context.Products.ToList();
return View(product);
}
```
Upvotes: 0 |
2018/03/20 | 885 | 2,868 | <issue_start>username_0: I am completely new to the assembly and I have some question about registers still after searching through.
currently I'm trying to divide a value over and over again by doing:
1.divide ax over bl (seems that remainder goes to ah, quotient goes to al)
2.move al(quotient) to ax
3.jump to 5 if ax is less or equal to 0
4.jump to 1
5.end
The problem occurs on instruction 2, as i'm trying to move 8 bit value into 16 bit value.
Anybody have idea on how to solve the problem?
I am using emu8086 so the register has only x, h and l.<issue_comment>username_1: Your question basically boils down to:
>
> How do I move `al` to `ax`.
>
>
>
And the answer to that is that you *don't* move it, it's already there. The 16-bit `ax` register is made of of the two 8-bit registers `ah` and `al`:
```
______________ ax ______________
/ \
+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
|f|e|d|c|b|a|9|8| |7|6|5|4|3|2|1|0| <- individual bits
+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
\____ _____/ \_____ ____/
ah al
```
If you want to ensure that the *entirety* of `ax` is set to whatever was in `al`, you just need to clear the `ah` part, with something like:
```
and ax, 0ffh
```
This will clear all but the lowest (rightmost) eight bits, effectively setting the `f..8` region to all zeros, and therefore ensuring that `ax` becomes `al`.
Upvotes: 4 [selected_answer]<issue_comment>username_2: Generally speaking, you can move a smaller value into a larger location using [movsx](http://www.felixcloutier.com/x86/MOVSX:MOVSXD.html) or [movzx](http://www.felixcloutier.com/x86/MOVZX.html). `Movsx` [maintains the sign of the value](https://en.wikipedia.org/wiki/Sign_extension) (so that if you move 0xfe, that becomes 0xfffe) whereas `movzx` zero-extends the value (so that 0xfe becomes 0x00fe).
However, in your specific case, you don't need to do any moving at all. `AL` already designates the lower 8 bits of `AX`. All you need to do is clear the high bits of AX, which you can do in a variety of ways, but `and ax, 0xff` is probably the simplest.
Upvotes: 1 <issue_comment>username_3: You have to distinguish between two cases:
**Case 1:**
`al` contains an unsigned number (0...255). In this case you have to clear the upper 8 bits of the 16-bit register `ax`.
As "username_1" wrote in his answer you could use `and ax, 0FFh` (3 bytes) for this job however the instruction `mov ah, 0` (2 bytes) should be more efficient. Both instructions would do the same.
**Case 2:**
`al` contains a signed number (-128...127). In this case you have to clear the upper 8 bits of `ax` if the highest bit of `al` is clear; otherwise you have to set them.
The `cbw` instruction (this instruction has no arguments because it will only work with the `ax` register) will do that job.
Upvotes: 2 |
2018/03/20 | 766 | 2,520 | <issue_start>username_0: I have tried capturing the back button action on the browser using pushstate and popstate but problem is pushstate alters the history, thus affecting the normal functioning of back button.<issue_comment>username_1: Your question basically boils down to:
>
> How do I move `al` to `ax`.
>
>
>
And the answer to that is that you *don't* move it, it's already there. The 16-bit `ax` register is made of of the two 8-bit registers `ah` and `al`:
```
______________ ax ______________
/ \
+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
|f|e|d|c|b|a|9|8| |7|6|5|4|3|2|1|0| <- individual bits
+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
\____ _____/ \_____ ____/
ah al
```
If you want to ensure that the *entirety* of `ax` is set to whatever was in `al`, you just need to clear the `ah` part, with something like:
```
and ax, 0ffh
```
This will clear all but the lowest (rightmost) eight bits, effectively setting the `f..8` region to all zeros, and therefore ensuring that `ax` becomes `al`.
Upvotes: 4 [selected_answer]<issue_comment>username_2: Generally speaking, you can move a smaller value into a larger location using [movsx](http://www.felixcloutier.com/x86/MOVSX:MOVSXD.html) or [movzx](http://www.felixcloutier.com/x86/MOVZX.html). `Movsx` [maintains the sign of the value](https://en.wikipedia.org/wiki/Sign_extension) (so that if you move 0xfe, that becomes 0xfffe) whereas `movzx` zero-extends the value (so that 0xfe becomes 0x00fe).
However, in your specific case, you don't need to do any moving at all. `AL` already designates the lower 8 bits of `AX`. All you need to do is clear the high bits of AX, which you can do in a variety of ways, but `and ax, 0xff` is probably the simplest.
Upvotes: 1 <issue_comment>username_3: You have to distinguish between two cases:
**Case 1:**
`al` contains an unsigned number (0...255). In this case you have to clear the upper 8 bits of the 16-bit register `ax`.
As "username_1" wrote in his answer you could use `and ax, 0FFh` (3 bytes) for this job however the instruction `mov ah, 0` (2 bytes) should be more efficient. Both instructions would do the same.
**Case 2:**
`al` contains a signed number (-128...127). In this case you have to clear the upper 8 bits of `ax` if the highest bit of `al` is clear; otherwise you have to set them.
The `cbw` instruction (this instruction has no arguments because it will only work with the `ax` register) will do that job.
Upvotes: 2 |
2018/03/20 | 603 | 1,861 | <issue_start>username_0: I'm upgrading Bugzilla from 4.2.1 to 5.0.4 on Centos 6.9
The 'checksetup.pl' says I'm missing optional module Apache2::SizeLimit v 0.96, but when I do:
```
/usr/bin/perl install-module.pl Apache2::SizeLimit
```
It tells me
>
> Installing Apache2::SizeLimit version 0.96...
>
>
> Apache2::SizeLimit is up to date (0.97).
>
>
>
So, it seems checksetup.pl doesn't recognise that 0.97 is already installed.
It doesn't seem like theres an easy process to downgrade this module. Is there another way to resolve this?<issue_comment>username_1: The problem stems from the module existing in two distributions: [mod\_perl2](https://metacpan.org/pod/distribution/mod_perl/docs/api/Apache2/SizeLimit.pod) and [Apache-SizeLimit](https://metacpan.org/pod/Apache::SizeLimit). Qualify the distro name to resolve to the dist with the higher version number:
```
cpan PHRED/Apache-SizeLimit-0.97.tar.gz
cpanm PHRED/Apache-SizeLimit-0.97.tar.gz
```
Unfortunately, `…/perl install-module.pl` is not able to resolve a qualified name, so you need to use `cpan` or `cpanm` or the like.
Please report these bugs at bugzilla.
Upvotes: 2 <issue_comment>username_2: Bugzilla project admin here. install-module.pl is hot garbage, but the real issue here is that you can't really (easily) get a working mod\_perl installed from cpan.
The correct-ish thing at the moment is use the distro's package manager to install mod\_perl.
Upvotes: 0 <issue_comment>username_3: I found answers with the help of a Bugzilla dev, I needed to do
```
curl -L https://cpanmin.us > /usr/local/bin/cpanm
chmod 755 /usr/local/bin/cpanm
```
to install cpanm, then
```
cpanm --installdeps --notest --with-recommends .
yum install mod_perl-devel
cpanm --notest Apache2::SizeLimit
```
after which `./checksetup` resolved the 0.96 version of SizeLimit
Upvotes: 0 |
2018/03/20 | 506 | 1,709 | <issue_start>username_0: I am using celery and redis as two services in my docker setup. Configuration is as below:
```
redis:
image: redis:latest
hostname: redis
ports:
- "0.0.0.0:6379:6379"
command:
--requirepass <PASSWORD>
celeryworker:
<<: *django
depends_on:
- redis
- postgres
command: "celery -E -A rhombus.taskapp worker --beat --scheduler redbeat.schedulers:RedBeatScheduler --loglevel INFO --uid taskmaster --concurrency=5"
```
When I try to build my containers and schedule some jobs once the workers are ready I get an exception
```
[2018-03-20 04:40:52,082: WARNING/Beat] redis.exceptions.ResponseError: NOAUTH Authentication required.
```
I have been unable to figure out what else would be required as configuration to get this setup working. Some insights and guidance into the issue is appreciable.
Below is the complete stack trace.
[](https://i.stack.imgur.com/mZLC2.png)<issue_comment>username_1: If you have authentication for redis, then URI should be in this format.
```
broker_url = 'redis://user:password@redishost:6379/0'
```
The URI you mentioned is not a valid redis uri. If you update URI, it should work.
Without authentication, uri should be
```
broker_url = 'redis://redishost:6379/0'
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: Alternatively, according to the [celery docs](https://docs.celeryq.dev/en/stable/getting-started/backends-and-brokers/redis.html#configuration), if you don't have an explicit user set up, you can set the broker url like this:
```py
broker_url='redis://:password@hostname:port/db_number'
```
Upvotes: 3 |
2018/03/20 | 502 | 2,223 | <issue_start>username_0: In Angularjs I am trying to search in json data which i am using in html template. My input json data is as below,
```
var data = JSON.parse(
'{
"Project": {
"_attributes": {
"gui": "ProjectGui",
"prjname": "MyProject"
},
"stringarr": [
{
"_attributes": {
"name": "Project.comments"
},
"_text": "MyComments"
},
{
"_attributes": {
"name": "Project.classpath"
},
"_text": "D:\\Project\\bin\\config.jar"
}
]
}
}'
);
```
And i am using this for displaying and editing name in my html template, which is working fine. When I edit input box , it reflects the changes in json data as well, that's exactly I want.
```
Name:
```
But I also want to display and edit comments in same way but not getting idea how to achieve this. The difference is, I have to search within json data where data.Project.stringProp[i].\_attributes.name is "Project.comments" and take "\_text" as input for displaying & editing. I have tried following that is not working.
```
Comments: {{x._text}}
```
Please suggest , what would be the best possible way to do this. I think it can be done using a get function and ng-change function but that approach will be lengthy and may put performance overheads.
Thanks<issue_comment>username_1: You can either implement a filter for filter \_text value if the name is 'Project.comments', or you can simply add an `ng-if` statement.
```
Comments: {{x._text}}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: I have resolved this by using ng-repeat and ng-if for specified condition.
```
Name:
check: {{x.\_text}}
comments :
```
Please find the following plunkr
<https://plnkr.co/edit/3jUaw73cHgAtbBZr8LuJ?p=preview>
Upvotes: 0 |
2018/03/20 | 2,164 | 6,018 | <issue_start>username_0: Currently I am trying to create some links that look like buttons. It's working fairly well, except I want to be able to align them horizontally. This what I have so far:
```css
.border {
display: table;
width: 220px;
height: 120px;
border: 2px solid #1E5034;
transition: all 250ms ease-out;
box-sizing: border-box;
border-spacing: 10px;
float:left;
}
.border:hover {
border-spacing: 2px;
}
a.btn {
display: table-cell;
vertical-align: middle;
text-align: center;
color: #ffffff;
font: 17.5px sans-serif;
text-decoration: none;
background-color: #1E5034;
line-height: 20px;
margin-bottom: 0;
}
a.btn:hover,
a.btn:focus,
a.btn:active,
a.btn:visited,
a.btn:link {
color: #ffffff;
background-color: #1E5034;
text-decoration: none;
cursor: pointer;
}
```
```html
[Some really long text link #1](#)
[Some other really long text link #2](#)
[Some more really really long text link #3](#)
[The last really long text link #4](#)
```
**Edit**:
[](https://i.stack.imgur.com/7Kawk.png)
If it has `display:inline-block;` it will mess up with formatting with heights and not center the text.
I'm trying to create something as shown here, but then be able to center this on the page as well.
Thanks!<issue_comment>username_1: Support in all browsers including IE.
```css
.btn-grp {
position: absolute;
top: 0%;
left: 50%;
transform: translate(-50%, 0%);
width: 80vw;
}
.border {
display: table;
width: 25%;
height: 120px;
border: 2px solid #1E5034;
transition: all 250ms ease-out;
box-sizing: border-box;
border-spacing: 10px;
float: left;
}
.border:hover {
border-spacing: 2px;
}
a.btn {
display: table-cell;
vertical-align: middle;
text-align: center;
color: #ffffff;
font: 17.5px sans-serif;
text-decoration: none;
background-color: #1E5034;
line-height: 20px;
margin-bottom: 0;
}
a.btn:hover,
a.btn:focus,
a.btn:active,
a.btn:visited,
a.btn:link {
color: #ffffff;
background-color: #1E5034;
text-decoration: none;
cursor: pointer;
}
```
```html
[Some really long text link #1](#)
[Some other really long text link #2](#)
[Some more really really long text link #3](#)
[The last really long text link #4](#)
```
If you need the 4 `div` at vertically centered then use:
```
.btn-grp {
position: absolute;
top: 50%;
left:50%;
transform: translate(-50%, -50%);
}
```
Upvotes: 1 <issue_comment>username_2: Because you are using width in `px` thats why then don't come in a single row...So try to use `%` width i.e. `25%`...
```css
.border {
display: table;
width: 25%;
height: 120px;
border: 2px solid #1E5034;
transition: all 250ms ease-out;
box-sizing: border-box;
border-spacing: 10px;
float: left;
}
.border:hover {
border-spacing: 2px;
}
a.btn {
display: table-cell;
vertical-align: middle;
text-align: center;
color: #ffffff;
font: 17.5px sans-serif;
text-decoration: none;
background-color: #1E5034;
line-height: 20px;
margin-bottom: 0;
}
a.btn:hover,
a.btn:focus,
a.btn:active,
a.btn:visited,
a.btn:link {
color: #ffffff;
background-color: #1E5034;
text-decoration: none;
cursor: pointer;
}
```
```html
[Some really long text link #1](#)
[Some other really long text link #2](#)
[Some more really really long text link #3](#)
[The last really long text link #4](#)
```
---
Well I recommend you to use **Flexbox** here...It will give you the full control to align the item vertically and horizontally...Also you will need to use `:after` for the background, as `flexbox` does not allow `border-spacing`
```css
.btn-grp {
display: flex;
justify-content: center;
}
.border {
width: 20%;
height: 120px;
border: 2px solid #1E5034;
transition: all 250ms ease-out;
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: center;
position: relative;
padding: 10px;
}
a.btn {
text-align: center;
color: #ffffff;
font: 16px sans-serif;
text-decoration: none;
line-height: 20px;
margin-bottom: 0;
flex: 1;
}
a.btn:hover,
a.btn:focus,
a.btn:active,
a.btn:visited {
color: #ffffff;
background-color: #1E5034;
text-decoration: none;
cursor: pointer;
}
.border:before {
content: "";
top: 0;
right: 0;
bottom: 0;
left: 0;
background: #1f5034;
position: absolute;
z-index: -1;
transition: all .3s ease;
transform: scale(0.85);
}
.border:hover:before {
transform: scale(0.95);
}
```
```html
[Some really long text link #1](#)
[Some other really long text link #2](#)
[Some more really really long text link #3](#)
[The last really long text link #4](#)
```
---
Well for IE 8 support use `display:inline-block` and `transform` to place the content in center...
```css
.btn-grp {
text-align: center;
font-size: 0;
}
.border {
width: 20%;
height: 120px;
border: 2px solid #1E5034;
transition: all 250ms ease-out;
box-sizing: border-box;
display: inline-block;
vertical-align: top;
position: relative;
padding: 10px;
}
a.btn {
text-align: center;
color: #ffffff;
font: 16px sans-serif;
text-decoration: none;
line-height: 20px;
margin-bottom: 0;
position: relative;
top: 50%;
transform: translateY(-50%);
display: block;
}
.border:before {
content: "";
top: 0;
right: 0;
bottom: 0;
left: 0;
background: #1f5034;
position: absolute;
z-index: -1;
transition: all .3s ease;
transform: scale(0.85);
}
.border:hover:before {
transform: scale(0.95);
}
```
```html
[Some really long text link #1](#)
[Some other really long text link #2](#)
[Some more really really long text link #3](#)
[The last really long text link #4](#)
```
Upvotes: 1 [selected_answer] |
2018/03/20 | 515 | 1,585 | <issue_start>username_0: I have 2 columns named `Debit` and `Credit`. I want to get the value from one column and put in the third column, `Balance`. I want to apply a condition that if `Debit` contains any value, it should be put in the `Balance` column, and if `Credit` has something, then it should insert that value in the column, but if both have some values in them, then only one should go there, either `Debit` or `Credit`.
```
Debit Credit Balance
------------------------------
1000 NULL 1000
2200 NULL 2200
NULL 3000 3000
1500 1500 1500
```
Query:
```
SELECT
Debit, Credit, SUM(Credit|Debit) AS Balance
FROM Table
```<issue_comment>username_1: If I understood correctly, you are looking for something like this.
```
SELECT Debit, Credit,
(
CASE WHEN Credit IS NOT NULL THEN Credit
ELSE Debit
END
) AS Balance
FROM [Table]
```
Upvotes: 2 <issue_comment>username_2: For instance `COALESCE()` is enough
```
SELECT Debit, Credit, COALESCE(Credit, Debit) AS Balance
FROM Table
```
Upvotes: 4 [selected_answer]<issue_comment>username_3: ```
declare @tab table(Debit int,Credit int)
insert into @tab
select 1000 , NULL
union all
select 2200 , NULL
union all
select NULL , 3000
union all
select 1500 , 1500
SELECT Debit, Credit,
CASE WHEN Debit is null then Credit
WHEN Credit is null then Debit else Debit end AS Balance
FROM @tab
```
output
```
Debit Credit Balance
1000 NULL 1000
2200 NULL 2200
NULL 3000 3000
1500 1500 1500
```
Upvotes: 2 |
2018/03/20 | 357 | 1,124 | <issue_start>username_0: I want Oracle database to connect with google sheets and export data into spreadsheet. Is there any way from oracle to authentication with google and export data to Google spreadsheet
Thanks in advance<issue_comment>username_1: If I understood correctly, you are looking for something like this.
```
SELECT Debit, Credit,
(
CASE WHEN Credit IS NOT NULL THEN Credit
ELSE Debit
END
) AS Balance
FROM [Table]
```
Upvotes: 2 <issue_comment>username_2: For instance `COALESCE()` is enough
```
SELECT Debit, Credit, COALESCE(Credit, Debit) AS Balance
FROM Table
```
Upvotes: 4 [selected_answer]<issue_comment>username_3: ```
declare @tab table(Debit int,Credit int)
insert into @tab
select 1000 , NULL
union all
select 2200 , NULL
union all
select NULL , 3000
union all
select 1500 , 1500
SELECT Debit, Credit,
CASE WHEN Debit is null then Credit
WHEN Credit is null then Debit else Debit end AS Balance
FROM @tab
```
output
```
Debit Credit Balance
1000 NULL 1000
2200 NULL 2200
NULL 3000 3000
1500 1500 1500
```
Upvotes: 2 |
2018/03/20 | 565 | 1,518 | <issue_start>username_0: My Table
| user\_number | user\_name | events | register\_date |
001
....
E01
01-01-2017
002
....
E01
01-01-2018
001
....
E02
01-01-2017
002
....
E02
01-01-2018
001
....
E02
01-03-2018
I want to display user number where user number and date of register are the same and more than one, where in the above cases are 001 --- 01-01-2017 and 002 --- 01-01-2018
how to query it ?<issue_comment>username_1: If I understood correctly, you are looking for something like this.
```
SELECT Debit, Credit,
(
CASE WHEN Credit IS NOT NULL THEN Credit
ELSE Debit
END
) AS Balance
FROM [Table]
```
Upvotes: 2 <issue_comment>username_2: For instance `COALESCE()` is enough
```
SELECT Debit, Credit, COALESCE(Credit, Debit) AS Balance
FROM Table
```
Upvotes: 4 [selected_answer]<issue_comment>username_3: ```
declare @tab table(Debit int,Credit int)
insert into @tab
select 1000 , NULL
union all
select 2200 , NULL
union all
select NULL , 3000
union all
select 1500 , 1500
SELECT Debit, Credit,
CASE WHEN Debit is null then Credit
WHEN Credit is null then Debit else Debit end AS Balance
FROM @tab
```
output
```
Debit Credit Balance
1000 NULL 1000
2200 NULL 2200
NULL 3000 3000
1500 1500 1500
```
Upvotes: 2 |
2018/03/20 | 2,080 | 8,135 | <issue_start>username_0: I am a newbie in Node.js so sorry.
In my code I am using API from some service. Basically it is many callbacks. These callbacks provide values from service that i need to use in another callbacks.
If it was synchronous manner then I would write as follows:
```
var value1 = 10;
var value2 = 0;
var value3 = '';
var value4 = '';
api.method1((error, data) => {
if (error) {
// some code
}
value2 = data.value1FromApi / value1;
});
if (value2 > 0) {
api.method2(value2, value1, (error, response) => {
if (error) {
// some code
}
value3 = response.value2FromApi;
value4 = response.value3FromApi;
});
// Check status
for (var i = 0; i < 10; i++) {
if (value4 !== 'some status') {
api.method3(value3, (error, response) => {
value4 = response.value4FromApi;
});
// wait(1000);
}
else {
break;
}
}
if (value4 !== 'some status') {
api.method4(value3, (error, response) => {
});
}
else {
// similar code as above
}
}
```
I know that it is wrong code, because after first callback `value2` will be **undefinied**.
Tell me what technology or what techniques i need to apply in order to solve that callback sequence?<issue_comment>username_1: You need to handle this in async way. You can try this:
```
api.method1((error, data) => {
if (error) {
// some code
}
value2 = data.value1FromApi / value1;
if (value2 > 0) {
api.method2(value2, value1, (error, response) => {
if (error) {
// some code
}
value3 = response.value2FromApi;
value4 = response.value3FromApi;
// Check status
for (var i = 0; i < 10; i++) {
if (value4 !== 'some status') {
api.method3(value3, (error, response) => {
value4 = response.value4FromApi;
if (value4 !== 'some status') {
api.method4(value3, (error, response) => {
});
}
else {
// similar code as above
}
});
}
else {
break;
}
}
});
}
});
```
Basically all the callbacks have to be nested within each other
Upvotes: 3 <issue_comment>username_2: `value2` is `undefined` because it is assigned in an asynchronous function. The usage of `value2` happens before the function is executed.
You may get some knowledge about JavaScript [EventLoop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop) for better understanding.
PS. There are many ways to deal with async functions and callback hells, for example [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), [async](https://github.com/caolan/async), [co](https://github.com/tj/co), [async & await in node 8](https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016).
Take a look at <http://callbackhell.com/> for more info.
Upvotes: 1 <issue_comment>username_3: In order to chain many requests you need to use [promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises).
```js
var method3CalledTimes = 0;
const api = { // Replace api with real API calls
method1: function() {
return Promise.resolve({ value1FromApi: 1 });
},
method2: function() {
return Promise.resolve({ value2FromApi: 2, value3FromApi: 3 });
},
method3: function() {
if (method3CalledTimes++ <= 3) // for demo
return Promise.resolve({ status: "not-correct-status-yet" });
return Promise.resolve({ status: "correct-status" });
},
method4: function() {
return Promise.resolve("Success");
}
};
var value1 = 10,
value2,
value3,
value4;
api.method1()
.then(function(data) {
value2 = data.value1FromApi / value1;
if (value2 <= 0)
return Promise.reject("v2 is non-positive");
return api.method2();
})
.then(function(data) {
value3 = data.value2FromApi;
value4 = data.value3FromApi;
return Promise.all([api.method3(), api.method4()]);
})
.then(function() {
return new Promise(function(resolve, reject) {
var tryCount = 10;
function checkStatus()
{
console.log("Trying to call method3(). Attempts left: " + tryCount);
api.method3()
.then(function(data) {
console.log("Status response: " + data.status);
if (data.status === "correct-status") {
console.log("Valid status, resolving...");
resolve(data.status); // status did change
} else {
if (tryCount-- <= 0) { // if no tries left
console.log("Invalid status, no attempts left. Failing...");
reject("statusnotchanged"); // status didn't change after N attempts
} else { // if we have tries
console.log("Invalid status, we have attempts. Trying again...");
setTimeout(checkStatus, 1000); // try again in 1 second
}
}
})
.catch(reject); // if error - reject
}
checkStatus(); // call once, then it will call itself with setTimeout
});
})
.then(function(newStatus) {
console.log("Complete! New status = " + newStatus);
})
.catch(function(r) {
if (reason === "statusnotchanged") {
// handle this specific reason if needed
}
console.error(r);
});
```
This code is just an example, it shows the idea. Your code sample intention is pretty unclear, so I couldn't optimize it.
See how error handling becomes easier by Promise. Any reject within a chain will result into `.catch` execution. Try to set `value1` to 0 to see what happens.
Upvotes: 2 [selected_answer]<issue_comment>username_4: I had the same problem recently while learning node.js.
I have a file that does calls to an external API and my server sends the response as json object when the user request a route.
---
EXTERNAL API CALLS
-------------------
var connection {user:"user", password:"<PASSWORD>"}
//this is just an example of my connection object
```
exports.getUsers = function(){
return new Promise(function(resolve, reject){
var params = {search_string:""};
var users = [];
connection.Users.get(params, function(error, response){
var user;
for(let i = 0; i < response.data.length; i++)
{
if(response.data[i].name=="user"
{
user = response.data[i];
}
}
users.push({user});
resolve(users); //return the user object
});
});
};
```
---
NODE.JS SERVER
--------------
```
const request = require('./requests.js'); //file with my external api calls
app.get('/users', function(req, res){
requests.getUsers()
.then(function(users){
res.contentType('application/json');
res.send(JSON.stringify(users));
})
.catch(function(err){
console.log(err);
});
});
```
If you use PROMISE, the function will wait until you get the required value before it continues.
.THEN you will be able to send that result as you want to the user calling your api.
At the MDN documentation you will find absolutely everything about JS and it is amazingly helpful.
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise>
---
EDIT
----
Reading a bit more about promises I found that other link, it can be useful as well:
<http://exploringjs.com/es6/ch_promises.html>
Upvotes: 1 |
2018/03/20 | 1,829 | 7,151 | <issue_start>username_0: Having a class:
```
abstract class Bird
```
and a subclass, where `Fish` extends `Food`:
```
class Falcon: Bird()
```
How do I create a method that returns a `Bird`:
```
fun getBird(type: Int): Bird {
if (type == SOME\_CONSTANT) {
return Falcon()
} else {
// Another bird
}
}
```
Getting:
```
Type mismatch: Required Bird, found Falcon
```<issue_comment>username_1: You need to handle this in async way. You can try this:
```
api.method1((error, data) => {
if (error) {
// some code
}
value2 = data.value1FromApi / value1;
if (value2 > 0) {
api.method2(value2, value1, (error, response) => {
if (error) {
// some code
}
value3 = response.value2FromApi;
value4 = response.value3FromApi;
// Check status
for (var i = 0; i < 10; i++) {
if (value4 !== 'some status') {
api.method3(value3, (error, response) => {
value4 = response.value4FromApi;
if (value4 !== 'some status') {
api.method4(value3, (error, response) => {
});
}
else {
// similar code as above
}
});
}
else {
break;
}
}
});
}
});
```
Basically all the callbacks have to be nested within each other
Upvotes: 3 <issue_comment>username_2: `value2` is `undefined` because it is assigned in an asynchronous function. The usage of `value2` happens before the function is executed.
You may get some knowledge about JavaScript [EventLoop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop) for better understanding.
PS. There are many ways to deal with async functions and callback hells, for example [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), [async](https://github.com/caolan/async), [co](https://github.com/tj/co), [async & await in node 8](https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016).
Take a look at <http://callbackhell.com/> for more info.
Upvotes: 1 <issue_comment>username_3: In order to chain many requests you need to use [promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises).
```js
var method3CalledTimes = 0;
const api = { // Replace api with real API calls
method1: function() {
return Promise.resolve({ value1FromApi: 1 });
},
method2: function() {
return Promise.resolve({ value2FromApi: 2, value3FromApi: 3 });
},
method3: function() {
if (method3CalledTimes++ <= 3) // for demo
return Promise.resolve({ status: "not-correct-status-yet" });
return Promise.resolve({ status: "correct-status" });
},
method4: function() {
return Promise.resolve("Success");
}
};
var value1 = 10,
value2,
value3,
value4;
api.method1()
.then(function(data) {
value2 = data.value1FromApi / value1;
if (value2 <= 0)
return Promise.reject("v2 is non-positive");
return api.method2();
})
.then(function(data) {
value3 = data.value2FromApi;
value4 = data.value3FromApi;
return Promise.all([api.method3(), api.method4()]);
})
.then(function() {
return new Promise(function(resolve, reject) {
var tryCount = 10;
function checkStatus()
{
console.log("Trying to call method3(). Attempts left: " + tryCount);
api.method3()
.then(function(data) {
console.log("Status response: " + data.status);
if (data.status === "correct-status") {
console.log("Valid status, resolving...");
resolve(data.status); // status did change
} else {
if (tryCount-- <= 0) { // if no tries left
console.log("Invalid status, no attempts left. Failing...");
reject("statusnotchanged"); // status didn't change after N attempts
} else { // if we have tries
console.log("Invalid status, we have attempts. Trying again...");
setTimeout(checkStatus, 1000); // try again in 1 second
}
}
})
.catch(reject); // if error - reject
}
checkStatus(); // call once, then it will call itself with setTimeout
});
})
.then(function(newStatus) {
console.log("Complete! New status = " + newStatus);
})
.catch(function(r) {
if (reason === "statusnotchanged") {
// handle this specific reason if needed
}
console.error(r);
});
```
This code is just an example, it shows the idea. Your code sample intention is pretty unclear, so I couldn't optimize it.
See how error handling becomes easier by Promise. Any reject within a chain will result into `.catch` execution. Try to set `value1` to 0 to see what happens.
Upvotes: 2 [selected_answer]<issue_comment>username_4: I had the same problem recently while learning node.js.
I have a file that does calls to an external API and my server sends the response as json object when the user request a route.
---
EXTERNAL API CALLS
-------------------
var connection {user:"user", password:"<PASSWORD>"}
//this is just an example of my connection object
```
exports.getUsers = function(){
return new Promise(function(resolve, reject){
var params = {search_string:""};
var users = [];
connection.Users.get(params, function(error, response){
var user;
for(let i = 0; i < response.data.length; i++)
{
if(response.data[i].name=="user"
{
user = response.data[i];
}
}
users.push({user});
resolve(users); //return the user object
});
});
};
```
---
NODE.JS SERVER
--------------
```
const request = require('./requests.js'); //file with my external api calls
app.get('/users', function(req, res){
requests.getUsers()
.then(function(users){
res.contentType('application/json');
res.send(JSON.stringify(users));
})
.catch(function(err){
console.log(err);
});
});
```
If you use PROMISE, the function will wait until you get the required value before it continues.
.THEN you will be able to send that result as you want to the user calling your api.
At the MDN documentation you will find absolutely everything about JS and it is amazingly helpful.
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise>
---
EDIT
----
Reading a bit more about promises I found that other link, it can be useful as well:
<http://exploringjs.com/es6/ch_promises.html>
Upvotes: 1 |
2018/03/20 | 1,804 | 7,111 | <issue_start>username_0: how to reorder the div elements on each time the page refresh?
for example-
```
[first](1.html)
[second](1.html)
[third](1.html)
```
i want to see reodering on page refresh like ..now the current order is 1-2-3
when i refresh it will become 2-3-1..
so each time the page refresh it will change its position of div?<issue_comment>username_1: You need to handle this in async way. You can try this:
```
api.method1((error, data) => {
if (error) {
// some code
}
value2 = data.value1FromApi / value1;
if (value2 > 0) {
api.method2(value2, value1, (error, response) => {
if (error) {
// some code
}
value3 = response.value2FromApi;
value4 = response.value3FromApi;
// Check status
for (var i = 0; i < 10; i++) {
if (value4 !== 'some status') {
api.method3(value3, (error, response) => {
value4 = response.value4FromApi;
if (value4 !== 'some status') {
api.method4(value3, (error, response) => {
});
}
else {
// similar code as above
}
});
}
else {
break;
}
}
});
}
});
```
Basically all the callbacks have to be nested within each other
Upvotes: 3 <issue_comment>username_2: `value2` is `undefined` because it is assigned in an asynchronous function. The usage of `value2` happens before the function is executed.
You may get some knowledge about JavaScript [EventLoop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop) for better understanding.
PS. There are many ways to deal with async functions and callback hells, for example [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), [async](https://github.com/caolan/async), [co](https://github.com/tj/co), [async & await in node 8](https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016).
Take a look at <http://callbackhell.com/> for more info.
Upvotes: 1 <issue_comment>username_3: In order to chain many requests you need to use [promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises).
```js
var method3CalledTimes = 0;
const api = { // Replace api with real API calls
method1: function() {
return Promise.resolve({ value1FromApi: 1 });
},
method2: function() {
return Promise.resolve({ value2FromApi: 2, value3FromApi: 3 });
},
method3: function() {
if (method3CalledTimes++ <= 3) // for demo
return Promise.resolve({ status: "not-correct-status-yet" });
return Promise.resolve({ status: "correct-status" });
},
method4: function() {
return Promise.resolve("Success");
}
};
var value1 = 10,
value2,
value3,
value4;
api.method1()
.then(function(data) {
value2 = data.value1FromApi / value1;
if (value2 <= 0)
return Promise.reject("v2 is non-positive");
return api.method2();
})
.then(function(data) {
value3 = data.value2FromApi;
value4 = data.value3FromApi;
return Promise.all([api.method3(), api.method4()]);
})
.then(function() {
return new Promise(function(resolve, reject) {
var tryCount = 10;
function checkStatus()
{
console.log("Trying to call method3(). Attempts left: " + tryCount);
api.method3()
.then(function(data) {
console.log("Status response: " + data.status);
if (data.status === "correct-status") {
console.log("Valid status, resolving...");
resolve(data.status); // status did change
} else {
if (tryCount-- <= 0) { // if no tries left
console.log("Invalid status, no attempts left. Failing...");
reject("statusnotchanged"); // status didn't change after N attempts
} else { // if we have tries
console.log("Invalid status, we have attempts. Trying again...");
setTimeout(checkStatus, 1000); // try again in 1 second
}
}
})
.catch(reject); // if error - reject
}
checkStatus(); // call once, then it will call itself with setTimeout
});
})
.then(function(newStatus) {
console.log("Complete! New status = " + newStatus);
})
.catch(function(r) {
if (reason === "statusnotchanged") {
// handle this specific reason if needed
}
console.error(r);
});
```
This code is just an example, it shows the idea. Your code sample intention is pretty unclear, so I couldn't optimize it.
See how error handling becomes easier by Promise. Any reject within a chain will result into `.catch` execution. Try to set `value1` to 0 to see what happens.
Upvotes: 2 [selected_answer]<issue_comment>username_4: I had the same problem recently while learning node.js.
I have a file that does calls to an external API and my server sends the response as json object when the user request a route.
---
EXTERNAL API CALLS
-------------------
var connection {user:"user", password:"<PASSWORD>"}
//this is just an example of my connection object
```
exports.getUsers = function(){
return new Promise(function(resolve, reject){
var params = {search_string:""};
var users = [];
connection.Users.get(params, function(error, response){
var user;
for(let i = 0; i < response.data.length; i++)
{
if(response.data[i].name=="user"
{
user = response.data[i];
}
}
users.push({user});
resolve(users); //return the user object
});
});
};
```
---
NODE.JS SERVER
--------------
```
const request = require('./requests.js'); //file with my external api calls
app.get('/users', function(req, res){
requests.getUsers()
.then(function(users){
res.contentType('application/json');
res.send(JSON.stringify(users));
})
.catch(function(err){
console.log(err);
});
});
```
If you use PROMISE, the function will wait until you get the required value before it continues.
.THEN you will be able to send that result as you want to the user calling your api.
At the MDN documentation you will find absolutely everything about JS and it is amazingly helpful.
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise>
---
EDIT
----
Reading a bit more about promises I found that other link, it can be useful as well:
<http://exploringjs.com/es6/ch_promises.html>
Upvotes: 1 |
2018/03/20 | 287 | 945 | <issue_start>username_0: 4 colums
```
| day of year | year | user A | user B |
1 1 john ron
2 1 ron john
1 2 john kyle
```
i need to count how many times a user appears in either UserA colum or UserB colum
group by UserA colum is not succifient i need to count how many times john appears in total from UserA and UserB cols
expected output
```
john 3
ron 2
kyle 1
```<issue_comment>username_1: You appears to want `union all`
```
select user, count(*) counts from
(
select [user A] as user from table t
union all
select [user B] as user from table t
)a
group by user
```
Upvotes: 2 <issue_comment>username_2: You can write a query like :-
```
select user, sum(cnt) total
from
(select userA as user, count(*) cnt from table group by userA
UNION ALL
select userB as user, count(*) cnt from table group by userB
) a11
group by user
```
Upvotes: 1 |
2018/03/20 | 336 | 1,202 | <issue_start>username_0: I imported a code from github and tried to run it on my device, and encountered this error:
>
> Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536
>
>
>
When I googled it, I found out that it has something to do with the **number of methods** where the code is getting too big, but it's not the fact that it only contains one Java class with a couple of methods. What else could be the problem?
Any suggestions will be appreciated.<issue_comment>username_1: You appears to want `union all`
```
select user, count(*) counts from
(
select [user A] as user from table t
union all
select [user B] as user from table t
)a
group by user
```
Upvotes: 2 <issue_comment>username_2: You can write a query like :-
```
select user, sum(cnt) total
from
(select userA as user, count(*) cnt from table group by userA
UNION ALL
select userB as user, count(*) cnt from table group by userB
) a11
group by user
```
Upvotes: 1 |
2018/03/20 | 389 | 1,365 | <issue_start>username_0: I want to redirect to an external url after some action. Please refer my code
```
this.http.get(this.apiurl+'api/insert.php?did='+this.did).subscribe(data=>{
var jsonData = data.json();
let url = jsonData.urlpass;
// redirect to this url like https://flipkart.com with my affilate params
window.open(url ,'_blank');
});
```
this `window.open(url ,'_blank');` shows the popup blocker.
So I tried like this
```
$("#anchorID")[0].click();
```
But this click event is not triggered inside the subscribe method.
If I use `var newWin = window.open();
newWin.location = url_pass;`
It creates the error as `Cannot assign to 'location' because it is a constant or a read-only property.`
I want to open this external url in new window with out popupblocker issue.
Please help anyone.<issue_comment>username_1: You appears to want `union all`
```
select user, count(*) counts from
(
select [user A] as user from table t
union all
select [user B] as user from table t
)a
group by user
```
Upvotes: 2 <issue_comment>username_2: You can write a query like :-
```
select user, sum(cnt) total
from
(select userA as user, count(*) cnt from table group by userA
UNION ALL
select userB as user, count(*) cnt from table group by userB
) a11
group by user
```
Upvotes: 1 |
2018/03/20 | 559 | 2,078 | <issue_start>username_0: I have a function that accepts an arbitrary file handle and either loads all the data or allows the data to be loaded lazily *if* the object supports random access.
```
class DataLoader:
def __init__(self, file):
self.file = file
self.headers = {}
def load_data(self):
# header is a hashable (e.g. namedtuple with name, size, offset)
header = self.load_next_header()
**if self.file.random\_access:**
# Return and load the data only as necessary if you can
self.headers[header.name] = (header, None)
self.file.seek(header.size + self.file.tell())
else:
# Load the data up front if you can't
self.headers[header.name] = (header, self.file.read(header.size))
```
How can I check if a file object supports random access?<issue_comment>username_1: You can use [`seekable`](https://docs.python.org/3/library/io.html#io.IOBase.seekable) method to check if the file supports random access.
>
> **seekable()**
>
>
> Return `True` if the stream supports random access. If `False`, `seek()`, `tell()` and `truncate()` will raise `OSError`.
>
>
>
Upvotes: 3 [selected_answer]<issue_comment>username_2: An alternative approach in line with the Python convention of [EAFP](https://docs.python.org/2/glossary.html#term-eafp) is to just assume the file object supports random access and handle the exception that occurs when it doesn't:
```
class DataLoader:
def __init__(self, file):
self.file = file
self.headers = {}
def load_data(self):
# header is a hashable (e.g. namedtuple with name, size, offset)
header = self.load_next_header()
try:
# Return and load the data only as necessary if you can
self.headers[header.name] = (header, None)
self.file.seek(header.size + self.file.tell())
except OSError:
# Load the data up front if you can't
self.headers[header.name] = (header, self.file.read(header.size))
```
Upvotes: 1 |
2018/03/20 | 320 | 1,157 | <issue_start>username_0: [enter image description here](https://i.stack.imgur.com/aXYRv.png)I tried with below code, but the labels of different screens are missing and not visible in User Interface and Can you tell me how to solve this issue
```
xml version="1.0" encoding="utf-8"?
```
See below Image I am getting output like this,I request you is there any corrections required in above code<issue_comment>username_1: did you mean Activity title? then you can use this
```
setTitle("Your Title");
```
or if you use toolbar
use
```
getSupportActionBar().setTitle("Your Title");`
```
or via AndroidManifest
```
android:label="My Activity Title"
```
Upvotes: 1 <issue_comment>username_2: This is very simple to accomplish
If you want to change it in code, call:
>
> setTitle("My title"); OR
>
>
> getSupportActionBar().setTitle("My title");
>
>
>
And set the values to whatever you please.
Or, in the Android manifest XML file:
```
```
The code should all be placed in your `onCreate` so that the label/icon changing is transparent to the user, but in reality it can be called anywhere during the activity's lifecycle.
Upvotes: 0 |
2018/03/20 | 1,124 | 3,731 | <issue_start>username_0: I'm creating a border using SASS for the rows in the '`tbody`' element, but I'm unable to remove it in a case.
For example,
In the 1st '`tbody`' element, `tbody` has 2 children with the class `compDetails-row`.
I'm creating a border there.
However, in the 2nd `tbody` element, as you can see, there's only 1 child with the class `compDetails-row`, I don't want the border to be applied.
Hence, I'm trying to use `only-of-type` selector, but it doesn't seem to work.
How do I fix it?
```
.compDetails-row {
position: relative;
&:before {
content: '';
display: inline-block;
height: 100%;
border-left: 1px solid grey;
float: right;
position: absolute;
right: 20%;
}
&.compDetails-row:only-of-type {
&:before {
border: none;
}
}
}
| Row1 Column1 | Row1 Column2 | Row1 Column3 |
| Row2 Column1 | Row2 Column2 | Row2 Column3 |
| View Details |
| Row1 Column1 | Row1 Column2 | Row1 Column3 |
| View Details |
```<issue_comment>username_1: I'll assume it has a table as a parent, so you can use the pseudo-selectors `first-of-type`, or `first-child` if the table has no
```css
table tbody:first-of-type .compDetails-row td {
border: 1px solid red;
}
```
```html
| Row1 Column1 | Row1 Column2 | Row1 Column3 |
| Row2 Column1 | Row2 Column2 | Row2 Column3 |
| View Details |
| Row1 Column1 | Row1 Column2 | Row1 Column3 |
| View Details |
```
Upvotes: -1 <issue_comment>username_2: Unfortunately `:first-of-type` literally only checks the tag name (in this case, `tr`) and currently there's no `:first-of-class` pseudo-class. Ideally, you'd be able to modify the table markup at runtime if there's more than one `.compDetails-row`, if not - your best bet is some JavaScript.
You have access to the CSS/SASS, do you not have access to the JavaScript? This question is tagged for CSS only, but as I mentioned it's not really feasible without changing your markup.
Provided you're able to access the JavaScript files, or add a JavaScript tag to the footer of the website, here's a simple pure/vanilla JavaScript way to do it that adds a class `multiple` to the `.compDetails-row` if there's more than one in the same `tbody`.
```js
// Grab all the `` elements in the document as an array
var tbodies = document.querySelectorAll('tbody');
// Loop through the ``'s we grabbed
for( i = 0; i < tbodies.length; i++ ){
// Grab all the `.compDetails-row` elements that exist in the current
rows = tbodies[i].querySelectorAll('.compDetails-row');
// If there's more than one `.compDetails-row`
if( rows.length > 1 ){
// Loop through the `.compDetails-row` elements
rows.forEach(function(item){
// Add the `multiple` class to them
item.classList.add('multiple');
});
}
}
```
```css
.compDetails-row {
position: relative;
}
.compDetails-row.multiple:before {
content: '';
display: inline-block;
height: 100%;
border-left: 1px solid grey;
float: right;
position: absolute;
right: 20%;
}
```
```html
| Row1 Column1 | Row1 Column2 | Row1 Column3 |
| Row2 Column1 | Row2 Column2 | Row2 Column3 |
| View Details |
| Row1 Column1 | Row1 Column2 | Row1 Column3 |
| View Details |
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: Using [the `:has()` pseudo-class](https://developer.mozilla.org/en-US/docs/Web/CSS/:has), [which is currently a working draft and behind a flag in Firefox](https://caniuse.com/css-has), this is achievable with CSS only.
```
tbody:not(:has(.compDetails-row ~ .compDetails-row)) .compDetails-row::before {
border: none;
}
```
[JSFiddle](https://jsfiddle.net/67mo5bdj/)
Upvotes: 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.