qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
listlengths 3
3
| response_j
stringlengths 17
26k
| response_k
stringlengths 26
26k
|
|---|---|---|---|---|---|
53,201,387
|
I am trying to write python code that organizes n-dimensional data into bins.
To do this, I'm initializing a list of empty lists using the following function, which takes an array with the number of bins for each dimension as an argument:
```
def empties(b):
invB = np.flip(b, axis=0)
empty = []
for b in invB:
build = deepcopy(empty)
empty = []
for i in range(0,b):
empty.append(build)
return np.array(empty).tolist() # workaround to clear list references
```
For example, for two dimensional data with 3 bins along each dimension, the following should be expected:
Input:
```
empties([3,3])
```
Output:
```
[ [[],[],[]], [[],[],[]], [[],[],[]] ]
```
I'd like to append objects to this list of lists. This is easy if the dimensions are known. If I wanted to append an object to the above list at position (1,2), I could use:
```
bins = empties([3,3])
obj = Object()
bins[1][2].append(obj)
```
However, I want this to work for any unknown number of dimensions and number of bins. Therefore, I cannot use "[ ][ ][ ]..." notation to define the list index. Lists do not take lists or tuples for the index, so this is not an option. Additionally, I cannot use a numpy array because all lists can be different lengths.
Is there any solution for how to set an element of a list based on a dynamic number of indices?
Ideally, if lists could take a list as the index, I would do this:
```
idx = some_function_that_gets_bin_numbers()
bins[idx].append(obj)
```
|
2018/11/08
|
[
"https://Stackoverflow.com/questions/53201387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4976543/"
] |
You can `reduce` into an array, iterating over each subarray, and then over each split number from the subarray items:
```js
const a = [
["1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526"],
["1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632"]
];
const [d, e] = a.reduce((a, arr) => {
arr.forEach((item) => {
item.split(',').map(Number).forEach((num, i) => {
if (!a[i]) a[i] = [];
a[i].push(num);
});
});
return a;
}, []);
console.log(d);
console.log(e);
```
|
One approach to this problem would be to take advantage of the ordering of number values in your string arrays.
First flatten the two arrays into a single array, and then reduce the result - per iteration of the reduce operation, split a string by `,` into it's two parts, and then put the number value for each part into the output array based on that values split index:
```js
var a = [
[ "1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526" ],
[ "1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632" ]
];
const result = a.flat().reduce((output, string) => {
string.split(',') // Split any string of array item
.map(Number) // Convert each string to number
.forEach((item, index) => {
output[index].push(item) // Map each number to corresponding output subarray
})
return output
}, [[],[]])
const [ d, e ] = result
console.log( 'd = ', d )
console.log( 'e = ', e )
```
|
53,201,387
|
I am trying to write python code that organizes n-dimensional data into bins.
To do this, I'm initializing a list of empty lists using the following function, which takes an array with the number of bins for each dimension as an argument:
```
def empties(b):
invB = np.flip(b, axis=0)
empty = []
for b in invB:
build = deepcopy(empty)
empty = []
for i in range(0,b):
empty.append(build)
return np.array(empty).tolist() # workaround to clear list references
```
For example, for two dimensional data with 3 bins along each dimension, the following should be expected:
Input:
```
empties([3,3])
```
Output:
```
[ [[],[],[]], [[],[],[]], [[],[],[]] ]
```
I'd like to append objects to this list of lists. This is easy if the dimensions are known. If I wanted to append an object to the above list at position (1,2), I could use:
```
bins = empties([3,3])
obj = Object()
bins[1][2].append(obj)
```
However, I want this to work for any unknown number of dimensions and number of bins. Therefore, I cannot use "[ ][ ][ ]..." notation to define the list index. Lists do not take lists or tuples for the index, so this is not an option. Additionally, I cannot use a numpy array because all lists can be different lengths.
Is there any solution for how to set an element of a list based on a dynamic number of indices?
Ideally, if lists could take a list as the index, I would do this:
```
idx = some_function_that_gets_bin_numbers()
bins[idx].append(obj)
```
|
2018/11/08
|
[
"https://Stackoverflow.com/questions/53201387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4976543/"
] |
You can `reduce` into an array, iterating over each subarray, and then over each split number from the subarray items:
```js
const a = [
["1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526"],
["1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632"]
];
const [d, e] = a.reduce((a, arr) => {
arr.forEach((item) => {
item.split(',').map(Number).forEach((num, i) => {
if (!a[i]) a[i] = [];
a[i].push(num);
});
});
return a;
}, []);
console.log(d);
console.log(e);
```
|
Please check if the following code matches your requirement.
```
function test3(a) {
let result = [];
for (let i=0; i<a.length; i++) {
let subArr = [];
for (let j=0; j<a[i].length; j++) {
let splits = a[i][j].split(',');
subArr.push(splits[0]);
subArr.push(splits[1]);
}
result.push(subArr);
}
console.log("Result ", result);
return result;
}
```
Then call the following code :
```
var a = [[ "1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526" ], [ "1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632" ]];
var b = a[0]
var c = a[1]
var d = test3(a)[0]
var e = test3(a)[1]
```
|
53,201,387
|
I am trying to write python code that organizes n-dimensional data into bins.
To do this, I'm initializing a list of empty lists using the following function, which takes an array with the number of bins for each dimension as an argument:
```
def empties(b):
invB = np.flip(b, axis=0)
empty = []
for b in invB:
build = deepcopy(empty)
empty = []
for i in range(0,b):
empty.append(build)
return np.array(empty).tolist() # workaround to clear list references
```
For example, for two dimensional data with 3 bins along each dimension, the following should be expected:
Input:
```
empties([3,3])
```
Output:
```
[ [[],[],[]], [[],[],[]], [[],[],[]] ]
```
I'd like to append objects to this list of lists. This is easy if the dimensions are known. If I wanted to append an object to the above list at position (1,2), I could use:
```
bins = empties([3,3])
obj = Object()
bins[1][2].append(obj)
```
However, I want this to work for any unknown number of dimensions and number of bins. Therefore, I cannot use "[ ][ ][ ]..." notation to define the list index. Lists do not take lists or tuples for the index, so this is not an option. Additionally, I cannot use a numpy array because all lists can be different lengths.
Is there any solution for how to set an element of a list based on a dynamic number of indices?
Ideally, if lists could take a list as the index, I would do this:
```
idx = some_function_that_gets_bin_numbers()
bins[idx].append(obj)
```
|
2018/11/08
|
[
"https://Stackoverflow.com/questions/53201387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4976543/"
] |
You can `reduce` into an array, iterating over each subarray, and then over each split number from the subarray items:
```js
const a = [
["1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526"],
["1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632"]
];
const [d, e] = a.reduce((a, arr) => {
arr.forEach((item) => {
item.split(',').map(Number).forEach((num, i) => {
if (!a[i]) a[i] = [];
a[i].push(num);
});
});
return a;
}, []);
console.log(d);
console.log(e);
```
|
Heres a quick and dirty way of doing, basically recursively look through the array until you find a string, once you have one split it at the comma, then add the results to two different arrays. Finally, return the two arrays.
```js
var a = [
[ "1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526" ],
[ "1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632" ]
];
function sort(array) {
var a = [], b = [];
function inner(c) {
c.forEach(function (d) {
if (Array.isArray(d)) {
inner(d);
} else {
var e = d.split(',');
a.push(e[0]);
b.push(e[1]);
}
})
}
inner(array);
return [a,b]
}
console.log(sort(a));
```
|
53,201,387
|
I am trying to write python code that organizes n-dimensional data into bins.
To do this, I'm initializing a list of empty lists using the following function, which takes an array with the number of bins for each dimension as an argument:
```
def empties(b):
invB = np.flip(b, axis=0)
empty = []
for b in invB:
build = deepcopy(empty)
empty = []
for i in range(0,b):
empty.append(build)
return np.array(empty).tolist() # workaround to clear list references
```
For example, for two dimensional data with 3 bins along each dimension, the following should be expected:
Input:
```
empties([3,3])
```
Output:
```
[ [[],[],[]], [[],[],[]], [[],[],[]] ]
```
I'd like to append objects to this list of lists. This is easy if the dimensions are known. If I wanted to append an object to the above list at position (1,2), I could use:
```
bins = empties([3,3])
obj = Object()
bins[1][2].append(obj)
```
However, I want this to work for any unknown number of dimensions and number of bins. Therefore, I cannot use "[ ][ ][ ]..." notation to define the list index. Lists do not take lists or tuples for the index, so this is not an option. Additionally, I cannot use a numpy array because all lists can be different lengths.
Is there any solution for how to set an element of a list based on a dynamic number of indices?
Ideally, if lists could take a list as the index, I would do this:
```
idx = some_function_that_gets_bin_numbers()
bins[idx].append(obj)
```
|
2018/11/08
|
[
"https://Stackoverflow.com/questions/53201387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4976543/"
] |
You can `reduce` into an array, iterating over each subarray, and then over each split number from the subarray items:
```js
const a = [
["1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526"],
["1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632"]
];
const [d, e] = a.reduce((a, arr) => {
arr.forEach((item) => {
item.split(',').map(Number).forEach((num, i) => {
if (!a[i]) a[i] = [];
a[i].push(num);
});
});
return a;
}, []);
console.log(d);
console.log(e);
```
|
Here's another solution using `map`, `flat` and `reduce`. The idea is to get one continuous array of all the numbers and then add alternating numbers to 2 different arrays using `reduce`:
```js
const a = [
["1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526"],
["1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632"]
];
const [d, e] = a.map(arr => arr.map(s => s.split(',').map(s => parseFloat(s))))
.flat(2)
.reduce((acc, curr, i) => {
acc[i % 2].push(curr);
return acc;
}, [[], []]);
console.log(d);
console.log(e);
```
|
53,201,387
|
I am trying to write python code that organizes n-dimensional data into bins.
To do this, I'm initializing a list of empty lists using the following function, which takes an array with the number of bins for each dimension as an argument:
```
def empties(b):
invB = np.flip(b, axis=0)
empty = []
for b in invB:
build = deepcopy(empty)
empty = []
for i in range(0,b):
empty.append(build)
return np.array(empty).tolist() # workaround to clear list references
```
For example, for two dimensional data with 3 bins along each dimension, the following should be expected:
Input:
```
empties([3,3])
```
Output:
```
[ [[],[],[]], [[],[],[]], [[],[],[]] ]
```
I'd like to append objects to this list of lists. This is easy if the dimensions are known. If I wanted to append an object to the above list at position (1,2), I could use:
```
bins = empties([3,3])
obj = Object()
bins[1][2].append(obj)
```
However, I want this to work for any unknown number of dimensions and number of bins. Therefore, I cannot use "[ ][ ][ ]..." notation to define the list index. Lists do not take lists or tuples for the index, so this is not an option. Additionally, I cannot use a numpy array because all lists can be different lengths.
Is there any solution for how to set an element of a list based on a dynamic number of indices?
Ideally, if lists could take a list as the index, I would do this:
```
idx = some_function_that_gets_bin_numbers()
bins[idx].append(obj)
```
|
2018/11/08
|
[
"https://Stackoverflow.com/questions/53201387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4976543/"
] |
One approach to this problem would be to take advantage of the ordering of number values in your string arrays.
First flatten the two arrays into a single array, and then reduce the result - per iteration of the reduce operation, split a string by `,` into it's two parts, and then put the number value for each part into the output array based on that values split index:
```js
var a = [
[ "1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526" ],
[ "1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632" ]
];
const result = a.flat().reduce((output, string) => {
string.split(',') // Split any string of array item
.map(Number) // Convert each string to number
.forEach((item, index) => {
output[index].push(item) // Map each number to corresponding output subarray
})
return output
}, [[],[]])
const [ d, e ] = result
console.log( 'd = ', d )
console.log( 'e = ', e )
```
|
Please check if the following code matches your requirement.
```
function test3(a) {
let result = [];
for (let i=0; i<a.length; i++) {
let subArr = [];
for (let j=0; j<a[i].length; j++) {
let splits = a[i][j].split(',');
subArr.push(splits[0]);
subArr.push(splits[1]);
}
result.push(subArr);
}
console.log("Result ", result);
return result;
}
```
Then call the following code :
```
var a = [[ "1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526" ], [ "1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632" ]];
var b = a[0]
var c = a[1]
var d = test3(a)[0]
var e = test3(a)[1]
```
|
53,201,387
|
I am trying to write python code that organizes n-dimensional data into bins.
To do this, I'm initializing a list of empty lists using the following function, which takes an array with the number of bins for each dimension as an argument:
```
def empties(b):
invB = np.flip(b, axis=0)
empty = []
for b in invB:
build = deepcopy(empty)
empty = []
for i in range(0,b):
empty.append(build)
return np.array(empty).tolist() # workaround to clear list references
```
For example, for two dimensional data with 3 bins along each dimension, the following should be expected:
Input:
```
empties([3,3])
```
Output:
```
[ [[],[],[]], [[],[],[]], [[],[],[]] ]
```
I'd like to append objects to this list of lists. This is easy if the dimensions are known. If I wanted to append an object to the above list at position (1,2), I could use:
```
bins = empties([3,3])
obj = Object()
bins[1][2].append(obj)
```
However, I want this to work for any unknown number of dimensions and number of bins. Therefore, I cannot use "[ ][ ][ ]..." notation to define the list index. Lists do not take lists or tuples for the index, so this is not an option. Additionally, I cannot use a numpy array because all lists can be different lengths.
Is there any solution for how to set an element of a list based on a dynamic number of indices?
Ideally, if lists could take a list as the index, I would do this:
```
idx = some_function_that_gets_bin_numbers()
bins[idx].append(obj)
```
|
2018/11/08
|
[
"https://Stackoverflow.com/questions/53201387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4976543/"
] |
One approach to this problem would be to take advantage of the ordering of number values in your string arrays.
First flatten the two arrays into a single array, and then reduce the result - per iteration of the reduce operation, split a string by `,` into it's two parts, and then put the number value for each part into the output array based on that values split index:
```js
var a = [
[ "1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526" ],
[ "1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632" ]
];
const result = a.flat().reduce((output, string) => {
string.split(',') // Split any string of array item
.map(Number) // Convert each string to number
.forEach((item, index) => {
output[index].push(item) // Map each number to corresponding output subarray
})
return output
}, [[],[]])
const [ d, e ] = result
console.log( 'd = ', d )
console.log( 'e = ', e )
```
|
Here's another solution using `map`, `flat` and `reduce`. The idea is to get one continuous array of all the numbers and then add alternating numbers to 2 different arrays using `reduce`:
```js
const a = [
["1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526"],
["1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632"]
];
const [d, e] = a.map(arr => arr.map(s => s.split(',').map(s => parseFloat(s))))
.flat(2)
.reduce((acc, curr, i) => {
acc[i % 2].push(curr);
return acc;
}, [[], []]);
console.log(d);
console.log(e);
```
|
53,201,387
|
I am trying to write python code that organizes n-dimensional data into bins.
To do this, I'm initializing a list of empty lists using the following function, which takes an array with the number of bins for each dimension as an argument:
```
def empties(b):
invB = np.flip(b, axis=0)
empty = []
for b in invB:
build = deepcopy(empty)
empty = []
for i in range(0,b):
empty.append(build)
return np.array(empty).tolist() # workaround to clear list references
```
For example, for two dimensional data with 3 bins along each dimension, the following should be expected:
Input:
```
empties([3,3])
```
Output:
```
[ [[],[],[]], [[],[],[]], [[],[],[]] ]
```
I'd like to append objects to this list of lists. This is easy if the dimensions are known. If I wanted to append an object to the above list at position (1,2), I could use:
```
bins = empties([3,3])
obj = Object()
bins[1][2].append(obj)
```
However, I want this to work for any unknown number of dimensions and number of bins. Therefore, I cannot use "[ ][ ][ ]..." notation to define the list index. Lists do not take lists or tuples for the index, so this is not an option. Additionally, I cannot use a numpy array because all lists can be different lengths.
Is there any solution for how to set an element of a list based on a dynamic number of indices?
Ideally, if lists could take a list as the index, I would do this:
```
idx = some_function_that_gets_bin_numbers()
bins[idx].append(obj)
```
|
2018/11/08
|
[
"https://Stackoverflow.com/questions/53201387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4976543/"
] |
Heres a quick and dirty way of doing, basically recursively look through the array until you find a string, once you have one split it at the comma, then add the results to two different arrays. Finally, return the two arrays.
```js
var a = [
[ "1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526" ],
[ "1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632" ]
];
function sort(array) {
var a = [], b = [];
function inner(c) {
c.forEach(function (d) {
if (Array.isArray(d)) {
inner(d);
} else {
var e = d.split(',');
a.push(e[0]);
b.push(e[1]);
}
})
}
inner(array);
return [a,b]
}
console.log(sort(a));
```
|
Please check if the following code matches your requirement.
```
function test3(a) {
let result = [];
for (let i=0; i<a.length; i++) {
let subArr = [];
for (let j=0; j<a[i].length; j++) {
let splits = a[i][j].split(',');
subArr.push(splits[0]);
subArr.push(splits[1]);
}
result.push(subArr);
}
console.log("Result ", result);
return result;
}
```
Then call the following code :
```
var a = [[ "1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526" ], [ "1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632" ]];
var b = a[0]
var c = a[1]
var d = test3(a)[0]
var e = test3(a)[1]
```
|
53,201,387
|
I am trying to write python code that organizes n-dimensional data into bins.
To do this, I'm initializing a list of empty lists using the following function, which takes an array with the number of bins for each dimension as an argument:
```
def empties(b):
invB = np.flip(b, axis=0)
empty = []
for b in invB:
build = deepcopy(empty)
empty = []
for i in range(0,b):
empty.append(build)
return np.array(empty).tolist() # workaround to clear list references
```
For example, for two dimensional data with 3 bins along each dimension, the following should be expected:
Input:
```
empties([3,3])
```
Output:
```
[ [[],[],[]], [[],[],[]], [[],[],[]] ]
```
I'd like to append objects to this list of lists. This is easy if the dimensions are known. If I wanted to append an object to the above list at position (1,2), I could use:
```
bins = empties([3,3])
obj = Object()
bins[1][2].append(obj)
```
However, I want this to work for any unknown number of dimensions and number of bins. Therefore, I cannot use "[ ][ ][ ]..." notation to define the list index. Lists do not take lists or tuples for the index, so this is not an option. Additionally, I cannot use a numpy array because all lists can be different lengths.
Is there any solution for how to set an element of a list based on a dynamic number of indices?
Ideally, if lists could take a list as the index, I would do this:
```
idx = some_function_that_gets_bin_numbers()
bins[idx].append(obj)
```
|
2018/11/08
|
[
"https://Stackoverflow.com/questions/53201387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4976543/"
] |
Heres a quick and dirty way of doing, basically recursively look through the array until you find a string, once you have one split it at the comma, then add the results to two different arrays. Finally, return the two arrays.
```js
var a = [
[ "1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526" ],
[ "1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632" ]
];
function sort(array) {
var a = [], b = [];
function inner(c) {
c.forEach(function (d) {
if (Array.isArray(d)) {
inner(d);
} else {
var e = d.split(',');
a.push(e[0]);
b.push(e[1]);
}
})
}
inner(array);
return [a,b]
}
console.log(sort(a));
```
|
Here's another solution using `map`, `flat` and `reduce`. The idea is to get one continuous array of all the numbers and then add alternating numbers to 2 different arrays using `reduce`:
```js
const a = [
["1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526"],
["1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632"]
];
const [d, e] = a.map(arr => arr.map(s => s.split(',').map(s => parseFloat(s))))
.flat(2)
.reduce((acc, curr, i) => {
acc[i % 2].push(curr);
return acc;
}, [[], []]);
console.log(d);
console.log(e);
```
|
39,290,932
|
How to change python code to **.exe** file using microsoft Visual Studio 2015 without installing any package? Under "Build" button, there is no convert to **.exe** file.
|
2016/09/02
|
[
"https://Stackoverflow.com/questions/39290932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6737263/"
] |
Here is the complete fix for the issue:
```
private async Task<IEnumerable<byte[]>> GetAttachmentsAsByteArrayAsync(Activity activity)
{
var attachments = activity?.Attachments?
.Where(attachment => attachment.ContentUrl != null)
.Select(c => Tuple.Create(c.ContentType, c.ContentUrl));
if (attachments != null && attachments.Any())
{
var contentBytes = new List<byte[]>();
using (var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl)))
{
var token = await (connectorClient.Credentials as MicrosoftAppCredentials).GetTokenAsync();
foreach (var content in attachments)
{
var uri = new Uri(content.Item2);
using (var httpClient = new HttpClient())
{
if (uri.Host.EndsWith("skype.com") && uri.Scheme == "https")
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
}
else
{
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(content.Item1));
}
contentBytes.Add(await httpClient.GetByteArrayAsync(uri));
}
}
}
return contentBytes;
}
return null;
}
```
|
<https://github.com/Microsoft/BotBuilder/issues/662#issuecomment-232223965>
you mean this fix? Did this work out for you?
|
39,290,932
|
How to change python code to **.exe** file using microsoft Visual Studio 2015 without installing any package? Under "Build" button, there is no convert to **.exe** file.
|
2016/09/02
|
[
"https://Stackoverflow.com/questions/39290932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6737263/"
] |
Here is the complete fix for the issue:
```
private async Task<IEnumerable<byte[]>> GetAttachmentsAsByteArrayAsync(Activity activity)
{
var attachments = activity?.Attachments?
.Where(attachment => attachment.ContentUrl != null)
.Select(c => Tuple.Create(c.ContentType, c.ContentUrl));
if (attachments != null && attachments.Any())
{
var contentBytes = new List<byte[]>();
using (var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl)))
{
var token = await (connectorClient.Credentials as MicrosoftAppCredentials).GetTokenAsync();
foreach (var content in attachments)
{
var uri = new Uri(content.Item2);
using (var httpClient = new HttpClient())
{
if (uri.Host.EndsWith("skype.com") && uri.Scheme == "https")
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
}
else
{
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(content.Item1));
}
contentBytes.Add(await httpClient.GetByteArrayAsync(uri));
}
}
}
return contentBytes;
}
return null;
}
```
|
I am using BotFramework with Node.js and received the same error.
Finally i found a workaround. I commented below lines in ChatConnector.js and its working fine for me now.
```js
if (isEmulator && decoded_1.payload.appid != this.settings.appId) {
logger.error('ChatConnector: receive - invalid token. Requested by unexpected app ID.');
res.status(403);
res.end();
return;
}
```
if (isEmulator && decoded\_1.payload.appid != this.settings.appId) {
logger.error('ChatConnector: receive - invalid token. Requested by unexpected app ID.');
res.status(403);
res.end();
return;
}
|
39,290,932
|
How to change python code to **.exe** file using microsoft Visual Studio 2015 without installing any package? Under "Build" button, there is no convert to **.exe** file.
|
2016/09/02
|
[
"https://Stackoverflow.com/questions/39290932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6737263/"
] |
<https://github.com/Microsoft/BotBuilder/issues/662#issuecomment-232223965>
you mean this fix? Did this work out for you?
|
I am using BotFramework with Node.js and received the same error.
Finally i found a workaround. I commented below lines in ChatConnector.js and its working fine for me now.
```js
if (isEmulator && decoded_1.payload.appid != this.settings.appId) {
logger.error('ChatConnector: receive - invalid token. Requested by unexpected app ID.');
res.status(403);
res.end();
return;
}
```
if (isEmulator && decoded\_1.payload.appid != this.settings.appId) {
logger.error('ChatConnector: receive - invalid token. Requested by unexpected app ID.');
res.status(403);
res.end();
return;
}
|
16,002,862
|
I'm rather new at using python and especially numpy, and matplotlib. Running the code below (which works fine without the `\frac{}{}` part) yields the error:
```
Normalized Distance in Chamber ($
rac{x}{L}$)
^
Expected end of text (at char 32), (line:1, col:33)
```
The math mode seems to work fine for everything else I've tried (symbols mostly, e.g. `$\mu$` works fine and displays µ) so I'm not sure what is happening here. I've looked up other peoples code for examples and they just seem to use `\frac{}{}` with nothing special and it works fine. I don't know what I'm doing differently. Here is the code. Thanks for the help!
```
import numpy as np
import math
import matplotlib.pylab as plt
[ ... bunch of calculations ... ]
plt.plot(xspace[:]/L,vals[:,60])
plt.axis([0,1,0,1])
plt.xlabel('Normalized Distance in Chamber ($\frac{x}{L}$)')
plt.savefig('test.eps')
```
Also, I did look up \f and it seems its an "escape character", but I don't know what that means or why it would be active within TeX mode.
|
2013/04/14
|
[
"https://Stackoverflow.com/questions/16002862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1411736/"
] |
In many languages, backslash-letter is a way to enter otherwise hard-to-type characters. In this case it's a "form feed". Examples:
```
\n — newline
\r — carriage return
\t — tab character
\b — backspace
```
To disable that, you either need to escape the backslash itself (backslash-backslash is a backslash)
```
'Normalized Distance in Chamber ($\\frac{x}{L}$)'
```
Or use "raw" strings where escape sequences are disabled:
```
r'Normalized Distance in Chamber ($\frac{x}{L}$)'
```
This is relevant to Python, not TeX.
[Documentation on Python string literals](http://docs.python.org/2.7/reference/lexical_analysis.html#string-literals)
|
`"\f"` is a form-feed character in Python. TeX never sees the backslash because Python interprets the `\f` in your Python source, before the string is sent to TeX. You can either double the backslash, or make your string a raw string by using `r'Normalized Distance ... etc.'`.
|
16,002,862
|
I'm rather new at using python and especially numpy, and matplotlib. Running the code below (which works fine without the `\frac{}{}` part) yields the error:
```
Normalized Distance in Chamber ($
rac{x}{L}$)
^
Expected end of text (at char 32), (line:1, col:33)
```
The math mode seems to work fine for everything else I've tried (symbols mostly, e.g. `$\mu$` works fine and displays µ) so I'm not sure what is happening here. I've looked up other peoples code for examples and they just seem to use `\frac{}{}` with nothing special and it works fine. I don't know what I'm doing differently. Here is the code. Thanks for the help!
```
import numpy as np
import math
import matplotlib.pylab as plt
[ ... bunch of calculations ... ]
plt.plot(xspace[:]/L,vals[:,60])
plt.axis([0,1,0,1])
plt.xlabel('Normalized Distance in Chamber ($\frac{x}{L}$)')
plt.savefig('test.eps')
```
Also, I did look up \f and it seems its an "escape character", but I don't know what that means or why it would be active within TeX mode.
|
2013/04/14
|
[
"https://Stackoverflow.com/questions/16002862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1411736/"
] |
In many languages, backslash-letter is a way to enter otherwise hard-to-type characters. In this case it's a "form feed". Examples:
```
\n — newline
\r — carriage return
\t — tab character
\b — backspace
```
To disable that, you either need to escape the backslash itself (backslash-backslash is a backslash)
```
'Normalized Distance in Chamber ($\\frac{x}{L}$)'
```
Or use "raw" strings where escape sequences are disabled:
```
r'Normalized Distance in Chamber ($\frac{x}{L}$)'
```
This is relevant to Python, not TeX.
[Documentation on Python string literals](http://docs.python.org/2.7/reference/lexical_analysis.html#string-literals)
|
You have to add an `r` front of the string to avoid parsing the `\f`.
|
16,002,862
|
I'm rather new at using python and especially numpy, and matplotlib. Running the code below (which works fine without the `\frac{}{}` part) yields the error:
```
Normalized Distance in Chamber ($
rac{x}{L}$)
^
Expected end of text (at char 32), (line:1, col:33)
```
The math mode seems to work fine for everything else I've tried (symbols mostly, e.g. `$\mu$` works fine and displays µ) so I'm not sure what is happening here. I've looked up other peoples code for examples and they just seem to use `\frac{}{}` with nothing special and it works fine. I don't know what I'm doing differently. Here is the code. Thanks for the help!
```
import numpy as np
import math
import matplotlib.pylab as plt
[ ... bunch of calculations ... ]
plt.plot(xspace[:]/L,vals[:,60])
plt.axis([0,1,0,1])
plt.xlabel('Normalized Distance in Chamber ($\frac{x}{L}$)')
plt.savefig('test.eps')
```
Also, I did look up \f and it seems its an "escape character", but I don't know what that means or why it would be active within TeX mode.
|
2013/04/14
|
[
"https://Stackoverflow.com/questions/16002862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1411736/"
] |
`"\f"` is a form-feed character in Python. TeX never sees the backslash because Python interprets the `\f` in your Python source, before the string is sent to TeX. You can either double the backslash, or make your string a raw string by using `r'Normalized Distance ... etc.'`.
|
You have to add an `r` front of the string to avoid parsing the `\f`.
|
31,438,147
|
it is my first post on stackoverflow so please go easy on me! :) I am also relatively new to python so bear with me :)
With all that said here is my issue: I am writing a bit of code for fun which calls an API and grabs the latest Bitcoin Nonce data. I have managed to do this fine, however now I want to be able to save the first nonce value found as a string such as Nonce1 and then recall the API every few seconds till I get another Nonce value and name it Nonce2 for example? Is this possible? My code is down bellow.
```
from __future__ import print_function
import blocktrail
client = blocktrail.APIClient(api_key="x", api_secret="x", network="BTC", testnet=False)
address = client.address('x')
latest_block = client.block_latest()
nonce = latest_block['nonce']
print(nonce)
noncestr = str(nonce)
```
Thanks, again please go easy on me I am very new to Python :)
|
2015/07/15
|
[
"https://Stackoverflow.com/questions/31438147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5120590/"
] |
Not entirely. It's right that the rules are only based on classes, and it does not matter if it is the same instance or another instance and that was basically your question.
However, you made a mistake about *protected* in general. From the documentation:
>
> Members declared protected can be accessed only within the class itself and by inherited **and** parent classes
>
>
>
(highlight added)
So, the following statements are **wrong**:
1. >
> Accessing protected members from a superclass is not OK.
>
>
>
2. >
> Accessing protected members from another instance of a superclass is not OK.
>
>
>
|
Yes, it's right.
The visibility rules are based only on classes, instances have no impact. So if a class has access to a particular member in the same instance, it also has access to that member in other instances of that class.
It's not a quirk, it's a deliberate design choice, similar to many other OO languages (I think the rules are essentially the same in C++, for instance). Once you grant that a class method is allowed to know about the implementation details of that class or some related class, it doesn't matter whether the instance it's dealing with is the one it was called on or some other instance of the class.
|
52,033,549
|
I have a csv file mentioned as below screen shot ...
[](https://i.stack.imgur.com/WAVzb.png)
and i want to convert the whole file in the below format in python.
[](https://i.stack.imgur.com/ladmh.png)
|
2018/08/27
|
[
"https://Stackoverflow.com/questions/52033549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8966278/"
] |
You can try this after reading your CSV file correct file path.
```
import pandas as pd
df = pd.read_csv("path/to/file", names=["Sentence", "Value"])
result = [(row["Sentence"], row["Value"]) for index, row in df.iterrows()]
print(result)
```
|
It's a single line using `apply()` method of dataframe
`df.apply(lambda x: x.tolist(), axis=1)`
OR
`df.values.tolist()` will also work
|
2,137,619
|
Is it possible to implement in Scala something equivalent to the Python `yield` statement where it remembers the local state of the function where it is used and "yields" the next value each time it is called?
I wanted to have something like this to convert a recursive function into an iterator. Sort of like this:
```
# this is python
def foo(i):
yield i
if i > 0:
for j in foo(i - 1):
yield j
for i in foo(5):
print i
```
Except, `foo` may be more complex and recurs through some acyclic object graph.
**Additional Edit:**
Let me add a more complex example (but still simple):
I can write a simple recursive function printing things as it goes along:
```
// this is Scala
def printClass(clazz:Class[_], indent:String=""): Unit = {
clazz match {
case null =>
case _ =>
println(indent + clazz)
printClass(clazz.getSuperclass, indent + " ")
for (c <- clazz.getInterfaces) {
printClass(c, indent + " ")
}
}
}
```
Ideally I would like to have a library that allows me to easily change a few statements and have it work as an Iterator:
```
// this is not Scala
def yieldClass(clazz:Class[_]): Iterator[Class[_]] = {
clazz match {
case null =>
case _ =>
sudoYield clazz
for (c <- yieldClass(clazz.getSuperclass)) sudoYield c
for (c <- clazz.getInterfaces; d <- yieldClasss(c)) sudoYield d
}
}
```
It does seem continuations allow to do that, but I just don't understand the `shift/reset` concept. Will continuation eventually make it into the main compiler and would it be possible to extract out the complexity in a library?
**Edit 2:**
check [Rich's answer](https://stackoverflow.com/questions/2201882/implementing-yield-yield-return-using-scala-continuations/2215182#2215182) in that other thread.
|
2010/01/26
|
[
"https://Stackoverflow.com/questions/2137619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257449/"
] |
While Python generators are cool, trying to duplicate them really isn't the best way to go about in Scala. For instance, the following code does the equivalent job to what you want:
```scala
def classStream(clazz: Class[_]): Stream[Class[_]] = clazz match {
case null => Stream.empty
case _ => (
clazz
#:: classStream(clazz.getSuperclass)
#::: clazz.getInterfaces.toStream.flatMap(classStream)
#::: Stream.empty
)
}
```
In it the stream is generated lazily, so it won't process any of the elements until asked for, which you can verify by running this:
```scala
def classStream(clazz: Class[_]): Stream[Class[_]] = clazz match {
case null => Stream.empty
case _ => (
clazz
#:: { println(clazz.toString+": super"); classStream(clazz.getSuperclass) }
#::: { println(clazz.toString+": interfaces"); clazz.getInterfaces.toStream.flatMap(classStream) }
#::: Stream.empty
)
}
```
The result can be converted into an `Iterator` simply by calling `.iterator` on the resulting `Stream`:
```
def classIterator(clazz: Class[_]): Iterator[Class[_]] = classStream(clazz).iterator
```
The `foo` definition, using `Stream`, would be rendered thus:
```scala
scala> def foo(i: Int): Stream[Int] = i #:: (if (i > 0) foo(i - 1) else Stream.empty)
foo: (i: Int)Stream[Int]
scala> foo(5) foreach println
5
4
3
2
1
0
```
Another alternative would be concatenating the various iterators, taking care to not pre-compute them. Here's an example, also with debugging messages to help trace the execution:
```
def yieldClass(clazz: Class[_]): Iterator[Class[_]] = clazz match {
case null => println("empty"); Iterator.empty
case _ =>
def thisIterator = { println("self of "+clazz); Iterator(clazz) }
def superIterator = { println("super of "+clazz); yieldClass(clazz.getSuperclass) }
def interfacesIterator = { println("interfaces of "+clazz); clazz.getInterfaces.iterator flatMap yieldClass }
thisIterator ++ superIterator ++ interfacesIterator
}
```
This is pretty close to your code. Instead of `sudoYield`, I have definitions, and then I just concatenate them as I wish.
So, while this is a non-answer, I just think you are barking up the wrong tree here. Trying to write Python in Scala is bound to be unproductive. Work harder at the Scala idioms that accomplish the same goals.
|
To do this in a general way, I think you need the [continuations plugin](http://blog.richdougherty.com/search/label/continuations).
A naive implementation (freehand, not compiled/checked):
```
def iterator = new {
private[this] var done = false
// Define your yielding state here
// This generator yields: 3, 13, 0, 1, 3, 6, 26, 27
private[this] var state: Unit=>Int = reset {
var x = 3
giveItUp(x)
x += 10
giveItUp(x)
x = 0
giveItUp(x)
List(1,2,3).foreach { i => x += i; giveItUp(x) }
x += 20
giveItUp(x)
x += 1
done = true
x
}
// Well, "yield" is a keyword, so how about giveItUp?
private[this] def giveItUp(i: Int) = shift { k: (Unit=>Int) =>
state = k
i
}
def hasNext = !done
def next = state()
}
```
What is happening is that any call to `shift` captures the control flow from where it is called to the end of the `reset` block that it is called in. This is passed as the `k` argument into the shift function.
So, in the example above, each `giveItUp(x)` returns the value of `x` (up to that point) and saves the rest of the computation in the `state` variable. It is driven from outside by the `hasNext` and `next` methods.
Go gentle, this is obviously a terrible way to implement this. But it best I could do late at night without a compiler handy.
|
2,137,619
|
Is it possible to implement in Scala something equivalent to the Python `yield` statement where it remembers the local state of the function where it is used and "yields" the next value each time it is called?
I wanted to have something like this to convert a recursive function into an iterator. Sort of like this:
```
# this is python
def foo(i):
yield i
if i > 0:
for j in foo(i - 1):
yield j
for i in foo(5):
print i
```
Except, `foo` may be more complex and recurs through some acyclic object graph.
**Additional Edit:**
Let me add a more complex example (but still simple):
I can write a simple recursive function printing things as it goes along:
```
// this is Scala
def printClass(clazz:Class[_], indent:String=""): Unit = {
clazz match {
case null =>
case _ =>
println(indent + clazz)
printClass(clazz.getSuperclass, indent + " ")
for (c <- clazz.getInterfaces) {
printClass(c, indent + " ")
}
}
}
```
Ideally I would like to have a library that allows me to easily change a few statements and have it work as an Iterator:
```
// this is not Scala
def yieldClass(clazz:Class[_]): Iterator[Class[_]] = {
clazz match {
case null =>
case _ =>
sudoYield clazz
for (c <- yieldClass(clazz.getSuperclass)) sudoYield c
for (c <- clazz.getInterfaces; d <- yieldClasss(c)) sudoYield d
}
}
```
It does seem continuations allow to do that, but I just don't understand the `shift/reset` concept. Will continuation eventually make it into the main compiler and would it be possible to extract out the complexity in a library?
**Edit 2:**
check [Rich's answer](https://stackoverflow.com/questions/2201882/implementing-yield-yield-return-using-scala-continuations/2215182#2215182) in that other thread.
|
2010/01/26
|
[
"https://Stackoverflow.com/questions/2137619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257449/"
] |
Another continuations plugin based solution, this time with a more or less encapsulated Generator type,
```
import scala.continuations._
import scala.continuations.ControlContext._
object Test {
def loopWhile(cond: =>Boolean)(body: =>(Unit @suspendable)): Unit @suspendable = {
if (cond) {
body
loopWhile(cond)(body)
} else ()
}
abstract class Generator[T] {
var producerCont : (Unit => Unit) = null
var consumerCont : (T => Unit) = null
protected def body : Unit @suspendable
reset {
body
}
def generate(t : T) : Unit @suspendable =
shift {
(k : Unit => Unit) => {
producerCont = k
if (consumerCont != null)
consumerCont(t)
}
}
def next : T @suspendable =
shift {
(k : T => Unit) => {
consumerCont = k
if (producerCont != null)
producerCont()
}
}
}
def main(args: Array[String]) {
val g = new Generator[Int] {
def body = {
var i = 0
loopWhile(i < 10) {
generate(i)
i += 1
}
}
}
reset {
loopWhile(true) {
println("Generated: "+g.next)
}
}
}
}
```
|
To do this in a general way, I think you need the [continuations plugin](http://blog.richdougherty.com/search/label/continuations).
A naive implementation (freehand, not compiled/checked):
```
def iterator = new {
private[this] var done = false
// Define your yielding state here
// This generator yields: 3, 13, 0, 1, 3, 6, 26, 27
private[this] var state: Unit=>Int = reset {
var x = 3
giveItUp(x)
x += 10
giveItUp(x)
x = 0
giveItUp(x)
List(1,2,3).foreach { i => x += i; giveItUp(x) }
x += 20
giveItUp(x)
x += 1
done = true
x
}
// Well, "yield" is a keyword, so how about giveItUp?
private[this] def giveItUp(i: Int) = shift { k: (Unit=>Int) =>
state = k
i
}
def hasNext = !done
def next = state()
}
```
What is happening is that any call to `shift` captures the control flow from where it is called to the end of the `reset` block that it is called in. This is passed as the `k` argument into the shift function.
So, in the example above, each `giveItUp(x)` returns the value of `x` (up to that point) and saves the rest of the computation in the `state` variable. It is driven from outside by the `hasNext` and `next` methods.
Go gentle, this is obviously a terrible way to implement this. But it best I could do late at night without a compiler handy.
|
2,137,619
|
Is it possible to implement in Scala something equivalent to the Python `yield` statement where it remembers the local state of the function where it is used and "yields" the next value each time it is called?
I wanted to have something like this to convert a recursive function into an iterator. Sort of like this:
```
# this is python
def foo(i):
yield i
if i > 0:
for j in foo(i - 1):
yield j
for i in foo(5):
print i
```
Except, `foo` may be more complex and recurs through some acyclic object graph.
**Additional Edit:**
Let me add a more complex example (but still simple):
I can write a simple recursive function printing things as it goes along:
```
// this is Scala
def printClass(clazz:Class[_], indent:String=""): Unit = {
clazz match {
case null =>
case _ =>
println(indent + clazz)
printClass(clazz.getSuperclass, indent + " ")
for (c <- clazz.getInterfaces) {
printClass(c, indent + " ")
}
}
}
```
Ideally I would like to have a library that allows me to easily change a few statements and have it work as an Iterator:
```
// this is not Scala
def yieldClass(clazz:Class[_]): Iterator[Class[_]] = {
clazz match {
case null =>
case _ =>
sudoYield clazz
for (c <- yieldClass(clazz.getSuperclass)) sudoYield c
for (c <- clazz.getInterfaces; d <- yieldClasss(c)) sudoYield d
}
}
```
It does seem continuations allow to do that, but I just don't understand the `shift/reset` concept. Will continuation eventually make it into the main compiler and would it be possible to extract out the complexity in a library?
**Edit 2:**
check [Rich's answer](https://stackoverflow.com/questions/2201882/implementing-yield-yield-return-using-scala-continuations/2215182#2215182) in that other thread.
|
2010/01/26
|
[
"https://Stackoverflow.com/questions/2137619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257449/"
] |
To do this in a general way, I think you need the [continuations plugin](http://blog.richdougherty.com/search/label/continuations).
A naive implementation (freehand, not compiled/checked):
```
def iterator = new {
private[this] var done = false
// Define your yielding state here
// This generator yields: 3, 13, 0, 1, 3, 6, 26, 27
private[this] var state: Unit=>Int = reset {
var x = 3
giveItUp(x)
x += 10
giveItUp(x)
x = 0
giveItUp(x)
List(1,2,3).foreach { i => x += i; giveItUp(x) }
x += 20
giveItUp(x)
x += 1
done = true
x
}
// Well, "yield" is a keyword, so how about giveItUp?
private[this] def giveItUp(i: Int) = shift { k: (Unit=>Int) =>
state = k
i
}
def hasNext = !done
def next = state()
}
```
What is happening is that any call to `shift` captures the control flow from where it is called to the end of the `reset` block that it is called in. This is passed as the `k` argument into the shift function.
So, in the example above, each `giveItUp(x)` returns the value of `x` (up to that point) and saves the rest of the computation in the `state` variable. It is driven from outside by the `hasNext` and `next` methods.
Go gentle, this is obviously a terrible way to implement this. But it best I could do late at night without a compiler handy.
|
[Dsl.scala](https://github.com/ThoughtWorksInc/Dsl.scala) is what you are looking for.
Suppose you want to create a random number generator. The generated numbers should be stored in a lazily evaluated infinite stream, which can be built with the help of our built-in domain-specific keyword `Yield`.
```
import com.thoughtworks.dsl.keys.Yield
def xorshiftRandomGenerator(seed: Int): Stream[Int] = {
val tmp1 = seed ^ (seed << 13)
val tmp2 = tmp1 ^ (tmp1 >>> 17)
val tmp3 = tmp2 ^ (tmp2 << 5)
!Yield(tmp3)
xorshiftRandomGenerator(tmp3)
}
```
Other examples can be found in the [Scaladoc](https://javadoc.io/page/com.thoughtworks.dsl/dsl_2.12/latest/com/thoughtworks/dsl/index.html).
|
2,137,619
|
Is it possible to implement in Scala something equivalent to the Python `yield` statement where it remembers the local state of the function where it is used and "yields" the next value each time it is called?
I wanted to have something like this to convert a recursive function into an iterator. Sort of like this:
```
# this is python
def foo(i):
yield i
if i > 0:
for j in foo(i - 1):
yield j
for i in foo(5):
print i
```
Except, `foo` may be more complex and recurs through some acyclic object graph.
**Additional Edit:**
Let me add a more complex example (but still simple):
I can write a simple recursive function printing things as it goes along:
```
// this is Scala
def printClass(clazz:Class[_], indent:String=""): Unit = {
clazz match {
case null =>
case _ =>
println(indent + clazz)
printClass(clazz.getSuperclass, indent + " ")
for (c <- clazz.getInterfaces) {
printClass(c, indent + " ")
}
}
}
```
Ideally I would like to have a library that allows me to easily change a few statements and have it work as an Iterator:
```
// this is not Scala
def yieldClass(clazz:Class[_]): Iterator[Class[_]] = {
clazz match {
case null =>
case _ =>
sudoYield clazz
for (c <- yieldClass(clazz.getSuperclass)) sudoYield c
for (c <- clazz.getInterfaces; d <- yieldClasss(c)) sudoYield d
}
}
```
It does seem continuations allow to do that, but I just don't understand the `shift/reset` concept. Will continuation eventually make it into the main compiler and would it be possible to extract out the complexity in a library?
**Edit 2:**
check [Rich's answer](https://stackoverflow.com/questions/2201882/implementing-yield-yield-return-using-scala-continuations/2215182#2215182) in that other thread.
|
2010/01/26
|
[
"https://Stackoverflow.com/questions/2137619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257449/"
] |
While Python generators are cool, trying to duplicate them really isn't the best way to go about in Scala. For instance, the following code does the equivalent job to what you want:
```scala
def classStream(clazz: Class[_]): Stream[Class[_]] = clazz match {
case null => Stream.empty
case _ => (
clazz
#:: classStream(clazz.getSuperclass)
#::: clazz.getInterfaces.toStream.flatMap(classStream)
#::: Stream.empty
)
}
```
In it the stream is generated lazily, so it won't process any of the elements until asked for, which you can verify by running this:
```scala
def classStream(clazz: Class[_]): Stream[Class[_]] = clazz match {
case null => Stream.empty
case _ => (
clazz
#:: { println(clazz.toString+": super"); classStream(clazz.getSuperclass) }
#::: { println(clazz.toString+": interfaces"); clazz.getInterfaces.toStream.flatMap(classStream) }
#::: Stream.empty
)
}
```
The result can be converted into an `Iterator` simply by calling `.iterator` on the resulting `Stream`:
```
def classIterator(clazz: Class[_]): Iterator[Class[_]] = classStream(clazz).iterator
```
The `foo` definition, using `Stream`, would be rendered thus:
```scala
scala> def foo(i: Int): Stream[Int] = i #:: (if (i > 0) foo(i - 1) else Stream.empty)
foo: (i: Int)Stream[Int]
scala> foo(5) foreach println
5
4
3
2
1
0
```
Another alternative would be concatenating the various iterators, taking care to not pre-compute them. Here's an example, also with debugging messages to help trace the execution:
```
def yieldClass(clazz: Class[_]): Iterator[Class[_]] = clazz match {
case null => println("empty"); Iterator.empty
case _ =>
def thisIterator = { println("self of "+clazz); Iterator(clazz) }
def superIterator = { println("super of "+clazz); yieldClass(clazz.getSuperclass) }
def interfacesIterator = { println("interfaces of "+clazz); clazz.getInterfaces.iterator flatMap yieldClass }
thisIterator ++ superIterator ++ interfacesIterator
}
```
This is pretty close to your code. Instead of `sudoYield`, I have definitions, and then I just concatenate them as I wish.
So, while this is a non-answer, I just think you are barking up the wrong tree here. Trying to write Python in Scala is bound to be unproductive. Work harder at the Scala idioms that accomplish the same goals.
|
Another continuations plugin based solution, this time with a more or less encapsulated Generator type,
```
import scala.continuations._
import scala.continuations.ControlContext._
object Test {
def loopWhile(cond: =>Boolean)(body: =>(Unit @suspendable)): Unit @suspendable = {
if (cond) {
body
loopWhile(cond)(body)
} else ()
}
abstract class Generator[T] {
var producerCont : (Unit => Unit) = null
var consumerCont : (T => Unit) = null
protected def body : Unit @suspendable
reset {
body
}
def generate(t : T) : Unit @suspendable =
shift {
(k : Unit => Unit) => {
producerCont = k
if (consumerCont != null)
consumerCont(t)
}
}
def next : T @suspendable =
shift {
(k : T => Unit) => {
consumerCont = k
if (producerCont != null)
producerCont()
}
}
}
def main(args: Array[String]) {
val g = new Generator[Int] {
def body = {
var i = 0
loopWhile(i < 10) {
generate(i)
i += 1
}
}
}
reset {
loopWhile(true) {
println("Generated: "+g.next)
}
}
}
}
```
|
2,137,619
|
Is it possible to implement in Scala something equivalent to the Python `yield` statement where it remembers the local state of the function where it is used and "yields" the next value each time it is called?
I wanted to have something like this to convert a recursive function into an iterator. Sort of like this:
```
# this is python
def foo(i):
yield i
if i > 0:
for j in foo(i - 1):
yield j
for i in foo(5):
print i
```
Except, `foo` may be more complex and recurs through some acyclic object graph.
**Additional Edit:**
Let me add a more complex example (but still simple):
I can write a simple recursive function printing things as it goes along:
```
// this is Scala
def printClass(clazz:Class[_], indent:String=""): Unit = {
clazz match {
case null =>
case _ =>
println(indent + clazz)
printClass(clazz.getSuperclass, indent + " ")
for (c <- clazz.getInterfaces) {
printClass(c, indent + " ")
}
}
}
```
Ideally I would like to have a library that allows me to easily change a few statements and have it work as an Iterator:
```
// this is not Scala
def yieldClass(clazz:Class[_]): Iterator[Class[_]] = {
clazz match {
case null =>
case _ =>
sudoYield clazz
for (c <- yieldClass(clazz.getSuperclass)) sudoYield c
for (c <- clazz.getInterfaces; d <- yieldClasss(c)) sudoYield d
}
}
```
It does seem continuations allow to do that, but I just don't understand the `shift/reset` concept. Will continuation eventually make it into the main compiler and would it be possible to extract out the complexity in a library?
**Edit 2:**
check [Rich's answer](https://stackoverflow.com/questions/2201882/implementing-yield-yield-return-using-scala-continuations/2215182#2215182) in that other thread.
|
2010/01/26
|
[
"https://Stackoverflow.com/questions/2137619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257449/"
] |
While Python generators are cool, trying to duplicate them really isn't the best way to go about in Scala. For instance, the following code does the equivalent job to what you want:
```scala
def classStream(clazz: Class[_]): Stream[Class[_]] = clazz match {
case null => Stream.empty
case _ => (
clazz
#:: classStream(clazz.getSuperclass)
#::: clazz.getInterfaces.toStream.flatMap(classStream)
#::: Stream.empty
)
}
```
In it the stream is generated lazily, so it won't process any of the elements until asked for, which you can verify by running this:
```scala
def classStream(clazz: Class[_]): Stream[Class[_]] = clazz match {
case null => Stream.empty
case _ => (
clazz
#:: { println(clazz.toString+": super"); classStream(clazz.getSuperclass) }
#::: { println(clazz.toString+": interfaces"); clazz.getInterfaces.toStream.flatMap(classStream) }
#::: Stream.empty
)
}
```
The result can be converted into an `Iterator` simply by calling `.iterator` on the resulting `Stream`:
```
def classIterator(clazz: Class[_]): Iterator[Class[_]] = classStream(clazz).iterator
```
The `foo` definition, using `Stream`, would be rendered thus:
```scala
scala> def foo(i: Int): Stream[Int] = i #:: (if (i > 0) foo(i - 1) else Stream.empty)
foo: (i: Int)Stream[Int]
scala> foo(5) foreach println
5
4
3
2
1
0
```
Another alternative would be concatenating the various iterators, taking care to not pre-compute them. Here's an example, also with debugging messages to help trace the execution:
```
def yieldClass(clazz: Class[_]): Iterator[Class[_]] = clazz match {
case null => println("empty"); Iterator.empty
case _ =>
def thisIterator = { println("self of "+clazz); Iterator(clazz) }
def superIterator = { println("super of "+clazz); yieldClass(clazz.getSuperclass) }
def interfacesIterator = { println("interfaces of "+clazz); clazz.getInterfaces.iterator flatMap yieldClass }
thisIterator ++ superIterator ++ interfacesIterator
}
```
This is pretty close to your code. Instead of `sudoYield`, I have definitions, and then I just concatenate them as I wish.
So, while this is a non-answer, I just think you are barking up the wrong tree here. Trying to write Python in Scala is bound to be unproductive. Work harder at the Scala idioms that accomplish the same goals.
|
Scala's for-loop of the form `for (e <- Producer) f(e)` translates into a `foreach` call, and not directly into `iterator` / `next`.
In the `foreach` we don't need to linearize objects' creations and have them in one place, as it would be needed for iterator's `next`. The consumer-function `f` can be inserted multiple times, exactly where it is needed (i.e. where an object is created).
This makes implementation of use cases for generators simple and efficient with `Traversable` / `foreach` in Scala.
---
The initial Foo-example:
```
case class Countdown(start: Int) extends Traversable[Int] {
def foreach[U](f: Int => U) {
var j = start
while (j >= 0) {f(j); j -= 1}
}
}
for (i <- Countdown(5)) println(i)
// or equivalent:
Countdown(5) foreach println
```
---
The initial printClass-example:
```
// v1 (without indentation)
case class ClassStructure(c: Class[_]) {
def foreach[U](f: Class[_] => U) {
if (c eq null) return
f(c)
ClassStructure(c.getSuperclass) foreach f
c.getInterfaces foreach (ClassStructure(_) foreach f)
}
}
for (c <- ClassStructure(<foo/>.getClass)) println(c)
// or equivalent:
ClassStructure(<foo/>.getClass) foreach println
```
Or with indentation:
```
// v2 (with indentation)
case class ClassWithIndent(c: Class[_], indent: String = "") {
override def toString = indent + c
}
implicit def Class2WithIndent(c: Class[_]) = ClassWithIndent(c)
case class ClassStructure(cwi: ClassWithIndent) {
def foreach[U](f: ClassWithIndent => U) {
if (cwi.c eq null) return
f(cwi)
ClassStructure(ClassWithIndent(cwi.c.getSuperclass, cwi.indent + " ")) foreach f
cwi.c.getInterfaces foreach (i => ClassStructure(ClassWithIndent(i, cwi.indent + " ")) foreach f)
}
}
for (c <- ClassStructure(<foo/>.getClass)) println(c)
// or equivalent:
ClassStructure(<foo/>.getClass) foreach println
```
Output:
```
class scala.xml.Elem
class scala.xml.Node
class scala.xml.NodeSeq
class java.lang.Object
interface scala.collection.immutable.Seq
interface scala.collection.immutable.Iterable
interface scala.collection.immutable.Traversable
interface scala.collection.Traversable
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.Immutable
interface scala.ScalaObject
interface scala.collection.Iterable
interface scala.collection.Traversable
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.collection.IterableLike
interface scala.Equals
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.collection.IterableLike
interface scala.Equals
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.Seq
interface scala.PartialFunction
interface scala.Function1
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.Iterable
interface scala.collection.Traversable
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.collection.IterableLike
interface scala.Equals
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.collection.SeqLike
interface scala.collection.IterableLike
interface scala.Equals
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.collection.SeqLike
interface scala.collection.IterableLike
interface scala.Equals
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.SeqLike
interface scala.collection.IterableLike
interface scala.Equals
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.xml.Equality
interface scala.Equals
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface java.io.Serializable
```
|
2,137,619
|
Is it possible to implement in Scala something equivalent to the Python `yield` statement where it remembers the local state of the function where it is used and "yields" the next value each time it is called?
I wanted to have something like this to convert a recursive function into an iterator. Sort of like this:
```
# this is python
def foo(i):
yield i
if i > 0:
for j in foo(i - 1):
yield j
for i in foo(5):
print i
```
Except, `foo` may be more complex and recurs through some acyclic object graph.
**Additional Edit:**
Let me add a more complex example (but still simple):
I can write a simple recursive function printing things as it goes along:
```
// this is Scala
def printClass(clazz:Class[_], indent:String=""): Unit = {
clazz match {
case null =>
case _ =>
println(indent + clazz)
printClass(clazz.getSuperclass, indent + " ")
for (c <- clazz.getInterfaces) {
printClass(c, indent + " ")
}
}
}
```
Ideally I would like to have a library that allows me to easily change a few statements and have it work as an Iterator:
```
// this is not Scala
def yieldClass(clazz:Class[_]): Iterator[Class[_]] = {
clazz match {
case null =>
case _ =>
sudoYield clazz
for (c <- yieldClass(clazz.getSuperclass)) sudoYield c
for (c <- clazz.getInterfaces; d <- yieldClasss(c)) sudoYield d
}
}
```
It does seem continuations allow to do that, but I just don't understand the `shift/reset` concept. Will continuation eventually make it into the main compiler and would it be possible to extract out the complexity in a library?
**Edit 2:**
check [Rich's answer](https://stackoverflow.com/questions/2201882/implementing-yield-yield-return-using-scala-continuations/2215182#2215182) in that other thread.
|
2010/01/26
|
[
"https://Stackoverflow.com/questions/2137619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257449/"
] |
While Python generators are cool, trying to duplicate them really isn't the best way to go about in Scala. For instance, the following code does the equivalent job to what you want:
```scala
def classStream(clazz: Class[_]): Stream[Class[_]] = clazz match {
case null => Stream.empty
case _ => (
clazz
#:: classStream(clazz.getSuperclass)
#::: clazz.getInterfaces.toStream.flatMap(classStream)
#::: Stream.empty
)
}
```
In it the stream is generated lazily, so it won't process any of the elements until asked for, which you can verify by running this:
```scala
def classStream(clazz: Class[_]): Stream[Class[_]] = clazz match {
case null => Stream.empty
case _ => (
clazz
#:: { println(clazz.toString+": super"); classStream(clazz.getSuperclass) }
#::: { println(clazz.toString+": interfaces"); clazz.getInterfaces.toStream.flatMap(classStream) }
#::: Stream.empty
)
}
```
The result can be converted into an `Iterator` simply by calling `.iterator` on the resulting `Stream`:
```
def classIterator(clazz: Class[_]): Iterator[Class[_]] = classStream(clazz).iterator
```
The `foo` definition, using `Stream`, would be rendered thus:
```scala
scala> def foo(i: Int): Stream[Int] = i #:: (if (i > 0) foo(i - 1) else Stream.empty)
foo: (i: Int)Stream[Int]
scala> foo(5) foreach println
5
4
3
2
1
0
```
Another alternative would be concatenating the various iterators, taking care to not pre-compute them. Here's an example, also with debugging messages to help trace the execution:
```
def yieldClass(clazz: Class[_]): Iterator[Class[_]] = clazz match {
case null => println("empty"); Iterator.empty
case _ =>
def thisIterator = { println("self of "+clazz); Iterator(clazz) }
def superIterator = { println("super of "+clazz); yieldClass(clazz.getSuperclass) }
def interfacesIterator = { println("interfaces of "+clazz); clazz.getInterfaces.iterator flatMap yieldClass }
thisIterator ++ superIterator ++ interfacesIterator
}
```
This is pretty close to your code. Instead of `sudoYield`, I have definitions, and then I just concatenate them as I wish.
So, while this is a non-answer, I just think you are barking up the wrong tree here. Trying to write Python in Scala is bound to be unproductive. Work harder at the Scala idioms that accomplish the same goals.
|
[Dsl.scala](https://github.com/ThoughtWorksInc/Dsl.scala) is what you are looking for.
Suppose you want to create a random number generator. The generated numbers should be stored in a lazily evaluated infinite stream, which can be built with the help of our built-in domain-specific keyword `Yield`.
```
import com.thoughtworks.dsl.keys.Yield
def xorshiftRandomGenerator(seed: Int): Stream[Int] = {
val tmp1 = seed ^ (seed << 13)
val tmp2 = tmp1 ^ (tmp1 >>> 17)
val tmp3 = tmp2 ^ (tmp2 << 5)
!Yield(tmp3)
xorshiftRandomGenerator(tmp3)
}
```
Other examples can be found in the [Scaladoc](https://javadoc.io/page/com.thoughtworks.dsl/dsl_2.12/latest/com/thoughtworks/dsl/index.html).
|
2,137,619
|
Is it possible to implement in Scala something equivalent to the Python `yield` statement where it remembers the local state of the function where it is used and "yields" the next value each time it is called?
I wanted to have something like this to convert a recursive function into an iterator. Sort of like this:
```
# this is python
def foo(i):
yield i
if i > 0:
for j in foo(i - 1):
yield j
for i in foo(5):
print i
```
Except, `foo` may be more complex and recurs through some acyclic object graph.
**Additional Edit:**
Let me add a more complex example (but still simple):
I can write a simple recursive function printing things as it goes along:
```
// this is Scala
def printClass(clazz:Class[_], indent:String=""): Unit = {
clazz match {
case null =>
case _ =>
println(indent + clazz)
printClass(clazz.getSuperclass, indent + " ")
for (c <- clazz.getInterfaces) {
printClass(c, indent + " ")
}
}
}
```
Ideally I would like to have a library that allows me to easily change a few statements and have it work as an Iterator:
```
// this is not Scala
def yieldClass(clazz:Class[_]): Iterator[Class[_]] = {
clazz match {
case null =>
case _ =>
sudoYield clazz
for (c <- yieldClass(clazz.getSuperclass)) sudoYield c
for (c <- clazz.getInterfaces; d <- yieldClasss(c)) sudoYield d
}
}
```
It does seem continuations allow to do that, but I just don't understand the `shift/reset` concept. Will continuation eventually make it into the main compiler and would it be possible to extract out the complexity in a library?
**Edit 2:**
check [Rich's answer](https://stackoverflow.com/questions/2201882/implementing-yield-yield-return-using-scala-continuations/2215182#2215182) in that other thread.
|
2010/01/26
|
[
"https://Stackoverflow.com/questions/2137619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257449/"
] |
Another continuations plugin based solution, this time with a more or less encapsulated Generator type,
```
import scala.continuations._
import scala.continuations.ControlContext._
object Test {
def loopWhile(cond: =>Boolean)(body: =>(Unit @suspendable)): Unit @suspendable = {
if (cond) {
body
loopWhile(cond)(body)
} else ()
}
abstract class Generator[T] {
var producerCont : (Unit => Unit) = null
var consumerCont : (T => Unit) = null
protected def body : Unit @suspendable
reset {
body
}
def generate(t : T) : Unit @suspendable =
shift {
(k : Unit => Unit) => {
producerCont = k
if (consumerCont != null)
consumerCont(t)
}
}
def next : T @suspendable =
shift {
(k : T => Unit) => {
consumerCont = k
if (producerCont != null)
producerCont()
}
}
}
def main(args: Array[String]) {
val g = new Generator[Int] {
def body = {
var i = 0
loopWhile(i < 10) {
generate(i)
i += 1
}
}
}
reset {
loopWhile(true) {
println("Generated: "+g.next)
}
}
}
}
```
|
Scala's for-loop of the form `for (e <- Producer) f(e)` translates into a `foreach` call, and not directly into `iterator` / `next`.
In the `foreach` we don't need to linearize objects' creations and have them in one place, as it would be needed for iterator's `next`. The consumer-function `f` can be inserted multiple times, exactly where it is needed (i.e. where an object is created).
This makes implementation of use cases for generators simple and efficient with `Traversable` / `foreach` in Scala.
---
The initial Foo-example:
```
case class Countdown(start: Int) extends Traversable[Int] {
def foreach[U](f: Int => U) {
var j = start
while (j >= 0) {f(j); j -= 1}
}
}
for (i <- Countdown(5)) println(i)
// or equivalent:
Countdown(5) foreach println
```
---
The initial printClass-example:
```
// v1 (without indentation)
case class ClassStructure(c: Class[_]) {
def foreach[U](f: Class[_] => U) {
if (c eq null) return
f(c)
ClassStructure(c.getSuperclass) foreach f
c.getInterfaces foreach (ClassStructure(_) foreach f)
}
}
for (c <- ClassStructure(<foo/>.getClass)) println(c)
// or equivalent:
ClassStructure(<foo/>.getClass) foreach println
```
Or with indentation:
```
// v2 (with indentation)
case class ClassWithIndent(c: Class[_], indent: String = "") {
override def toString = indent + c
}
implicit def Class2WithIndent(c: Class[_]) = ClassWithIndent(c)
case class ClassStructure(cwi: ClassWithIndent) {
def foreach[U](f: ClassWithIndent => U) {
if (cwi.c eq null) return
f(cwi)
ClassStructure(ClassWithIndent(cwi.c.getSuperclass, cwi.indent + " ")) foreach f
cwi.c.getInterfaces foreach (i => ClassStructure(ClassWithIndent(i, cwi.indent + " ")) foreach f)
}
}
for (c <- ClassStructure(<foo/>.getClass)) println(c)
// or equivalent:
ClassStructure(<foo/>.getClass) foreach println
```
Output:
```
class scala.xml.Elem
class scala.xml.Node
class scala.xml.NodeSeq
class java.lang.Object
interface scala.collection.immutable.Seq
interface scala.collection.immutable.Iterable
interface scala.collection.immutable.Traversable
interface scala.collection.Traversable
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.Immutable
interface scala.ScalaObject
interface scala.collection.Iterable
interface scala.collection.Traversable
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.collection.IterableLike
interface scala.Equals
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.collection.IterableLike
interface scala.Equals
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.Seq
interface scala.PartialFunction
interface scala.Function1
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.Iterable
interface scala.collection.Traversable
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.collection.IterableLike
interface scala.Equals
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.collection.SeqLike
interface scala.collection.IterableLike
interface scala.Equals
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.collection.SeqLike
interface scala.collection.IterableLike
interface scala.Equals
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.SeqLike
interface scala.collection.IterableLike
interface scala.Equals
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.xml.Equality
interface scala.Equals
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface java.io.Serializable
```
|
2,137,619
|
Is it possible to implement in Scala something equivalent to the Python `yield` statement where it remembers the local state of the function where it is used and "yields" the next value each time it is called?
I wanted to have something like this to convert a recursive function into an iterator. Sort of like this:
```
# this is python
def foo(i):
yield i
if i > 0:
for j in foo(i - 1):
yield j
for i in foo(5):
print i
```
Except, `foo` may be more complex and recurs through some acyclic object graph.
**Additional Edit:**
Let me add a more complex example (but still simple):
I can write a simple recursive function printing things as it goes along:
```
// this is Scala
def printClass(clazz:Class[_], indent:String=""): Unit = {
clazz match {
case null =>
case _ =>
println(indent + clazz)
printClass(clazz.getSuperclass, indent + " ")
for (c <- clazz.getInterfaces) {
printClass(c, indent + " ")
}
}
}
```
Ideally I would like to have a library that allows me to easily change a few statements and have it work as an Iterator:
```
// this is not Scala
def yieldClass(clazz:Class[_]): Iterator[Class[_]] = {
clazz match {
case null =>
case _ =>
sudoYield clazz
for (c <- yieldClass(clazz.getSuperclass)) sudoYield c
for (c <- clazz.getInterfaces; d <- yieldClasss(c)) sudoYield d
}
}
```
It does seem continuations allow to do that, but I just don't understand the `shift/reset` concept. Will continuation eventually make it into the main compiler and would it be possible to extract out the complexity in a library?
**Edit 2:**
check [Rich's answer](https://stackoverflow.com/questions/2201882/implementing-yield-yield-return-using-scala-continuations/2215182#2215182) in that other thread.
|
2010/01/26
|
[
"https://Stackoverflow.com/questions/2137619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257449/"
] |
Another continuations plugin based solution, this time with a more or less encapsulated Generator type,
```
import scala.continuations._
import scala.continuations.ControlContext._
object Test {
def loopWhile(cond: =>Boolean)(body: =>(Unit @suspendable)): Unit @suspendable = {
if (cond) {
body
loopWhile(cond)(body)
} else ()
}
abstract class Generator[T] {
var producerCont : (Unit => Unit) = null
var consumerCont : (T => Unit) = null
protected def body : Unit @suspendable
reset {
body
}
def generate(t : T) : Unit @suspendable =
shift {
(k : Unit => Unit) => {
producerCont = k
if (consumerCont != null)
consumerCont(t)
}
}
def next : T @suspendable =
shift {
(k : T => Unit) => {
consumerCont = k
if (producerCont != null)
producerCont()
}
}
}
def main(args: Array[String]) {
val g = new Generator[Int] {
def body = {
var i = 0
loopWhile(i < 10) {
generate(i)
i += 1
}
}
}
reset {
loopWhile(true) {
println("Generated: "+g.next)
}
}
}
}
```
|
[Dsl.scala](https://github.com/ThoughtWorksInc/Dsl.scala) is what you are looking for.
Suppose you want to create a random number generator. The generated numbers should be stored in a lazily evaluated infinite stream, which can be built with the help of our built-in domain-specific keyword `Yield`.
```
import com.thoughtworks.dsl.keys.Yield
def xorshiftRandomGenerator(seed: Int): Stream[Int] = {
val tmp1 = seed ^ (seed << 13)
val tmp2 = tmp1 ^ (tmp1 >>> 17)
val tmp3 = tmp2 ^ (tmp2 << 5)
!Yield(tmp3)
xorshiftRandomGenerator(tmp3)
}
```
Other examples can be found in the [Scaladoc](https://javadoc.io/page/com.thoughtworks.dsl/dsl_2.12/latest/com/thoughtworks/dsl/index.html).
|
2,137,619
|
Is it possible to implement in Scala something equivalent to the Python `yield` statement where it remembers the local state of the function where it is used and "yields" the next value each time it is called?
I wanted to have something like this to convert a recursive function into an iterator. Sort of like this:
```
# this is python
def foo(i):
yield i
if i > 0:
for j in foo(i - 1):
yield j
for i in foo(5):
print i
```
Except, `foo` may be more complex and recurs through some acyclic object graph.
**Additional Edit:**
Let me add a more complex example (but still simple):
I can write a simple recursive function printing things as it goes along:
```
// this is Scala
def printClass(clazz:Class[_], indent:String=""): Unit = {
clazz match {
case null =>
case _ =>
println(indent + clazz)
printClass(clazz.getSuperclass, indent + " ")
for (c <- clazz.getInterfaces) {
printClass(c, indent + " ")
}
}
}
```
Ideally I would like to have a library that allows me to easily change a few statements and have it work as an Iterator:
```
// this is not Scala
def yieldClass(clazz:Class[_]): Iterator[Class[_]] = {
clazz match {
case null =>
case _ =>
sudoYield clazz
for (c <- yieldClass(clazz.getSuperclass)) sudoYield c
for (c <- clazz.getInterfaces; d <- yieldClasss(c)) sudoYield d
}
}
```
It does seem continuations allow to do that, but I just don't understand the `shift/reset` concept. Will continuation eventually make it into the main compiler and would it be possible to extract out the complexity in a library?
**Edit 2:**
check [Rich's answer](https://stackoverflow.com/questions/2201882/implementing-yield-yield-return-using-scala-continuations/2215182#2215182) in that other thread.
|
2010/01/26
|
[
"https://Stackoverflow.com/questions/2137619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257449/"
] |
Scala's for-loop of the form `for (e <- Producer) f(e)` translates into a `foreach` call, and not directly into `iterator` / `next`.
In the `foreach` we don't need to linearize objects' creations and have them in one place, as it would be needed for iterator's `next`. The consumer-function `f` can be inserted multiple times, exactly where it is needed (i.e. where an object is created).
This makes implementation of use cases for generators simple and efficient with `Traversable` / `foreach` in Scala.
---
The initial Foo-example:
```
case class Countdown(start: Int) extends Traversable[Int] {
def foreach[U](f: Int => U) {
var j = start
while (j >= 0) {f(j); j -= 1}
}
}
for (i <- Countdown(5)) println(i)
// or equivalent:
Countdown(5) foreach println
```
---
The initial printClass-example:
```
// v1 (without indentation)
case class ClassStructure(c: Class[_]) {
def foreach[U](f: Class[_] => U) {
if (c eq null) return
f(c)
ClassStructure(c.getSuperclass) foreach f
c.getInterfaces foreach (ClassStructure(_) foreach f)
}
}
for (c <- ClassStructure(<foo/>.getClass)) println(c)
// or equivalent:
ClassStructure(<foo/>.getClass) foreach println
```
Or with indentation:
```
// v2 (with indentation)
case class ClassWithIndent(c: Class[_], indent: String = "") {
override def toString = indent + c
}
implicit def Class2WithIndent(c: Class[_]) = ClassWithIndent(c)
case class ClassStructure(cwi: ClassWithIndent) {
def foreach[U](f: ClassWithIndent => U) {
if (cwi.c eq null) return
f(cwi)
ClassStructure(ClassWithIndent(cwi.c.getSuperclass, cwi.indent + " ")) foreach f
cwi.c.getInterfaces foreach (i => ClassStructure(ClassWithIndent(i, cwi.indent + " ")) foreach f)
}
}
for (c <- ClassStructure(<foo/>.getClass)) println(c)
// or equivalent:
ClassStructure(<foo/>.getClass) foreach println
```
Output:
```
class scala.xml.Elem
class scala.xml.Node
class scala.xml.NodeSeq
class java.lang.Object
interface scala.collection.immutable.Seq
interface scala.collection.immutable.Iterable
interface scala.collection.immutable.Traversable
interface scala.collection.Traversable
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.Immutable
interface scala.ScalaObject
interface scala.collection.Iterable
interface scala.collection.Traversable
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.collection.IterableLike
interface scala.Equals
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.collection.IterableLike
interface scala.Equals
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.Seq
interface scala.PartialFunction
interface scala.Function1
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.Iterable
interface scala.collection.Traversable
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.collection.IterableLike
interface scala.Equals
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.collection.SeqLike
interface scala.collection.IterableLike
interface scala.Equals
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.generic.GenericTraversableTemplate
interface scala.collection.generic.HasNewBuilder
interface scala.ScalaObject
interface scala.collection.SeqLike
interface scala.collection.IterableLike
interface scala.Equals
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.collection.SeqLike
interface scala.collection.IterableLike
interface scala.Equals
interface scala.collection.TraversableLike
interface scala.collection.generic.HasNewBuilder
interface scala.collection.generic.FilterMonadic
interface scala.collection.TraversableOnce
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.xml.Equality
interface scala.Equals
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface scala.ScalaObject
interface java.io.Serializable
```
|
[Dsl.scala](https://github.com/ThoughtWorksInc/Dsl.scala) is what you are looking for.
Suppose you want to create a random number generator. The generated numbers should be stored in a lazily evaluated infinite stream, which can be built with the help of our built-in domain-specific keyword `Yield`.
```
import com.thoughtworks.dsl.keys.Yield
def xorshiftRandomGenerator(seed: Int): Stream[Int] = {
val tmp1 = seed ^ (seed << 13)
val tmp2 = tmp1 ^ (tmp1 >>> 17)
val tmp3 = tmp2 ^ (tmp2 << 5)
!Yield(tmp3)
xorshiftRandomGenerator(tmp3)
}
```
Other examples can be found in the [Scaladoc](https://javadoc.io/page/com.thoughtworks.dsl/dsl_2.12/latest/com/thoughtworks/dsl/index.html).
|
69,978,383
|
everyone,
beforehand - I'm a bloody but motivated developer beginner.
I am currently trying to react to simple events (click on a button) in the HTML code in my Django project. Unfortunately without success ...
HTML:
```
<form>
{% csrf_token %}
<button id="CSVDownload" type="button">CSV Download!</button>
</form>
```
JavaScript:
```
<script>
document.addEventListener("DOMContentLoaded", () => {
const CSVDownload = document.querySelector("#CSVDownload")
CSVDownload.addEventListener("click", () => {
console.dir("Test")
})
})
</script>
```
Do I need JavaScript for this? Or is there a way to react directly to such events in python (Django)?
I am really grateful for all the support.
Since I'm not really "good" yet - a simple solution would be great :)
Python (Django)
```
if request.method == "POST":
projectName = request.POST["projectName"]
rootDomain = request.POST["rootDomain"]
startURL = request.POST["startURL"]
....
```
With this, for example, I managed to react to a kind of event, i.e. when the user sends the form. The problem here, however, is - if I have several forms on one page, then I cannot distinguish which function should be carried out: / I am at a loss
|
2021/11/15
|
[
"https://Stackoverflow.com/questions/69978383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17420473/"
] |
You should be able to use
```
delete a,b from `t
```
to delete in place (The backtick implies in place).
Alternatively, for more flexibility you could use the functional form;
```
![`t;();0b;`a`b]
```
|
The simplest way to achieve column deletion in place is using qSQL:
`t:([]a:1 2 3;b:4 5 6;c:`d`e`f)`
`delete a,b from `t` -- here, the backtick before `t` makes the change in place.
```
q)t
c
-
d
e
f
```
|
69,978,383
|
everyone,
beforehand - I'm a bloody but motivated developer beginner.
I am currently trying to react to simple events (click on a button) in the HTML code in my Django project. Unfortunately without success ...
HTML:
```
<form>
{% csrf_token %}
<button id="CSVDownload" type="button">CSV Download!</button>
</form>
```
JavaScript:
```
<script>
document.addEventListener("DOMContentLoaded", () => {
const CSVDownload = document.querySelector("#CSVDownload")
CSVDownload.addEventListener("click", () => {
console.dir("Test")
})
})
</script>
```
Do I need JavaScript for this? Or is there a way to react directly to such events in python (Django)?
I am really grateful for all the support.
Since I'm not really "good" yet - a simple solution would be great :)
Python (Django)
```
if request.method == "POST":
projectName = request.POST["projectName"]
rootDomain = request.POST["rootDomain"]
startURL = request.POST["startURL"]
....
```
With this, for example, I managed to react to a kind of event, i.e. when the user sends the form. The problem here, however, is - if I have several forms on one page, then I cannot distinguish which function should be carried out: / I am at a loss
|
2021/11/15
|
[
"https://Stackoverflow.com/questions/69978383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17420473/"
] |
The simplest way to achieve column deletion in place is using qSQL:
`t:([]a:1 2 3;b:4 5 6;c:`d`e`f)`
`delete a,b from `t` -- here, the backtick before `t` makes the change in place.
```
q)t
c
-
d
e
f
```
|
Michael & Kyle have covered the q-SQL options; for completeness, here are a couple of other options using `_`:
Using `_` as in your question, you can re-assign this back to t e.g.
```
t:`a`b _ t
```
You can also use `.` amend with an empty list of indexes i.e. "[amend entire](https://code.kx.com/q/ref/amend/#amend-entire)", which can be done in-place by passing ``t` or not in-place by passing just `t` e.g.
```
q).[t;();`a`b _] / not in-place
c
-
d
e
f
q).[`t;();`a`b _] / in-place
`t
q)t
c
-
d
e
f
```
|
69,978,383
|
everyone,
beforehand - I'm a bloody but motivated developer beginner.
I am currently trying to react to simple events (click on a button) in the HTML code in my Django project. Unfortunately without success ...
HTML:
```
<form>
{% csrf_token %}
<button id="CSVDownload" type="button">CSV Download!</button>
</form>
```
JavaScript:
```
<script>
document.addEventListener("DOMContentLoaded", () => {
const CSVDownload = document.querySelector("#CSVDownload")
CSVDownload.addEventListener("click", () => {
console.dir("Test")
})
})
</script>
```
Do I need JavaScript for this? Or is there a way to react directly to such events in python (Django)?
I am really grateful for all the support.
Since I'm not really "good" yet - a simple solution would be great :)
Python (Django)
```
if request.method == "POST":
projectName = request.POST["projectName"]
rootDomain = request.POST["rootDomain"]
startURL = request.POST["startURL"]
....
```
With this, for example, I managed to react to a kind of event, i.e. when the user sends the form. The problem here, however, is - if I have several forms on one page, then I cannot distinguish which function should be carried out: / I am at a loss
|
2021/11/15
|
[
"https://Stackoverflow.com/questions/69978383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17420473/"
] |
You should be able to use
```
delete a,b from `t
```
to delete in place (The backtick implies in place).
Alternatively, for more flexibility you could use the functional form;
```
![`t;();0b;`a`b]
```
|
Michael & Kyle have covered the q-SQL options; for completeness, here are a couple of other options using `_`:
Using `_` as in your question, you can re-assign this back to t e.g.
```
t:`a`b _ t
```
You can also use `.` amend with an empty list of indexes i.e. "[amend entire](https://code.kx.com/q/ref/amend/#amend-entire)", which can be done in-place by passing ``t` or not in-place by passing just `t` e.g.
```
q).[t;();`a`b _] / not in-place
c
-
d
e
f
q).[`t;();`a`b _] / in-place
`t
q)t
c
-
d
e
f
```
|
45,096,654
|
I recently signed up and started playing with GAE for python. I was able to get their standard/flask/hello\_world project. But, when I tried to upload a simple cron job following the instructions at <https://cloud.google.com/appengine/docs/standard/python/config/cron>, I get an "Internal Server Error".
My cron.yaml
```
cron:
- description: test cron
url: /
schedule: every 24 hours
```
The error I see
```
Do you want to continue (Y/n)? y
Updating config [cron]...failed.
ERROR: (gcloud.app.deploy) Server responded with code [500]:
Internal Server Error.
Server Error (500)
A server error has occurred.
```
Have I done something wrong here or is it possible that I am not eligible to add cron jobs as a free user?
|
2017/07/14
|
[
"https://Stackoverflow.com/questions/45096654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/593644/"
] |
I was having this problem as well, at about the same timeline. Without any changes, the deploy worked this morning, so my guess is that this was a transient server problem on Google's part.
|
I was just struggling with this same issue. In my case, I am using the PHP standard environment and kept receiving the '500 Internal Server Error' when I tried to publish our cron.yaml file from the Google Cloud SDK with the command:
```
gcloud app deploy cron.yaml --project {PROJECT_NAME}
```
To fix it, I did the following:
1. I removed all credentials from my gcloud client
`gcloud auth revoke --all`
2. Reauthenticated within the client
`gcloud auth login`
3. Published the cron.yaml
`gcloud app deploy cron.yaml --project {PROJECT NAME}`
From what I can tell, the permissions in my gcloud client got out of sync which is what caused the internal server error. Hopefully that's the same case for you!
|
74,041,729
|
I have a dataset like this
```
ID Year Day
1 2001 150
2 2001 140
3 2001 120
3 2002 160
3 2002 160
3 2017 75
3 2017 75
4 2017 80
```
I would like to drop the duplicates within each year, but keep those were the year differs. End result would be this:
```
1 2001 150
2 2001 140
3 2001 120
3 2002 160
3 2017 75
4 2017 80
```
I tried to do something like this in python with my pandas dataframe:
```
data = read_csv('data.csv')
data = data.drop_duplicates(subset = ['ID'], keep = first)
```
But this will delete duplicates between years, while I would like to keep this.
How do I keep the duplicates between years?
|
2022/10/12
|
[
"https://Stackoverflow.com/questions/74041729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12546311/"
] |
add 'year' in your subset.
```
data.drop_duplicates(subset = ['ID','Year'], keep = 'first')
```
```
ID Year Day
0 1 2001 150
1 2 2001 140
2 3 2001 120
3 3 2002 160
5 3 2017 75
7 4 2017 80
```
|
Another possible solution:
```
df.groupby('Year').apply(lambda g: g.drop_duplicates()).reset_index(drop=True)
```
Output:
```
ID Year Day
0 1 2001 150
1 2 2001 140
2 3 2001 120
3 3 2002 160
4 3 2017 75
5 4 2017 80
```
|
57,015,932
|
I'm developing an GUI for multi-robot system using ROS, but i'm freezing in the last thing i want in my interface: embedding the RVIZ, GMAPPING or another screen in my application. I already put an terminal in the interface, but i can't get around of how to add an external application window to my app. I know that PyQt5 have the createWindowContainer, with uses the window ID to dock an external application, but i didn't find any example to help me with that.
If possible, i would like to drag and drop an external window inside of a tabbed frame in my application. But, if this is not possible or is too hard, i'm good with only opening the window inside a tabbed frame after the click of a button.
I already tried to open the window similar to the terminal approach (see the code bellow), but the RVIZ window opens outside of my app.
Already tried to translate the [attaching/detaching code](https://stackoverflow.com/questions/54388685/issues-when-attaching-and-detaching-external-app-from-qdockwidget) code to linux using the wmctrl command, but didn't work wither. See [my code here](https://pastebin.com/kWtKb4UN).
Also already tried the [rviz Python Tutorial](http://docs.ros.org/indigo/api/rviz_python_tutorial/html/) but i'm receveing the error:
Traceback (most recent call last):
File "rvizTutorial.py", line 23, in
import rviz
File "/opt/ros/indigo/lib/python2.7/dist-packages/rviz/**init**.py", line 19, in
import librviz\_shiboken
ImportError: No module named librviz\_shiboken
```
# Frame where i want to open the external Window embedded
self.Simulation = QtWidgets.QTabWidget(self.Base)
self.Simulation.setGeometry(QtCore.QRect(121, 95, 940, 367))
self.Simulation.setTabPosition(QtWidgets.QTabWidget.North)
self.Simulation.setObjectName("Simulation")
self.SimulationFrame = QtWidgets.QWidget()
self.SimulationFrame.setObjectName("SimulationFrame")
self.Simulation.addTab(rviz(), "rViz")
# Simulation Approach like Terminal
class rviz(QtWidgets.QWidget):
def __init__(self, parent=None):
super(rviz, self).__init__(parent)
self.process = QtCore.QProcess(self)
self.rvizProcess = QtWidgets.QWidget(self)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.rvizProcess)
# Works also with urxvt:
self.process.start('rViz', [str(int(self.winId()))])
self.setGeometry(121, 95, 940, 367)
```
|
2019/07/13
|
[
"https://Stackoverflow.com/questions/57015932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11595480/"
] |
Solved it! just pass the style to the scrollableTabView
style={{width: '100%' }}
|
Solved it! Replace DefaultTabBar with ScrollableTabBar (don't forget to import it)
|
27,780,868
|
I need to use Backpropagation Neural Netwrok for multiclass classification purposes in my application. I have found [this code](http://danielfrg.com/blog/2013/07/03/basic-neural-network-python/#disqus_thread) and try to adapt it to my needs. It is based on the lections of Machine Learning in Coursera from Andrew Ng.
I have tested it in IRIS dataset and achieved good results (accuracy of classification around 0.96), whereas on my real data I get terrible results. I assume there is some implementation error, because the data is very simple. But I cannot figure out what exactly is the problem.
What are the parameters that it make sense to adjust?
I tried with:
* number of units in hidden layer
* generalization parameter (lambda)
* number of iterations for minimization function
Built-in minimization function used in this code is pretty much confusing me. It is used just once, as @goncalopp has mentioned in comment. Shouldn't it iteratively update the weights? How it can be implemented?
Here is my training data (target class is in the last column):
---
```
65535, 3670, 65535, 3885, -0.73, 1
65535, 3962, 65535, 3556, -0.72, 1
65535, 3573, 65535, 3529, -0.61, 1
3758, 3123, 4117, 3173, -0.21, 0
3906, 3119, 4288, 3135, -0.28, 0
3750, 3073, 4080, 3212, -0.26, 0
65535, 3458, 65535, 3330, -0.85, 2
65535, 3315, 65535, 3306, -0.87, 2
65535, 3950, 65535, 3613, -0.84, 2
65535, 32576, 65535, 19613, -0.35, 3
65535, 16657, 65535, 16618, -0.37, 3
65535, 16657, 65535, 16618, -0.32, 3
```
The dependencies are so obvious, I think it should be so easy to classify it...
But results are terrible. I get accuracy of 0.6 to 0.8. This is absolutely inappropriate for my application. Can someone please point out possible improvements I could make in order to achieve better results.
Here is the code:
```
import numpy as np
from scipy import optimize
from sklearn import cross_validation
from sklearn.metrics import accuracy_score
import math
class NN_1HL(object):
def __init__(self, reg_lambda=0, epsilon_init=0.12, hidden_layer_size=25, opti_method='TNC', maxiter=500):
self.reg_lambda = reg_lambda
self.epsilon_init = epsilon_init
self.hidden_layer_size = hidden_layer_size
self.activation_func = self.sigmoid
self.activation_func_prime = self.sigmoid_prime
self.method = opti_method
self.maxiter = maxiter
def sigmoid(self, z):
return 1 / (1 + np.exp(-z))
def sigmoid_prime(self, z):
sig = self.sigmoid(z)
return sig * (1 - sig)
def sumsqr(self, a):
return np.sum(a ** 2)
def rand_init(self, l_in, l_out):
self.epsilon_init = (math.sqrt(6))/(math.sqrt(l_in + l_out))
return np.random.rand(l_out, l_in + 1) * 2 * self.epsilon_init - self.epsilon_init
def pack_thetas(self, t1, t2):
return np.concatenate((t1.reshape(-1), t2.reshape(-1)))
def unpack_thetas(self, thetas, input_layer_size, hidden_layer_size, num_labels):
t1_start = 0
t1_end = hidden_layer_size * (input_layer_size + 1)
t1 = thetas[t1_start:t1_end].reshape((hidden_layer_size, input_layer_size + 1))
t2 = thetas[t1_end:].reshape((num_labels, hidden_layer_size + 1))
return t1, t2
def _forward(self, X, t1, t2):
m = X.shape[0]
ones = None
if len(X.shape) == 1:
ones = np.array(1).reshape(1,)
else:
ones = np.ones(m).reshape(m,1)
# Input layer
a1 = np.hstack((ones, X))
# Hidden Layer
z2 = np.dot(t1, a1.T)
a2 = self.activation_func(z2)
a2 = np.hstack((ones, a2.T))
# Output layer
z3 = np.dot(t2, a2.T)
a3 = self.activation_func(z3)
return a1, z2, a2, z3, a3
def function(self, thetas, input_layer_size, hidden_layer_size, num_labels, X, y, reg_lambda):
t1, t2 = self.unpack_thetas(thetas, input_layer_size, hidden_layer_size, num_labels)
m = X.shape[0]
Y = np.eye(num_labels)[y]
_, _, _, _, h = self._forward(X, t1, t2)
costPositive = -Y * np.log(h).T
costNegative = (1 - Y) * np.log(1 - h).T
cost = costPositive - costNegative
J = np.sum(cost) / m
if reg_lambda != 0:
t1f = t1[:, 1:]
t2f = t2[:, 1:]
reg = (self.reg_lambda / (2 * m)) * (self.sumsqr(t1f) + self.sumsqr(t2f))
J = J + reg
return J
def function_prime(self, thetas, input_layer_size, hidden_layer_size, num_labels, X, y, reg_lambda):
t1, t2 = self.unpack_thetas(thetas, input_layer_size, hidden_layer_size, num_labels)
m = X.shape[0]
t1f = t1[:, 1:]
t2f = t2[:, 1:]
Y = np.eye(num_labels)[y]
Delta1, Delta2 = 0, 0
for i, row in enumerate(X):
a1, z2, a2, z3, a3 = self._forward(row, t1, t2)
# Backprop
d3 = a3 - Y[i, :].T
d2 = np.dot(t2f.T, d3) * self.activation_func_prime(z2)
Delta2 += np.dot(d3[np.newaxis].T, a2[np.newaxis])
Delta1 += np.dot(d2[np.newaxis].T, a1[np.newaxis])
Theta1_grad = (1 / m) * Delta1
Theta2_grad = (1 / m) * Delta2
if reg_lambda != 0:
Theta1_grad[:, 1:] = Theta1_grad[:, 1:] + (reg_lambda / m) * t1f
Theta2_grad[:, 1:] = Theta2_grad[:, 1:] + (reg_lambda / m) * t2f
return self.pack_thetas(Theta1_grad, Theta2_grad)
def fit(self, X, y):
num_features = X.shape[0]
input_layer_size = X.shape[1]
num_labels = len(set(y))
theta1_0 = self.rand_init(input_layer_size, self.hidden_layer_size)
theta2_0 = self.rand_init(self.hidden_layer_size, num_labels)
thetas0 = self.pack_thetas(theta1_0, theta2_0)
options = {'maxiter': self.maxiter}
_res = optimize.minimize(self.function, thetas0, jac=self.function_prime, method=self.method,
args=(input_layer_size, self.hidden_layer_size, num_labels, X, y, 0), options=options)
self.t1, self.t2 = self.unpack_thetas(_res.x, input_layer_size, self.hidden_layer_size, num_labels)
np.savetxt("weights_t1.txt", self.t1, newline="\n")
np.savetxt("weights_t2.txt", self.t2, newline="\n")
def predict(self, X):
return self.predict_proba(X).argmax(0)
def predict_proba(self, X):
_, _, _, _, h = self._forward(X, self.t1, self.t2)
return h
##################
# IR data #
##################
values = np.loadtxt('infrared_data.txt', delimiter=', ', usecols=[0,1,2,3,4])
targets = np.loadtxt('infrared_data.txt', delimiter=', ', dtype=(int), usecols=[5])
X_train, X_test, y_train, y_test = cross_validation.train_test_split(values, targets, test_size=0.4)
nn = NN_1HL()
nn.fit(values, targets)
print("Accuracy of classification: "+str(accuracy_score(y_test, nn.predict(X_test))))
```
|
2015/01/05
|
[
"https://Stackoverflow.com/questions/27780868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4202221/"
] |
Try `$eval` on `attr.target` like
```
var data = $scope.$eval($attrs.target)
```
Or if your data is dynamic you can $watch the attr
```
var data = [];
$scope.$watch($attrs.target, function(newValue, oldValue){
data = newValue;
})
```
Also correct your controller injection like below, else if you will get error if you minified your source code.
```
controller: ['$scope','$element','$attrs', function($scope, $element, $attrs) {
var data = $scope.$eval($attrs.target)
this.foo = function(){
console.log('click');
};
}]
```
|
What I went with was removing the `target` attribute altogether, and instead broadcasting on the `$rootScope`.
Directive:
```
this.foo = function(){
$rootScope.$broadcast('sortButtons', {
predicate: 'foo',
reverse: false
});
};
```
Controller:
```
$rootScope.$on('sortButtons', function(event, data){
$scope.filters.sort = data;
});
```
|
55,050,699
|
### Task
I have a text file with alphanumeric filenames:
```
\abc1.txt. \abc2.txt \abc3.txt \abcde3.txt
\Zxcv1.txt \mnbd2.txt \dhtdv.txt
```
I need to extract all `.txt` extensions from the file, which will be in the same line and also different line in the file in python.
### Desired Output:
```
abc1.txt
abc2.txt
abc3.txt
abcde3.txt
Zxcv1.txt
mnbd2.txt
dhtdv.txt
```
I appreciate your help.
|
2019/03/07
|
[
"https://Stackoverflow.com/questions/55050699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11167162/"
] |
Another way to do this, is to wrap the `CupertinoDatePicker` in `CupertinoTheme`.
```
CupertinoTheme(
data: CupertinoThemeData(
textTheme: CupertinoTextThemeData(
dateTimePickerTextStyle: TextStyle(
fontSize: 16,
),
),
),
child: CupertinoDatePicker(
...
```
|
Finally got it, works as expected.
```
DefaultTextStyle.merge(
style: TextStyle(fontSize: 20),
child: CupertinoDatePicker(....)
)
```
|
45,300,287
|
I'm new in python programming and I'm having some issues in developing a specific part of my GUI with Tkinter.
What I'm trying to do is, a space where the user could enter (type) his math equation and the software make the calculation with the variables previously calculated.
I've found a lot of calculators for Tkinter, but none of then is what I'm looking for. And I don't have much experience with classes definitions.
I made this simple layout to explain better what I want to do:
```
import tkinter as tk
root = tk.Tk()
Iflabel = tk.Label(root, text = "If...")
Iflabel.pack()
IfEntry = tk.Entry(root)
IfEntry.pack()
thenlabel = tk.Label(root, text = "Then...")
thenEntry = tk.Entry(root)
thenlabel.pack()
thenEntry.pack()
elselabel = tk.Label(root, text = "else..")
elseEntry = tk.Entry(root)
elselabel.pack()
elseEntry.pack()
applybutton = tk.Button(root, text = "Calculate")
applybutton.pack()
root.mainloop()
```
This simple code for Python 3 have 3 Entry spaces
1st) If...
2nd Then...
3rd) Else...
So, the user will enter with his conditional expression and the software will do the job. In my mind, another important thing is if the user left the "if" space in blank, he will just type his expression inside "Then..." Entry and press the button "calculate" or build all expression with the statements.
If someone could give some ideas about how and what to do....
(without classes, if it is possible)
I'l give some situations for exemplification
1st using statements:
```
var = the variable previously calculated and stored in the script
out = output
if var >= 10
then out = 4
else out = 2
```
2nd Without using statement the user will type in "Then" Entry the expression that he want to calculate and that would be:
```
Then: Out = (((var)**2) +(2*var))**(1/2)
```
Again, it's just for exemplification...I don't need this specific layout. If anyone has an idea how to construct it better, is welcome.
Thanks all.
|
2017/07/25
|
[
"https://Stackoverflow.com/questions/45300287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8267211/"
] |
For a start webview consumes memory because it load has to load and render html data. Rather than using a webview in a recycler view, I think it would be better if you implemented it either of these two ways:
1. You handle the list of data in html and send it into the webview and remove the recycler view completely
2. You draw the layout of the expected contents in xml and inflate it directly into the recyclerview and remove webview completed. (Note: you can inflate different views into a recycler depending on the adapter position and data at that position).
Using a webview might seem the easy way to implement whatever you are trying but trust me, the drawbacks outweight the benefit. So its just best to avoid it.
|
This problem can arrive for many possible reasons
* When you scroll very fast
Recyclerview is purely based on Inflating the view minimal times and reusing the existing views. This means that while you are scrolling when a view(An item) exits your screen the same view is bought below just by changing its contents.When you load from internet it's always better to first download all the data and then display it. Webview's consume a lot of data and its totally Against the design principle to have them in a Recyclerview.
To repair this you could possibly add some button to reload data or refresh each time you display the view.
* Nougat removed some functions from http urlconnection class
I am not sure about this one. But in one of google developer video ,T had seen something about depreciation of some functions and methods
hope You find this Helpful.
|
45,300,287
|
I'm new in python programming and I'm having some issues in developing a specific part of my GUI with Tkinter.
What I'm trying to do is, a space where the user could enter (type) his math equation and the software make the calculation with the variables previously calculated.
I've found a lot of calculators for Tkinter, but none of then is what I'm looking for. And I don't have much experience with classes definitions.
I made this simple layout to explain better what I want to do:
```
import tkinter as tk
root = tk.Tk()
Iflabel = tk.Label(root, text = "If...")
Iflabel.pack()
IfEntry = tk.Entry(root)
IfEntry.pack()
thenlabel = tk.Label(root, text = "Then...")
thenEntry = tk.Entry(root)
thenlabel.pack()
thenEntry.pack()
elselabel = tk.Label(root, text = "else..")
elseEntry = tk.Entry(root)
elselabel.pack()
elseEntry.pack()
applybutton = tk.Button(root, text = "Calculate")
applybutton.pack()
root.mainloop()
```
This simple code for Python 3 have 3 Entry spaces
1st) If...
2nd Then...
3rd) Else...
So, the user will enter with his conditional expression and the software will do the job. In my mind, another important thing is if the user left the "if" space in blank, he will just type his expression inside "Then..." Entry and press the button "calculate" or build all expression with the statements.
If someone could give some ideas about how and what to do....
(without classes, if it is possible)
I'l give some situations for exemplification
1st using statements:
```
var = the variable previously calculated and stored in the script
out = output
if var >= 10
then out = 4
else out = 2
```
2nd Without using statement the user will type in "Then" Entry the expression that he want to calculate and that would be:
```
Then: Out = (((var)**2) +(2*var))**(1/2)
```
Again, it's just for exemplification...I don't need this specific layout. If anyone has an idea how to construct it better, is welcome.
Thanks all.
|
2017/07/25
|
[
"https://Stackoverflow.com/questions/45300287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8267211/"
] |
This problem can arrive for many possible reasons
* When you scroll very fast
Recyclerview is purely based on Inflating the view minimal times and reusing the existing views. This means that while you are scrolling when a view(An item) exits your screen the same view is bought below just by changing its contents.When you load from internet it's always better to first download all the data and then display it. Webview's consume a lot of data and its totally Against the design principle to have them in a Recyclerview.
To repair this you could possibly add some button to reload data or refresh each time you display the view.
* Nougat removed some functions from http urlconnection class
I am not sure about this one. But in one of google developer video ,T had seen something about depreciation of some functions and methods
hope You find this Helpful.
|
I solved this problem by floating a WebView in a up layer of RecyclerView, meanwhile placing a HOLDER view in RecyclerView.
And then I register an listener to the scroll event of RecyclerView. I Control the position and visibility of the floating WebView
|
45,300,287
|
I'm new in python programming and I'm having some issues in developing a specific part of my GUI with Tkinter.
What I'm trying to do is, a space where the user could enter (type) his math equation and the software make the calculation with the variables previously calculated.
I've found a lot of calculators for Tkinter, but none of then is what I'm looking for. And I don't have much experience with classes definitions.
I made this simple layout to explain better what I want to do:
```
import tkinter as tk
root = tk.Tk()
Iflabel = tk.Label(root, text = "If...")
Iflabel.pack()
IfEntry = tk.Entry(root)
IfEntry.pack()
thenlabel = tk.Label(root, text = "Then...")
thenEntry = tk.Entry(root)
thenlabel.pack()
thenEntry.pack()
elselabel = tk.Label(root, text = "else..")
elseEntry = tk.Entry(root)
elselabel.pack()
elseEntry.pack()
applybutton = tk.Button(root, text = "Calculate")
applybutton.pack()
root.mainloop()
```
This simple code for Python 3 have 3 Entry spaces
1st) If...
2nd Then...
3rd) Else...
So, the user will enter with his conditional expression and the software will do the job. In my mind, another important thing is if the user left the "if" space in blank, he will just type his expression inside "Then..." Entry and press the button "calculate" or build all expression with the statements.
If someone could give some ideas about how and what to do....
(without classes, if it is possible)
I'l give some situations for exemplification
1st using statements:
```
var = the variable previously calculated and stored in the script
out = output
if var >= 10
then out = 4
else out = 2
```
2nd Without using statement the user will type in "Then" Entry the expression that he want to calculate and that would be:
```
Then: Out = (((var)**2) +(2*var))**(1/2)
```
Again, it's just for exemplification...I don't need this specific layout. If anyone has an idea how to construct it better, is welcome.
Thanks all.
|
2017/07/25
|
[
"https://Stackoverflow.com/questions/45300287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8267211/"
] |
This problem can arrive for many possible reasons
* When you scroll very fast
Recyclerview is purely based on Inflating the view minimal times and reusing the existing views. This means that while you are scrolling when a view(An item) exits your screen the same view is bought below just by changing its contents.When you load from internet it's always better to first download all the data and then display it. Webview's consume a lot of data and its totally Against the design principle to have them in a Recyclerview.
To repair this you could possibly add some button to reload data or refresh each time you display the view.
* Nougat removed some functions from http urlconnection class
I am not sure about this one. But in one of google developer video ,T had seen something about depreciation of some functions and methods
hope You find this Helpful.
|
You can try this code in `onCreateViewHolder`
```
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
WebView web = new WebView(parent.getContext());
web.setLayoutParams(lp);
String url="...";
WebSettings settings = web.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
web.loadUrl(url);
holder = new ViewHolder(web);
```
|
45,300,287
|
I'm new in python programming and I'm having some issues in developing a specific part of my GUI with Tkinter.
What I'm trying to do is, a space where the user could enter (type) his math equation and the software make the calculation with the variables previously calculated.
I've found a lot of calculators for Tkinter, but none of then is what I'm looking for. And I don't have much experience with classes definitions.
I made this simple layout to explain better what I want to do:
```
import tkinter as tk
root = tk.Tk()
Iflabel = tk.Label(root, text = "If...")
Iflabel.pack()
IfEntry = tk.Entry(root)
IfEntry.pack()
thenlabel = tk.Label(root, text = "Then...")
thenEntry = tk.Entry(root)
thenlabel.pack()
thenEntry.pack()
elselabel = tk.Label(root, text = "else..")
elseEntry = tk.Entry(root)
elselabel.pack()
elseEntry.pack()
applybutton = tk.Button(root, text = "Calculate")
applybutton.pack()
root.mainloop()
```
This simple code for Python 3 have 3 Entry spaces
1st) If...
2nd Then...
3rd) Else...
So, the user will enter with his conditional expression and the software will do the job. In my mind, another important thing is if the user left the "if" space in blank, he will just type his expression inside "Then..." Entry and press the button "calculate" or build all expression with the statements.
If someone could give some ideas about how and what to do....
(without classes, if it is possible)
I'l give some situations for exemplification
1st using statements:
```
var = the variable previously calculated and stored in the script
out = output
if var >= 10
then out = 4
else out = 2
```
2nd Without using statement the user will type in "Then" Entry the expression that he want to calculate and that would be:
```
Then: Out = (((var)**2) +(2*var))**(1/2)
```
Again, it's just for exemplification...I don't need this specific layout. If anyone has an idea how to construct it better, is welcome.
Thanks all.
|
2017/07/25
|
[
"https://Stackoverflow.com/questions/45300287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8267211/"
] |
For a start webview consumes memory because it load has to load and render html data. Rather than using a webview in a recycler view, I think it would be better if you implemented it either of these two ways:
1. You handle the list of data in html and send it into the webview and remove the recycler view completely
2. You draw the layout of the expected contents in xml and inflate it directly into the recyclerview and remove webview completed. (Note: you can inflate different views into a recycler depending on the adapter position and data at that position).
Using a webview might seem the easy way to implement whatever you are trying but trust me, the drawbacks outweight the benefit. So its just best to avoid it.
|
I solved this problem by floating a WebView in a up layer of RecyclerView, meanwhile placing a HOLDER view in RecyclerView.
And then I register an listener to the scroll event of RecyclerView. I Control the position and visibility of the floating WebView
|
45,300,287
|
I'm new in python programming and I'm having some issues in developing a specific part of my GUI with Tkinter.
What I'm trying to do is, a space where the user could enter (type) his math equation and the software make the calculation with the variables previously calculated.
I've found a lot of calculators for Tkinter, but none of then is what I'm looking for. And I don't have much experience with classes definitions.
I made this simple layout to explain better what I want to do:
```
import tkinter as tk
root = tk.Tk()
Iflabel = tk.Label(root, text = "If...")
Iflabel.pack()
IfEntry = tk.Entry(root)
IfEntry.pack()
thenlabel = tk.Label(root, text = "Then...")
thenEntry = tk.Entry(root)
thenlabel.pack()
thenEntry.pack()
elselabel = tk.Label(root, text = "else..")
elseEntry = tk.Entry(root)
elselabel.pack()
elseEntry.pack()
applybutton = tk.Button(root, text = "Calculate")
applybutton.pack()
root.mainloop()
```
This simple code for Python 3 have 3 Entry spaces
1st) If...
2nd Then...
3rd) Else...
So, the user will enter with his conditional expression and the software will do the job. In my mind, another important thing is if the user left the "if" space in blank, he will just type his expression inside "Then..." Entry and press the button "calculate" or build all expression with the statements.
If someone could give some ideas about how and what to do....
(without classes, if it is possible)
I'l give some situations for exemplification
1st using statements:
```
var = the variable previously calculated and stored in the script
out = output
if var >= 10
then out = 4
else out = 2
```
2nd Without using statement the user will type in "Then" Entry the expression that he want to calculate and that would be:
```
Then: Out = (((var)**2) +(2*var))**(1/2)
```
Again, it's just for exemplification...I don't need this specific layout. If anyone has an idea how to construct it better, is welcome.
Thanks all.
|
2017/07/25
|
[
"https://Stackoverflow.com/questions/45300287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8267211/"
] |
For a start webview consumes memory because it load has to load and render html data. Rather than using a webview in a recycler view, I think it would be better if you implemented it either of these two ways:
1. You handle the list of data in html and send it into the webview and remove the recycler view completely
2. You draw the layout of the expected contents in xml and inflate it directly into the recyclerview and remove webview completed. (Note: you can inflate different views into a recycler depending on the adapter position and data at that position).
Using a webview might seem the easy way to implement whatever you are trying but trust me, the drawbacks outweight the benefit. So its just best to avoid it.
|
You can try this code in `onCreateViewHolder`
```
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
WebView web = new WebView(parent.getContext());
web.setLayoutParams(lp);
String url="...";
WebSettings settings = web.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
web.loadUrl(url);
holder = new ViewHolder(web);
```
|
51,927,893
|
So I started learning python 3 and I wanted to run a very simple code on ubuntu:
```
print type("Hello World")
^
SyntaxError: invalid syntax
```
When I tried to compile that with command python3 hello.py in terminal it gave me the error above, but when used python hello.py (I think it means to use python 2 instead of 3) then it's all fine. Same when using python 3 and 2 shells in the terminal.
It seems like I'm missing something really stupid because I did some research and found no one with the same issue.
|
2018/08/20
|
[
"https://Stackoverflow.com/questions/51927893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10140067/"
] |
In Python3, `print` [was changed](https://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function) from a statement to a function (with brackets):
i.e.
```
# In Python 2.x
print type("Hello World")
# In Python 3.x
print(type("Hello World"))
```
|
In Python 3.x [`print()`](https://docs.python.org/3/library/functions.html#print) is a function, while in 2.x it was a statement. The correct syntax in Python 3 would be:
```
print(type("Hello World"))
```
|
51,927,893
|
So I started learning python 3 and I wanted to run a very simple code on ubuntu:
```
print type("Hello World")
^
SyntaxError: invalid syntax
```
When I tried to compile that with command python3 hello.py in terminal it gave me the error above, but when used python hello.py (I think it means to use python 2 instead of 3) then it's all fine. Same when using python 3 and 2 shells in the terminal.
It seems like I'm missing something really stupid because I did some research and found no one with the same issue.
|
2018/08/20
|
[
"https://Stackoverflow.com/questions/51927893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10140067/"
] |
In Python3, `print` [was changed](https://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function) from a statement to a function (with brackets):
i.e.
```
# In Python 2.x
print type("Hello World")
# In Python 3.x
print(type("Hello World"))
```
|
[This is because from Python 3, `print` is a **function**, not a statement anymore.](https://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html#the-print-function) Therefore, Python 3 only accepts:
```py
print(type("Hello World"))
```
|
51,927,893
|
So I started learning python 3 and I wanted to run a very simple code on ubuntu:
```
print type("Hello World")
^
SyntaxError: invalid syntax
```
When I tried to compile that with command python3 hello.py in terminal it gave me the error above, but when used python hello.py (I think it means to use python 2 instead of 3) then it's all fine. Same when using python 3 and 2 shells in the terminal.
It seems like I'm missing something really stupid because I did some research and found no one with the same issue.
|
2018/08/20
|
[
"https://Stackoverflow.com/questions/51927893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10140067/"
] |
In Python 3.x [`print()`](https://docs.python.org/3/library/functions.html#print) is a function, while in 2.x it was a statement. The correct syntax in Python 3 would be:
```
print(type("Hello World"))
```
|
[This is because from Python 3, `print` is a **function**, not a statement anymore.](https://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html#the-print-function) Therefore, Python 3 only accepts:
```py
print(type("Hello World"))
```
|
10,352,538
|
I am stuck with this problem for the past few hours.
This is how the XML looks like
```
<xmlblock>
<data1>
<username>someusername</username>
<id>12345</id>
</data1>
<data2>
<username>username</username>
<id>11111</id>
</data1>
</xmlblock>
```
The problem is this:
I need the username when it matches a given id.
I am not sure how to do a double search using iterfind or any other lxml module in python.
Any help will be greatly appreciated. Thanks!
|
2012/04/27
|
[
"https://Stackoverflow.com/questions/10352538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/897906/"
] |
A (probably not the best) solution
```
>>> id_to_match = 12345
>>> for event, element in cElementTree.iterparse('xmlfile.xml'):
... if 'data' in element.tag:
... for data in element:
... if data.tag == 'username':
... username = data.text
... if data.tag == 'id':
... if data.text == id_to_match:
... print username
someusername
```
|
If you are ok with using [minidom](http://docs.python.org/library/xml.dom.minidom.html) the following should work
```
from xml.dom import minidom
doc = minidom.parseString('<xmlblock><data1><username>someusername</username><id>12345</id></data1><data2><username>username</username><id>11111</id></data2></xmlblock>')
username = [elem.parentNode.getElementsByTagName('username') for elem in doc.getElementsByTagName('id') if elem.firstChild.data == '12345'][0][0].firstChild.data
print username
```
|
10,352,538
|
I am stuck with this problem for the past few hours.
This is how the XML looks like
```
<xmlblock>
<data1>
<username>someusername</username>
<id>12345</id>
</data1>
<data2>
<username>username</username>
<id>11111</id>
</data1>
</xmlblock>
```
The problem is this:
I need the username when it matches a given id.
I am not sure how to do a double search using iterfind or any other lxml module in python.
Any help will be greatly appreciated. Thanks!
|
2012/04/27
|
[
"https://Stackoverflow.com/questions/10352538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/897906/"
] |
A (probably not the best) solution
```
>>> id_to_match = 12345
>>> for event, element in cElementTree.iterparse('xmlfile.xml'):
... if 'data' in element.tag:
... for data in element:
... if data.tag == 'username':
... username = data.text
... if data.tag == 'id':
... if data.text == id_to_match:
... print username
someusername
```
|
Here's an example using [lxml](http://lxml.de/) and [xpath](http://en.wikipedia.org/wiki/XPath)
---
```
>>> xml = '''
<xmlblock>
<data1>
<username>someusername</username>
<id>12345</id>
</data1>
<data2>
<username>username</username>
<id>11111</id>
</data2>
</xmlblock>'''
>>> doc = lxml.etree.fromstring(xml)
>>> matching_nodes = doc.xpath('//id[text()="11111"]/../username')
>>> for node in matching_nodes:
print node.text
username
```
|
66,910,159
|
Consider the below set of lists that contain two strings each.
The pairing of two strings in a given list means the values they represent are equal. So item A is the same as item B and C, and so on.
```
l1 = [ 'A' , 'B' ]
l2 = [ 'A' , 'C' ]
l3 = [ 'B' , 'C' ]
```
What is the most efficient/pythonic way to collect these relationships into a dict such as the one below:
```
{ "A" : [ "B" , "C" ] }
```
p.s. Apologies for the poor title, I did not know how to describe the problem!
**EDIT:**
To make the problem clearer, I am trying to filter out duplicated samples from thousands of records.
I have pairwise comparisons for each sample in the data set which indicate if they are a duplicate of one another.
Sometimes a sample may appear in the data set in triplicate/quadruplicate with a different identifier.
It is important to keep just ONE of the duplicated samples.
Hence wanting a dict or similar structure which contains the selected sample as a key, and a list of its duplicates in the dataset as values.
|
2021/04/01
|
[
"https://Stackoverflow.com/questions/66910159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3234810/"
] |
I would use a defaultdict from collections so the dictionary expands and just takes whatever you throw into it. If this is a one way correspondence I would use this code (assuming you make a list of the lists)
```
dd = collections.defaultdict(list)
for line in lists:
dd[line[0]].append(line[1])
```
for given set this will make dictionaries
```
{"A" : ["B", "C"] }
{"B" : ["C"] }
'''
this should be a good starting point
```
|
---
Assuming you can get a list of those lists like so:
```
[[ 'A' , 'B' ], [ 'A' , 'C' ],[ 'B' , 'C' ]]
```
This should give you the relation you want:
```
d = {}
l1 = [[ 'A' , 'B' ],[ 'A' , 'C' ],[ 'B' , 'C' ]]
for sublist in l1:
if sublist[0] not in d.keys(): #check if first value is already a key in the dict
d[sublist[0]] = [] #init new key with empty list
d[sublist[0]].append(sublist[1]) #append second value
```
output:
```
{'A': ['B', 'C'], 'B': ['C']}
```
|
66,910,159
|
Consider the below set of lists that contain two strings each.
The pairing of two strings in a given list means the values they represent are equal. So item A is the same as item B and C, and so on.
```
l1 = [ 'A' , 'B' ]
l2 = [ 'A' , 'C' ]
l3 = [ 'B' , 'C' ]
```
What is the most efficient/pythonic way to collect these relationships into a dict such as the one below:
```
{ "A" : [ "B" , "C" ] }
```
p.s. Apologies for the poor title, I did not know how to describe the problem!
**EDIT:**
To make the problem clearer, I am trying to filter out duplicated samples from thousands of records.
I have pairwise comparisons for each sample in the data set which indicate if they are a duplicate of one another.
Sometimes a sample may appear in the data set in triplicate/quadruplicate with a different identifier.
It is important to keep just ONE of the duplicated samples.
Hence wanting a dict or similar structure which contains the selected sample as a key, and a list of its duplicates in the dataset as values.
|
2021/04/01
|
[
"https://Stackoverflow.com/questions/66910159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3234810/"
] |
I would use a defaultdict from collections so the dictionary expands and just takes whatever you throw into it. If this is a one way correspondence I would use this code (assuming you make a list of the lists)
```
dd = collections.defaultdict(list)
for line in lists:
dd[line[0]].append(line[1])
```
for given set this will make dictionaries
```
{"A" : ["B", "C"] }
{"B" : ["C"] }
'''
this should be a good starting point
```
|
I have a rather long-winded answer that stores an ID if it has been added to the dict already.
There must be a more efficient answer though!
```
l = [["A", "B"], ["A", "C"], ["B", "C"]]
d = dict()
used_list = list()
for i in l:
id_one, id_two = i
if not id_one in used_list and id_one not in d.keys():
d[id_one] = [id_two]
used_list.append(id_two)
continue
if not id_one in used_list and id_one in d.keys():
d[id_one].append(id_two)
used_list.append(id_two)
print( d )
```
Returns:
```
{'A': ['B', 'C']}
```
|
17,039,457
|
I want to convert the first column of data from a text file into a list in python
```
data = open ('data.txt', 'r')
data.read()
```
provides
```
'12 45\n13 46\n14 47\n15 48\n16 49\n17 50\n18 51'
```
Any help, please.
|
2013/06/11
|
[
"https://Stackoverflow.com/questions/17039457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2473267/"
] |
You can use `str.split` and a `list comprehension` here:
```
with open('data.txt') as f:
lis = [int(line.split()[0]) for line in f]
>>> lis
[12, 13, 14, 15, 16, 17, 18]
```
If the numbers to be strings:
```
>>> with open('abc') as f:
lis = [line.split()[0] for line in f]
>>> lis
['12', '13', '14', '15', '16', '17', '18']
```
Simplified version:
```
>>> with open('abc') as f: #Always use with statement for handling files
... lis = []
... for line in f: # for loop on file object returns one line at a time
... spl = line.split() # split the line at whitespaces, str.split returns a list
... lis.append(spl[0]) # append the first item to the output list, use int() get an integer
... print lis
...
['12', '13', '14', '15', '16', '17', '18']
```
help and example on `str.split`:
```
>>> strs = "a b c d ef gh i"
>>> strs.split()
['a', 'b', 'c', 'd', 'ef', 'gh', 'i']
>>> print str.split.__doc__
S.split([sep [,maxsplit]]) -> list of strings
Return a list of the words in the string S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are removed
from the result.
```
|
```
import csv
with open ('data.txt', 'rb') as f:
print [row[0] for row in csv.reader(f, delimiter=' ')]
```
---
```
['12', '13', '14', '15', '16', '17', '18']
```
|
27,801,200
|
How do i put this in a loop in python so that it keeps asking if player 1 has won the game, until it reaches the number of games in the match. i tried a while loop but it didn't work :(
```
Y="yes"
N="no"
PlayerOneScore=0
PlayerTwoScore=0
NoOfGamesInMatch=int(input("How many games? :- "))
while PlayerOneScore < NoOfGamesInMatch:
PlayerOneWinsGame=str(input("Did Player 1 win the game?\n(Enter Y or N): "))
if PlayerOneWinsGame== "Y":
PlayerOneScore= PlayerOneScore+1
else:
PlayerTwoScore= PlayerTwoScore+1
print("Player 1: " ,PlayerOneScore)
print("Player 2: " ,PlayerTwoScore)
print("\n\nPress the RETURN key to end")
```
|
2015/01/06
|
[
"https://Stackoverflow.com/questions/27801200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4424276/"
] |
You can have a preRender set on the *listLabelsPage.xhtml* page you're loading
```
<f:event type="preRenderView" listener="#{yourBean.showGrowl}" />
```
and a showGrowl method having only
```
public void showGrowl() {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Success!", "Label has been added with success!"));
}
```
|
I post an answer to my own question in order to help another people which face the same problem like I did:
```
public String addLabelInDB() {
try {
//some logic to insert in db
//below I set a flag on context which helps me to display a growl message only when the insertion was done with success
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.getRequestMap().put("addedWithSuccess","true");
} catch (Exception e) {
logger.debug(e.getMessage());
}
return "listLabelsPage";
}
public void showGrowl() {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
String labelAddedWithSuccess = (String) ec.getRequestMap().get("addedWithSuccess");
//if the flag on context is true show the growl message
if (labelAddedWithSuccess!=null && labelAddedWithSuccess.equals("true")) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Success!", "Label has been added with success!"));
}
}
```
and in my xhtml I have:
```
<f:event type="preRenderView" listener="#{labelsManager.showGrowl}" />
```
|
27,801,200
|
How do i put this in a loop in python so that it keeps asking if player 1 has won the game, until it reaches the number of games in the match. i tried a while loop but it didn't work :(
```
Y="yes"
N="no"
PlayerOneScore=0
PlayerTwoScore=0
NoOfGamesInMatch=int(input("How many games? :- "))
while PlayerOneScore < NoOfGamesInMatch:
PlayerOneWinsGame=str(input("Did Player 1 win the game?\n(Enter Y or N): "))
if PlayerOneWinsGame== "Y":
PlayerOneScore= PlayerOneScore+1
else:
PlayerTwoScore= PlayerTwoScore+1
print("Player 1: " ,PlayerOneScore)
print("Player 2: " ,PlayerTwoScore)
print("\n\nPress the RETURN key to end")
```
|
2015/01/06
|
[
"https://Stackoverflow.com/questions/27801200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4424276/"
] |
You can have a preRender set on the *listLabelsPage.xhtml* page you're loading
```
<f:event type="preRenderView" listener="#{yourBean.showGrowl}" />
```
and a showGrowl method having only
```
public void showGrowl() {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Success!", "Label has been added with success!"));
}
```
|
How about this? Make a separated redirect button which will be hit after showing msg:
HTML:
```
<h:form prependId="false">
<p:growl />
<p:button outcome="gotoABC" id="rdr-btn" style="display: none;" />
<p:commandButton action="#{bean.process()}" update="@form" />
</form>
```
Bean:
```
public void process(){
addInfoMsg(summary, msgDetail); //Add msg func
RequestContext.getCurrentInstance().execute("setTimeout(function(){ $('#rdr-btn').click(); }, 3000);"); // 3 seconds delay. I put the script in Constants to config later.
}
```
|
27,801,200
|
How do i put this in a loop in python so that it keeps asking if player 1 has won the game, until it reaches the number of games in the match. i tried a while loop but it didn't work :(
```
Y="yes"
N="no"
PlayerOneScore=0
PlayerTwoScore=0
NoOfGamesInMatch=int(input("How many games? :- "))
while PlayerOneScore < NoOfGamesInMatch:
PlayerOneWinsGame=str(input("Did Player 1 win the game?\n(Enter Y or N): "))
if PlayerOneWinsGame== "Y":
PlayerOneScore= PlayerOneScore+1
else:
PlayerTwoScore= PlayerTwoScore+1
print("Player 1: " ,PlayerOneScore)
print("Player 2: " ,PlayerTwoScore)
print("\n\nPress the RETURN key to end")
```
|
2015/01/06
|
[
"https://Stackoverflow.com/questions/27801200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4424276/"
] |
I post an answer to my own question in order to help another people which face the same problem like I did:
```
public String addLabelInDB() {
try {
//some logic to insert in db
//below I set a flag on context which helps me to display a growl message only when the insertion was done with success
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.getRequestMap().put("addedWithSuccess","true");
} catch (Exception e) {
logger.debug(e.getMessage());
}
return "listLabelsPage";
}
public void showGrowl() {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
String labelAddedWithSuccess = (String) ec.getRequestMap().get("addedWithSuccess");
//if the flag on context is true show the growl message
if (labelAddedWithSuccess!=null && labelAddedWithSuccess.equals("true")) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Success!", "Label has been added with success!"));
}
}
```
and in my xhtml I have:
```
<f:event type="preRenderView" listener="#{labelsManager.showGrowl}" />
```
|
How about this? Make a separated redirect button which will be hit after showing msg:
HTML:
```
<h:form prependId="false">
<p:growl />
<p:button outcome="gotoABC" id="rdr-btn" style="display: none;" />
<p:commandButton action="#{bean.process()}" update="@form" />
</form>
```
Bean:
```
public void process(){
addInfoMsg(summary, msgDetail); //Add msg func
RequestContext.getCurrentInstance().execute("setTimeout(function(){ $('#rdr-btn').click(); }, 3000);"); // 3 seconds delay. I put the script in Constants to config later.
}
```
|
51,413,816
|
Before I begin, I'd like to preface that I'm relatively new to python, and haven't had to use it much before this little project of mine. I'm trying to make a twitter bot as part of an art project, and I can't seem to get tweepy to import. I'm using macOS High Sierra and Python 3.7. I first installed tweepy by using
```
pip3 install tweepy
```
and this appeared to work, as I'm able to find the tweepy files in finder. However, when I simply input
```
import tweepy
```
into the IDLE, I get this error:
```
Traceback (most recent call last):
File "/Users/jacobhill/Documents/CicadaCacophony.py", line 1, in <module>
import tweepy
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tweepy/__init__.py", line 17, in <module>
from tweepy.streaming import Stream, StreamListener
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tweepy/streaming.py", line 358
def _start(self, async):
^
SyntaxError: invalid syntax
```
Any idea on how to remedy this? I've looked at other posts on here and the other errors seem to be along the lines of "tweepy module not found", so I don't know what to do with my error. Thanks!
|
2018/07/19
|
[
"https://Stackoverflow.com/questions/51413816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10102844/"
] |
Using `async` as an identifier [has been deprecated since Python 3.5, and became an error in Python 3.7](https://www.python.org/dev/peps/pep-0492/#deprecation-plans), because it's a keyword.
This Tweepy bug was [reported on 16 Mar](https://github.com/tweepy/tweepy/issues/1017), and [fixed on 12 May](https://github.com/tweepy/tweepy/pull/1042), but [there hasn't been a new release yet](https://github.com/tweepy/tweepy/issues/1063). Which is why, as [the repo's main page says](https://github.com/tweepy/tweepy):
>
> Python 2.7, 3.4, 3.5 & 3.6 are supported.
>
>
>
---
For the time being, you can install the development version:
```
pip3 install git+https://github.com/tweepy/tweepy.git
```
Or, since you've already installed an earlier version:
```
pip3 install --upgrade git+https://github.com/tweepy/tweepy.git
```
---
You could also follow the instructions from the repo:
```
git clone https://github.com/tweepy/tweepy.git
cd tweepy
python3 setup.py install
```
However, this will mean `pip` may not fully understand what you've installed.
|
In Python3.7, [`async`](https://docs.python.org/3/reference/compound_stmts.html#async) became a reserved word (as can be seen in *whats new* section [here](https://docs.python.org/3/whatsnew/3.7.html)) and therefore cannot be used as argument. This is why this `Syntax Error` is raised.
That said, and following `tweetpy`s official GitHub ([here](https://github.com/tweepy/tweepy)), only
>
> Python 2.7, 3.4, 3.5 & 3.6 are supported.
>
>
>
---
However, if you really must use Python3.7, there is a workaround. Following [this](https://github.com/tweepy/tweepy/issues/1017) suggestion, you can
>
> open streaming.py and replace `async` with `async_`
>
>
>
and it should work
|
48,143,394
|
So I play a game in which I have 12 pieces of gear. Each piece of gear (for the purposes of my endeavor) has four buffs I am interested in: power, haste, critical damage, critical rating.
I have a formula in which I can enter the total power, haste, CD, and CR and generate the expected damage per second output.
However, not every piece of gear has all four buffs. Currently I am interested in two case scenarios: gear that only has one of the four, and gear that has three of the four.
In the first scenario, each of the twelve pieces of gear will have a single buff on it that can be any of the four. What I want to do is write a program that finds which arrangement outputs the most damage.
So then what I need to do is write a program that tries every possible arrangement in this scenario. If we figure that each of the twelve pieces can have one of four values, that's 4^12 possible arrangements to test - or 16,777,216 - easy-peasy for a machine, right?
However I have to loop through all these arrangements, and at the moment I can only imagine 12 nested FOR loops of value 1-4 each, with the formula in the middle.
This seems un-pythonic in terms of readability and just duplication of effort.
Is there a better, more pythonic way to check to see which my formula likes best (generates max damage), or is 12 nested FOR loops, as excessive as that seems, the best and clearest way?
|
2018/01/08
|
[
"https://Stackoverflow.com/questions/48143394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5208967/"
] |
Use iterator to replace for-loop:
```
keys = ['p', 'h', 'cd', 'cr']
iter_keys = itertools.product(*([keys] * 12))
for item in iter_keys:
print item
```
Output:
```
('p', 'p', 'p', 'p', 'p', 'cr', 'cd', 'h', 'cr', 'p', 'h', 'cr')
('p', 'p', 'p', 'p', 'p', 'cr', 'cd', 'h', 'cr', 'p', 'cd', 'p')
('p', 'p', 'p', 'p', 'p', 'cr', 'cd', 'h', 'cr', 'p', 'cd', 'h')
('p', 'p', 'p', 'p', 'p', 'cr', 'cd', 'h', 'cr', 'p', 'cd', 'cd')
('p', 'p', 'p', 'p', 'p', 'cr', 'cd', 'h', 'cr', 'p', 'cd', 'cr')
....
('cr', 'cr', 'cr', 'cr', 'cr', 'cr', 'cr', 'cr', 'cr', 'cr', 'cr', 'cr')
```
|
If you have 12 nested for loops, you probably need a recursive design like this :
```
def loops (values, num, current_list):
if num > 0:
for v in values:
loops(values, num-1, current_list+list(v))
else:
print current_list
loops (('a', 'b', 'c', 'd'), 12, [])
```
Then, you will probably rewrite it in a pythonic way like Mad Lee's one, but this shows the principle.
|
12,969,897
|
I have some questions about encoding in python 2.7.
1.The python code is as below,
```
#s = u"严"
s = u'\u4e25'
print 's is:', s
print 'len of s is:', len(s)
s1 = "a" + s
print 's1 is:', s1
print 'len of s1 is:', len(s1)
```
the output is:
```
s is: 严
len of s is: 1
s1 is: a严
len of s1 is: 2
```
I am confused that why the len of `s` is 1, how could `4e25` be stored in 1 byte? I also notice that USC-2 is 2-bytes long and USC-4 is 4-bytes long, why unicode string `s`'s length is 1?
2.
(1)New a file named `a.py` with notepad++(Windows 7), and set the file's encoding `ANSI`, code in `a.py` is as below:
```
# -*- encoding:utf-8 -*-
import sys
print sys.getdefaultencoding()
s = "严"
print "s:", s
print "type of s:", type(s)
```
the output is:
```
ascii
s: 严
type of s: <type 'str'>
```
(2)New a file named `b.py` with notepad++(Windows 7), and set the file's encoding `UTF-8`, code in `b.py` is as below:
```
# -*- encoding:gbk -*-
import sys
print sys.getdefaultencoding()
s = "严"
print "s:", s
print "type of s:", type(s)
```
the output is:
```
File "D:\pyws\code\\b.py", line 1
SyntaxError: encoding problem: utf-8
```
(3)change file `b.py` as below(the file's encoding style is `UTF-8`):
```
import sys
print sys.getdefaultencoding()
s = "严"
print "s:", s
print "type of s:", type(s)
```
the output is:
```
ascii
s: 涓
type of s: <type 'str'>
```
(4)change file `a.py` as below(the file's encoding style is `ANSI`):
```
import sys
print sys.getdefaultencoding()
s = "严"
print "s:", s
print "type of s:", type(s)
```
the output is:
```
File "D:\pyws\code\a1.py", line 3
SyntaxError: Non-ASCII character '\xd1' in file D:\pyws\code\a1.py on
line 3, but no encoding declared; see http://www.python.org/peps/pep-0263.html f
or details
```
Why these 4 cases' outputs in question2 are different? Anybody can figure it out in detail?
|
2012/10/19
|
[
"https://Stackoverflow.com/questions/12969897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1477871/"
] |
>
> I am confused that why the len of s is 1, how could 4e25 be stored in 1 byte? I also notice that USC-2 is 2-bytes long and USC-4 is 4-bytes long, why unicode string s's length is 1?
>
>
>
The whole point of unicode strings is to do this. The length of a unicode string is the number of *characters* (i.e., code points), not the number of bytes. The number of bytes may vary depending on the encoding, but the number of characters is an abstract invariant that doesn't change with encoding.
As for your second question, the answer is that in setting a file's encoding, you are telling Python how to map bytes in that file to characters. If you specify an encoding (with the `# encoding` syntax) that is inconsistent with the file's actual encoding, you will get unpredictable behavior, because Python is trying to interpret the bytes one way, but the file is set up so the bytes actually mean something else.
The kind of behavior you get will depend on the specifics of the encodings you use. Some possibilities are:
1. You'll get lucky and it will work even though you use conflicting encodings; this is what happened in your first case.
2. It will raise an error because the bytes in the file aren't consistent with the specified encoding; this is what happened in your second case.
3. It will seem to work, but produce different characters, because the bytes in the file's actual encoding mean something else when interpreted with the specified encoding. This seems to be what happened in your third case, although it ought to raise an error since that character isn't ASCII. (By "the file's encoding style is UTF-8" did you mean you set an `# encoding` directive to that effect in the file?)
4. If you don't specify any encoding, you'll get an error if you try to use any bytes that aren't in plain ASCII. This is what happened in your last case.
Also, the type of the string is `str` in all cases, because you didn't specify the string as being unicode (e.g., with `u"..."`). Specifying a file encoding doesn't make strings unicode. It just tells Python how to interpret the characters in the file.
However, there's a bigger question here, which is: why are you playing those games with encodings in your examples? There is no reason whatsoever to use an `# encoding` marker to specify an encoding other than the one the file is actually encoded in, and doing so is guaranteed to cause problems. Don't do it. You have to know what encoding the file is in, and specify that same encoding in the `# encoding` marker.
|
### Answer to Question 1:
In Python versions <3.3, length for a Unicode string `u''` is the number of UTF-16 or UTF-32 code units used (depending on build flags), not the number of bytes. `\u4e25` is one code unit, but not all characters are represented by one code unit if UTF-16 (default on Windows) is used.
```
>>> len(u'\u42e5')
1
>>> len(u'\U00010123')
2
```
In Python 3.3, the above will return 1 for both functions.
Also Unicode characters can be composed of combining code units, such as `é`. The `normalize` function can be used to generate the combined or decomposed form:
```
>>> import unicodedata as ud
>>> ud.name(u'\xe9')
'LATIN SMALL LETTER E WITH ACUTE'
>>> ud.normalize('NFD',u'\xe9')
u'e\u0301'
>>> ud.normalize('NFC',u'e\u0301')
u'\xe9'
```
So even in Python 3.3, a single display character can have 1 or more code units, and it is best to normalize to one form or another for consistent answers.
### Answer to Question 2:
The encoding declared at the top of the file **must** agree with the encoding in which the file is saved. The declaration lets Python know how to interpret the bytes in the file.
For example, the character `严` is saved as 3 bytes in a file saved as UTF-8, but two bytes in a file saved as GBK:
```
>>> u'严'.encode('utf8')
'\xe4\xb8\xa5'
>>> u'严'.encode('gbk')
'\xd1\xcf'
```
If you declare the wrong encoding, the bytes are interpreted incorrectly and Python either displays the wrong characters or throws an exception.
**Edit per comment**
**2(1)** - This is system dependent due to ANSI being the system locale default encoding. On my system that is `cp1252` and Notepad++ can't display a Chinese character. If I set my system locale to `Chinese(PRC)` then I get your results on a console terminal. The reason it works correctly in that case is a byte string is used and the bytes are just sent to the terminal. Since the file was encoded in `ANSI` on a `Chinese(PRC)` locale, the bytes the byte string contains are correctly interpreted by the `Chinese(PRC)` locale terminal.
**2(2)** - The file is encoded in UTF-8 but the encoding is declared as GBK. When Python reads the encoding it tries to interpret the file as GBK and fails. You've chosen `UTF-8` as the encoding, which on Notepad++ also includes a UTF-8 encoded byte order mark (BOM) as the first character in the file and the GBK codec doesn't read it as a valid GBK-encoded character, so fails on line 1.
**2(3)** - The file is encoded in UTF-8 (with BOM), but missing an encoding declaration. Python recognizes the UTF-8-encoded BOM and uses UTF-8 as the encoding, but the file is in GBK. Since a byte string was used, the UTF-8-encoded bytes are sent to the GBK terminal and you get:
```
>>> u'严'.encode('utf8').decode(
'\xe4\xb8\xa5'
>>> '\xe4\xb8'.decode('gbk')
u'\u6d93'
>>> print '\xe4\xb8'.decode('gbk')
涓
```
In this case I am surprised, because Python is ignoring the byte `\xa5`, and as you see below when I explicitly decode incorrectly Python throws an exception:
```
>>> u'严'.encode('utf8').decode('gbk')
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
UnicodeDecodeError: 'gbk' codec can't decode byte 0xa5 in position 2: incomplete multibyte sequence
```
**2(4)** - In this case, then encoding is ANSI (GBK) but no encoding is declared, and there is no BOM like in UTF-8 to give Python a hint, so it assumes ASCII and can't handle the GBK-encoded character on line 3.
|
13,623,634
|
Why doesn't following code print anything:
```
#!/usr/bin/python3
class test:
def do_someting(self,value):
print(value)
return value
def fun1(self):
map(self.do_someting,range(10))
if __name__=="__main__":
t = test()
t.fun1()
```
I'm executing the above code in Python 3. I think i'm missing something very basic but not able to figure it out.
|
2012/11/29
|
[
"https://Stackoverflow.com/questions/13623634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1651941/"
] |
[`map()` returns an iterator](http://docs.python.org/3/library/functions.html#map), and will not process elements until you ask it to.
Turn it into a list to force all elements to be processed:
```
list(map(self.do_someting,range(10)))
```
or use `collections.deque()` with the length set to 0 to not produce a list if you don't need the map output:
```
from collections import deque
deque(map(self.do_someting, range(10)))
```
but note that simply using a `for` loop is far more readable for any future maintainers of your code:
```
for i in range(10):
self.do_someting(i)
```
|
Before Python 3, map() returned a list, not an iterator. So your example would work in Python 2.7.
list() creates a new list by iterating over its argument. ( list() is NOT JUST a type conversion from say tuple to list. So list(list((1,2))) returns [1,2]. ) So list(map(...)) is backwards compatible with Python 2.7.
|
13,623,634
|
Why doesn't following code print anything:
```
#!/usr/bin/python3
class test:
def do_someting(self,value):
print(value)
return value
def fun1(self):
map(self.do_someting,range(10))
if __name__=="__main__":
t = test()
t.fun1()
```
I'm executing the above code in Python 3. I think i'm missing something very basic but not able to figure it out.
|
2012/11/29
|
[
"https://Stackoverflow.com/questions/13623634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1651941/"
] |
[`map()` returns an iterator](http://docs.python.org/3/library/functions.html#map), and will not process elements until you ask it to.
Turn it into a list to force all elements to be processed:
```
list(map(self.do_someting,range(10)))
```
or use `collections.deque()` with the length set to 0 to not produce a list if you don't need the map output:
```
from collections import deque
deque(map(self.do_someting, range(10)))
```
but note that simply using a `for` loop is far more readable for any future maintainers of your code:
```
for i in range(10):
self.do_someting(i)
```
|
I just want to add the following:
`With multiple iterables, the iterator stops when the shortest iterable is exhausted` [ <https://docs.python.org/3.4/library/functions.html#map> ]
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
```
>>> list(map(lambda a, b: [a, b], [1, 2, 3], ['a', 'b']))
[[1, 'a'], [2, 'b'], [3, None]]
```
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
```
>>> list(map(lambda a, b: [a, b], [1, 2, 3], ['a', 'b']))
[[1, 'a'], [2, 'b']]
```
That difference makes the answer about simple wrapping with `list(...)` not completely correct
The same could be achieved with:
```
>>> import itertools
>>> [[a, b] for a, b in itertools.zip_longest([1, 2, 3], ['a', 'b'])]
[[1, 'a'], [2, 'b'], [3, None]]
```
|
13,623,634
|
Why doesn't following code print anything:
```
#!/usr/bin/python3
class test:
def do_someting(self,value):
print(value)
return value
def fun1(self):
map(self.do_someting,range(10))
if __name__=="__main__":
t = test()
t.fun1()
```
I'm executing the above code in Python 3. I think i'm missing something very basic but not able to figure it out.
|
2012/11/29
|
[
"https://Stackoverflow.com/questions/13623634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1651941/"
] |
Before Python 3, map() returned a list, not an iterator. So your example would work in Python 2.7.
list() creates a new list by iterating over its argument. ( list() is NOT JUST a type conversion from say tuple to list. So list(list((1,2))) returns [1,2]. ) So list(map(...)) is backwards compatible with Python 2.7.
|
I just want to add the following:
`With multiple iterables, the iterator stops when the shortest iterable is exhausted` [ <https://docs.python.org/3.4/library/functions.html#map> ]
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
```
>>> list(map(lambda a, b: [a, b], [1, 2, 3], ['a', 'b']))
[[1, 'a'], [2, 'b'], [3, None]]
```
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
```
>>> list(map(lambda a, b: [a, b], [1, 2, 3], ['a', 'b']))
[[1, 'a'], [2, 'b']]
```
That difference makes the answer about simple wrapping with `list(...)` not completely correct
The same could be achieved with:
```
>>> import itertools
>>> [[a, b] for a, b in itertools.zip_longest([1, 2, 3], ['a', 'b'])]
[[1, 'a'], [2, 'b'], [3, None]]
```
|
48,055,372
|
I Converted a csv to list:
```
import csv
with open('DataAnalizada.csv', 'rb') as f:
reader = csv.reader(f)
a = list(reader)
```
I need to analyze the information on that list where it is analyzed by customer groups and dates first as AAA customer on 12/27/2017, AAA on 12/28/2017, BBB on 12/27/2017, BBB on 28 / 12/2017, CCC on 12/27/2017, CCC on 12/28/2017 and within each of these groups the Analysis is taken into account (Stable Alert or Increment, which are the 3 variables that can be presented) in this case if for the AAA client on 12/27/2017 all the Analysis values were Stable, I want the new csv file to appear: AAA, 12/27/2017, The client's performance was Stable and so on for each client and date!
I need some function that is conditional where for each list that the client and the date are equal analyze the column of Analisis and according to this if they are all Estable, AAA, 12/27/2017, Estable: The client's performance was Estable and if no AAA, 12/27/2017, No Analized
I'm fairly new to python and I can not do it on my own sincerely. I do not know how to go through a nested list and group it as I ask earlier. My apologies for the lack of code in the question
```
a = [['Cliente', 'Fecha', 'Variables', 'Dia Previo', 'Mayor/Menor', 'Dia a Analizar', 'Analisis'],
['AAA', '27/12/2017', 'ECPM_medio', '0.41', 'Dentro del Margen', '0.35', 'Estable'],
['AAA', '27/12/2017', 'Fill_rate', '2.25', 'Dentro del Margen', '2.7', 'Estable'],
['AAA', '27/12/2017', 'Importe_a_pagar_a_medio', '62.4', 'Dentro del Margen', '61.21', 'Estable'],
['AAA', '27/12/2017', 'Impresiones_exchange', '153927.0', 'Dentro del Margen', '173663.0', 'Estable'],
['AAA', '27/12/2017', 'Subastas', '6827946.0', 'Dentro del Margen', '6431093.0', 'Estable'],
['BBB', '27/12/2017', 'ECPM_medio', '1.06', 'Dentro del Margen', '1.06', 'Alerta'],
['BBB', '27/12/2017', 'Fill_rate', '26.67', 'Dentro del Margen', '27.2', 'Alerta'],
['BBB', '27/12/2017', 'Importe_a_pagar_a_medio', '11.34', 'Dentro del Margen', '12.77', 'Estable'],
['BBB', '27/12/2017', 'Impresiones_exchange', '10648.0', 'Dentro del Margen', '12099.0', 'Estable'],
['BBB', '27/12/2017', 'Subastas', '39930.0', 'Dentro del Margen', '44479.0', 'Estable'],
['AAA', '28/12/2017', 'ECPM_medio', '0.41', 'Dentro del Margen', '0.35', 'Estable'],
['AAA', '28/12/2017', 'Fill_rate', '2.25', 'Dentro del Margen', '2.7', 'Estable'],
['AAA', '28/12/2017', 'Importe_a_pagar_a_medio', '62.4', 'Dentro del Margen', '61.21', 'Estable'],
['AAA', '28/12/2017', 'Impresiones_exchange', '153927.0', 'Dentro del Margen', '173663.0', 'Estable'],
['AAA', '28/12/2017', 'Subastas', '6827946.0', 'Dentro del Margen', '6431093.0', 'Estable'],
['BBB', '28/12/2017', 'ECPM_medio', '1.06', 'Dentro del Margen', '1.06', 'Estable'],
['BBB', '28/12/2017', 'Fill_rate', '26.67', 'Dentro del Margen', '27.2', 'Estable'],
['BBB', '28/12/2017', 'Importe_a_pagar_a_medio', '11.34', 'Dentro del Margen', '12.77', 'Estable'],
['BBB', '28/12/2017', 'Impresiones_exchange', '10648.0', 'Dentro del Margen', '12099.0', 'Estable'],
['BBB', '28/12/2017', 'Subastas', '39930.0', 'Dentro del Margen', '44479.0', 'Estable']]
```
An example of the New csv I need:
```
Cliente,Fecha,Analisis
AAA,27/12/2017,Stable: The client's performance was Stable
AAA,28/12/2017,Stable: The client's performance was Stable
BBB,27/12/2017,Stable: The client's performance was Stable
BBB,28/12/2017, Stable: The client's performance was Stable
CCC,27/12/2017,Stable: The client's performance was Stable
CCC,28/12/2017,Stable: The client's performance was Stable
```
|
2018/01/02
|
[
"https://Stackoverflow.com/questions/48055372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8717507/"
] |
I thought this might lead you to what you want, however, not sure this will be totally helpful. Since you don't have a condition to filter data, I tried the following way to just get your desired output. Note, this is just a try to guide you towards pandas.
`pandas` would be the best way to go about this as you could manipulate the data, the way you want. To read csv in [pandas](http://pythonhow.com/data-analysis-with-python-pandas/).
I just did like this to get your data into pandas data frame,
```
import pandas as pd
headers = a.pop(0)
df = pd.DataFrame(a, columns = headers)
df
```
output:
```
Cliente Fecha Variables Dia Previo Mayor/Menor Dia a Analizar Analisis
0 AAA 27/12/2017 ECPM_medio 0.41 Dentro del Margen 0.35 Estable
1 AAA 27/12/2017 Fill_rate 2.25 Dentro del Margen 2.7 Estable
...
```
After this, I created a new column with status (Still don't know the exact condition)
```
for i in df['Analisis']:
if i == 'Estable' or i == 'Alerta':
df['Status'] = 'Stable: The client''s performance was Stable'
```
Now, you can use `groupby` function in pandas to create your desired output.
```
df1= df.groupby(['Cliente','Fecha', 'Status']).size()
df1
```
output,
```
Cliente Fecha Status
AAA 27/12/2017 Stable: The clients performance was Stable 5
28/12/2017 Stable: The clients performance was Stable 5
BBB 27/12/2017 Stable: The clients performance was Stable 5
28/12/2017 Stable: The clients performance was Stable 5
```
When you use `groupby` you have to use an aggregate function, I used `.size()`.
Now, you can write this dataframe df1 into csv. You can always wrap these into a function also. Hope this will lead you to an efficient method of analysis for your purposes.
|
The Pandas package has the tools you need. However I would recommend starting with [scipy](https://www.scipy.org/about.html "scipy") and [anaconda](https://www.anaconda.com/download/#linux "anaconda") since I found installing Pandas on its own to be quite difficult.
|
48,055,372
|
I Converted a csv to list:
```
import csv
with open('DataAnalizada.csv', 'rb') as f:
reader = csv.reader(f)
a = list(reader)
```
I need to analyze the information on that list where it is analyzed by customer groups and dates first as AAA customer on 12/27/2017, AAA on 12/28/2017, BBB on 12/27/2017, BBB on 28 / 12/2017, CCC on 12/27/2017, CCC on 12/28/2017 and within each of these groups the Analysis is taken into account (Stable Alert or Increment, which are the 3 variables that can be presented) in this case if for the AAA client on 12/27/2017 all the Analysis values were Stable, I want the new csv file to appear: AAA, 12/27/2017, The client's performance was Stable and so on for each client and date!
I need some function that is conditional where for each list that the client and the date are equal analyze the column of Analisis and according to this if they are all Estable, AAA, 12/27/2017, Estable: The client's performance was Estable and if no AAA, 12/27/2017, No Analized
I'm fairly new to python and I can not do it on my own sincerely. I do not know how to go through a nested list and group it as I ask earlier. My apologies for the lack of code in the question
```
a = [['Cliente', 'Fecha', 'Variables', 'Dia Previo', 'Mayor/Menor', 'Dia a Analizar', 'Analisis'],
['AAA', '27/12/2017', 'ECPM_medio', '0.41', 'Dentro del Margen', '0.35', 'Estable'],
['AAA', '27/12/2017', 'Fill_rate', '2.25', 'Dentro del Margen', '2.7', 'Estable'],
['AAA', '27/12/2017', 'Importe_a_pagar_a_medio', '62.4', 'Dentro del Margen', '61.21', 'Estable'],
['AAA', '27/12/2017', 'Impresiones_exchange', '153927.0', 'Dentro del Margen', '173663.0', 'Estable'],
['AAA', '27/12/2017', 'Subastas', '6827946.0', 'Dentro del Margen', '6431093.0', 'Estable'],
['BBB', '27/12/2017', 'ECPM_medio', '1.06', 'Dentro del Margen', '1.06', 'Alerta'],
['BBB', '27/12/2017', 'Fill_rate', '26.67', 'Dentro del Margen', '27.2', 'Alerta'],
['BBB', '27/12/2017', 'Importe_a_pagar_a_medio', '11.34', 'Dentro del Margen', '12.77', 'Estable'],
['BBB', '27/12/2017', 'Impresiones_exchange', '10648.0', 'Dentro del Margen', '12099.0', 'Estable'],
['BBB', '27/12/2017', 'Subastas', '39930.0', 'Dentro del Margen', '44479.0', 'Estable'],
['AAA', '28/12/2017', 'ECPM_medio', '0.41', 'Dentro del Margen', '0.35', 'Estable'],
['AAA', '28/12/2017', 'Fill_rate', '2.25', 'Dentro del Margen', '2.7', 'Estable'],
['AAA', '28/12/2017', 'Importe_a_pagar_a_medio', '62.4', 'Dentro del Margen', '61.21', 'Estable'],
['AAA', '28/12/2017', 'Impresiones_exchange', '153927.0', 'Dentro del Margen', '173663.0', 'Estable'],
['AAA', '28/12/2017', 'Subastas', '6827946.0', 'Dentro del Margen', '6431093.0', 'Estable'],
['BBB', '28/12/2017', 'ECPM_medio', '1.06', 'Dentro del Margen', '1.06', 'Estable'],
['BBB', '28/12/2017', 'Fill_rate', '26.67', 'Dentro del Margen', '27.2', 'Estable'],
['BBB', '28/12/2017', 'Importe_a_pagar_a_medio', '11.34', 'Dentro del Margen', '12.77', 'Estable'],
['BBB', '28/12/2017', 'Impresiones_exchange', '10648.0', 'Dentro del Margen', '12099.0', 'Estable'],
['BBB', '28/12/2017', 'Subastas', '39930.0', 'Dentro del Margen', '44479.0', 'Estable']]
```
An example of the New csv I need:
```
Cliente,Fecha,Analisis
AAA,27/12/2017,Stable: The client's performance was Stable
AAA,28/12/2017,Stable: The client's performance was Stable
BBB,27/12/2017,Stable: The client's performance was Stable
BBB,28/12/2017, Stable: The client's performance was Stable
CCC,27/12/2017,Stable: The client's performance was Stable
CCC,28/12/2017,Stable: The client's performance was Stable
```
|
2018/01/02
|
[
"https://Stackoverflow.com/questions/48055372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8717507/"
] |
```
import csv
from collections import namedtuple
with open('DataAnalizada.csv', 'rb') as f:
reader = csv.reader(f)
first_col = reader.next()
header = namedtuple('header', first_col)
data = {}
for val in reader:
get_ = header(*val)
if get_.Analisis == 'Estable':
get_data = (get_.Cliente, get_.Fecha)
if get_data in data:
get_list = data[get_data]
get_list.append(val)
else:
data.setdefault(get_data, [])
with open('DataAnalizada_new.csv', 'wb+') as filename:
header = ['Cliente','Fecha','Analisis']
writer = csv.writer(filename)
writer.writerow(header)
for val in data.keys():
writer.writerow(val + ["Stable: The client's performance was Stable"])
```
|
The Pandas package has the tools you need. However I would recommend starting with [scipy](https://www.scipy.org/about.html "scipy") and [anaconda](https://www.anaconda.com/download/#linux "anaconda") since I found installing Pandas on its own to be quite difficult.
|
52,571,930
|
I have a 2D array A:
```
28 39 52
77 80 66
7 18 24
9 97 68
```
And a vector array of column indexes B:
```
1
0
2
0
```
How, in a pythonian way, using base Python or Numpy, can I select the elements from A which DO NOT correspond to the column indexes in B?
I should get this 2D array which contains the elements of A, Not corresponding to the column indexes stored in B:
```
28 52
80 66
7 18
97 68
```
|
2018/09/29
|
[
"https://Stackoverflow.com/questions/52571930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10434696/"
] |
You can make use of broadcasting and a row-wise mask to select elements not contained in your array for each row:
***Setup***
```
B = np.array([1, 0, 2, 0])
cols = np.arange(A.shape[1])
```
---
Now use broadcasting to create a mask, and index your array.
```
mask = B[:, None] != cols
A[mask].reshape(-1, 2)
```
```
array([[28, 52],
[80, 66],
[ 7, 18],
[97, 68]])
```
|
A spin off of my answer to your other question,
[Replace 2D array elements with zeros, using a column index vector](https://stackoverflow.com/questions/52573733/replace-2d-array-elements-with-zeros-using-a-column-index-vector)
We can make a boolean `mask` with the same indexing used before:
```
In [124]: mask = np.ones(A.shape, dtype=bool)
In [126]: mask[np.arange(4), B] = False
In [127]: mask
Out[127]:
array([[ True, False, True],
[False, True, True],
[ True, True, False],
[False, True, True]])
```
Indexing an array with a boolean mask produces a 1d array, since in the most general case such a mask could select a different number of elements in each row.
```
In [128]: A[mask]
Out[128]: array([28, 52, 80, 66, 7, 18, 97, 68])
```
In this case the result can be reshaped back to 2d:
```
In [129]: A[mask].reshape(4,2)
Out[129]:
array([[28, 52],
[80, 66],
[ 7, 18],
[97, 68]])
```
Since you allowed for 'base Python' here's list comprehension answer:
```
In [136]: [[y for i,y in enumerate(x) if i!=b] for b,x in zip(B,A)]
Out[136]: [[28, 52], [80, 66], [7, 18], [97, 68]]
```
If all the 0's in the other `A` come from the insertion, then we can also get the `mask` (`Out[127]`) with
```
In [142]: A!=0
Out[142]:
array([[ True, False, True],
[False, True, True],
[ True, True, False],
[False, True, True]])
```
|
55,808,362
|
I have just started working with python 3.7 and I am trying to create a series e.g from 0 to 23 and repeat it. Using
```
rep1 = pd.Series(range(24))
```
I figured out how to make the first 24 values and I wanted to "copy-paste" it many times so that the final series is the original 5 times, one after the other. The result with `rep = pd.Series.repeat(rep1, 5)` gives me a result that looks like this and it's not what I want
```
0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 ...
```
What I seek for is the 0-23 range multiple times. Any advice?
|
2019/04/23
|
[
"https://Stackoverflow.com/questions/55808362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11167002/"
] |
you can try this:
```
pd.concat([rep1]*5)
```
This will repeat your series 5 times.
|
You could use a list to generate directly your Series.
```
rep = pd.Series(list(range(24))*5)
```
|
55,808,362
|
I have just started working with python 3.7 and I am trying to create a series e.g from 0 to 23 and repeat it. Using
```
rep1 = pd.Series(range(24))
```
I figured out how to make the first 24 values and I wanted to "copy-paste" it many times so that the final series is the original 5 times, one after the other. The result with `rep = pd.Series.repeat(rep1, 5)` gives me a result that looks like this and it's not what I want
```
0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 ...
```
What I seek for is the 0-23 range multiple times. Any advice?
|
2019/04/23
|
[
"https://Stackoverflow.com/questions/55808362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11167002/"
] |
you can try this:
```
pd.concat([rep1]*5)
```
This will repeat your series 5 times.
|
Another solution using [`numpy.tile`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html):
```
import numpy as np
rep = pd.Series(np.tile(rep1, 5))
```
|
55,808,362
|
I have just started working with python 3.7 and I am trying to create a series e.g from 0 to 23 and repeat it. Using
```
rep1 = pd.Series(range(24))
```
I figured out how to make the first 24 values and I wanted to "copy-paste" it many times so that the final series is the original 5 times, one after the other. The result with `rep = pd.Series.repeat(rep1, 5)` gives me a result that looks like this and it's not what I want
```
0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 ...
```
What I seek for is the 0-23 range multiple times. Any advice?
|
2019/04/23
|
[
"https://Stackoverflow.com/questions/55808362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11167002/"
] |
you can try this:
```
pd.concat([rep1]*5)
```
This will repeat your series 5 times.
|
If you want the repeated Series as one data object then use a pandas DataFrame for this. A DataFrame is multiple pandas Series in one object, sharing an index.
So firstly I am creating a python list, of 0-23, 5 times.
Then I put this into a DataFrame and optionally transpose so that I have the rows going down rather than across in this example.
```
import pandas as pd
lst = [list(range(0,24))] * 5
rep = pd.DataFrame(lst).transpose()
```
[](https://i.stack.imgur.com/EyfLO.png)
|
55,808,362
|
I have just started working with python 3.7 and I am trying to create a series e.g from 0 to 23 and repeat it. Using
```
rep1 = pd.Series(range(24))
```
I figured out how to make the first 24 values and I wanted to "copy-paste" it many times so that the final series is the original 5 times, one after the other. The result with `rep = pd.Series.repeat(rep1, 5)` gives me a result that looks like this and it's not what I want
```
0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 ...
```
What I seek for is the 0-23 range multiple times. Any advice?
|
2019/04/23
|
[
"https://Stackoverflow.com/questions/55808362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11167002/"
] |
Another solution using [`numpy.tile`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html):
```
import numpy as np
rep = pd.Series(np.tile(rep1, 5))
```
|
You could use a list to generate directly your Series.
```
rep = pd.Series(list(range(24))*5)
```
|
55,808,362
|
I have just started working with python 3.7 and I am trying to create a series e.g from 0 to 23 and repeat it. Using
```
rep1 = pd.Series(range(24))
```
I figured out how to make the first 24 values and I wanted to "copy-paste" it many times so that the final series is the original 5 times, one after the other. The result with `rep = pd.Series.repeat(rep1, 5)` gives me a result that looks like this and it's not what I want
```
0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 ...
```
What I seek for is the 0-23 range multiple times. Any advice?
|
2019/04/23
|
[
"https://Stackoverflow.com/questions/55808362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11167002/"
] |
Another solution using [`numpy.tile`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html):
```
import numpy as np
rep = pd.Series(np.tile(rep1, 5))
```
|
If you want the repeated Series as one data object then use a pandas DataFrame for this. A DataFrame is multiple pandas Series in one object, sharing an index.
So firstly I am creating a python list, of 0-23, 5 times.
Then I put this into a DataFrame and optionally transpose so that I have the rows going down rather than across in this example.
```
import pandas as pd
lst = [list(range(0,24))] * 5
rep = pd.DataFrame(lst).transpose()
```
[](https://i.stack.imgur.com/EyfLO.png)
|
6,474,923
|
I'm getting errors building an App store and Adhoc distributions of my project. I'm using the latest version of the three20 which I integrated into my Xcode 4 project using the given python script.
The release and debug version of the project build just fine without any build errors.
Here's the summary of the errors:
error: Three20/Three20.h: No such file or directory
.. cannot find interface declaration for 'TTDefaultStyleSheet', superclass of 'MyTTStyleSheet'
|
2011/06/25
|
[
"https://Stackoverflow.com/questions/6474923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/539115/"
] |
I have figured out whats going on here. The python script the header search paths for three20 to:
```
$(BUILT_PRODUCTS_DIR)/../three20
$(BUILT_PRODUCTS_DIR)/../../three20
../../libs/external/three20/Build/Products/three20
```
These paths work fine for Debug and Release builds as the macros expand to paths without any spaces like (build/Debug-iphoneos/ and build/Release-iphoneos). Xcode 4 doesn't seem to like the Adhoc and Appstore distribution build folders since it has spaces in them. Those are build/Ad Hoc Distribution-iphoneos & build/Appstore Distribution-iphoneos. Double quoting the build path string has fixed these issues.
Set your header search path for three20 to:
```
"$(BUILT_PRODUCTS_DIR)/../three20"
"$(BUILT_PRODUCTS_DIR)/../../three20"
"../../libs/external/three20/Build/Products/three20"
```
|
It might have happened because you added these 2 new targets AFTER you use the python script to add three20 project.
You will need to run the python script again to add three20 to your new targets:
```
python three20/src/scripts/ttmodule.py -p ProjectName/ProjectName.xcodeproj -c NEW_TARGET_NAME Three20
```
|
35,562,234
|
I have a python script that displays the Date, hour and IP Address for an attack in a log file. My issue is that i need to be able to count how many attacks occur per hour per day but when i implement a count it just counts the total not what i want.
**The log file looks like this:**
```
Feb 3 08:50:39 j4-be02 sshd[620]: Failed password for bin from 211.167.103.172 port 39701 ssh2
Feb 3 08:50:45 j4-be02 sshd[622]: Failed password for invalid user virus from 211.167.103.172 port 41354 ssh2
Feb 3 08:50:49 j4-be02 sshd[624]: Failed password for invalid user virus from 211.167.103.172 port 42994 ssh2
Feb 3 13:34:00 j4-be02 sshd[666]: Failed password for root from 85.17.188.70 port 45481 ssh2
Feb 3 13:34:01 j4-be02 sshd[670]: Failed password for root from 85.17.188.70 port 46802 ssh2
Feb 3 13:34:03 j4-be02 sshd[672]: Failed password for root from 85.17.188.70 port 47613 ssh2
Feb 3 13:34:05 j4-be02 sshd[676]: Failed password for root from 85.17.188.70 port 48495 ssh2
Feb 3 21:45:18 j4-be02 sshd[746]: Failed password for invalid user test from 62.45.87.113 port 50636 ssh2
Feb 4 08:39:46 j4-be02 sshd[1078]: Failed password for root from 1.234.51.243 port 60740 ssh2
Feb 4 08:39:55 j4-be02 sshd[1082]: Failed password for root from 1.234.51.243 port 34124 ssh2
```
**the code i have so far is:**
```
import re
myAuthlog=open('auth.log', 'r') #open the auth.log for reading
for line in myAuthlog: #go through each line of the file and return it to the variable line
ip_addresses = re.findall(r'([A-Z][a-z]{2}\s\s\d\s\d\d).+Failed password for .+? from (\S+)', line)
print ip_addresses
```
**the outcome is as shown**
```
[('Feb 5 08', '5.199.133.223')]
[]
[('Feb 5 08', '5.199.133.223')]
[]
[('Feb 5 08', '5.199.133.223')]
[]
[('Feb 5 08', '5.199.133.223')]
[]
[('Feb 5 08', '5.199.133.223')]
```
|
2016/02/22
|
[
"https://Stackoverflow.com/questions/35562234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4671509/"
] |
The python function [`groupby()`](https://docs.python.org/2/library/itertools.html#itertools.groupby) will group your items according to any criteria you specify.
This code will print the number of attacks per hour, per day:
```
from itertools import groupby
with open('auth.log') as myAuthlog:
for key, group in groupby(myAuthlog, key = lambda x: x[:9]):
print "%d attacks in hour %s"%(len(list(group)), key)
```
Or, with an additional requirement from the comments:
```
from itertools import groupby
with open('auth.log') as myAuthlog:
myAuthlog = (line for line in myAuthlog if "Failed password for" in line)
for key, group in groupby(myAuthlog, key = lambda x: x[:9]):
print "%d attacks in hour %s"%(len(list(group)), key)
```
Or, with different formatting:
```
from itertools import groupby
with open('auth.log') as myAuthlog:
myAuthlog = (line for line in myAuthlog if "Failed password for" in line)
for key, group in groupby(myAuthlog, key = lambda x: x[:9]):
month, day, hour = key[0:3], key[4:6], key[7:9]
print "%s:00 %s-%s: %d"%(hour, day, month, len(list(group)))
```
|
```
import collections
from datetime import datetime as dt
answer = collections.defaultdict(int)
with open('path/to/logfile') as infile:
for line in infile:
stamp = line[:9]
t = dt.strptime(stamp, "%b\t%d\t%H")
answer[t] += 1
```
|
70,088,746
|
In python I am returning numbers but I only want the last 10 numbers
Ex: 221234567890 should return 1234567890
In excel it looks like: if(len(cell) > 10, right (cell,10),.. but don't know how to do this in python
|
2021/11/23
|
[
"https://Stackoverflow.com/questions/70088746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17492723/"
] |
```py
a = 221234567890
result = a % 10000000000
```
This should work for ints and
```py
a = "221234567890"
result = a[-10:]
```
should work for strings
|
```
a = '123456789abcdefg'
a[-10:]
```
|
70,951,954
|
So im trying to make a script using Lexing and Parsing. I wanted to try and change the color of the texts when a user inputs something.
Say in python when I do:
'''print("Hello")'''
It changes the color of print, string, parens, etc. I just wanted to know how to do it
and/or the code to do it.
Say if my user types:
'''hello NAME'''
It will change the color of "hello" to green or something. Does anyone know how?
|
2022/02/02
|
[
"https://Stackoverflow.com/questions/70951954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18097622/"
] |
You can do like this
```
import colorama
from colorama import Fore
print(Fore.RED + 'This text is red in color')
```
|
Try using colorama, or termcolor in python:
Here is a link:
<https://www.geeksforgeeks.org/print-colors-python-terminal/>
|
63,345,648
|
I have been able to filter all the image url from a page and displayed them one after the other
```
import requests
from bs4 import BeautifulSoup
article_URL = "https://medium.com/bhavaniravi/build-your-1st-python-web-app-with-flask-b039d11f101c"
response = requests.get(article_URL)
soup = bs4.BeautifulSoup(response.text,'html.parser')
images = soup.find('body').find_all('img')
i = 0
image_url = []
for im in images:
print(im)
i+=1
url = im.get('src')
image_url.append(url)
print('Downloading: ', url)
try:
response = requests.get(url, stream=True)
with open(str(i) + '.jpg', 'wb') as out_file:
shutil.copyfileobj(response.raw, out_file)
del response
except:
print('Could not download: ', url)
new = [x for x in image_url if x is not None]
for url in new:
resp = requests.get(url, stream=True).raw
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
# height, width, channels = image.shape
height, width, _ = image.shape
dimension = []
for items in height, width:
dimension.append(items)
# print(height, width)
print(dimension)
```
**I want to print the image with the largest dimension from the list of url**
This is the result I have from the list which is not good enough
```
[72, 72]
[95, 96]
[13, 60]
[227, 973]
[17, 60]
[229, 771]
```
|
2020/08/10
|
[
"https://Stackoverflow.com/questions/63345648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8053783/"
] |
There is no native javascript api that allows you to find event listeners that were added using `eventTarget.addEventListener`.
You can still get events added using the `onclick` attribute whether the attribute was set using javascript or inline through html - in this case u are not getting the event listener, but you are getting the value of the `onclick`attribute which are two different things.
Javascript offers no api for doing so, because dom elements can be removed while event listeners still referencing them.
If you want to keep track of event listeners attached to dom elements you have to do that yourself.
Apart from that chrome has `getEventListeners` command line api which works with dom elements, however it is a developer tools command line api and so it only
works when called from developer tools.
|
There is no way, to do so directly with JavaScript.
However, you can use this approach and add an attribute while binding events to the elements.
```js
document.getElementById('test2').addEventListener('keypress', function() {
this.setAttribute("event", "yes");
console.log("foo");
}
)
document.querySelectorAll('test3').forEach(item => {
item.addEventListener('click', event => {
this.setAttribute("event", "yes");
console.log("bar");
})
})
document.getElementById('test4').onclick = function(event) {
let target = event.target;
this.setAttribute("event", "yes");
if (target.tagName != 'li') {
event.target.addClass('highlight');
}
};
```
And this is how you can find the elements having events bind to them :
```js
var eventElements = document.querySelectorAll("[event='yes']");
var countEventElements = eventElements.length;
```
|
67,137,419
|
I have started to use AWS SAM for python. When testing my functions locally I run:
```
sam build --use-container
sam local start-api
You can now browse to the above endpoints to invoke your functions. You do **not** need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically.
sam local invoke ...
```
Then, if I make changes to the code it is not reflected without rebuilding when I invoke my function again. Is there any trick that I am missing here? This prompt is not clear to me.
|
2021/04/17
|
[
"https://Stackoverflow.com/questions/67137419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6281479/"
] |
I believe your goal as follows.
* You want to reduce the process cost of the following script.
```
resultsSheet.hideColumns(11);
resultsSheet.hideColumns(18);
resultsSheet.hideColumns(19);
resultsSheet.showColumns(26);
resultsSheet.showColumns(27);
resultsSheet.showColumns(28);
resultsSheet.showColumns(29);
```
### Modification points:
* When `hideColumns` and `showColumns` are used, the arguments are `columnIndex, numColumns`. In this case, when the columns you want to hide and show are continuously existing like the column "A", "B" and "C", you can achieve this using one `hideColumns` and `showColumns`. But when the columns you want to hide and show are scattered, multiple `hideColumns` and `showColumns` are required to be used.
* In this case, in order to achieve your goal using one call, I would like to propose to use the method of batchUpdate in Sheets API. When Sheets API is used, both `hideColumns` and `showColumns` can be used by one API call.
The sample script is as follows.
### Sample script:
Please copy and paste the following script to the script editor of Spreadsheet you want to use. Before you use this script, [please enable Sheets API at Advanced Google services](https://developers.google.com/apps-script/guides/services/advanced#enable_advanced_services). And, please set the sheet name.
```
function myFunction() {
const hideColumns = [11, 18, 19];
const showColumns = [26, 27, 28, 29];
const sheetName = "Sheet1";
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheetId = ss.getSheetByName(sheetName).getSheetId();
const requests = [];
// Create requests for the hide columns.
if (hideColumns.length > 0) {
hideColumns.forEach(c =>
requests.push({ updateDimensionProperties: { properties: { hiddenByUser: true }, range: { sheetId: sheetId, dimension: "COLUMNS", startIndex: c - 1, endIndex: c }, fields: "hiddenByUser" } })
);
}
// Create requests for the show columns.
if (showColumns.length > 0) {
showColumns.forEach(c =>
requests.push({ updateDimensionProperties: { properties: { hiddenByUser: false }, range: { sheetId: sheetId, dimension: "COLUMNS", startIndex: c - 1, endIndex: c }, fields: "hiddenByUser" } })
);
}
// Request to Sheets API using the created requests.
if (requests.length > 0) Sheets.Spreadsheets.batchUpdate({requests: requests}, ss.getId());
}
```
* In above sample script, when only `hideColumns` is declared, the columns are hidden using `hideColumns`. when only `showColumns` is declared, the columns are shown using `showColumns`. When both `hideColumns` and `showColumns` are declared, the columns are hidden and shown using `hideColumns` and `showColumns`.
+ Above process is done by one API call.
* The values of `hideColumns` and `showColumns` are from your script
### References:
* [hideColumns(columnIndex, numColumns)](https://developers.google.com/apps-script/reference/spreadsheet/sheet#hideColumns(Integer,Integer))
* [showColumns(columnIndex, numColumns)](https://developers.google.com/apps-script/reference/spreadsheet/sheet#showcolumnscolumnindex,-numcolumns)
* [Method: spreadsheets.batchUpdate](https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate)
* [UpdateDimensionPropertiesRequest](https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#updatedimensionpropertiesrequest)
|
To do this faster, you can hide and show rows in groups, with one SpreadsheetApp call required per group. For example, you can hide the seven columns listed in your code sample with this:
`hideColumns_(resultSheet, [11, 18, 19, 26, 27, 28, 29]);`
To show columns, use a similar pattern with `showColumns_()`. Here's the code:
```
/**
* Shows and hides columns that have a magic value in a given row.
*/
function showAndHideColumnsByValue() {
const rowToWatch = 2; // 1-indexed
const valueShow = 'show';
const valueHide = 'hide';
const sheet = SpreadsheetApp.getActive().getActiveSheet();
const columnStart = sheet.getFrozenColumns() + 1;
const showOrHideValues = sheet.getRange(rowToWatch, columnStart, 1, sheet.getLastColumn())
.getValues()
.flat();
const columnsToShow = showOrHideValues
.map((value, index) => value === valueShow ? columnStart + index : 0)
.filter(Number);
showColumns_(sheet, columnsToShow);
const columnsToHide = showOrHideValues
.map((value, index) => value === valueHide ? columnStart + index : 0)
.filter(Number);
hideColumns_(sheet, columnsToHide);
}
/**
* Shows columns fast by grouping them before unhiding.
*
* @param {SpreadsheetApp.Sheet} sheet The sheet where to show rows.
* @param {Number[]} columnsToShow The 1-indexed column numbers of columns to show.
*/
function showColumns_(sheet, columnsToShow) {
countConsecutives_(columnsToShow.sort((a, b) => a - b))
.forEach(group => sheet.showColumns(group[0], group[1]));
}
/**
* Hides columns fast by grouping them before hiding.
*
* @param {SpreadsheetApp.Sheet} sheet The sheet where to hide rows.
* @param {Number[]} columnsToHide The 1-indexed column numbers of columns to hide.
*/
function hideColumns_(sheet, columnsToHide) {
countConsecutives_(columnsToHide.sort((a, b) => a - b))
.forEach(group => sheet.hideColumns(group[0], group[1]));
}
/**
* Counts consecutive numbers in an array and returns a 2D array that
* lists the first number of each run and the count of numbers in each run.
* Duplicate values in numbers will give duplicates in result.
*
* The numbers array [1, 2, 3, 5, 8, 9, 11, 12, 13, 5, 4] will get
* the result [[1, 3], [5, 1], [8, 2], [11, 3], [5, 1], [4, 1]].
*
* Typical usage:
* const runLengths = countConsecutives_(numbers.sort((a, b) => a - b));
*
* @param {Number[]} numbers The numbers to group into runs.
* @return {Number[][]} The numbers grouped into runs.
*/
function countConsecutives_(numbers) {
return numbers.reduce(function (acc, value, index) {
if (!index || value !== 1 + numbers[index - 1]) {
acc.push([value]);
}
acc[acc.length - 1][1] = (acc[acc.length - 1][1] || 0) + 1;
return acc;
}, []);
}
```
This will use the minimum number of hide operations when using the SpreadsheetApp API, but it may still be slow if many of the columns are separated by other columns. The Sheets API lets you do the same with just one call — see the answer by @Tanaike in this thread.
|
6,576,829
|
I'am looking for python async SMTP client to connect it with Torando IoLoop. I found only simple implmementation (<http://tornadogists.org/907491/>) but it's a blocking solution so it might bring performance issues.
Does anyone encountered non blocking SMTP client for Tornado? Some code snippet would be also very useful.
|
2011/07/04
|
[
"https://Stackoverflow.com/questions/6576829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/747179/"
] |
I wrote solution based on threads and queue. One thread per tornado process. This thread is a worker, gets email from queue and then send it via SMTP. You send emails from tornado application by adding it to queue. Simple and easy.
Here is sample code on GitHub: [link](https://github.com/marcinc81/quemail)
|
Just FYI - I just whipped up a ioloop based smtp client. While I can't say it's production tested, it will be in the near future.
<https://gist.github.com/1358253>
|
6,576,829
|
I'am looking for python async SMTP client to connect it with Torando IoLoop. I found only simple implmementation (<http://tornadogists.org/907491/>) but it's a blocking solution so it might bring performance issues.
Does anyone encountered non blocking SMTP client for Tornado? Some code snippet would be also very useful.
|
2011/07/04
|
[
"https://Stackoverflow.com/questions/6576829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/747179/"
] |
I wrote solution based on threads and queue. One thread per tornado process. This thread is a worker, gets email from queue and then send it via SMTP. You send emails from tornado application by adding it to queue. Simple and easy.
Here is sample code on GitHub: [link](https://github.com/marcinc81/quemail)
|
<https://github.com/equeny/tornadomail> - here is my attemp to port django mail system and python smtplib to tornado ioloop.
Will be happy to hear some feedback.
|
6,576,829
|
I'am looking for python async SMTP client to connect it with Torando IoLoop. I found only simple implmementation (<http://tornadogists.org/907491/>) but it's a blocking solution so it might bring performance issues.
Does anyone encountered non blocking SMTP client for Tornado? Some code snippet would be also very useful.
|
2011/07/04
|
[
"https://Stackoverflow.com/questions/6576829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/747179/"
] |
I wrote solution based on threads and queue. One thread per tornado process. This thread is a worker, gets email from queue and then send it via SMTP. You send emails from tornado application by adding it to queue. Simple and easy.
Here is sample code on GitHub: [link](https://github.com/marcinc81/quemail)
|
I'm not using my own SMTP server but figured this would be useful to someone:
I've just had to add email sending to my app. Most of the sample python code for the web emailing services use a blocking design so I dont want to use it.
Mailchimp's [Mandrill](https://mandrillapp.com/) uses HTTP POST requests so it can work in an Async fashion fitting in with Tornado's design.
```
class EmailMeHandler(BaseHandler):
@tornado.web.asynchronous
@tornado.gen.engine
def get(self):
http_client = AsyncHTTPClient()
mail_url = self.settings["mandrill_url"] + "/messages/send.json"
mail_data = {
"key": self.settings["mandrill_key"],
"message": {
"html": "html email from tornado sample app <b>bold</b>",
"text": "plain text email from tornado sample app",
"subject": "from tornado sample app",
"from_email": "hello@example.com",
"from_name": "Hello Team",
"to":[{"email": "sample@example.com"}]
}
}
body = tornado.escape.json_encode(mail_data)
response = yield tornado.gen.Task(http_client.fetch, mail_url, method='POST', body=body)
logging.info(response)
logging.info(response.body)
if response.code == 200:
self.redirect('/?notification=sent')
else:
self.redirect('/?notification=FAIL')
```
|
6,576,829
|
I'am looking for python async SMTP client to connect it with Torando IoLoop. I found only simple implmementation (<http://tornadogists.org/907491/>) but it's a blocking solution so it might bring performance issues.
Does anyone encountered non blocking SMTP client for Tornado? Some code snippet would be also very useful.
|
2011/07/04
|
[
"https://Stackoverflow.com/questions/6576829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/747179/"
] |
I wrote solution based on threads and queue. One thread per tornado process. This thread is a worker, gets email from queue and then send it via SMTP. You send emails from tornado application by adding it to queue. Simple and easy.
Here is sample code on GitHub: [link](https://github.com/marcinc81/quemail)
|
I was looking for the solution to the same problem at work. Since there was no readily available solution, I ported Python smtplib to implementation based on tornado non-blocking IOStream. The syntax follows that of smtplib as close as possible.
```
# create SMTP client
s = SMTPAsync()
yield s.connect('your.email.host',587)
yield s.starttls()
yield s.login('username', 'password')
yield s.sendmail('from_addr', 'to_addr', 'msg')
```
It currently only supports Python 3.3 and above. Here's the [github repo](https://github.com/vuamitom/tornado-smtpclient)
|
51,307,411
|
I'm trying to make an api for Pokemon, and I was thinking of packaging it, but no matter what I do, as soon as I try to import from this file, it comes up with this error.
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/student/anaconda3/lib/python3.6/site-packages/pokeapi/__init__.py", line 1, in <module>
from Pokemon import *
ModuleNotFoundError: No module named 'Pokemon'
```
The directory is like this:
```
/pokeapi
/pokeapi
__init__.py
Pokemon.py
setup.py
```
I install it with pip, and that error comes up.
Code for **init**.py:
```
from Pokemon import *
```
Code for Pokemon.py: <https://hastebin.com/qegupucuma.py>
I don't know what I'm doing wrong
|
2018/07/12
|
[
"https://Stackoverflow.com/questions/51307411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4503723/"
] |
I think the `if btnState == 2` statement is in the wrong block.
Also, what is `questionNumber`, when will it be incremented? How does it relate to `self.turn`?
You could try this:
```
@IBAction func btnUncoverQuestion(_ sender: RoundedButton) {
btnUncoverQuestion.setTitle(questionArray?[questionNumber].title ?? "No question here", for: .normal)
btnState = btnState + 1
if btnState == 1 {
sender.setTitle("Başlat", for: .normal)
sender.setTitleColor(UIColor.flatWhite, for: .normal)
startTimer()
} else if btnState == 2 {
btnState = 0
sender.setTitle("Tamam", for: .normal)
sender.setTitleColor(UIColor.flatWhite, for: .normal)
stopTimer()
let alert = UIAlertController(title: "Sizce cevap doğru mu", message: "Seçimin yap", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Doğru", style: .default, handler: { (trueAction) in
self.playerArray[self.turn].point += 1
self.turn += 1
self.updateQuestionScreen(button: sender)
}))
alert.addAction(UIAlertAction(title: "Yanlış", style: .default, handler: { (wrongAction) in
self.turn += 1
self.updateQuestionScreen(button: sender)
}))
}
}
```
|
Please use tag for different event.Example in 1st press you set the button.tag = 100 and 2nd press set the tag 200.
Check the tag in button action:
```
@IBAction func btnAction(_ sender: UIButton) {
switch sender.tag {
case 100:
//your action
sender.tag = 200
case 200:
//your action
sender.tag = 300
case 300:
//your action
sender.tag = 100
default:
break
}
}
```
Hope it helps you.Thank you
|
22,391,419
|
what is the difference between curly brace and square bracket in python?
```
A ={1,2}
B =[1,2]
```
when I print `A` and `B` on my terminal, they made no difference. Is it real?
And sometimes, I noticed some code use `{}` and `[]` to initialize different variables.
E.g. `A=[]`, `B={}`
Is there any difference there?
|
2014/03/13
|
[
"https://Stackoverflow.com/questions/22391419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2911587/"
] |
Curly braces create [dictionaries](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict) or [sets](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset). Square brackets create [lists](https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range).
They are called *literals*; a set literal:
```
aset = {'foo', 'bar'}
```
or a dictionary literal:
```
adict = {'foo': 42, 'bar': 81}
empty_dict = {}
```
or a list literal:
```
alist = ['foo', 'bar', 'bar']
empty_list = []
```
To create an empty set, you can only use `set()`.
Sets are collections of *unique* elements and you cannot order them. Lists are ordered sequences of elements, and values can be repeated. Dictionaries map keys to values, keys must be unique. Set and dictionary keys must meet other restrictions as well, so that Python can actually keep track of them efficiently and know they are and will remain unique.
There is also the [`tuple` type](https://docs.python.org/3/library/stdtypes.html#tuple), using a comma for 1 or more elements, with parenthesis being optional in many contexts:
```
atuple = ('foo', 'bar')
another_tuple = 'spam',
empty_tuple = ()
WARNING_not_a_tuple = ('eggs')
```
Note the comma in the `another_tuple` definition; it is that comma that makes it a `tuple`, not the parenthesis. `WARNING_not_a_tuple` is not a tuple, it has no comma. Without the parentheses all you have left is a string, instead.
See the [data structures chapter](http://docs.python.org/3/tutorial/datastructures.html) of the Python tutorial for more details; lists are introduced in the [introduction chapter](http://docs.python.org/3/tutorial/introduction.html#lists).
Literals for containers such as these are also called [displays](https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries) and the syntax allows for procedural creation of the contents based of looping, called *comprehensions*.
|
They create different types.
```
>>> type({})
<type 'dict'>
>>> type([])
<type 'list'>
>>> type({1, 2})
<type 'set'>
>>> type({1: 2})
<type 'dict'>
>>> type([1, 2])
<type 'list'>
```
|
22,391,419
|
what is the difference between curly brace and square bracket in python?
```
A ={1,2}
B =[1,2]
```
when I print `A` and `B` on my terminal, they made no difference. Is it real?
And sometimes, I noticed some code use `{}` and `[]` to initialize different variables.
E.g. `A=[]`, `B={}`
Is there any difference there?
|
2014/03/13
|
[
"https://Stackoverflow.com/questions/22391419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2911587/"
] |
Curly braces create [dictionaries](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict) or [sets](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset). Square brackets create [lists](https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range).
They are called *literals*; a set literal:
```
aset = {'foo', 'bar'}
```
or a dictionary literal:
```
adict = {'foo': 42, 'bar': 81}
empty_dict = {}
```
or a list literal:
```
alist = ['foo', 'bar', 'bar']
empty_list = []
```
To create an empty set, you can only use `set()`.
Sets are collections of *unique* elements and you cannot order them. Lists are ordered sequences of elements, and values can be repeated. Dictionaries map keys to values, keys must be unique. Set and dictionary keys must meet other restrictions as well, so that Python can actually keep track of them efficiently and know they are and will remain unique.
There is also the [`tuple` type](https://docs.python.org/3/library/stdtypes.html#tuple), using a comma for 1 or more elements, with parenthesis being optional in many contexts:
```
atuple = ('foo', 'bar')
another_tuple = 'spam',
empty_tuple = ()
WARNING_not_a_tuple = ('eggs')
```
Note the comma in the `another_tuple` definition; it is that comma that makes it a `tuple`, not the parenthesis. `WARNING_not_a_tuple` is not a tuple, it has no comma. Without the parentheses all you have left is a string, instead.
See the [data structures chapter](http://docs.python.org/3/tutorial/datastructures.html) of the Python tutorial for more details; lists are introduced in the [introduction chapter](http://docs.python.org/3/tutorial/introduction.html#lists).
Literals for containers such as these are also called [displays](https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries) and the syntax allows for procedural creation of the contents based of looping, called *comprehensions*.
|
These two braces are used for different purposes. If you just want a list to contain some elements and organize them by index numbers (starting from 0), just use the `[]` and add elements as necessary. `{}` are special in that you can give custom id's to values like `a = {"John": 14}`. Now, instead of making a list with ages and remembering whose age is where, you can just access John's age by `a["John"]`.
The `[]` is called a list and `{}` is called a dictionary (in Python). Dictionaries are basically a convenient form of list which allow you to access data in a much easier way.
However, there is a catch to dictionaries. Many times, the data that you put in the dictionary doesn't stay in the same order as before. Hence, when you go through each value one by one, it won't be in the order you expect. There is a special dictionary to get around this, but you have to add this line `from collections import OrderedDict` and replace `{}` with `OrderedDict()`. But, I don't think you will need to worry about that for now.
|
22,391,419
|
what is the difference between curly brace and square bracket in python?
```
A ={1,2}
B =[1,2]
```
when I print `A` and `B` on my terminal, they made no difference. Is it real?
And sometimes, I noticed some code use `{}` and `[]` to initialize different variables.
E.g. `A=[]`, `B={}`
Is there any difference there?
|
2014/03/13
|
[
"https://Stackoverflow.com/questions/22391419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2911587/"
] |
They create different types.
```
>>> type({})
<type 'dict'>
>>> type([])
<type 'list'>
>>> type({1, 2})
<type 'set'>
>>> type({1: 2})
<type 'dict'>
>>> type([1, 2])
<type 'list'>
```
|
These two braces are used for different purposes. If you just want a list to contain some elements and organize them by index numbers (starting from 0), just use the `[]` and add elements as necessary. `{}` are special in that you can give custom id's to values like `a = {"John": 14}`. Now, instead of making a list with ages and remembering whose age is where, you can just access John's age by `a["John"]`.
The `[]` is called a list and `{}` is called a dictionary (in Python). Dictionaries are basically a convenient form of list which allow you to access data in a much easier way.
However, there is a catch to dictionaries. Many times, the data that you put in the dictionary doesn't stay in the same order as before. Hence, when you go through each value one by one, it won't be in the order you expect. There is a special dictionary to get around this, but you have to add this line `from collections import OrderedDict` and replace `{}` with `OrderedDict()`. But, I don't think you will need to worry about that for now.
|
17,904,216
|
I've done some searches, but I'm actually not sure of the way to word what I want to take place, so I started a question. I'm sure its been covered before, so my apologies.
The code below doesn't work, but hopefully it illustrates what I'm trying to do.
```
sieve[i*2::i] *= ((i-1) / i):
```
I want to take a list and go through each item in the list that is a multiple of "i" and change its value by multiplying by the same amount.
So for example if I had a list
```
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
and I want to start at 2 and change every 2nd item in the list, by itself \* (2 - 1 ) / 2. So after it would look like
```
[1, 2, 3, 2, 5, 3, 7, 4, 9, 5]
```
how do I do that pythonically?
thank you very much!
EDIT to add:
sorry, I see where my poor wording has caused some confusion (ive changed it in the above).
I dont want to change every multiple of 2, I want to change every second item in the list, even if its not a multiple of 2. So I cant use x % 2 == 0. Sorry!
|
2013/07/28
|
[
"https://Stackoverflow.com/questions/17904216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2209860/"
] |
You can do:
```
>>> def sieve(L, i):
... temp = L[:i]
... for x, y in zip(L[i::2], L[i+1::2]):
... temp.append(x)
... temp.append(y/2)
... return temp
...
>>> sieve([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2)
[1, 2, 3, 2, 5, 3, 7, 4, 9, 5]
```
Note that `itself * (2 - 1 ) / 2` is equivalent to `itself * 1 / 2` which is equivalent to `itself / 2`.
|
```
map(lambda x : x * (2 - 1) / 2 if x % 2 == 0 else x, list)
```
This should do what you want it to.
**Edit:**
Alternately in style, you could use list comprehensions for this as follows:
```
i = 2
list[:i] + [x * (i - 1) / i if x % i == 0 else x for x in list[i:]]
```
|
17,904,216
|
I've done some searches, but I'm actually not sure of the way to word what I want to take place, so I started a question. I'm sure its been covered before, so my apologies.
The code below doesn't work, but hopefully it illustrates what I'm trying to do.
```
sieve[i*2::i] *= ((i-1) / i):
```
I want to take a list and go through each item in the list that is a multiple of "i" and change its value by multiplying by the same amount.
So for example if I had a list
```
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
and I want to start at 2 and change every 2nd item in the list, by itself \* (2 - 1 ) / 2. So after it would look like
```
[1, 2, 3, 2, 5, 3, 7, 4, 9, 5]
```
how do I do that pythonically?
thank you very much!
EDIT to add:
sorry, I see where my poor wording has caused some confusion (ive changed it in the above).
I dont want to change every multiple of 2, I want to change every second item in the list, even if its not a multiple of 2. So I cant use x % 2 == 0. Sorry!
|
2013/07/28
|
[
"https://Stackoverflow.com/questions/17904216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2209860/"
] |
[NumPy](http://www.numpy.org/) would actually let you do that!
```
>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> i = 2
>>> a[i*2::2] *= (i-1.0)/i
>>> a
array([0, 1, 2, 3, 2, 5, 3, 7, 4, 9])
```
If you can't use NumPy or prefer not to, a loop would probably be clearest:
```
>>> a = range(10)
>>> for j in range(i*2, len(a), i):
# Not *= since we want ints
... a[j] = a[j] * (i - 1) / i
```
|
```
map(lambda x : x * (2 - 1) / 2 if x % 2 == 0 else x, list)
```
This should do what you want it to.
**Edit:**
Alternately in style, you could use list comprehensions for this as follows:
```
i = 2
list[:i] + [x * (i - 1) / i if x % i == 0 else x for x in list[i:]]
```
|
17,904,216
|
I've done some searches, but I'm actually not sure of the way to word what I want to take place, so I started a question. I'm sure its been covered before, so my apologies.
The code below doesn't work, but hopefully it illustrates what I'm trying to do.
```
sieve[i*2::i] *= ((i-1) / i):
```
I want to take a list and go through each item in the list that is a multiple of "i" and change its value by multiplying by the same amount.
So for example if I had a list
```
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
and I want to start at 2 and change every 2nd item in the list, by itself \* (2 - 1 ) / 2. So after it would look like
```
[1, 2, 3, 2, 5, 3, 7, 4, 9, 5]
```
how do I do that pythonically?
thank you very much!
EDIT to add:
sorry, I see where my poor wording has caused some confusion (ive changed it in the above).
I dont want to change every multiple of 2, I want to change every second item in the list, even if its not a multiple of 2. So I cant use x % 2 == 0. Sorry!
|
2013/07/28
|
[
"https://Stackoverflow.com/questions/17904216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2209860/"
] |
You can use Python's [extended slicing](http://docs.python.org/release/2.3.5/whatsnew/section-slices.html) and slice assignment to do that:
```
>>> li=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> li[3::2]=[x/2 for x in li[3::2]]
>>> li
[1, 2, 3, 2, 5, 3, 7, 4, 9, 5]
```
|
```
map(lambda x : x * (2 - 1) / 2 if x % 2 == 0 else x, list)
```
This should do what you want it to.
**Edit:**
Alternately in style, you could use list comprehensions for this as follows:
```
i = 2
list[:i] + [x * (i - 1) / i if x % i == 0 else x for x in list[i:]]
```
|
17,904,216
|
I've done some searches, but I'm actually not sure of the way to word what I want to take place, so I started a question. I'm sure its been covered before, so my apologies.
The code below doesn't work, but hopefully it illustrates what I'm trying to do.
```
sieve[i*2::i] *= ((i-1) / i):
```
I want to take a list and go through each item in the list that is a multiple of "i" and change its value by multiplying by the same amount.
So for example if I had a list
```
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
and I want to start at 2 and change every 2nd item in the list, by itself \* (2 - 1 ) / 2. So after it would look like
```
[1, 2, 3, 2, 5, 3, 7, 4, 9, 5]
```
how do I do that pythonically?
thank you very much!
EDIT to add:
sorry, I see where my poor wording has caused some confusion (ive changed it in the above).
I dont want to change every multiple of 2, I want to change every second item in the list, even if its not a multiple of 2. So I cant use x % 2 == 0. Sorry!
|
2013/07/28
|
[
"https://Stackoverflow.com/questions/17904216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2209860/"
] |
You can do:
```
>>> def sieve(L, i):
... temp = L[:i]
... for x, y in zip(L[i::2], L[i+1::2]):
... temp.append(x)
... temp.append(y/2)
... return temp
...
>>> sieve([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2)
[1, 2, 3, 2, 5, 3, 7, 4, 9, 5]
```
Note that `itself * (2 - 1 ) / 2` is equivalent to `itself * 1 / 2` which is equivalent to `itself / 2`.
|
Per your edit, you can do this with a range.
```
for i in range(1, len(listnums), 2):
listnums[i] /= 2
```
If you want to do this with a list comprehension, you can do it similarly to the other version using `enumerate`.
```
def sieve(listnums, divisor):
return [num if i % divisor else num/divisor for i, num in enumerate(listnums, 1)]
```
|
17,904,216
|
I've done some searches, but I'm actually not sure of the way to word what I want to take place, so I started a question. I'm sure its been covered before, so my apologies.
The code below doesn't work, but hopefully it illustrates what I'm trying to do.
```
sieve[i*2::i] *= ((i-1) / i):
```
I want to take a list and go through each item in the list that is a multiple of "i" and change its value by multiplying by the same amount.
So for example if I had a list
```
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
and I want to start at 2 and change every 2nd item in the list, by itself \* (2 - 1 ) / 2. So after it would look like
```
[1, 2, 3, 2, 5, 3, 7, 4, 9, 5]
```
how do I do that pythonically?
thank you very much!
EDIT to add:
sorry, I see where my poor wording has caused some confusion (ive changed it in the above).
I dont want to change every multiple of 2, I want to change every second item in the list, even if its not a multiple of 2. So I cant use x % 2 == 0. Sorry!
|
2013/07/28
|
[
"https://Stackoverflow.com/questions/17904216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2209860/"
] |
[NumPy](http://www.numpy.org/) would actually let you do that!
```
>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> i = 2
>>> a[i*2::2] *= (i-1.0)/i
>>> a
array([0, 1, 2, 3, 2, 5, 3, 7, 4, 9])
```
If you can't use NumPy or prefer not to, a loop would probably be clearest:
```
>>> a = range(10)
>>> for j in range(i*2, len(a), i):
# Not *= since we want ints
... a[j] = a[j] * (i - 1) / i
```
|
You can do:
```
>>> def sieve(L, i):
... temp = L[:i]
... for x, y in zip(L[i::2], L[i+1::2]):
... temp.append(x)
... temp.append(y/2)
... return temp
...
>>> sieve([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2)
[1, 2, 3, 2, 5, 3, 7, 4, 9, 5]
```
Note that `itself * (2 - 1 ) / 2` is equivalent to `itself * 1 / 2` which is equivalent to `itself / 2`.
|
17,904,216
|
I've done some searches, but I'm actually not sure of the way to word what I want to take place, so I started a question. I'm sure its been covered before, so my apologies.
The code below doesn't work, but hopefully it illustrates what I'm trying to do.
```
sieve[i*2::i] *= ((i-1) / i):
```
I want to take a list and go through each item in the list that is a multiple of "i" and change its value by multiplying by the same amount.
So for example if I had a list
```
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
and I want to start at 2 and change every 2nd item in the list, by itself \* (2 - 1 ) / 2. So after it would look like
```
[1, 2, 3, 2, 5, 3, 7, 4, 9, 5]
```
how do I do that pythonically?
thank you very much!
EDIT to add:
sorry, I see where my poor wording has caused some confusion (ive changed it in the above).
I dont want to change every multiple of 2, I want to change every second item in the list, even if its not a multiple of 2. So I cant use x % 2 == 0. Sorry!
|
2013/07/28
|
[
"https://Stackoverflow.com/questions/17904216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2209860/"
] |
[NumPy](http://www.numpy.org/) would actually let you do that!
```
>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> i = 2
>>> a[i*2::2] *= (i-1.0)/i
>>> a
array([0, 1, 2, 3, 2, 5, 3, 7, 4, 9])
```
If you can't use NumPy or prefer not to, a loop would probably be clearest:
```
>>> a = range(10)
>>> for j in range(i*2, len(a), i):
# Not *= since we want ints
... a[j] = a[j] * (i - 1) / i
```
|
Per your edit, you can do this with a range.
```
for i in range(1, len(listnums), 2):
listnums[i] /= 2
```
If you want to do this with a list comprehension, you can do it similarly to the other version using `enumerate`.
```
def sieve(listnums, divisor):
return [num if i % divisor else num/divisor for i, num in enumerate(listnums, 1)]
```
|
17,904,216
|
I've done some searches, but I'm actually not sure of the way to word what I want to take place, so I started a question. I'm sure its been covered before, so my apologies.
The code below doesn't work, but hopefully it illustrates what I'm trying to do.
```
sieve[i*2::i] *= ((i-1) / i):
```
I want to take a list and go through each item in the list that is a multiple of "i" and change its value by multiplying by the same amount.
So for example if I had a list
```
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
and I want to start at 2 and change every 2nd item in the list, by itself \* (2 - 1 ) / 2. So after it would look like
```
[1, 2, 3, 2, 5, 3, 7, 4, 9, 5]
```
how do I do that pythonically?
thank you very much!
EDIT to add:
sorry, I see where my poor wording has caused some confusion (ive changed it in the above).
I dont want to change every multiple of 2, I want to change every second item in the list, even if its not a multiple of 2. So I cant use x % 2 == 0. Sorry!
|
2013/07/28
|
[
"https://Stackoverflow.com/questions/17904216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2209860/"
] |
You can use Python's [extended slicing](http://docs.python.org/release/2.3.5/whatsnew/section-slices.html) and slice assignment to do that:
```
>>> li=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> li[3::2]=[x/2 for x in li[3::2]]
>>> li
[1, 2, 3, 2, 5, 3, 7, 4, 9, 5]
```
|
Per your edit, you can do this with a range.
```
for i in range(1, len(listnums), 2):
listnums[i] /= 2
```
If you want to do this with a list comprehension, you can do it similarly to the other version using `enumerate`.
```
def sieve(listnums, divisor):
return [num if i % divisor else num/divisor for i, num in enumerate(listnums, 1)]
```
|
17,904,216
|
I've done some searches, but I'm actually not sure of the way to word what I want to take place, so I started a question. I'm sure its been covered before, so my apologies.
The code below doesn't work, but hopefully it illustrates what I'm trying to do.
```
sieve[i*2::i] *= ((i-1) / i):
```
I want to take a list and go through each item in the list that is a multiple of "i" and change its value by multiplying by the same amount.
So for example if I had a list
```
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
and I want to start at 2 and change every 2nd item in the list, by itself \* (2 - 1 ) / 2. So after it would look like
```
[1, 2, 3, 2, 5, 3, 7, 4, 9, 5]
```
how do I do that pythonically?
thank you very much!
EDIT to add:
sorry, I see where my poor wording has caused some confusion (ive changed it in the above).
I dont want to change every multiple of 2, I want to change every second item in the list, even if its not a multiple of 2. So I cant use x % 2 == 0. Sorry!
|
2013/07/28
|
[
"https://Stackoverflow.com/questions/17904216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2209860/"
] |
[NumPy](http://www.numpy.org/) would actually let you do that!
```
>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> i = 2
>>> a[i*2::2] *= (i-1.0)/i
>>> a
array([0, 1, 2, 3, 2, 5, 3, 7, 4, 9])
```
If you can't use NumPy or prefer not to, a loop would probably be clearest:
```
>>> a = range(10)
>>> for j in range(i*2, len(a), i):
# Not *= since we want ints
... a[j] = a[j] * (i - 1) / i
```
|
You can use Python's [extended slicing](http://docs.python.org/release/2.3.5/whatsnew/section-slices.html) and slice assignment to do that:
```
>>> li=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> li[3::2]=[x/2 for x in li[3::2]]
>>> li
[1, 2, 3, 2, 5, 3, 7, 4, 9, 5]
```
|
50,567,475
|
I am upgrading my django application from `Django 1.5` to `Django 1.7`. While upgrading I am getting `django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet` error. I tried with some solution I got by searching. But nothing is worked for me. I think it because of one of my model. Please help me to fix this.
```
Traceback (most recent call last):
File "./manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute
django.setup()
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/apps/config.py", line 197, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/venkat/sample-applications/wfmis-django-upgrade/wfmis-upgrade/django-pursuite/apps/admin/models/__init__.py", line 14, in <module>
from occupational_standard import *
File "/home/venkat/sample-applications/wfmis-django-upgrade/wfmis-upgrade/django-pursuite/apps/admin/models/occupational_standard.py", line 160, in <module>
admin.site.register(OccupationalStandard, OccupationalStandardAdmin)
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 99, in register
admin_class.check(model)
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 153, in check
return cls.checks_class().check(cls, model, **kwargs)
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/contrib/admin/checks.py", line 497, in check
errors.extend(self._check_list_filter(cls, model))
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/contrib/admin/checks.py", line 668, in _check_list_filter
for index, item in enumerate(cls.list_filter)
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/contrib/admin/checks.py", line 713, in _check_list_filter_item
get_fields_from_path(model, field)
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/contrib/admin/utils.py", line 457, in get_fields_from_path
fields.append(parent._meta.get_field_by_name(piece)[0])
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/db/models/options.py", line 416, in get_field_by_name
cache = self.init_name_map()
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/db/models/options.py", line 445, in init_name_map
for f, model in self.get_all_related_m2m_objects_with_model():
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/db/models/options.py", line 563, in get_all_related_m2m_objects_with_model
cache = self._fill_related_many_to_many_cache()
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/db/models/options.py", line 577, in _fill_related_many_to_many_cache
for klass in self.apps.get_models():
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/utils/lru_cache.py", line 101, in wrapper
result = user_function(*args, **kwds)
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 168, in get_models
self.check_models_ready()
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 131, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
```
This is my project strucutre.
[](https://i.stack.imgur.com/K8C1p.jpg)
setting.py
```
INSTALLED_APPS = (
'admin.apps.AdminConfig',
'account.apps.AccountConfig',
'...............'
)
```
wsgi.py
```
import os
import sys
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(PROJECT_ROOT, '../apps'))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pursuite.settings.production")
import settings
import django.core.management
django.core.management.setup_environ(settings) # Setup settings for core mgmt
utility = django.core.management.ManagementUtility()
command = utility.fetch_command('runserver')
command.validate()
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
```
apps/admin/apps.py
```
from django.apps import AppConfig
class AdminConfig(AppConfig):
name = 'apps.admin'
label = 'wfmis_admin'
```
apps/admin/models/occupational\_standard.py
```
from tinymce.models import HTMLField
from django.db import models
from django.contrib import admin
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.core.exceptions import ValidationError
from haystack import indexes
from .validators import validate_os_code, validate_version
import admin.common as common
__all__ = ['OccupationalStandard', 'OccupationalStandardIndex']
class OccupationalStandard(models.Model):
'''
Occupational Standard
'''
class Meta:
'''
Meta properties for this model
'''
app_label = 'wfmis_admin'
unique_together = ('code', 'version')
code = models.CharField(
max_length=9, default=None, validators=[validate_os_code],
db_index=True,
)
version = models.CharField(
max_length=8, default=None, validators=[validate_version],
db_index=True,
)
is_draft = models.BooleanField(default=True, verbose_name="Draft")
sub_sector = models.ForeignKey(
'SubSector', db_index=True, verbose_name="Industry Sub-sector",
)
title = models.CharField(
max_length=50, default=None, db_index=True, verbose_name="Unit Title",
)
description = models.TextField(default=None)
scope = HTMLField(default=None)
performace_criteria = HTMLField(default=None)
knowledge = HTMLField(default=None)
skills = HTMLField(default=None)
attachment = models.FileField(upload_to='os_attachments')
drafted_on = models.DateTimeField(auto_now_add=True)
last_reviewed_on = models.DateTimeField(auto_now=True) # Write date
next_review_on = models.DateField()
def __unicode__(self):
'''
Returns object display name. This comprises code and version.
For example: SSC/O2601-V0.1
'''
return "%s-V%s%s (%s)" % (
self.code, self.version, "draft" if self.is_draft else "",
self.title,
)
@property
def sector(self):
"""
Returns sector corresponding to occupational standard.
"""
return self.sub_sector.sector
def get_absolute_url(self):
'''
get absolute url
'''
return reverse('occupational_standard', args=(self.code,))
def clean(self):
'''
Validate model instance
'''
if OccupationalStandard.objects.filter(code=self.code, is_draft=True) \
.exclude(pk=self.pk):
# Check one OS should have one version in draft
raise ValidationError(
'There is already a version in draft for %s' % self.code
)
```
Reference links : [Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet](https://stackoverflow.com/questions/25537905/django-1-7-throws-django-core-exceptions-appregistrynotready-models-arent-load)
|
2018/05/28
|
[
"https://Stackoverflow.com/questions/50567475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5939865/"
] |
From the traceback I see the following:
```
File "/home/venkat/sample-applications/wfmis-django-upgrade/wfmis-upgrade/django-pursuite/apps/admin/models/__init__.py", line 14, in <module>
from occupational_standard import *
File "/home/venkat/sample-applications/wfmis-django-upgrade/wfmis-upgrade/django-pursuite/apps/admin/models/occupational_standard.py", line 160, in <module>
admin.site.register(OccupationalStandard, OccupationalStandardAdmin)
```
There is a call to `admin.site.register` in the `models`. Registering models should happen in `admin` not in `models`.
|
Stop the venv before upgrading django.
Stop the server before upgrading.
Update to 1.7 style wsgi handler.
Also, use pip to manage & upgrade packages, your script is bound to break the packages otherwise.
|
11,055,165
|
From a file, i have taken a line, split the line into 5 columns using `split()`. But i have to write those columns as tab separated values in an output file.
Lets say that i have `l[1], l[2], l[3], l[4], l[5]`...a total of 5 entries. How can i achieve this using python? And also, i am not able to write `l[1], l[2], l[3], l[4], l[5]` values to an output file.
I tried both these codes, both not working(i am using python 2.6):
code 1:
```
with open('output', 'w'):
print l[1], l[2], l[3], l[4], l[5] > output
```
code 2:
```
with open('output', 'w') as outf:
outf.write(l[1], l[2], l[3], l[4], l[5])
```
|
2012/06/15
|
[
"https://Stackoverflow.com/questions/11055165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1411416/"
] |
The `write()` method takes a string as its first argument (not a variable number of strings). Try this:
```
outf.write(l[1] + l[2] + l[3] + l[4] + l[5])
```
or better yet:
```
outf.write('\t'.join(l) + '\n')
```
|
```
outf.write('{0[1]}\t{0[2]}\t{0[3]}\t{0[4]}\t{0[4]}\n'.format(l))
```
will write the data to the file tab separated. Note that write doesn't automatically append a `\n`, so if you need it you'll have to supply it yourself.
Also, it's better to open the file using `with`:
```
with open('output', 'w') as outf:
outf.write('{0[1]}\t{0[2]}\t{0[3]}\t{0[4]}\t{0[4]}\n'.format(l))
```
as this will automatically close your file for you when you are done or an exception is encountered.
|
11,055,165
|
From a file, i have taken a line, split the line into 5 columns using `split()`. But i have to write those columns as tab separated values in an output file.
Lets say that i have `l[1], l[2], l[3], l[4], l[5]`...a total of 5 entries. How can i achieve this using python? And also, i am not able to write `l[1], l[2], l[3], l[4], l[5]` values to an output file.
I tried both these codes, both not working(i am using python 2.6):
code 1:
```
with open('output', 'w'):
print l[1], l[2], l[3], l[4], l[5] > output
```
code 2:
```
with open('output', 'w') as outf:
outf.write(l[1], l[2], l[3], l[4], l[5])
```
|
2012/06/15
|
[
"https://Stackoverflow.com/questions/11055165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1411416/"
] |
You can use a parameter in the `with` statement representing the file you're writing to. From there, use `.write()`. This assumes that everything in `l` is a string, otherwise you'd have to wrap all of them with `str()`.
```
with open('output', 'w') as f:
f.write(l[1] + "\t" + l[2] + "\t" + l[3] + "\t" + l[4] + "\t" + l[5] + "\n")
```
Alternatively, and more efficiently, you can use `.join()`:
```
with open('output', 'w') as f:
f.write('\t'.join(l[1:]) + '\n')
```
|
The `write()` method takes a string as its first argument (not a variable number of strings). Try this:
```
outf.write(l[1] + l[2] + l[3] + l[4] + l[5])
```
or better yet:
```
outf.write('\t'.join(l) + '\n')
```
|
11,055,165
|
From a file, i have taken a line, split the line into 5 columns using `split()`. But i have to write those columns as tab separated values in an output file.
Lets say that i have `l[1], l[2], l[3], l[4], l[5]`...a total of 5 entries. How can i achieve this using python? And also, i am not able to write `l[1], l[2], l[3], l[4], l[5]` values to an output file.
I tried both these codes, both not working(i am using python 2.6):
code 1:
```
with open('output', 'w'):
print l[1], l[2], l[3], l[4], l[5] > output
```
code 2:
```
with open('output', 'w') as outf:
outf.write(l[1], l[2], l[3], l[4], l[5])
```
|
2012/06/15
|
[
"https://Stackoverflow.com/questions/11055165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1411416/"
] |
You can use a parameter in the `with` statement representing the file you're writing to. From there, use `.write()`. This assumes that everything in `l` is a string, otherwise you'd have to wrap all of them with `str()`.
```
with open('output', 'w') as f:
f.write(l[1] + "\t" + l[2] + "\t" + l[3] + "\t" + l[4] + "\t" + l[5] + "\n")
```
Alternatively, and more efficiently, you can use `.join()`:
```
with open('output', 'w') as f:
f.write('\t'.join(l[1:]) + '\n')
```
|
```
outf.write('{0[1]}\t{0[2]}\t{0[3]}\t{0[4]}\t{0[4]}\n'.format(l))
```
will write the data to the file tab separated. Note that write doesn't automatically append a `\n`, so if you need it you'll have to supply it yourself.
Also, it's better to open the file using `with`:
```
with open('output', 'w') as outf:
outf.write('{0[1]}\t{0[2]}\t{0[3]}\t{0[4]}\t{0[4]}\n'.format(l))
```
as this will automatically close your file for you when you are done or an exception is encountered.
|
56,899,892
|
I am following along with this pycon video on python packaging.
I have a directory:
* `mypackage/`
+ `__init__.py`
+ `mypackage.py`
* `readme.md`
* `setup.py`
The contents of `mypackage.py`:
```
class MyPackage():
'''
My Damn Package
'''
def spam(self):
return "eggs"
```
The contents of `setup.py`:
```
import setuptools
setuptools.setup(
name='mypackage',
version='0.0.1',
description='My first package',
packages=setuptools.find_packages()
)
```
Now I create a virtual env and install the package with:
```
pip install -e .
```
Now I do:
```
python
>>> import mypackage
>>> mypackage.MyPackage().spam()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'mypackage' has no attribute 'MyPackage'
```
Why is this not working as per the guy's tutorial?
|
2019/07/05
|
[
"https://Stackoverflow.com/questions/56899892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2118666/"
] |
First, you usually can find the root cause on **last** `Caused by` statement for debugging.
Therefore, according to the error log you posted, `Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set` should be key!
Although Hibernate is database agnostic, we can specify the current database dialect to let it generate better SQL queries for that database. Therefore, this exception can be solved by simply identifying `hibernate.dialect` in your properties file as follows:
For application.properties:
```
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
```
For application.yml:
```
spring:
jpa:
database-platform: org.hibernate.dialect.MySQL5Dialect
```
|
In my case:
1. I have created **separate new project** with the **same code** and in the **same work-space**.
2. Started the application.
3. This time tomcat started successfully in the first instance itself.
|
56,899,892
|
I am following along with this pycon video on python packaging.
I have a directory:
* `mypackage/`
+ `__init__.py`
+ `mypackage.py`
* `readme.md`
* `setup.py`
The contents of `mypackage.py`:
```
class MyPackage():
'''
My Damn Package
'''
def spam(self):
return "eggs"
```
The contents of `setup.py`:
```
import setuptools
setuptools.setup(
name='mypackage',
version='0.0.1',
description='My first package',
packages=setuptools.find_packages()
)
```
Now I create a virtual env and install the package with:
```
pip install -e .
```
Now I do:
```
python
>>> import mypackage
>>> mypackage.MyPackage().spam()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'mypackage' has no attribute 'MyPackage'
```
Why is this not working as per the guy's tutorial?
|
2019/07/05
|
[
"https://Stackoverflow.com/questions/56899892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2118666/"
] |
First, you usually can find the root cause on **last** `Caused by` statement for debugging.
Therefore, according to the error log you posted, `Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set` should be key!
Although Hibernate is database agnostic, we can specify the current database dialect to let it generate better SQL queries for that database. Therefore, this exception can be solved by simply identifying `hibernate.dialect` in your properties file as follows:
For application.properties:
```
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
```
For application.yml:
```
spring:
jpa:
database-platform: org.hibernate.dialect.MySQL5Dialect
```
|
1: please create a new project, make it work well, and the tomcat is working well, 2: then copy the codes which you had write with your old project to the new
project.
3: is's work very well
it's maybe the old workplace with old project is broken, wo can't repair it
i hope i can help you!
|
56,899,892
|
I am following along with this pycon video on python packaging.
I have a directory:
* `mypackage/`
+ `__init__.py`
+ `mypackage.py`
* `readme.md`
* `setup.py`
The contents of `mypackage.py`:
```
class MyPackage():
'''
My Damn Package
'''
def spam(self):
return "eggs"
```
The contents of `setup.py`:
```
import setuptools
setuptools.setup(
name='mypackage',
version='0.0.1',
description='My first package',
packages=setuptools.find_packages()
)
```
Now I create a virtual env and install the package with:
```
pip install -e .
```
Now I do:
```
python
>>> import mypackage
>>> mypackage.MyPackage().spam()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'mypackage' has no attribute 'MyPackage'
```
Why is this not working as per the guy's tutorial?
|
2019/07/05
|
[
"https://Stackoverflow.com/questions/56899892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2118666/"
] |
First, you usually can find the root cause on **last** `Caused by` statement for debugging.
Therefore, according to the error log you posted, `Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set` should be key!
Although Hibernate is database agnostic, we can specify the current database dialect to let it generate better SQL queries for that database. Therefore, this exception can be solved by simply identifying `hibernate.dialect` in your properties file as follows:
For application.properties:
```
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
```
For application.yml:
```
spring:
jpa:
database-platform: org.hibernate.dialect.MySQL5Dialect
```
|
Probably the port that tomcat is starting is busy. Check this.
Or simply define another port for your project, edit the ***application.properties*** file with the instruction.
Example
```
server.port=9000
```
|
56,899,892
|
I am following along with this pycon video on python packaging.
I have a directory:
* `mypackage/`
+ `__init__.py`
+ `mypackage.py`
* `readme.md`
* `setup.py`
The contents of `mypackage.py`:
```
class MyPackage():
'''
My Damn Package
'''
def spam(self):
return "eggs"
```
The contents of `setup.py`:
```
import setuptools
setuptools.setup(
name='mypackage',
version='0.0.1',
description='My first package',
packages=setuptools.find_packages()
)
```
Now I create a virtual env and install the package with:
```
pip install -e .
```
Now I do:
```
python
>>> import mypackage
>>> mypackage.MyPackage().spam()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'mypackage' has no attribute 'MyPackage'
```
Why is this not working as per the guy's tutorial?
|
2019/07/05
|
[
"https://Stackoverflow.com/questions/56899892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2118666/"
] |
First, you usually can find the root cause on **last** `Caused by` statement for debugging.
Therefore, according to the error log you posted, `Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set` should be key!
Although Hibernate is database agnostic, we can specify the current database dialect to let it generate better SQL queries for that database. Therefore, this exception can be solved by simply identifying `hibernate.dialect` in your properties file as follows:
For application.properties:
```
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
```
For application.yml:
```
spring:
jpa:
database-platform: org.hibernate.dialect.MySQL5Dialect
```
|
Resolved it by adding a missing property to application.properties file.
spring.jpa.hibernate.ddl-auto=update
|
56,899,892
|
I am following along with this pycon video on python packaging.
I have a directory:
* `mypackage/`
+ `__init__.py`
+ `mypackage.py`
* `readme.md`
* `setup.py`
The contents of `mypackage.py`:
```
class MyPackage():
'''
My Damn Package
'''
def spam(self):
return "eggs"
```
The contents of `setup.py`:
```
import setuptools
setuptools.setup(
name='mypackage',
version='0.0.1',
description='My first package',
packages=setuptools.find_packages()
)
```
Now I create a virtual env and install the package with:
```
pip install -e .
```
Now I do:
```
python
>>> import mypackage
>>> mypackage.MyPackage().spam()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'mypackage' has no attribute 'MyPackage'
```
Why is this not working as per the guy's tutorial?
|
2019/07/05
|
[
"https://Stackoverflow.com/questions/56899892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2118666/"
] |
Resolved it by adding a missing property to application.properties file.
spring.jpa.hibernate.ddl-auto=update
|
In my case:
1. I have created **separate new project** with the **same code** and in the **same work-space**.
2. Started the application.
3. This time tomcat started successfully in the first instance itself.
|
56,899,892
|
I am following along with this pycon video on python packaging.
I have a directory:
* `mypackage/`
+ `__init__.py`
+ `mypackage.py`
* `readme.md`
* `setup.py`
The contents of `mypackage.py`:
```
class MyPackage():
'''
My Damn Package
'''
def spam(self):
return "eggs"
```
The contents of `setup.py`:
```
import setuptools
setuptools.setup(
name='mypackage',
version='0.0.1',
description='My first package',
packages=setuptools.find_packages()
)
```
Now I create a virtual env and install the package with:
```
pip install -e .
```
Now I do:
```
python
>>> import mypackage
>>> mypackage.MyPackage().spam()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'mypackage' has no attribute 'MyPackage'
```
Why is this not working as per the guy's tutorial?
|
2019/07/05
|
[
"https://Stackoverflow.com/questions/56899892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2118666/"
] |
Resolved it by adding a missing property to application.properties file.
spring.jpa.hibernate.ddl-auto=update
|
1: please create a new project, make it work well, and the tomcat is working well, 2: then copy the codes which you had write with your old project to the new
project.
3: is's work very well
it's maybe the old workplace with old project is broken, wo can't repair it
i hope i can help you!
|
56,899,892
|
I am following along with this pycon video on python packaging.
I have a directory:
* `mypackage/`
+ `__init__.py`
+ `mypackage.py`
* `readme.md`
* `setup.py`
The contents of `mypackage.py`:
```
class MyPackage():
'''
My Damn Package
'''
def spam(self):
return "eggs"
```
The contents of `setup.py`:
```
import setuptools
setuptools.setup(
name='mypackage',
version='0.0.1',
description='My first package',
packages=setuptools.find_packages()
)
```
Now I create a virtual env and install the package with:
```
pip install -e .
```
Now I do:
```
python
>>> import mypackage
>>> mypackage.MyPackage().spam()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'mypackage' has no attribute 'MyPackage'
```
Why is this not working as per the guy's tutorial?
|
2019/07/05
|
[
"https://Stackoverflow.com/questions/56899892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2118666/"
] |
Resolved it by adding a missing property to application.properties file.
spring.jpa.hibernate.ddl-auto=update
|
Probably the port that tomcat is starting is busy. Check this.
Or simply define another port for your project, edit the ***application.properties*** file with the instruction.
Example
```
server.port=9000
```
|
8,077,756
|
in my views.py i obtain 5 dicts, which all are something like {date:value}
all 5 dicts have the same length and in my template i want to obtain some urls based on these dicts, with the common field being the date - as you would do in an sql query when joining 5 tables based on a common column
in python you would do something like:
```
for key, value in loc.items():
print key, loc[key], ctg[key], sctg[key], title[key], id[key]
```
but in django templates all i could come up with is this:
```
{% for lock, locv in loc.items %}
{% for ctgk, ctgv in ctg.items %}
{% for subctgk, subctgv in subctg.items %}
{% for titlek, titlev in titlu.items %}
{% for idk, idv in id.items %}
{% ifequal lock ctgk %}
{% ifequal ctgk subctgk %}
{% ifequal subctgk titlek %}
{% ifequal titlek idk %}
<br />{{ lock|date:"d b H:i" }} - {{ locv }} - {{ ctgv }} - {{ subctgv }} - {{ titlev }} - {{idv }}
.... {% endifequals & endfors %}
```
which of course is ugly and takes a lot of time to be rendered
right now i am looking into building a custom tag, but i was wondering if you guys have any feedback on this topic?
|
2011/11/10
|
[
"https://Stackoverflow.com/questions/8077756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023857/"
] |
`youredittext.requestFocus()` call it from activity
```
oncreate();
```
and use the above code there
|
```
>>you can write your code like
if (TextUtils.isEmpty(username)) {
editTextUserName.setError("Please enter username");
editTextUserName.requestFocus();
return;
}
if (TextUtils.isEmpty(password)) {
editTextPassword.setError("Enter a password");
editTextPassword.requestFocus();
return;
}
```
|
8,077,756
|
in my views.py i obtain 5 dicts, which all are something like {date:value}
all 5 dicts have the same length and in my template i want to obtain some urls based on these dicts, with the common field being the date - as you would do in an sql query when joining 5 tables based on a common column
in python you would do something like:
```
for key, value in loc.items():
print key, loc[key], ctg[key], sctg[key], title[key], id[key]
```
but in django templates all i could come up with is this:
```
{% for lock, locv in loc.items %}
{% for ctgk, ctgv in ctg.items %}
{% for subctgk, subctgv in subctg.items %}
{% for titlek, titlev in titlu.items %}
{% for idk, idv in id.items %}
{% ifequal lock ctgk %}
{% ifequal ctgk subctgk %}
{% ifequal subctgk titlek %}
{% ifequal titlek idk %}
<br />{{ lock|date:"d b H:i" }} - {{ locv }} - {{ ctgv }} - {{ subctgv }} - {{ titlev }} - {{idv }}
.... {% endifequals & endfors %}
```
which of course is ugly and takes a lot of time to be rendered
right now i am looking into building a custom tag, but i was wondering if you guys have any feedback on this topic?
|
2011/11/10
|
[
"https://Stackoverflow.com/questions/8077756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023857/"
] |
`youredittext.requestFocus()` call it from activity
```
oncreate();
```
and use the above code there
|
Set to the Activity in Manifest:
```
android:windowSoftInputMode="adjustResize"
```
Set focus, when a view is ready:
```
fun setFocus(view: View, showKeyboard: Boolean = true){
view.post {
if (view.requestFocus() && showKeyboard)
activity?.openKeyboard() // call extension function
}
}
```
|
8,077,756
|
in my views.py i obtain 5 dicts, which all are something like {date:value}
all 5 dicts have the same length and in my template i want to obtain some urls based on these dicts, with the common field being the date - as you would do in an sql query when joining 5 tables based on a common column
in python you would do something like:
```
for key, value in loc.items():
print key, loc[key], ctg[key], sctg[key], title[key], id[key]
```
but in django templates all i could come up with is this:
```
{% for lock, locv in loc.items %}
{% for ctgk, ctgv in ctg.items %}
{% for subctgk, subctgv in subctg.items %}
{% for titlek, titlev in titlu.items %}
{% for idk, idv in id.items %}
{% ifequal lock ctgk %}
{% ifequal ctgk subctgk %}
{% ifequal subctgk titlek %}
{% ifequal titlek idk %}
<br />{{ lock|date:"d b H:i" }} - {{ locv }} - {{ ctgv }} - {{ subctgv }} - {{ titlev }} - {{idv }}
.... {% endifequals & endfors %}
```
which of course is ugly and takes a lot of time to be rendered
right now i am looking into building a custom tag, but i was wondering if you guys have any feedback on this topic?
|
2011/11/10
|
[
"https://Stackoverflow.com/questions/8077756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023857/"
] |
Programatically:
```
edittext.requestFocus();
```
Through xml:
```
<EditText...>
<requestFocus />
</EditText>
```
Or call onClick method manually.
|
```
>>you can write your code like
if (TextUtils.isEmpty(username)) {
editTextUserName.setError("Please enter username");
editTextUserName.requestFocus();
return;
}
if (TextUtils.isEmpty(password)) {
editTextPassword.setError("Enter a password");
editTextPassword.requestFocus();
return;
}
```
|
8,077,756
|
in my views.py i obtain 5 dicts, which all are something like {date:value}
all 5 dicts have the same length and in my template i want to obtain some urls based on these dicts, with the common field being the date - as you would do in an sql query when joining 5 tables based on a common column
in python you would do something like:
```
for key, value in loc.items():
print key, loc[key], ctg[key], sctg[key], title[key], id[key]
```
but in django templates all i could come up with is this:
```
{% for lock, locv in loc.items %}
{% for ctgk, ctgv in ctg.items %}
{% for subctgk, subctgv in subctg.items %}
{% for titlek, titlev in titlu.items %}
{% for idk, idv in id.items %}
{% ifequal lock ctgk %}
{% ifequal ctgk subctgk %}
{% ifequal subctgk titlek %}
{% ifequal titlek idk %}
<br />{{ lock|date:"d b H:i" }} - {{ locv }} - {{ ctgv }} - {{ subctgv }} - {{ titlev }} - {{idv }}
.... {% endifequals & endfors %}
```
which of course is ugly and takes a lot of time to be rendered
right now i am looking into building a custom tag, but i was wondering if you guys have any feedback on this topic?
|
2011/11/10
|
[
"https://Stackoverflow.com/questions/8077756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023857/"
] |
Programatically:
```
edittext.requestFocus();
```
Through xml:
```
<EditText...>
<requestFocus />
</EditText>
```
Or call onClick method manually.
|
having the soft keyboard disabled (only external keyboards enabled), I fixed it by moving the cursors at the end on the EditText:
```
editText.setSelection(editText.getText().length)
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.