qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
50,956,396 | I wanted to find an intersection between two arraylist that are of byte[] format and return the common indices. I have the code as follows and it works correctly:
```
ArrayList<Integer> intersect = new ArrayList<Integer>();
for(int j = 0; j < A.size(); j++)
{
byte [] t = A.get(j);
for (int j1 = 0; j1 < B.size(); j1++)
{
byte[] t1 = B.get(j1);
if (Arrays.equals(t, t1))
{
intersect.add(j);
break;
}
}
}
```
However, as you can see, I have to use two for loops. Is there any way I can do it without using any for loops? I have tried to use **"retainAll"** but for some reason, it kept giving me an empty array. What can be the possible reason for that? | 2018/06/20 | [
"https://Stackoverflow.com/questions/50956396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9732420/"
] | If you just dont want to use for loops, you may try the Java 8 streams, since you have not shared the complete code I did not try it out.
```
List<T> intersect = list1.stream()
.filter(list2::contains)
.collect(Collectors.toList());
``` | This may help:
```
public <T> List<T> intersection(List<T> list1, List<T> list2) {
List<T> list = new ArrayList<T>();
for (T t : list1) {
if(list2.contains(t)) {
list.add(t);
}
}
return list;
}
```
Reference:
[Intersection and union of ArrayLists in Java](https://stackoverflow.com/questions/5283047/intersection-and-union-of-arraylists-in-java) |
50,956,396 | I wanted to find an intersection between two arraylist that are of byte[] format and return the common indices. I have the code as follows and it works correctly:
```
ArrayList<Integer> intersect = new ArrayList<Integer>();
for(int j = 0; j < A.size(); j++)
{
byte [] t = A.get(j);
for (int j1 = 0; j1 < B.size(); j1++)
{
byte[] t1 = B.get(j1);
if (Arrays.equals(t, t1))
{
intersect.add(j);
break;
}
}
}
```
However, as you can see, I have to use two for loops. Is there any way I can do it without using any for loops? I have tried to use **"retainAll"** but for some reason, it kept giving me an empty array. What can be the possible reason for that? | 2018/06/20 | [
"https://Stackoverflow.com/questions/50956396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9732420/"
] | I think for `T` your solution with brutforce is not so bad. This is a small refactoring of it. Yes, for specific `T` (e.g. `int`) you could use special structures, but in general case, I think this is not implementable.
```
public static <T> List<Integer> intersect(List<T> A, List<T> B, BiPredicate<T, T> isEqual) {
List<Integer> intersect = new LinkedList<>();
int i = -1;
for (T a : A) {
i++;
if (B.stream().anyMatch(b -> isEqual.test(a, b)))
intersect.add(i);
}
return intersect;
}
```
Client code could look like:
```
List<byte[]> a = Collections.emptyList();
List<byte[]> b = Collections.emptyList();
List<Integer> intersect = intersect(a, b, Arrays::equals);
``` | This may help:
```
public <T> List<T> intersection(List<T> list1, List<T> list2) {
List<T> list = new ArrayList<T>();
for (T t : list1) {
if(list2.contains(t)) {
list.add(t);
}
}
return list;
}
```
Reference:
[Intersection and union of ArrayLists in Java](https://stackoverflow.com/questions/5283047/intersection-and-union-of-arraylists-in-java) |
3,145 | I recently upgraded my site from SharePoint 2007 to SharePoint 2010.
The first issue I noticed was that the "lookup" columns in "Display view" showed up as the hyperlink instead of the string.
```
Salesman "<a onclick="OpenPopUpPage('http://sharepoint2010:72/blackbook/_layouts/listform.aspx?PageType=4&ListId={FB9575AE-F747-49F1-9122-D15D095C7D0A}&ID=1&RootFolder=*', RefreshPage); return false;" href="[http://sharepoint2010:72/blackbook/_layouts/listform.aspx?PageType=4&ListId={FB9575AE-F747-49F1-9122-D15D095C7D0A}&ID=1&RootFolder=*">RRH</a>
```
I fixed it in SharePoint Designer by right clicking on it and "Format Item as... Label". Afterwards my string shows up, but as a hyperlink.
`Salesman RRH` -> RRH is a hyperlink
The problem is that I have a javascript pushing values of 8 of my columns to a "New Item".
All of the "text" and "number" columns work just as they did in SP2007, but the "Lookup" columns send the hyperlink.
Does anyone know how to resolve this? | 2010/05/26 | [
"https://sharepoint.stackexchange.com/questions/3145",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/-1/"
] | 1- one solution is to use XPath functions to extract the simple inner text. see below sample
```
<xsl:value-of select="substring-before( substring-after(@Service_, '>') , '<') "/>
```
you can use some useful auto-complete XPath editor or more advanced editor in ribbon (see below image)
[](https://i.stack.imgur.com/SA3Ka.png)
2- note the **disable-output-escaping="yes"** attribute which essentially disable escaping of final tag attribute which leads to seeing
```
<xsl:value-of disable-output-escaping="yes" select="@Vendor_"/>
``` | Check this URL
This may help u
<http://www.chakkaradeep.com/post/Using-the-SharePoint-2010-Modal-Dialog.aspx> |
39,740,575 | I used `DownloadManager` to download a file from server, I expect when the network is not connected to internet I receive `STATUS_PAUSED` in `BroadcastReceiver`. But it doesn't call `onReceive()`.
```
downloadReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// ...
}
}
registerReceiver(downloadReceiver,
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
``` | 2016/09/28 | [
"https://Stackoverflow.com/questions/39740575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5221941/"
] | What you are trying to do doesn't make any sense.
As mentioned on [Beautiful Soup Documentation](https://www.crummy.com/software/BeautifulSoup/bs4/doc/):
>
> Beautiful Soup is a Python library for pulling data out of HTML and XML files. It works with your favorite parser to provide idiomatic ways of navigating, searching, and modifying the parse tree. It commonly saves programmers hours or days of work.
>
>
>
You do not seem to be pulling any data but you are trying to write a `BeautifulSoup` object into a file which doesn't make sense.
```
>>> type(data)
<class 'bs4.BeautifulSoup'>
```
What you should be using [`BeautifulSoup`](https://www.crummy.com/software/BeautifulSoup/bs4/doc/) for is to search the data for some information, and then use that information, here's a useless example:
```
from bs4 import BeautifulSoup
import requests
page = requests.get("http://www.gigantti.fi/catalog/tietokoneet/fi_kannettavat/kannettavat-tietokoneet")
data = BeautifulSoup(page.content)
with open("test.txt", "wb+") as f:
# find the first `<title>` tag and retrieve its value
value = data.findAll('title')[0].text
f.write(value)
```
It seems like you should be using `BeautifulSoup` to be retreiving all the information on each product in the product listing and putting them into columns in a csv file if I'm guessing correctly, but I will leave that work up to you. You must use `BeautifulSoup` to find each product in the `html` and then retrieve all of its details and print to a csv | I don't know whether someone was able to solve it or not but my hit and trial worked. the problem was I was not converting the content to string.
```
#what i needed to add was:
#after line data=BeautifulSoup(page.content)
a=str(data)
```
Hopefully this helps |
58,805,703 | I'm new to this VBA for excel.
I'm trying to write some code that will check (for 2 specific columns: let' say C and I) until it comes to a specific text and copies the column next to that value (from the column before) in a different spreadsheet.
For Example, check if in column **C** and column **I** the word "Yes" exist:
[](https://i.stack.imgur.com/93Iq5.png)
If so, paste the Value (in the corresponding value in the Column before) in this case.
the cell: (1,2): **2000** and cell (2,9): **98** in a new spreadsheet.
[](https://i.stack.imgur.com/XmOgt.png)
So far I've built this code (it only check the column **C)**
The **1st part** (only check if the value that I'm searching exists)
```
Sub Button1_Click()
Dim i As Long
With Worksheets("Sheet1") ' t
On Error Resume Next
i = Application.WorksheetFunction.Match("Yes", .Range("C:C"), 0)
On Error GoTo 0
If i <> 0 Then
MsgBox "Yes found at " & .Cells(i, 3).Address(0, 0)
Else
MsgBox "Yes not found in Column"
End If
End With
End Sub
```
But I'm stuck when I try to implement the **2nd part** (copy the value from the column beside and paste it on a different spreadsheet) | 2019/11/11 | [
"https://Stackoverflow.com/questions/58805703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11613489/"
] | You can do that without a rotation matrix, just by vector calculus.
A point `S` along the line through `P` and `Q` is computed by `P + t.PQ` where `t` is a scalar. Now take any point in space, let `R` and find its orthogonal projection `S` on the line, by solving `RS.PQ = 0` or `(RP + t.PQ).PQ = 0`, or `t = - RP.PQ / PQ.PQ`.
The vector `RS` defines the direction of a diagonal of the square. Hence we find a first vertex `R'` at length `L/√2` along `SR` by applying a coefficient `L/√2|SR|`.
A second vertex `U` is such that `U = S + R'S`.
The remaining two vertices `V` and `W` are found by constructing the vector `VS` orthogonal to `RS` using a cross product with the direction of the line, `R'S x PQ/|PQ|`.
[](https://i.stack.imgur.com/wNLrM.png) | Quaternions are interesting, but not necessary. A rotation matrix can be used here.
Outline of the algorithm:
* suppose p1 and p2 are the 3D points of the line
* let p1p2 be the normalized vector from p1 towards p2 (normalize(p2-p1))
* place four points s1, s2, s3, s4 at (0,1,1), (0,1,-1), (0,-1,-1), (0,-1,1); these are the initial positions of the points forming a square perpendicular to the x-axis; if too small, just multiply them by a desired size
* let xvec be a unit x-vector (1, 0, 0)
* let axis be the crossproduct of p1p2 and xvec
* if the norm of axis is zero, no rotation is needed --> skip the rotation steps, else:
+ theta = acos(dotproduct(xvec, p1p2))
+ build a rotation matrix as in [this wikipedia page](https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle) using theta and axis
+ multiply s1, s2, s3, s4 with the rotation matrix
* add p1 to s1, s2, s3, s4 to get the square at position p1
* add p2 to s1, s2, s3, s4 to get the square at position p2
PS: If you choose s1, s2, s3, s4 as (1,0,1), (1,0,-1), (-1,0,-1), (-1,0,1), you can do the same with yvec = (0,1,0) |
58,805,703 | I'm new to this VBA for excel.
I'm trying to write some code that will check (for 2 specific columns: let' say C and I) until it comes to a specific text and copies the column next to that value (from the column before) in a different spreadsheet.
For Example, check if in column **C** and column **I** the word "Yes" exist:
[](https://i.stack.imgur.com/93Iq5.png)
If so, paste the Value (in the corresponding value in the Column before) in this case.
the cell: (1,2): **2000** and cell (2,9): **98** in a new spreadsheet.
[](https://i.stack.imgur.com/XmOgt.png)
So far I've built this code (it only check the column **C)**
The **1st part** (only check if the value that I'm searching exists)
```
Sub Button1_Click()
Dim i As Long
With Worksheets("Sheet1") ' t
On Error Resume Next
i = Application.WorksheetFunction.Match("Yes", .Range("C:C"), 0)
On Error GoTo 0
If i <> 0 Then
MsgBox "Yes found at " & .Cells(i, 3).Address(0, 0)
Else
MsgBox "Yes not found in Column"
End If
End With
End Sub
```
But I'm stuck when I try to implement the **2nd part** (copy the value from the column beside and paste it on a different spreadsheet) | 2019/11/11 | [
"https://Stackoverflow.com/questions/58805703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11613489/"
] | You can do that without a rotation matrix, just by vector calculus.
A point `S` along the line through `P` and `Q` is computed by `P + t.PQ` where `t` is a scalar. Now take any point in space, let `R` and find its orthogonal projection `S` on the line, by solving `RS.PQ = 0` or `(RP + t.PQ).PQ = 0`, or `t = - RP.PQ / PQ.PQ`.
The vector `RS` defines the direction of a diagonal of the square. Hence we find a first vertex `R'` at length `L/√2` along `SR` by applying a coefficient `L/√2|SR|`.
A second vertex `U` is such that `U = S + R'S`.
The remaining two vertices `V` and `W` are found by constructing the vector `VS` orthogonal to `RS` using a cross product with the direction of the line, `R'S x PQ/|PQ|`.
[](https://i.stack.imgur.com/wNLrM.png) | ```
func drawline(starting_point, finishing_point):
var width = 0.1
var diference_vector = finishing_point - starting_point
var diference_vector_norm = sqrt(pow(diference_vector[0],2.0) + pow(diference_vector[1],2.0) + pow(diference_vector[2],2.0))
var normalized_difference_vector
if diference_vector_norm != 0:
normalized_difference_vector = Vector3(diference_vector[0]/diference_vector_norm, diference_vector[1]/diference_vector_norm, diference_vector[2]/diference_vector_norm)
else:
normalized_difference_vector = Vector3(0,0,0)
var s1 = Vector3(0, width, -width)
var s2 = Vector3(0, width, width)
var s3 = Vector3(0, -width, width)
var s4 = Vector3(0, -width, -width)
var x_vec = Vector3(1,0,0)
var axis_vector = normalized_difference_vector.cross(x_vec)
var axis_vector_norm = sqrt(pow(axis_vector[0],2.0) + pow(axis_vector[1],2.0) + pow(axis_vector[2],2.0))
if axis_vector_norm != 0:
var normalized_axis_vector = Vector3(axis_vector[0]/axis_vector_norm, axis_vector[1]/axis_vector_norm, axis_vector[2]/axis_vector_norm)
var theta = acos(x_vec.dot(normalized_difference_vector))
var matrix_0_0 = cos(theta) + (pow(normalized_axis_vector[0],2.0) * (1-cos(theta)))
var matrix_0_1 = (normalized_axis_vector[0] * normalized_axis_vector[1] * (1-cos(theta))) - (normalized_axis_vector[2] * sin(theta))
var matrix_0_2 = (normalized_axis_vector[0] * normalized_axis_vector[2] * (1-cos(theta))) + (normalized_axis_vector[1] * sin(theta))
var matrix_1_0 = (normalized_axis_vector[1] * normalized_axis_vector[0] * (1-cos(theta))) + (normalized_axis_vector[2] * sin(theta))
var matrix_1_1 = cos(theta) + (pow(normalized_axis_vector[1],2.0) * (1-cos(theta)))
var matrix_1_2 = (normalized_axis_vector[1] * normalized_axis_vector[2] * (1-cos(theta))) - (normalized_axis_vector[0] * sin(theta))
var matrix_2_0 = (normalized_axis_vector[2] * normalized_axis_vector[0] * (1-cos(theta))) - (normalized_axis_vector[1] * sin(theta))
var matrix_2_1 = (normalized_axis_vector[2] * normalized_axis_vector[1] * (1-cos(theta))) - (normalized_axis_vector[0] * sin(theta))
var matrix_2_2 = cos(theta) + (pow(normalized_axis_vector[2],2.0) * (1-cos(theta)))
var matrix = Transform(Vector3(matrix_0_0, matrix_0_1, matrix_0_2), Vector3(matrix_1_0, matrix_1_1, matrix_1_2), Vector3(matrix_2_0, matrix_2_1, matrix_2_2), Vector3(0,0,0))
var a1 = matrix.basis.xform(s1) + starting_point
var a2 = matrix.basis.xform(s2) + starting_point
var a3 = matrix.basis.xform(s3) + starting_point
var a4 = matrix.basis.xform(s4) + starting_point
var b1 = matrix.basis.xform(s1) + finishing_point
var b2 = matrix.basis.xform(s2) + finishing_point
var b3 = matrix.basis.xform(s3) + finishing_point
var b4 = matrix.basis.xform(s4) + finishing_point
``` |
29,367,533 | I have array with integers something like this:
```
[1, 2, 3, 6, 10]
```
My question is what is the easiest way to get lowest positive integer that is not already in this array?
Something like:
```
[1, 2, 3, 6, 10].lowest_available => 4
[1, 8, 3, 6, 10].lowest_available => 2
[5, 8, 3, 6, 10].lowest_available => 1
```
Does any one have an idea how to manage this in ruby? | 2015/03/31 | [
"https://Stackoverflow.com/questions/29367533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2945241/"
] | >
> By lowest i mean integer that is > 0 and not already in the array
>
>
>
Basically you are looking for the first value that is not equal to its `index+1` when sorted. Here:
```
def lowest_available(arr)
res = nil
arr.sort.each.with_index(1) { |a, i|
if i != a
res = i
break
end
}
res
end
lowest_available([1, 2, 3, 6, 10])
# => 4
lowest_available([1, 8, 3, 6, 10])
# => 2
lowest_available([5, 8, 3, 6, 10])
# => 1
```
**Update**
The above method can be shortened by returning value along with `break`. (As suggested by Cary and Stefan in comments below).
```
def lowest_available(arr)
arr.sort.find.with_index(1) { |a, i| break i if i != a }
end
``` | ```
class Array
def lowest_available; (1..Float::INFINITY).find{|e| include?(e).!} end
end
[1, 2, 3, 6, 10].lowest_available # => 4
[1, 8, 3, 6, 10].lowest_available # => 2
[5, 8, 3, 6, 10].lowest_available # => 1
```
or, as suggested by Stefan:
```
class Array
def lowest_available; 1.step.find{|e| include?(e).!} end
end
``` |
29,367,533 | I have array with integers something like this:
```
[1, 2, 3, 6, 10]
```
My question is what is the easiest way to get lowest positive integer that is not already in this array?
Something like:
```
[1, 2, 3, 6, 10].lowest_available => 4
[1, 8, 3, 6, 10].lowest_available => 2
[5, 8, 3, 6, 10].lowest_available => 1
```
Does any one have an idea how to manage this in ruby? | 2015/03/31 | [
"https://Stackoverflow.com/questions/29367533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2945241/"
] | >
> By lowest i mean integer that is > 0 and not already in the array
>
>
>
Basically you are looking for the first value that is not equal to its `index+1` when sorted. Here:
```
def lowest_available(arr)
res = nil
arr.sort.each.with_index(1) { |a, i|
if i != a
res = i
break
end
}
res
end
lowest_available([1, 2, 3, 6, 10])
# => 4
lowest_available([1, 8, 3, 6, 10])
# => 2
lowest_available([5, 8, 3, 6, 10])
# => 1
```
**Update**
The above method can be shortened by returning value along with `break`. (As suggested by Cary and Stefan in comments below).
```
def lowest_available(arr)
arr.sort.find.with_index(1) { |a, i| break i if i != a }
end
``` | There is a very simple way
```
def lowest_available (array)
min = array.min
max = array.max
number = (min..max).to_a - array
number = array.select { |v| v>0 }
number = number.min + 1
end
```
What I am doing is to create another array that contains all numbers in the interval of the array in question.
Once that is done, I remove the original array numbers from the created array
Then I add 1 to the lowest number |
29,367,533 | I have array with integers something like this:
```
[1, 2, 3, 6, 10]
```
My question is what is the easiest way to get lowest positive integer that is not already in this array?
Something like:
```
[1, 2, 3, 6, 10].lowest_available => 4
[1, 8, 3, 6, 10].lowest_available => 2
[5, 8, 3, 6, 10].lowest_available => 1
```
Does any one have an idea how to manage this in ruby? | 2015/03/31 | [
"https://Stackoverflow.com/questions/29367533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2945241/"
] | ```
class Array
def lowest_available; (1..Float::INFINITY).find{|e| include?(e).!} end
end
[1, 2, 3, 6, 10].lowest_available # => 4
[1, 8, 3, 6, 10].lowest_available # => 2
[5, 8, 3, 6, 10].lowest_available # => 1
```
or, as suggested by Stefan:
```
class Array
def lowest_available; 1.step.find{|e| include?(e).!} end
end
``` | There is a very simple way
```
def lowest_available (array)
min = array.min
max = array.max
number = (min..max).to_a - array
number = array.select { |v| v>0 }
number = number.min + 1
end
```
What I am doing is to create another array that contains all numbers in the interval of the array in question.
Once that is done, I remove the original array numbers from the created array
Then I add 1 to the lowest number |
29,367,533 | I have array with integers something like this:
```
[1, 2, 3, 6, 10]
```
My question is what is the easiest way to get lowest positive integer that is not already in this array?
Something like:
```
[1, 2, 3, 6, 10].lowest_available => 4
[1, 8, 3, 6, 10].lowest_available => 2
[5, 8, 3, 6, 10].lowest_available => 1
```
Does any one have an idea how to manage this in ruby? | 2015/03/31 | [
"https://Stackoverflow.com/questions/29367533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2945241/"
] | >
> By lowest i mean integer that is > 0 and not already in the array
>
>
>
Basically you are looking for the first value that is not equal to its `index+1` when sorted. Here:
```
def lowest_available(arr)
res = nil
arr.sort.each.with_index(1) { |a, i|
if i != a
res = i
break
end
}
res
end
lowest_available([1, 2, 3, 6, 10])
# => 4
lowest_available([1, 8, 3, 6, 10])
# => 2
lowest_available([5, 8, 3, 6, 10])
# => 1
```
**Update**
The above method can be shortened by returning value along with `break`. (As suggested by Cary and Stefan in comments below).
```
def lowest_available(arr)
arr.sort.find.with_index(1) { |a, i| break i if i != a }
end
``` | 1. Sort the array
2. Iterate over the array and compare each item's value with the current index+1, if this pair is not equal you found the lowest available integer which is index+1. |
29,367,533 | I have array with integers something like this:
```
[1, 2, 3, 6, 10]
```
My question is what is the easiest way to get lowest positive integer that is not already in this array?
Something like:
```
[1, 2, 3, 6, 10].lowest_available => 4
[1, 8, 3, 6, 10].lowest_available => 2
[5, 8, 3, 6, 10].lowest_available => 1
```
Does any one have an idea how to manage this in ruby? | 2015/03/31 | [
"https://Stackoverflow.com/questions/29367533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2945241/"
] | >
> By lowest i mean integer that is > 0 and not already in the array
>
>
>
Basically you are looking for the first value that is not equal to its `index+1` when sorted. Here:
```
def lowest_available(arr)
res = nil
arr.sort.each.with_index(1) { |a, i|
if i != a
res = i
break
end
}
res
end
lowest_available([1, 2, 3, 6, 10])
# => 4
lowest_available([1, 8, 3, 6, 10])
# => 2
lowest_available([5, 8, 3, 6, 10])
# => 1
```
**Update**
The above method can be shortened by returning value along with `break`. (As suggested by Cary and Stefan in comments below).
```
def lowest_available(arr)
arr.sort.find.with_index(1) { |a, i| break i if i != a }
end
``` | To get the lowest possible number > 0 in an array containing negative values, I would add something to the given solution by [@shivam](https://stackoverflow.com/a/29367766/14048071), and finally, a function looks something like this:
```rb
def lowest_element(arr)
res = nil
arr = arr.reject { |e| e < 0 }
arr.sort.each.with_index(1) do |e, i|
if i != e
res = i
break
end
end
res.nil? ? (arr.size > 0 ? arr.sort.last + 1 : 1) : res
end
lowest_element([1, 5, 6, 3, 8, 7, 2]) => 4
lowest_element([1, 5, 6, 3, 8, 7, 2, 4]) => 9
lowest_element([-1, -7, -9]) => 1
lowest_element([-1, -7, -9, 1]) => 2
lowest_element([-1, -7, -9, 0]) => 1
``` |
29,367,533 | I have array with integers something like this:
```
[1, 2, 3, 6, 10]
```
My question is what is the easiest way to get lowest positive integer that is not already in this array?
Something like:
```
[1, 2, 3, 6, 10].lowest_available => 4
[1, 8, 3, 6, 10].lowest_available => 2
[5, 8, 3, 6, 10].lowest_available => 1
```
Does any one have an idea how to manage this in ruby? | 2015/03/31 | [
"https://Stackoverflow.com/questions/29367533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2945241/"
] | >
> By lowest i mean integer that is > 0 and not already in the array
>
>
>
Basically you are looking for the first value that is not equal to its `index+1` when sorted. Here:
```
def lowest_available(arr)
res = nil
arr.sort.each.with_index(1) { |a, i|
if i != a
res = i
break
end
}
res
end
lowest_available([1, 2, 3, 6, 10])
# => 4
lowest_available([1, 8, 3, 6, 10])
# => 2
lowest_available([5, 8, 3, 6, 10])
# => 1
```
**Update**
The above method can be shortened by returning value along with `break`. (As suggested by Cary and Stefan in comments below).
```
def lowest_available(arr)
arr.sort.find.with_index(1) { |a, i| break i if i != a }
end
``` | Another way (it's late):
```
def first_missing(a)
a.reduce(0) { |tot,n|
exp=expected(tot); return exp if n>exp; tot + n }
end
def expected(tot)
((-1.0 + Math.sqrt(1.0+8*tot))/2).round + 1
end
first_missing([1, 2, 3, 6, 10]) #=> 4
first_missing([1, 8, 3, 6, 10]) #=> 2
first_missing([5, 8, 3, 6, 10]) #=> 1
``` |
29,367,533 | I have array with integers something like this:
```
[1, 2, 3, 6, 10]
```
My question is what is the easiest way to get lowest positive integer that is not already in this array?
Something like:
```
[1, 2, 3, 6, 10].lowest_available => 4
[1, 8, 3, 6, 10].lowest_available => 2
[5, 8, 3, 6, 10].lowest_available => 1
```
Does any one have an idea how to manage this in ruby? | 2015/03/31 | [
"https://Stackoverflow.com/questions/29367533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2945241/"
] | ```
class Array
def lowest_available; (1..Float::INFINITY).find{|e| include?(e).!} end
end
[1, 2, 3, 6, 10].lowest_available # => 4
[1, 8, 3, 6, 10].lowest_available # => 2
[5, 8, 3, 6, 10].lowest_available # => 1
```
or, as suggested by Stefan:
```
class Array
def lowest_available; 1.step.find{|e| include?(e).!} end
end
``` | Another way (it's late):
```
def first_missing(a)
a.reduce(0) { |tot,n|
exp=expected(tot); return exp if n>exp; tot + n }
end
def expected(tot)
((-1.0 + Math.sqrt(1.0+8*tot))/2).round + 1
end
first_missing([1, 2, 3, 6, 10]) #=> 4
first_missing([1, 8, 3, 6, 10]) #=> 2
first_missing([5, 8, 3, 6, 10]) #=> 1
``` |
29,367,533 | I have array with integers something like this:
```
[1, 2, 3, 6, 10]
```
My question is what is the easiest way to get lowest positive integer that is not already in this array?
Something like:
```
[1, 2, 3, 6, 10].lowest_available => 4
[1, 8, 3, 6, 10].lowest_available => 2
[5, 8, 3, 6, 10].lowest_available => 1
```
Does any one have an idea how to manage this in ruby? | 2015/03/31 | [
"https://Stackoverflow.com/questions/29367533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2945241/"
] | Not that elegant, but if your arrays are small, you could create the entire integer array and use [`Array#-`](http://ruby-doc.org/core-2.2.1/Array.html#method-i-2D) to find the difference:
```
def lowest_available(arr)
((1..arr.size).to_a - arr).first
end
lowest_available([1, 2, 3, 6, 10]) #=> 4
lowest_available([1, 8, 3, 6, 10]) #=> 2
lowest_available([5, 8, 3, 6, 10]) #=> 1
``` | 1. Sort the array
2. Iterate over the array and compare each item's value with the current index+1, if this pair is not equal you found the lowest available integer which is index+1. |
29,367,533 | I have array with integers something like this:
```
[1, 2, 3, 6, 10]
```
My question is what is the easiest way to get lowest positive integer that is not already in this array?
Something like:
```
[1, 2, 3, 6, 10].lowest_available => 4
[1, 8, 3, 6, 10].lowest_available => 2
[5, 8, 3, 6, 10].lowest_available => 1
```
Does any one have an idea how to manage this in ruby? | 2015/03/31 | [
"https://Stackoverflow.com/questions/29367533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2945241/"
] | ```
class Array
def lowest_available; (1..Float::INFINITY).find{|e| include?(e).!} end
end
[1, 2, 3, 6, 10].lowest_available # => 4
[1, 8, 3, 6, 10].lowest_available # => 2
[5, 8, 3, 6, 10].lowest_available # => 1
```
or, as suggested by Stefan:
```
class Array
def lowest_available; 1.step.find{|e| include?(e).!} end
end
``` | 1. Sort the array
2. Iterate over the array and compare each item's value with the current index+1, if this pair is not equal you found the lowest available integer which is index+1. |
29,367,533 | I have array with integers something like this:
```
[1, 2, 3, 6, 10]
```
My question is what is the easiest way to get lowest positive integer that is not already in this array?
Something like:
```
[1, 2, 3, 6, 10].lowest_available => 4
[1, 8, 3, 6, 10].lowest_available => 2
[5, 8, 3, 6, 10].lowest_available => 1
```
Does any one have an idea how to manage this in ruby? | 2015/03/31 | [
"https://Stackoverflow.com/questions/29367533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2945241/"
] | ```
class Array
def lowest_available; (1..Float::INFINITY).find{|e| include?(e).!} end
end
[1, 2, 3, 6, 10].lowest_available # => 4
[1, 8, 3, 6, 10].lowest_available # => 2
[5, 8, 3, 6, 10].lowest_available # => 1
```
or, as suggested by Stefan:
```
class Array
def lowest_available; 1.step.find{|e| include?(e).!} end
end
``` | To get the lowest possible number > 0 in an array containing negative values, I would add something to the given solution by [@shivam](https://stackoverflow.com/a/29367766/14048071), and finally, a function looks something like this:
```rb
def lowest_element(arr)
res = nil
arr = arr.reject { |e| e < 0 }
arr.sort.each.with_index(1) do |e, i|
if i != e
res = i
break
end
end
res.nil? ? (arr.size > 0 ? arr.sort.last + 1 : 1) : res
end
lowest_element([1, 5, 6, 3, 8, 7, 2]) => 4
lowest_element([1, 5, 6, 3, 8, 7, 2, 4]) => 9
lowest_element([-1, -7, -9]) => 1
lowest_element([-1, -7, -9, 1]) => 2
lowest_element([-1, -7, -9, 0]) => 1
``` |
10,714,790 | I am trying to implement a generic thread-safe Cache method, and I wonder how I should implement the lock in it.
**It should look something like this:**
```
//private static readonly lockObject = new Object();
public T GetCache<T>(string key, Func<T> valueFactory...)
{
// try to pull from cache here
lock (lockObject) // I don't want to use static object lock here because then every time a lock is performed, all cached objects in my site have to wait, regarding of the cache key.
{
// cache was empty before we got the lock, check again inside the lock
// cache is still empty, so retreive the value here
// store the value in the cache here
}
// return the cached value here
}
``` | 2012/05/23 | [
"https://Stackoverflow.com/questions/10714790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/897259/"
] | For non shared data among pools
-------------------------------
When you have many pools (web garden) each pool can have their static data. There I have measure this days that the `ConcurrentDictionary<TKey, TItem>` is the faster because they have implement some kind of technique that don't use look inside, so they have make it extreme fast.
So I suggest the `ConcurrentDictionary<TKey, TItem>` for non shared data among pools.
In this case you must take care the synchronization of the data him self to avoid concurrent data change on the same the data. There you can use the SlimLock, or a Lock.
common resources change among pools
-----------------------------------
Now, when you have resource that are shared among pools, you need to use mutex. For example if you try to go to save a file from many threads, of open a file for change it from many threads - you need mutex to synchronize that common resource
So for common resource you use the [mutex](http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx)
**Mutex** can use a Key to lock to lock base on that key - but you can not change the same resource!.
```
public T GetCache<T>(string key, Func<T> valueFactory...)
{
// note here that I use the key as the name of the mutex
// also here you need to check that the key have no invalid charater
// to used as mutex name.
var mut = new Mutex(true, key);
try
{
// Wait until it is safe to enter.
mut.WaitOne();
// here you create your cache
}
finally
{
// Release the Mutex.
mut.ReleaseMutex();
}
}
```
What kind of lock
-----------------
we have two case for lock.
1. One case is when we use **common resources in all pools**, all threads. Common resource can be a file, or the database its self.
In the common resources we need to use **mutex**.
2. Second case is when we use variables that are visible only to the inside of a pool - different pools can not see that resources. For example a **static List<>**, a static Dictionary etc. This static variables, arrays can access only inside the pool and they are not the same across different pools.
In this second case, the **lock()** is the most easy and common way to use.
Faster than lock
----------------
Now, when we have a static dictionary that we keep for long time and make too many reads/writes there, a faster approach to avoid the full program to wait, is the [`ReaderWriterLockSlim`](https://learn.microsoft.com/en-us/dotnet/api/system.threading.readerwriterlockslim?view=netframework-4.7.2)
you can take a full example from here: [`ReaderWriterLockSlim`](https://learn.microsoft.com/en-us/dotnet/api/system.threading.readerwriterlockslim?view=netframework-4.7.2)
Using the ReaderWriterLockSlim, we can avoid the locks when we do not need them - and we do not need to lock the static values when we read - only when we write on them. So I can suggest it for static values that we use them as cache.
What is a pool in asp.net.
--------------------------
Imaging as if different programs that run isolate each other but serves the incoming requests from users. Each pool have his own world and they are not communicate each other. Each pool have their initialize, their static values, and their life. To have some common resource between pools you need some other third program, like a database, like a file on disk, like a service.
So if you have many pools (web garden) to synchronize them for common resource you need mutex. To synchronize them inside you use lock.
[IIS app pools, worker processes, app domains](https://stackoverflow.com/questions/14105345/iis-app-pools-worker-processes-app-domains/14105747#14105747)
[Lifetime of ASP.NET Static Variable](https://stackoverflow.com/questions/8919095/lifetime-of-asp-net-static-variable/8919336#8919336) | The .NET `ConcurrentDictionary<TKey, TItem>` implements this internally by creating a separate lock for each key hash. This has the benefit of only locking the one relevant hash, even when processing item additions and removals. |
10,714,790 | I am trying to implement a generic thread-safe Cache method, and I wonder how I should implement the lock in it.
**It should look something like this:**
```
//private static readonly lockObject = new Object();
public T GetCache<T>(string key, Func<T> valueFactory...)
{
// try to pull from cache here
lock (lockObject) // I don't want to use static object lock here because then every time a lock is performed, all cached objects in my site have to wait, regarding of the cache key.
{
// cache was empty before we got the lock, check again inside the lock
// cache is still empty, so retreive the value here
// store the value in the cache here
}
// return the cached value here
}
``` | 2012/05/23 | [
"https://Stackoverflow.com/questions/10714790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/897259/"
] | For non shared data among pools
-------------------------------
When you have many pools (web garden) each pool can have their static data. There I have measure this days that the `ConcurrentDictionary<TKey, TItem>` is the faster because they have implement some kind of technique that don't use look inside, so they have make it extreme fast.
So I suggest the `ConcurrentDictionary<TKey, TItem>` for non shared data among pools.
In this case you must take care the synchronization of the data him self to avoid concurrent data change on the same the data. There you can use the SlimLock, or a Lock.
common resources change among pools
-----------------------------------
Now, when you have resource that are shared among pools, you need to use mutex. For example if you try to go to save a file from many threads, of open a file for change it from many threads - you need mutex to synchronize that common resource
So for common resource you use the [mutex](http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx)
**Mutex** can use a Key to lock to lock base on that key - but you can not change the same resource!.
```
public T GetCache<T>(string key, Func<T> valueFactory...)
{
// note here that I use the key as the name of the mutex
// also here you need to check that the key have no invalid charater
// to used as mutex name.
var mut = new Mutex(true, key);
try
{
// Wait until it is safe to enter.
mut.WaitOne();
// here you create your cache
}
finally
{
// Release the Mutex.
mut.ReleaseMutex();
}
}
```
What kind of lock
-----------------
we have two case for lock.
1. One case is when we use **common resources in all pools**, all threads. Common resource can be a file, or the database its self.
In the common resources we need to use **mutex**.
2. Second case is when we use variables that are visible only to the inside of a pool - different pools can not see that resources. For example a **static List<>**, a static Dictionary etc. This static variables, arrays can access only inside the pool and they are not the same across different pools.
In this second case, the **lock()** is the most easy and common way to use.
Faster than lock
----------------
Now, when we have a static dictionary that we keep for long time and make too many reads/writes there, a faster approach to avoid the full program to wait, is the [`ReaderWriterLockSlim`](https://learn.microsoft.com/en-us/dotnet/api/system.threading.readerwriterlockslim?view=netframework-4.7.2)
you can take a full example from here: [`ReaderWriterLockSlim`](https://learn.microsoft.com/en-us/dotnet/api/system.threading.readerwriterlockslim?view=netframework-4.7.2)
Using the ReaderWriterLockSlim, we can avoid the locks when we do not need them - and we do not need to lock the static values when we read - only when we write on them. So I can suggest it for static values that we use them as cache.
What is a pool in asp.net.
--------------------------
Imaging as if different programs that run isolate each other but serves the incoming requests from users. Each pool have his own world and they are not communicate each other. Each pool have their initialize, their static values, and their life. To have some common resource between pools you need some other third program, like a database, like a file on disk, like a service.
So if you have many pools (web garden) to synchronize them for common resource you need mutex. To synchronize them inside you use lock.
[IIS app pools, worker processes, app domains](https://stackoverflow.com/questions/14105345/iis-app-pools-worker-processes-app-domains/14105747#14105747)
[Lifetime of ASP.NET Static Variable](https://stackoverflow.com/questions/8919095/lifetime-of-asp-net-static-variable/8919336#8919336) | I just found [LazyCache](https://github.com/alastairtree/LazyCache) lib. I haven't tried it yet in production though.
```
IAppCache cache = new CachingService();
ComplexObject cachedResults = cache.GetOrAdd("uniqueKey",
() => methodThatTakesTimeOrResources());
``` |
10,714,790 | I am trying to implement a generic thread-safe Cache method, and I wonder how I should implement the lock in it.
**It should look something like this:**
```
//private static readonly lockObject = new Object();
public T GetCache<T>(string key, Func<T> valueFactory...)
{
// try to pull from cache here
lock (lockObject) // I don't want to use static object lock here because then every time a lock is performed, all cached objects in my site have to wait, regarding of the cache key.
{
// cache was empty before we got the lock, check again inside the lock
// cache is still empty, so retreive the value here
// store the value in the cache here
}
// return the cached value here
}
``` | 2012/05/23 | [
"https://Stackoverflow.com/questions/10714790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/897259/"
] | I just found [LazyCache](https://github.com/alastairtree/LazyCache) lib. I haven't tried it yet in production though.
```
IAppCache cache = new CachingService();
ComplexObject cachedResults = cache.GetOrAdd("uniqueKey",
() => methodThatTakesTimeOrResources());
``` | The .NET `ConcurrentDictionary<TKey, TItem>` implements this internally by creating a separate lock for each key hash. This has the benefit of only locking the one relevant hash, even when processing item additions and removals. |
71,452,373 | I'm trying to create a JDBC application using Java and MySQL in **Eclipse IDE** and **Ubuntu 20.04** OS.
I'm getting the very common error while connecting to database that is "java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)" and I've tried every possible solution from stack overflow answers, youtube videos, articles, etc. but **nothing seems to work**.
**The error:**
[](https://i.stack.imgur.com/RuPkx.png)
**My java code:**
```java
package jdbcDemo;
import java.sql.*;
public class jdbcConnect {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/jdbcDemo";
String user = "root";
String pswd = "1234";
Connection con = DriverManager.getConnection(url, user, pswd);
if(con == null) {
System.out.println("Connection not established");
}
else {
System.out.println("Connection established");
}
}
}
```
**Users in my database:**
[](https://i.stack.imgur.com/miX0h.png)
**Databse information:**
[](https://i.stack.imgur.com/G9aM6.png)
Connection details (screenshots of mysql workbench):
[](https://i.stack.imgur.com/G4Qou.png)
[](https://i.stack.imgur.com/CAWul.png)
I'm trying to access database through user **"root"** which has password **"1234"** and plugin is **"mysql\_native\_password"**.
I'm trying to make connection with **jdbcDemo** database which has **student** table.
I'm able to successfully access and manipulate database using the same user and password through **CLI and Workbench** but getting the same error again and again in **JDBC**.
**Some of the solutions that I've tried till now that didn't work:**
* Creating new user with all privileges
* re installing mysql server
* creating database via mysql workbench
* changing plugin of the users
* tried all different ways to write the url
* different types of connections (tci/ip, local socket/pipe)
All the solutions are either **outdated, not working or specific to windows** operating system.
Please suggest some solutions to solve this issue in Ubuntu 20.04 or different alternatives to do this task (remote databse, etc.)
**Thanks in advance !** | 2022/03/12 | [
"https://Stackoverflow.com/questions/71452373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15661685/"
] | In application.properties, add this statement:
`server.port = 8034` in case you've got some other application running that might be useing port 8080.
This helped me with this problem, took me several hours to find this solution.
Hope it helps someone. | try to do this
```
GRANT ALL PRIVILEGES ON *.* TO 'username'@'localhost';
GRANT ALL PRIVILEGES ON *.* TO 'username'@'127.0.0.1';
``` |
71,452,373 | I'm trying to create a JDBC application using Java and MySQL in **Eclipse IDE** and **Ubuntu 20.04** OS.
I'm getting the very common error while connecting to database that is "java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)" and I've tried every possible solution from stack overflow answers, youtube videos, articles, etc. but **nothing seems to work**.
**The error:**
[](https://i.stack.imgur.com/RuPkx.png)
**My java code:**
```java
package jdbcDemo;
import java.sql.*;
public class jdbcConnect {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/jdbcDemo";
String user = "root";
String pswd = "1234";
Connection con = DriverManager.getConnection(url, user, pswd);
if(con == null) {
System.out.println("Connection not established");
}
else {
System.out.println("Connection established");
}
}
}
```
**Users in my database:**
[](https://i.stack.imgur.com/miX0h.png)
**Databse information:**
[](https://i.stack.imgur.com/G9aM6.png)
Connection details (screenshots of mysql workbench):
[](https://i.stack.imgur.com/G4Qou.png)
[](https://i.stack.imgur.com/CAWul.png)
I'm trying to access database through user **"root"** which has password **"1234"** and plugin is **"mysql\_native\_password"**.
I'm trying to make connection with **jdbcDemo** database which has **student** table.
I'm able to successfully access and manipulate database using the same user and password through **CLI and Workbench** but getting the same error again and again in **JDBC**.
**Some of the solutions that I've tried till now that didn't work:**
* Creating new user with all privileges
* re installing mysql server
* creating database via mysql workbench
* changing plugin of the users
* tried all different ways to write the url
* different types of connections (tci/ip, local socket/pipe)
All the solutions are either **outdated, not working or specific to windows** operating system.
Please suggest some solutions to solve this issue in Ubuntu 20.04 or different alternatives to do this task (remote databse, etc.)
**Thanks in advance !** | 2022/03/12 | [
"https://Stackoverflow.com/questions/71452373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15661685/"
] | In application.properties, add this statement:
`server.port = 8034` in case you've got some other application running that might be useing port 8080.
This helped me with this problem, took me several hours to find this solution.
Hope it helps someone. | Execute this sql statement:
```
update mysql.user set host = '%' where user = 'root' and host = 'localhost';
flush privileges;
```
And try again. It worked for me in a similar situation. Good luck! |
30,133 | I am trying to **add a dashed line border** around a coupon I've made using CS6. I tried adding a shape (rectangle) with the dashed Stroke option but **the rectangle shape covers my coupon**. Can I make everything but the dashed border transparent?
Or is there a better way to accomplish this? I am new to Photoshop and will need step by step instructions.
This is what I want to achieve:
 | 2014/04/24 | [
"https://graphicdesign.stackexchange.com/questions/30133",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/22567/"
] | The way you authenticate a piece of software (a font is a piece of software) is you have a receipt of purchase and a license agreement on paper stored on file. Without these 2 options its nearly impossible to verify ownership. In case of digital stuff you still need to have a paper copy of the money transaction and the license key. Then the vendor can authenticate the key itself.
In essence is you have some sort of letter of authentication that guarantees ownership. If you buy stuff from 3rd parties you need to get a receipt and the original receipts to trace the source down. But beware many countries do not allow you to transfer licenses without special permission from the license holder.
In practice its actually pretty hard to validate ownership of licensed items. Best purchase the stuff from the vendor directly WITH the company credit card as this is often a problem if it was bought by somebody else.
**PS**: I'm not a lawyer, better yet I'm not YOUR lawyer and don't know your jurisdiction so please check with a legal counsel. | Do you own a licence for the fonts? If so, most foundries will let you redownload a fresh, unmodified file that you can be sure is authentic. ;) |
1,023,339 | When I download a video with `youtube-dl` and the `--all-subs`, `--write-sub`, `--write-auto-sub` options, I get a mixture of prewritten subtitles and autogenerated ones.
For example, this video: <https://www.youtube.com/watch?v=kHYZDveT46c> has prewritten English subtitles and autogenerated ones. When using the aforementioned switches, I only end up with the prewritten ones. I want the autogenerated ones too. Is there any way for me to do that? | 2018/04/09 | [
"https://askubuntu.com/questions/1023339",
"https://askubuntu.com",
"https://askubuntu.com/users/816488/"
] | The other answer is wrong and actually misleads and wastes people's time with this "latest version" thing which is an issue on his end and has nothing to do with the question...
The actual answer is that youtube-dl names its subtitle files only with the language in it (ex: `file.en.vtt`), which means that a potential `auto-en` would be named the same way as `en`, hence the resulting rule that real subtitles will always be prioritized over auto subtitles if both are asked for in the command. This is something that needs to be asked of the devs if we want to be able to do it with `youtube-dl` alone.
**Source :**
<https://github.com/ytdl-org/youtube-dl/issues/1412>
>
> Done, but currently --write-sub --write-auto-sub --all-sub would
> download en, fr, auto-es. Downloading both en and auto-en would
> require creating a new field in info dicts for automatic captions.
>
>
> | I had same problem with your video. When I used the --write-auto-sub switch (which writes automatically generated subtitle file) I ended up with this:
```
[youtube] kHYZDveT46c: Looking for automatic captions
WARNING: Couldn't find automatic captions for kHYZDveT46c
```
Then I update youtube-dl to the latest version and problem solved!
```
sudo pip install -U youtube-dl
```
so make sure you are using the latest version.
**[Edited]**
As discussed [here](https://github.com/rg3/youtube-dl/issues/1412) before, manually created subtitles are preferred over automatic captions, because the automatic captions come from translating manual subtitles or from translating audio/speech recognition of the audio sources.
so for example, if the available subtitles are en, fr, automatic-caption-en, automatic-caption-es:
```
--write-sub --sub-lang en: Download en
--write-sub --write-auto-sub --sub-lang en: Download en
--write-sub --all-sub: Download en, fr
--write-sub --write-auto-sub --all-sub: Download en, fr, automatic-caption-es
``` |
7,229 | I'm having issues with ripples on the first layer of big flat prints. The initial corner of a big flat print is fine, but then ripples begin to form as shown in the screenshot.
I'm just a newbie, so I was thinking they might have something to do with heat or contraction or something. Normally, I use the default and print with no turbofan on the first layer. When I tried adding fan 20% or 50%, nothing much changed (slight differences in the ripple pattern and area, but that pattern varies anyway).
I also wonder if one strip gets bent, then maybe the rest just follow the bends. As far as I know, my heating plate is working fine, has no serious hot spots, and I'm using a high-quality PLA+ filament. I also tried adjusting the print temperature from 205-220 (the range on the box is 205-230). Nothing seemed to help. I am running a default first layer thickness of 0.3 mm because that is supposed to help adhesion (and adhesion is fine).
The ripples look worse than they feel. They feel fairly flat, only slightly rippled, even though they look terrible! (And I don't know what that weird row with blobs is in the top left of the picture. That only happened once; almost like junk was in the nozzle or the feed gears slipped or something).
I'm running a Qidi Xpro machine, Sunlu PLA+ (wonderful) filaments, bed 50 C, print temp 205-215, print speed 30-40 mm/s on the first layer, and first layer thickness 0.3 mm (normal layer thickness is 0.2 mm). This machine has a direct drive with gears immediately above the nozzle.
Does anyone know why this rippling effect occurs, and what I might to do to correct it? Thanks
UPDATE: I'm adding this info here to respond to several comments concerning bed leveling, etc. (Thank you to those who made comments!)
1) I'm sure that the bed is as level as I can make it because I always go through the cycle twice).
2) Regarding clearance, if anything I worry that my clearance is too small since there is a fair amount of drag on my leveling card under the nozzle. So, there is definitely drag on all three level points, about midrange between the lightest drag and the heaviest drag that makes me think I'm filing off part of the nozzle.
3) I do have two nozzles, so I suppose the problem could show up on one but not the other if the nozzles were screwed into the block to give different heights. But the ripple shows up on both nozzles, always in the middle of the build plate, always in the middle of a big flat print. Corners don't usually show ripple effects. I don't want to believe that my build plate dips in the middle on my new machine, either ... :-) Adhesion is fine on small prints in the middle of the plate.
Here is a picture of the bottom of the piece. A careful examination shows an oscillation in the squished filament segments on a filament thread. Almost like the extruder was oscillating vertically in the z-axis at that frequency, or perhaps the filament squishyness was oscillating at that frequency. Looks almost like a weave pattern, since the squished parts alternate position on alternating lines.
It's worth saying again that the piece feels pretty smooth on both the top and bottom sides, even though it looks awful. I don't know what to make of that.
[](https://i.stack.imgur.com/n1zZA.jpg) | 2018/10/22 | [
"https://3dprinting.stackexchange.com/questions/7229",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/12981/"
] | First layer rippling is usually caused by a too low of a first layer height (for the amount of extruded filament).
Are you sure that:
1. Your bed is leveled as good as possible, and
2. the initial height between the nozzle and the bed is correct when Z=0 (A4 paper thickness, when moved should be giving some drag), and
3. the bed is flat. *(This is most probably your actual problem!)*
To minimize the effects, you could try to:
* increase the first layer height, or
* set an additional Z offset in the slicer, or
* reduce the filament flow for the first layer, or
* install an automatic bed leveling sensor, or
* perform a manual bed levelling mesh procedure (if you have Marlin Firmware).
This usually helps fighting these ripples. | 1. The first that I have in mind was connected with an acceleration, so you could play with it (set to half the current value and see the results)
2. The other source of that could be drive belt that is fiddling a little bit on the motor and idler shaft (visual check for any play on the motor/shaft)
3. Next one could be connected with some obstructions in the filament path (as this is direct drive, the Bowden tube could add an extra load if it was bent or spool is blocked)
4. As this is coreXY type printer could you set in slicer filing angles to 0deg and 90deg? That will force booth motors to run in the same time and eliminate a not holding torque on the other motor (or from other hand please check if the other motor gets some play when the head is going diagonally) |
7,229 | I'm having issues with ripples on the first layer of big flat prints. The initial corner of a big flat print is fine, but then ripples begin to form as shown in the screenshot.
I'm just a newbie, so I was thinking they might have something to do with heat or contraction or something. Normally, I use the default and print with no turbofan on the first layer. When I tried adding fan 20% or 50%, nothing much changed (slight differences in the ripple pattern and area, but that pattern varies anyway).
I also wonder if one strip gets bent, then maybe the rest just follow the bends. As far as I know, my heating plate is working fine, has no serious hot spots, and I'm using a high-quality PLA+ filament. I also tried adjusting the print temperature from 205-220 (the range on the box is 205-230). Nothing seemed to help. I am running a default first layer thickness of 0.3 mm because that is supposed to help adhesion (and adhesion is fine).
The ripples look worse than they feel. They feel fairly flat, only slightly rippled, even though they look terrible! (And I don't know what that weird row with blobs is in the top left of the picture. That only happened once; almost like junk was in the nozzle or the feed gears slipped or something).
I'm running a Qidi Xpro machine, Sunlu PLA+ (wonderful) filaments, bed 50 C, print temp 205-215, print speed 30-40 mm/s on the first layer, and first layer thickness 0.3 mm (normal layer thickness is 0.2 mm). This machine has a direct drive with gears immediately above the nozzle.
Does anyone know why this rippling effect occurs, and what I might to do to correct it? Thanks
UPDATE: I'm adding this info here to respond to several comments concerning bed leveling, etc. (Thank you to those who made comments!)
1) I'm sure that the bed is as level as I can make it because I always go through the cycle twice).
2) Regarding clearance, if anything I worry that my clearance is too small since there is a fair amount of drag on my leveling card under the nozzle. So, there is definitely drag on all three level points, about midrange between the lightest drag and the heaviest drag that makes me think I'm filing off part of the nozzle.
3) I do have two nozzles, so I suppose the problem could show up on one but not the other if the nozzles were screwed into the block to give different heights. But the ripple shows up on both nozzles, always in the middle of the build plate, always in the middle of a big flat print. Corners don't usually show ripple effects. I don't want to believe that my build plate dips in the middle on my new machine, either ... :-) Adhesion is fine on small prints in the middle of the plate.
Here is a picture of the bottom of the piece. A careful examination shows an oscillation in the squished filament segments on a filament thread. Almost like the extruder was oscillating vertically in the z-axis at that frequency, or perhaps the filament squishyness was oscillating at that frequency. Looks almost like a weave pattern, since the squished parts alternate position on alternating lines.
It's worth saying again that the piece feels pretty smooth on both the top and bottom sides, even though it looks awful. I don't know what to make of that.
[](https://i.stack.imgur.com/n1zZA.jpg) | 2018/10/22 | [
"https://3dprinting.stackexchange.com/questions/7229",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/12981/"
] | The main problem is solved (first layer thickness vs leveled nozzle height).
The following image shows the problem. I was running with a default 0.3 mm first layer (the tooltip setting says a slightly thicker layer helps with adhesion). The build plate was correctly leveled with "midrange" friction on the leveling card at the leveling points.
Problem cause: The midrange leveling height put the nozzle too close to the plate and caused rippling. The first layer thickness was set to 0.3 mm and the thickness of the leveling card was 0.25 mm.
The following image illustrates the problem (and one of the solutions). The bottom right of the image shows rippling. Not knowing what else to do with the "too close" or "too far" or "unlevel" tips in the comments, I just manually lowered the build plate knobs 1/4 turn while the print was in progress. The print began in the lower right. You can see the smooth area where I manually lowered the build plate. Then, to be sure, I raised the plate by restoring the 1/4 turn on the knobs. The rippling returned.
[](https://i.stack.imgur.com/S4Gdr.jpg "Ripples disappear when build plate is lowered 1/4 turn on the knobs")
To further explore the 0-90 degree suggestion provided by profesor79, I changed the slicer degree settings to 0-90 degrees and set the first layer thickness to 0.2 mm, which was equivalent to lowering the build plate knobs by 1/4 turn. I kept the same "midrange" friction settings when leveling. The result was a first-layer print with no rippling.
[](https://i.stack.imgur.com/Eixiu.jpg "No ripples with 0-90 degree settings and new build plate distance")
### Closing Thoughts
From this experience, I think:
1. 0.05 mm difference between a thickness of 0.3 mm on the first layer and a leveling-card nozzle height of 0.25 mm makes a rippling difference.
2. Using mid-range friction vs light friction on the leveling card also makes a difference. You don't need much of a height difference to reach 0.05 mm. Maybe even less is required to cause a ripple.
3. When printing with a first layer thickness of 0.2 mm, tolerances were tight and I discovered a spot on my build plate that had no adhesion because of a buildup of old adhesive. It left a 1/2-inch hole in the 0.2 mm-thick first layer. I also noticed just a hint of ripple in another place on the build plate, which (I think) indicates a tiny magnetic build plate thickness or warp issue of some kind. Hardly noticeable.
4. I think I will go forward with a 0.3 mm layer thickness to "absorb" minor flatness inconsistencies in my plate. (I have a glass plate but I have never used it because the magnetic plate is vastly more convenient.) But, to compensate for rippling effects, I will also use a "very light" friction amount when leveling the plate to ensure that the nozzle doesn't get too close to the plate on the first layer.
5. I found that manually adjusting the build plate height during a solid first layer print was a wonderful way to detect, see, and explore all the relationships between plate leveling, plate flatness, first layer thickness, and friction adjustments on the nozzle. It's very easy to immediately see, understand, and adjust all the related settings to get the best print possible from the machine.
---
Thank you again to everyone who contributed ideas to understanding the problem. It's hard to pick any particular answer because the solution involved multiple ideas, so I have added my own answer to share. | 1. The first that I have in mind was connected with an acceleration, so you could play with it (set to half the current value and see the results)
2. The other source of that could be drive belt that is fiddling a little bit on the motor and idler shaft (visual check for any play on the motor/shaft)
3. Next one could be connected with some obstructions in the filament path (as this is direct drive, the Bowden tube could add an extra load if it was bent or spool is blocked)
4. As this is coreXY type printer could you set in slicer filing angles to 0deg and 90deg? That will force booth motors to run in the same time and eliminate a not holding torque on the other motor (or from other hand please check if the other motor gets some play when the head is going diagonally) |
7,229 | I'm having issues with ripples on the first layer of big flat prints. The initial corner of a big flat print is fine, but then ripples begin to form as shown in the screenshot.
I'm just a newbie, so I was thinking they might have something to do with heat or contraction or something. Normally, I use the default and print with no turbofan on the first layer. When I tried adding fan 20% or 50%, nothing much changed (slight differences in the ripple pattern and area, but that pattern varies anyway).
I also wonder if one strip gets bent, then maybe the rest just follow the bends. As far as I know, my heating plate is working fine, has no serious hot spots, and I'm using a high-quality PLA+ filament. I also tried adjusting the print temperature from 205-220 (the range on the box is 205-230). Nothing seemed to help. I am running a default first layer thickness of 0.3 mm because that is supposed to help adhesion (and adhesion is fine).
The ripples look worse than they feel. They feel fairly flat, only slightly rippled, even though they look terrible! (And I don't know what that weird row with blobs is in the top left of the picture. That only happened once; almost like junk was in the nozzle or the feed gears slipped or something).
I'm running a Qidi Xpro machine, Sunlu PLA+ (wonderful) filaments, bed 50 C, print temp 205-215, print speed 30-40 mm/s on the first layer, and first layer thickness 0.3 mm (normal layer thickness is 0.2 mm). This machine has a direct drive with gears immediately above the nozzle.
Does anyone know why this rippling effect occurs, and what I might to do to correct it? Thanks
UPDATE: I'm adding this info here to respond to several comments concerning bed leveling, etc. (Thank you to those who made comments!)
1) I'm sure that the bed is as level as I can make it because I always go through the cycle twice).
2) Regarding clearance, if anything I worry that my clearance is too small since there is a fair amount of drag on my leveling card under the nozzle. So, there is definitely drag on all three level points, about midrange between the lightest drag and the heaviest drag that makes me think I'm filing off part of the nozzle.
3) I do have two nozzles, so I suppose the problem could show up on one but not the other if the nozzles were screwed into the block to give different heights. But the ripple shows up on both nozzles, always in the middle of the build plate, always in the middle of a big flat print. Corners don't usually show ripple effects. I don't want to believe that my build plate dips in the middle on my new machine, either ... :-) Adhesion is fine on small prints in the middle of the plate.
Here is a picture of the bottom of the piece. A careful examination shows an oscillation in the squished filament segments on a filament thread. Almost like the extruder was oscillating vertically in the z-axis at that frequency, or perhaps the filament squishyness was oscillating at that frequency. Looks almost like a weave pattern, since the squished parts alternate position on alternating lines.
It's worth saying again that the piece feels pretty smooth on both the top and bottom sides, even though it looks awful. I don't know what to make of that.
[](https://i.stack.imgur.com/n1zZA.jpg) | 2018/10/22 | [
"https://3dprinting.stackexchange.com/questions/7229",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/12981/"
] | The main problem is solved (first layer thickness vs leveled nozzle height).
The following image shows the problem. I was running with a default 0.3 mm first layer (the tooltip setting says a slightly thicker layer helps with adhesion). The build plate was correctly leveled with "midrange" friction on the leveling card at the leveling points.
Problem cause: The midrange leveling height put the nozzle too close to the plate and caused rippling. The first layer thickness was set to 0.3 mm and the thickness of the leveling card was 0.25 mm.
The following image illustrates the problem (and one of the solutions). The bottom right of the image shows rippling. Not knowing what else to do with the "too close" or "too far" or "unlevel" tips in the comments, I just manually lowered the build plate knobs 1/4 turn while the print was in progress. The print began in the lower right. You can see the smooth area where I manually lowered the build plate. Then, to be sure, I raised the plate by restoring the 1/4 turn on the knobs. The rippling returned.
[](https://i.stack.imgur.com/S4Gdr.jpg "Ripples disappear when build plate is lowered 1/4 turn on the knobs")
To further explore the 0-90 degree suggestion provided by profesor79, I changed the slicer degree settings to 0-90 degrees and set the first layer thickness to 0.2 mm, which was equivalent to lowering the build plate knobs by 1/4 turn. I kept the same "midrange" friction settings when leveling. The result was a first-layer print with no rippling.
[](https://i.stack.imgur.com/Eixiu.jpg "No ripples with 0-90 degree settings and new build plate distance")
### Closing Thoughts
From this experience, I think:
1. 0.05 mm difference between a thickness of 0.3 mm on the first layer and a leveling-card nozzle height of 0.25 mm makes a rippling difference.
2. Using mid-range friction vs light friction on the leveling card also makes a difference. You don't need much of a height difference to reach 0.05 mm. Maybe even less is required to cause a ripple.
3. When printing with a first layer thickness of 0.2 mm, tolerances were tight and I discovered a spot on my build plate that had no adhesion because of a buildup of old adhesive. It left a 1/2-inch hole in the 0.2 mm-thick first layer. I also noticed just a hint of ripple in another place on the build plate, which (I think) indicates a tiny magnetic build plate thickness or warp issue of some kind. Hardly noticeable.
4. I think I will go forward with a 0.3 mm layer thickness to "absorb" minor flatness inconsistencies in my plate. (I have a glass plate but I have never used it because the magnetic plate is vastly more convenient.) But, to compensate for rippling effects, I will also use a "very light" friction amount when leveling the plate to ensure that the nozzle doesn't get too close to the plate on the first layer.
5. I found that manually adjusting the build plate height during a solid first layer print was a wonderful way to detect, see, and explore all the relationships between plate leveling, plate flatness, first layer thickness, and friction adjustments on the nozzle. It's very easy to immediately see, understand, and adjust all the related settings to get the best print possible from the machine.
---
Thank you again to everyone who contributed ideas to understanding the problem. It's hard to pick any particular answer because the solution involved multiple ideas, so I have added my own answer to share. | First layer rippling is usually caused by a too low of a first layer height (for the amount of extruded filament).
Are you sure that:
1. Your bed is leveled as good as possible, and
2. the initial height between the nozzle and the bed is correct when Z=0 (A4 paper thickness, when moved should be giving some drag), and
3. the bed is flat. *(This is most probably your actual problem!)*
To minimize the effects, you could try to:
* increase the first layer height, or
* set an additional Z offset in the slicer, or
* reduce the filament flow for the first layer, or
* install an automatic bed leveling sensor, or
* perform a manual bed levelling mesh procedure (if you have Marlin Firmware).
This usually helps fighting these ripples. |
26,360 | This is talking about a promise to meet at a certain place. However, is it grammatically correct? Is it badly phrased? It seems that it can be misinterpreted to mean that at a certain place a promise was made to meet, rather than promising to meet at a certain place later. | 2011/05/21 | [
"https://english.stackexchange.com/questions/26360",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/5877/"
] | It is grammatical (as far as it goes - I assume you're using it as part of a longer sentence!).
It is also potentially ambiguous, as you say - it *could* be interpreted to mean *the place where we made the promise* rather than *the place where the meeting will take place*. However, it is more likely to be interpreted the way you want; moreover in context it is unlikely to cause much confusion, especially if there are more cues in the sentence to indicate which meaning is intended, for example:
>
> At the appointed time, I went to the place where we agreed to meet, and began to wait.
>
>
>
This is very unlikely to be interpreted as *the place where we made our agreement*. | If confusion reigns due to misunderstanding of that phrase, try changing it a little so that it retains it romantic taste while being absolutely clear:
>
> **The place we had promised we would meet.**
>
>
>
There can be no ambiguity about the above. |
26,360 | This is talking about a promise to meet at a certain place. However, is it grammatically correct? Is it badly phrased? It seems that it can be misinterpreted to mean that at a certain place a promise was made to meet, rather than promising to meet at a certain place later. | 2011/05/21 | [
"https://english.stackexchange.com/questions/26360",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/5877/"
] | To remove any ambiguity (although I agree with @psmears that the sentence is unlikely to be misinterpreted) you could use *meeting place* or *meeting point*.
>
> I went to the meeting point, as promised.
>
>
>
However, *the place that we promised to meet* has some poetic vein to it that is lost in the above example. | If confusion reigns due to misunderstanding of that phrase, try changing it a little so that it retains it romantic taste while being absolutely clear:
>
> **The place we had promised we would meet.**
>
>
>
There can be no ambiguity about the above. |
26,360 | This is talking about a promise to meet at a certain place. However, is it grammatically correct? Is it badly phrased? It seems that it can be misinterpreted to mean that at a certain place a promise was made to meet, rather than promising to meet at a certain place later. | 2011/05/21 | [
"https://english.stackexchange.com/questions/26360",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/5877/"
] | It is grammatical (as far as it goes - I assume you're using it as part of a longer sentence!).
It is also potentially ambiguous, as you say - it *could* be interpreted to mean *the place where we made the promise* rather than *the place where the meeting will take place*. However, it is more likely to be interpreted the way you want; moreover in context it is unlikely to cause much confusion, especially if there are more cues in the sentence to indicate which meaning is intended, for example:
>
> At the appointed time, I went to the place where we agreed to meet, and began to wait.
>
>
>
This is very unlikely to be interpreted as *the place where we made our agreement*. | To remove any ambiguity (although I agree with @psmears that the sentence is unlikely to be misinterpreted) you could use *meeting place* or *meeting point*.
>
> I went to the meeting point, as promised.
>
>
>
However, *the place that we promised to meet* has some poetic vein to it that is lost in the above example. |
26,360 | This is talking about a promise to meet at a certain place. However, is it grammatically correct? Is it badly phrased? It seems that it can be misinterpreted to mean that at a certain place a promise was made to meet, rather than promising to meet at a certain place later. | 2011/05/21 | [
"https://english.stackexchange.com/questions/26360",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/5877/"
] | It is grammatical (as far as it goes - I assume you're using it as part of a longer sentence!).
It is also potentially ambiguous, as you say - it *could* be interpreted to mean *the place where we made the promise* rather than *the place where the meeting will take place*. However, it is more likely to be interpreted the way you want; moreover in context it is unlikely to cause much confusion, especially if there are more cues in the sentence to indicate which meaning is intended, for example:
>
> At the appointed time, I went to the place where we agreed to meet, and began to wait.
>
>
>
This is very unlikely to be interpreted as *the place where we made our agreement*. | For a rather archaic, but unambiguous option you could use *tryst* or *trysting place*. |
26,360 | This is talking about a promise to meet at a certain place. However, is it grammatically correct? Is it badly phrased? It seems that it can be misinterpreted to mean that at a certain place a promise was made to meet, rather than promising to meet at a certain place later. | 2011/05/21 | [
"https://english.stackexchange.com/questions/26360",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/5877/"
] | It is grammatical (as far as it goes - I assume you're using it as part of a longer sentence!).
It is also potentially ambiguous, as you say - it *could* be interpreted to mean *the place where we made the promise* rather than *the place where the meeting will take place*. However, it is more likely to be interpreted the way you want; moreover in context it is unlikely to cause much confusion, especially if there are more cues in the sentence to indicate which meaning is intended, for example:
>
> At the appointed time, I went to the place where we agreed to meet, and began to wait.
>
>
>
This is very unlikely to be interpreted as *the place where we made our agreement*. | Yes, there is ambiguity from the possibilities that you could be discussing the *content* of the promise or the situation of the promise's *making*.
I think that while mildly ambiguous your phrase would be clearly understood, and that if you were intending to refer to your location at the time of promising, you would use additional words to distinguish this meaning.
It's like if you said "I kissed her in the belfry", someone could ask "what part of the body is that?" But it would be only as a joke because your meaning was clearly understood as the most likely. |
26,360 | This is talking about a promise to meet at a certain place. However, is it grammatically correct? Is it badly phrased? It seems that it can be misinterpreted to mean that at a certain place a promise was made to meet, rather than promising to meet at a certain place later. | 2011/05/21 | [
"https://english.stackexchange.com/questions/26360",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/5877/"
] | To remove any ambiguity (although I agree with @psmears that the sentence is unlikely to be misinterpreted) you could use *meeting place* or *meeting point*.
>
> I went to the meeting point, as promised.
>
>
>
However, *the place that we promised to meet* has some poetic vein to it that is lost in the above example. | For a rather archaic, but unambiguous option you could use *tryst* or *trysting place*. |
26,360 | This is talking about a promise to meet at a certain place. However, is it grammatically correct? Is it badly phrased? It seems that it can be misinterpreted to mean that at a certain place a promise was made to meet, rather than promising to meet at a certain place later. | 2011/05/21 | [
"https://english.stackexchange.com/questions/26360",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/5877/"
] | To remove any ambiguity (although I agree with @psmears that the sentence is unlikely to be misinterpreted) you could use *meeting place* or *meeting point*.
>
> I went to the meeting point, as promised.
>
>
>
However, *the place that we promised to meet* has some poetic vein to it that is lost in the above example. | Yes, there is ambiguity from the possibilities that you could be discussing the *content* of the promise or the situation of the promise's *making*.
I think that while mildly ambiguous your phrase would be clearly understood, and that if you were intending to refer to your location at the time of promising, you would use additional words to distinguish this meaning.
It's like if you said "I kissed her in the belfry", someone could ask "what part of the body is that?" But it would be only as a joke because your meaning was clearly understood as the most likely. |
41,593,484 | I'm having an issue getting an association to populate in my Doctrine entity. The entity gets populated fully with the single exception of the association, even when set to eager loading. I have other similar associations working so I suspect there is some fundamental understanding that I'm missing here.
What I am trying to do here is populate `$s` in the entity with the `S` object, known as `s` in the query. I apologize in advance for the naming, but I've had to strip out anything potentially identifying as this is part of proprietary code.
Here's the bulk of my `SHealth` entity class:
```
// -------------------------------------------------------------------
// ENTITY FOR SHealth
// -------------------------------------------------------------------
/**
* Used for tracking the current health of shares.
* @Entity(repositoryClass="SHealthRepository")
* @Table(name="s_health")
*/
class SHealth
{
/**
* @Id
* @Column(type="integer", name="s_id")
*/
protected $sId;
/**
* @Id
* @Column(type="integer", name="l_id")
*/
protected $lId;
/**
* @Id
* @Column(type="smallint", name="s_type")
*/
protected $sType;
/**
* @Id
* @Column(type="smallint", name="s_subtype")
*/
protected $sSubtype;
/**
* @Column(type="smallint", name="health_status")
*/
protected $healthStatus;
/**
* @Column(type="datetime", name="update_time")
*/
protected $updateTime;
/**
* Scalar value
*/
protected $active;
/**
* @ManyToOne(targetEntity="S")
* @JoinColumns({
* @JoinColumn(name="l_id", referencedColumnName="l_id"),
* @JoinColumn(name="s_id", referencedColumnName="id")
* })
*/
protected $s;
// [Accessors and mutators omitted]
}
```
Here's a snippet of the associated repository class:
```
// -------------------------------------------------------------------
// Repository fetch function
// -------------------------------------------------------------------
$rtime_check = !$include_rtimed ? " AND s.rtime IS NULL" : "";
$limit_check = $limit > 0 ? " LIMIT " . $limit : "";
$sql = "SELECT
s.l_id,
s.id AS s_id,
COALESCE(s_health.s_type, s.type) AS s_type,
COALESCE(s_health.s_subtype, 0) AS s_subtype,
s_health.health_status,
s_health.update_time,
(s.enabled AND
COALESCE(orsr.status, orsh.status, 0) > 0) AS active
FROM s
LEFT JOIN s_health ON
s.l_id = s_health.l_id AND
s.id = s_health.s_id AND
s.type = s_health.s_type AND
s_health.s_subtype = 0
LEFT JOIN orsr ON
s.l_id = orsr.l_id AND
s.se_id = orsr.se_id AND
orsr.status IN ([omitted])
LEFT JOIN orsh ON
s.l_id = orsh.l_id AND
s.id = orsh.s_id AND
orsh.status IN ([omitted])
WHERE s.l_id IN (:d_ids)
{$rtime_check}
GROUP BY s.l_id, s.id
{$limit_check}";
// Map the SQL result columns to class properties.
$rsm = new ResultSetMappingBuilder($this->_em);
$rsm->addRootEntityFromClassMetadata(SHealth::class, 's_alias');
$rsm->addScalarResult('active', 'active');
$query = $this->_em->createNativeQuery($sql, $rsm);
$query->setParameter("d_ids", $d_ids);
$results = $query->getResult();
// Inject aggregate function results into the resulting object.
$health_objects = [];
foreach ($results as $result)
{
$health_object = $result[0];
$health_object->setActive($result['active']);
$health_objects[] = $health_object;
}
return $health_objects;
```
Finally, here's the `S` class, with some members removed:
```
// -------------------------------------------------------------------
// ENTITY FOR S
// -------------------------------------------------------------------
/**
* @Entity
* @Table(name="s")
*/
class S
{
/**
* @Id
* @Column(type="integer")
*/
protected $id;
/**
* @Id
* @Column(type="integer", name="l_id")
*/
protected $lId;
/**
* @Column(type="integer", name="se_id")
*/
protected $seId;
/**
* @Column(type="smallint")
*/
protected $type;
/**
* @Column(type="boolean")
*/
protected $enabled;
/**
* @Column(type="datetime")
*/
protected $rtime;
// [Accessors and mutators omitted]
}
```
I have all of the necessary getters and setters, and all the necessary database data is present in both tables so there shouldn't be any issue with the join columns. | 2017/01/11 | [
"https://Stackoverflow.com/questions/41593484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/506488/"
] | This is the way the language is defined. You divide an `int` by an `int`, so the calculation is performed resulting in an `int`, giving `3` (truncating, rather than rounding).
You then store `3` into a `float`, giving `3.0`.
If you want the division performed using `float`s, make (at least) one of the arguments a `float`, e.g. `360f / 100`. In this way, they other argument will be converted to a `float` *before* the division is performed.
`360 / 100f` will work equally well, but I think it probably make sense to make it clear as early as possible that this is a floating point calculation, rather than an integral one; that's a human consideration, rather than a technical one.
(Note that `360.0` is actually a `double`, although using that will work as well. The division would be performed as a `double`, then the result converted to a `float` for the assignment). | `360/100` is computed in *integer* arithmetic *before* it's assigned to the `float`.
Reworking to `360f / 100` is my favourite way of fixing this.
Finally these days `float`s are for quiche eaters, girls, and folk who don't understand how modern chipsets work. Use a `double` type instead - which will probably be faster -, and `360.0 / 100`. |
46,444,487 | I have configured `MySQL` + `phpMyAdmin` + `prestashop` containers.
I would like to build a unique image with my own custom containers.
How can I do?
Thanks for your help. | 2017/09/27 | [
"https://Stackoverflow.com/questions/46444487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3279494/"
] | What you are looking for is [Docker Compose](https://docs.docker.com/compose/compose-file/). Docker compose will automatically start the images that you have and you can also [link](https://docs.docker.com/compose/compose-file/#links) these images automatically inside docker-compose.
If you have done some manual changes to the containers running, you can commit the container and the changes to a new image using
```
docker commit <mysqlcontainer> mysql-custom-image
```
And then in the compose file, you can just reference those commits.
```
...
image: mysql-custom-image
``` | A container is made from a Dockerfile
<https://docs.docker.com/engine/reference/builder/>
If you want to build your custom container, you should create one and make it as you want it to be!
Here's a tutorial: <https://www.howtoforge.com/tutorial/how-to-create-docker-images-with-dockerfile/> |
1,814 | This question popped back onto the main screen recently:
[Why did Facebook not use HSTS for a long time after it became available?](https://security.stackexchange.com/questions/51796/why-doesnt-facebook-use-hsts/51798#51798)
Both the question and all answers are now incorrect, because Facebook now use HSTS. I'm not sure when they started doing so.
I have edited my answer to include a warning, but I wonder: how do we want to deal with this? Some questions have been closed because the answers would be too transient, but that seems a shame, as I think the question was interesting and useful at the time. | 2015/05/21 | [
"https://security.meta.stackexchange.com/questions/1814",
"https://security.meta.stackexchange.com",
"https://security.meta.stackexchange.com/users/31625/"
] | I think what you have done is probably the best first step. I think the question can now be closed as well - it doesn't mean deleted. With your edit, and the votes, it can be seen that this was valuable at a point in time, but is no longer current. | I agree, the question remains useful. It's now a question about the history of security mechanisms instead of current usage of security mechanisms. It's also a question about when to use and not to use HSTS, just as it was before.
The question and, where relevant, should be updated to not imply that Facebook currently doesn't use HSTS. (Done, at least for the question.) It would be a good complement for answers to explain why Facebook changed their policy, as it would inform the decision of someone deciding whether to use HSTS for their site.
There's no reason to close the question. It hasn't magically stopped being on-topic or answerable. There's still room for someone to post a better answer. The reason we close questions is because we don't want them to be answered, for one reason or another (already answered elsewhere, not the right place for people to evaluate answers, impossible to write a good answer, …). Answers to this question still remain worthwhile an on-topic, so the question should remain open. |
13,489,306 | let's say i have this generic class which does some work and produces a result:
```
public abstract class Work<T> {
private T mResult;
public Work(T result) {
mResult = result;
}
public abstract <T> void doWork(T result);
public T getResult() {
return mResult;
}
}
```
For the users of this class i want type safety that would look something like this:
```
Work<MyResult> work = new Work<MyResult>(new MyResult()){
public void work(MyResult result){
//...
}
}
```
The problem is Java doesn't work this way and forces me to cast from the generic type:
```
Work<MyResult> work = new Work<MyResult>(new MyResult()){
public <T> void work (T result){
// (MyResult)result - not nice
}
}
```
Is there a way to have type safety in a nice way like in the first example?
Thanks,
Teo | 2012/11/21 | [
"https://Stackoverflow.com/questions/13489306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/439719/"
] | You don't need the `<T>` in the declaration of `doWork`, because you want to use the T that is declared at the class level - you need
```
public abstract void doWork(T result);
```
The current declaration is the same as
```
public abstract <A> void doWork(A result);
```
it isn't necessarily the same T as the rest of your class. | Try this instead:
```
Work<MyResult> work = new Work<MyResult>(new MyResult()){
public void work(MyResult result){
// Do something
}
}
```
---
Your current design of the `Work` class is a little strange. I'm not sure why your `doWork` method requires a result object as an argument. The abstract class also seems to offer little in the way of functionality (although I appreciate this may be a prototype). Perhaps consider an interface instead:
```
public interface Work<T> {
public T doWork();
}
``` |
114,861 | When I try to download Remote.app or Find my friends on a device that is stuck on iOS 6 I am presented with this alert?
>
> This application requires iOS 7.0 or later.
>
>
> You must update to iOS 7.0 in order to download and use this
> application.
>
>
>
Is there anyway around this if I've previously downloaded these applications on my device but deleted them? | 2013/12/24 | [
"https://apple.stackexchange.com/questions/114861",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/4160/"
] | Did you backup your phone to your computer? If so, you probably have the old version of the app in the Mobile Applications folder inside your iTunes folder. If you only backed up to iCloud I think you may be out of luck. | It's easy. I'm using "vshare" from Cydia. You need to jailbreak your device, but it's much better than when you need to buy a new apple device just to get your favorite iOS 7 apps. Jailbreak your device. It's free. Learn how to do that with YouTube. I've downloaded a lot of apps that need iOS 7. I downloaded the old version one. I hope this answer will be helpful. |
114,861 | When I try to download Remote.app or Find my friends on a device that is stuck on iOS 6 I am presented with this alert?
>
> This application requires iOS 7.0 or later.
>
>
> You must update to iOS 7.0 in order to download and use this
> application.
>
>
>
Is there anyway around this if I've previously downloaded these applications on my device but deleted them? | 2013/12/24 | [
"https://apple.stackexchange.com/questions/114861",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/4160/"
] | If you access the store directly from your iPhone, you get the option to download the latest version still compatible with iOS 6. | It's easy. I'm using "vshare" from Cydia. You need to jailbreak your device, but it's much better than when you need to buy a new apple device just to get your favorite iOS 7 apps. Jailbreak your device. It's free. Learn how to do that with YouTube. I've downloaded a lot of apps that need iOS 7. I downloaded the old version one. I hope this answer will be helpful. |
114,861 | When I try to download Remote.app or Find my friends on a device that is stuck on iOS 6 I am presented with this alert?
>
> This application requires iOS 7.0 or later.
>
>
> You must update to iOS 7.0 in order to download and use this
> application.
>
>
>
Is there anyway around this if I've previously downloaded these applications on my device but deleted them? | 2013/12/24 | [
"https://apple.stackexchange.com/questions/114861",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/4160/"
] | I was able to download a 'last compatible' version of some of Apple's apps. It looks like here were my options:
1. Buy an iOS 7 device (not ideal when you have lots of iOS 6 only devices around).
2. Download a 'last compatible' version of an iOS 7 only app if I had purchased that app while an iOS 6 version was out.
3. Find an iTunes backup of the iOS 6 version of the app on my computer.
My issue was that I was trying to do option '2' but with a new Apple ID. | It's easy. I'm using "vshare" from Cydia. You need to jailbreak your device, but it's much better than when you need to buy a new apple device just to get your favorite iOS 7 apps. Jailbreak your device. It's free. Learn how to do that with YouTube. I've downloaded a lot of apps that need iOS 7. I downloaded the old version one. I hope this answer will be helpful. |
427,586 | I was searching for a simple software that encrypts given text using either PGP or GPG. The alternatives I have found so far are very complicated and hard to operate.
Are there any encryption programs that generates public and private key, encrypts/decrypts text given proper key? | 2012/05/22 | [
"https://superuser.com/questions/427586",
"https://superuser.com",
"https://superuser.com/users/19707/"
] | [Gpg4win](http://www.gpg4win.org/) might be your best bet. **Assemetric encryption is already a pretty complicated topic** and would be pretty hard to dumb down any further. Still, it looks as if this particular software at least **provides a GUI to navigate around in as opposed other command line tools** like [GnuPG](http://www.gnupg.org/documentation/manuals/gnupg/).
The only downside I can see is they throw in a few extra added features that you may not use.
On the other side, **if you don't require assemetric** encryption, you can always use a **WinZIP** or **WinRAR** to encrypt as long as you **use a strong password** (at least 8 character, using numbers, upper, lower, special characters, etc) | In the GNOME 2 builds that ship with GPG (such as Debian or Ubuntu) this is built-in; you just right-click the file and select "Encrypt..." and you are prompted to pick the public keys you wish to use.
I'm not sure which program provides this functionality, it's probably a plugin to nautilus.
You may have luck with GPGME (GPG Made Easy) which apparently has Win32 builds.
<http://freecode.com/projects/gpgme>
Please re-tag your question with the operating system you're interested in. |
22,090,122 | I don't like the way var\_dump prints out objects. I want to override it with this function:
```
function var_dump($object, $die = true) {
print '<pre>';
print_r($object);
if ($die) die();
}
```
I know how to override it in my application, but is there a way to override it globally for all sites on a PHP config level? | 2014/02/28 | [
"https://Stackoverflow.com/questions/22090122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146366/"
] | You can not do that currently (via "good way") in PHP. And more - you shouldn't.
`var_dump()` is doing right for what it's intended: *plain* output and nothing more. If you want to change that, then by definition you want some *user-defined* behavior. Therefore:
* Create **your own function**. That is what you have now. User-defined functions are for user-defined behavior.
* Or else, if you want to do it with `var_dump()` name by some reason, use `namespace` like:
```
namespace Utils;
function var_dump($var, $exit=true, $return=true)
{
$result = sprintf('<pre>%s</pre>', print_r($var, true));
if($exit)
{
echo $result;
exit;
}
if($return)
{
return $result;
}
echo $result;
}
```
so usage will look like:
```
$obj = new StdClass();
$str = \Utils\var_dump($obj, false);
//do domething with $str
echo $str; //or use second false
```
* Worst case: [`runkit_function_redefine()`](http://us1.php.net/runkit_function_redefine) Remember, this is **evil**. You should not do that because redefining goes against what is function and why it was defined. It is a global side-effect and you should avoid such behavior. | You can use the `override_function`: <http://www.php.net/manual/en/function.override-function.php> to replace the behavior of the `var_dump` function. If you want to include this piece of code in all of your sites, you can put this in your `php.ini` file:
```
php_value auto_prepend_file /path/to/file_where_you_override_function.php
``` |
72,204 | I have an electric road bike with disc brakes. Its stock front and rear tires
have only 28 spokes and a slightly deeper than ordinary rim. The hubs are cheap
non-Shimano hubs, but their flange diameter is the same as for Shimano
FH/HB-R7070 hubs, i.e. 44mm.
After about 100 kilometers of riding, I noticed the front wheel became wobbly
and had lost all of its spoke tension. The rear had some slack spokes, but only
some. Now I have replaced the wheels with 36-spoke wheels.
The frame is a Cannondale AI (asymmetric integration) frame so the rear wheel
dish is reduced by 6mm.
Usually I have understood that rear wheels have more problems than front
wheels, but in this case it clearly was the front that was having problems. Why
is this the case? | 2020/09/20 | [
"https://bicycles.stackexchange.com/questions/72204",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/33932/"
] | I would say that your wheels were not initially tensioned properly. The load-unload cycle of riding will work to back off the tension on spokes that aren't tight enough.
That you have disk brakes isn't the root cause, though the forces of disks braking act through the spokes whereas rim brakes are already acting directly on the rims. So braking with disk brakes is stressing the spokes the other way, perhaps doubling the load/unload cycle count for the time you're actively braking.
When the wheel is built, the tension should "preload" each spoke sufficiently that it doesn't stretch as much during riding. If the spoke tension is low but equal, then that will eventually lead to problems, often breaking at the J-bend. | The cause is the disc brake braking torque. A wheel having a reduced number of
spokes should have larger-flange hubs to withstand torque more efficiently and
a stiffer rim to withstand radial loads more efficiently.
This wheel lacks the large-flange hub. This rim also is only very slightly
stiffer than my DT Swiss TK 540 replacement rims with 36 spoke holes.
I estimated based on the dimension and cross sectional view of the TK 540 rim
that its second moment of area is 3283 mm4. I also estimated that
the slightly deeper 28-hole rim has a second moment of area of about 4500
mm4 (this is only very approximate as I do not have a cross
sectional view of the no-brand rim). In comparison, Mavic MA2 second moment of
area is according to my calculations 1388 mm4.
My [bicycle wheel tension simulator](https://bicycles.stackexchange.com/questions/72184/how-to-model-the-dynamic-tension-distribution-of-a-loaded-bicycle-wheel)
shows that the 28-hole wheels have 38% of radial
load on one spoke, that the 36-hole TK 540 wheels have 30% of radial load on
one spoke and that Mavic MA2 wheels have 39% of radial load on one spoke. Thus
the TK 540 wheels better withstand radial load than the others.
We also need to calculate how well a bicycle hub shaft transmits torque. My
calculations show about 311 Nm per degree of twist for these hubs. Braking
torque for 111 kg rider + 20 kg bicycle at 0.6 g deceleration is 261.02 Nm.
The 28-spoke wheels with their 1-cross spoke pattern twist 0.95426 degrees
(left) and 0.29978 degrees (right) to generate 157.94 Nm of torque (left) and
103.08 Nm of torque (right). The torque results in alternating tension
change of 626.77 N (left) and 409.07 N (right) for the spoking pattern.
This 626.77 N braking tension change can be combined with the fact that when
braking hard on the front brake, all of the 131 kg weight is on the front wheel
so there's 1285.1 N of load that reduces the tension of one spoke by 491 N.
Thus there's about 1118 N of tension loss on the worst-affected spoke, so
clearly there is no safety margin in these 28-spoke wheels if the rider is
heavy and brakes hard.
This can be compared with 36-spoke TK540 wheels that twist 0.72795 degrees
(left) and 0.25080 degrees (right) to generate 165.43 Nm of torque (left) and
95.584 Nm of torque (right). The torque results in alternating tension change
of 465.59 N (left) and 269.01 N (right) for the spoking pattern.
This 466 N tension change is added to the 384 N tension loss in largest
load-carrying spoke. Thus the worst-affected spoke has 850 N tension change.
This can be combined with typical spoke tension of 1200 N, so with these
36-spoke wheels there actually is some safety margin, albeit small.
The conclusion is that when selecting hubs for disc brake front wheels, best
hubs have (1) lots of spokes and (2) large flange. It also helps to have a
stiff shaft like these hubs do. Disc brake front rims should be of high quality
so that even spoke tension can be achieved, and the spokes need to be evenly
tensioned to high tensions.
The rear disc brake in comparison provides minimal forces and is rarely used,
so it is not a problem, especially considering that the Cannondale AI frame
achieves even spoke tension in the rear. |
29,374,553 | How can I make a countdown with an `NSTimer` using Swift? | 2015/03/31 | [
"https://Stackoverflow.com/questions/29374553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4548796/"
] | For use in Playground for fellow newbies, in Swift 5, Xcode 11:
```
Import UIKit
var secondsRemaining = 10
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (Timer) in
if secondsRemaining > 0 {
print ("\(secondsRemaining) seconds")
secondsRemaining -= 1
} else {
Timer.invalidate()
}
}
``` | For Egg Countdown Timer.
```
class ViewController: UIViewController {
var secondsRemaining = 60
var eggCountdown = 0
let eggTimes = ["Soft": 5, "Medium": 7,"Hard": 12]
@IBAction func hardnessSelected(_ sender: UIButton) {
let hardness = sender.currentTitle!
let result = eggTimes[hardness]!
eggCountdown = result * secondsRemaining
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (Timer) in
if self.eggCountdown > 0 {
print ("\(self.eggCountdown) seconds.")
self.eggCountdown -= 1
} else {
Timer.invalidate()
}
}
}
}
``` |
29,374,553 | How can I make a countdown with an `NSTimer` using Swift? | 2015/03/31 | [
"https://Stackoverflow.com/questions/29374553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4548796/"
] | this for the now swift 5.0 and newst
```
var secondsRemaining = 60
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
}
@objc func updateCounter(){
if secondsRemaining > 0 {
print("\(secondsRemaining) seconds.")
secondsRemaining -= 1
}
}
``` | You really shouldn’t. Grand Central Dispatch is much more reliable. |
29,374,553 | How can I make a countdown with an `NSTimer` using Swift? | 2015/03/31 | [
"https://Stackoverflow.com/questions/29374553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4548796/"
] | Variable for your timer
```
var timer = 60
```
NSTimer with 1.0 as interval
```
var clock = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "countdown", userInfo: nil, repeats: true)
```
Here you can decrease the timer
```
func countdown() {
timer--
}
``` | You really shouldn’t. Grand Central Dispatch is much more reliable. |
29,374,553 | How can I make a countdown with an `NSTimer` using Swift? | 2015/03/31 | [
"https://Stackoverflow.com/questions/29374553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4548796/"
] | **Swift 4.1 and Swift 5.** The updatetime method will called after every second and seconds will display on UIlabel.
```
var timer: Timer?
var totalTime = 60
private func startOtpTimer() {
self.totalTime = 60
self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
}
@objc func updateTimer() {
print(self.totalTime)
self.lblTimer.text = self.timeFormatted(self.totalTime) // will show timer
if totalTime != 0 {
totalTime -= 1 // decrease counter timer
} else {
if let timer = self.timer {
timer.invalidate()
self.timer = nil
}
}
}
func timeFormatted(_ totalSeconds: Int) -> String {
let seconds: Int = totalSeconds % 60
let minutes: Int = (totalSeconds / 60) % 60
return String(format: "%02d:%02d", minutes, seconds)
}
``` | Make Countdown app Xcode 8.1, Swift 3
```
import UIKit
import Foundation
class ViewController: UIViewController, UITextFieldDelegate {
var timerCount = 0
var timerRunning = false
@IBOutlet weak var timerLabel: UILabel! //ADD Label
@IBOutlet weak var textField: UITextField! //Add TextField /Enter any number to Countdown
override func viewDidLoad() {
super.viewDidLoad()
//Reset
timerLabel.text = ""
if timerCount == 0 {
timerRunning = false
}
}
//Figure out Count method
func Counting() {
if timerCount > 0 {
timerLabel.text = "\(timerCount)"
timerCount -= 1
} else {
timerLabel.text = "GO!"
}
}
//ADD Action Button
@IBAction func startButton(sender: UIButton) {
//Figure out timer
if timerRunning == false {
_ = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.Counting), userInfo: nil, repeats: true)
timerRunning = true
}
//unwrap textField and Display result
if let countebleNumber = Int(textField.text!) {
timerCount = countebleNumber
textField.text = "" //Clean Up TextField
} else {
timerCount = 3 //Defoult Number to Countdown if TextField is nil
textField.text = "" //Clean Up TextField
}
}
//Dismiss keyboard
func keyboardDismiss() {
textField.resignFirstResponder()
}
//ADD Gesture Recignizer to Dismiss keyboard then view tapped
@IBAction func viewTapped(_ sender: AnyObject) {
keyboardDismiss()
}
//Dismiss keyboard using Return Key (Done) Button
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
keyboardDismiss()
return true
}
}
```
<https://github.com/nikae/CountDown-> |
29,374,553 | How can I make a countdown with an `NSTimer` using Swift? | 2015/03/31 | [
"https://Stackoverflow.com/questions/29374553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4548796/"
] | Question 1:
```
@IBOutlet var countDownLabel: UILabel!
var count = 10
override func viewDidLoad() {
super.viewDidLoad()
var timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(UIMenuController.update), userInfo: nil, repeats: true)
}
func update() {
if(count > 0) {
countDownLabel.text = String(count--)
}
}
```
Question 2:
You can do both. SpriteKit is the SDK you use for scene, motion, etc. Simple View Application is the project template. They should not conflict | **Timer with Combine**
```
var counter = 30
let cancellable = Timer.publish(every: 1, on: .main, in: .default).autoconnect().sink(receiveValue: { _ in
counter = counter > 0 ? counter - 1 : 0
print("timer: ", counter)
})
``` |
29,374,553 | How can I make a countdown with an `NSTimer` using Swift? | 2015/03/31 | [
"https://Stackoverflow.com/questions/29374553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4548796/"
] | Question 1:
```
@IBOutlet var countDownLabel: UILabel!
var count = 10
override func viewDidLoad() {
super.viewDidLoad()
var timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(UIMenuController.update), userInfo: nil, repeats: true)
}
func update() {
if(count > 0) {
countDownLabel.text = String(count--)
}
}
```
Question 2:
You can do both. SpriteKit is the SDK you use for scene, motion, etc. Simple View Application is the project template. They should not conflict | **Swift 5 another way. *Resistant to interaction with UI***
I would like to show a solution that is resistant to user interaction with other UI elements during countdown.
In the comments I explained what each line of code means.
```
var timeToSet = 0
var timer: Timer?
...
@IBAction func btnWasPressed(_ sender: UIButton) {
//Setting the countdown time
timeLeft = timeToSet
//Disabling any previous timers.
timer?.invalidate()
//Initialization of the Timer with interval every 1 second with the function call.
timer = Timer(timeInterval: 1.0, target: self, selector: #selector(countDown), userInfo: nil, repeats: true)
//Adding Timer to the current loop
RunLoop.current.add(timer!, forMode: .common)
}
...
@objc func countDown() {
if timeLeft > 0 {
print(timeLeft)
timeLeft -= 1
} else {
// Timer stopping
timer?.invalidate()
}
}
``` |
29,374,553 | How can I make a countdown with an `NSTimer` using Swift? | 2015/03/31 | [
"https://Stackoverflow.com/questions/29374553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4548796/"
] | Variable for your timer
```
var timer = 60
```
NSTimer with 1.0 as interval
```
var clock = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "countdown", userInfo: nil, repeats: true)
```
Here you can decrease the timer
```
func countdown() {
timer--
}
``` | this is an egg timer.
```
import UIKit
class ViewController: UIViewController {
let eggTimes = ["Soft": 0.1, "Medium": 2, "Hard": 3]
var eggTime = 0
var timer = Timer()
@IBOutlet weak var label: UILabel!
@IBAction func b(_ sender: UIButton) {
timer.invalidate()
let hardness = sender.currentTitle!
eggTime = Int(eggTimes[hardness]! * 60)
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(update), userInfo: nil, repeats: true)
}
@objc func update() {
if (eggTime > 0) {
print("\(eggTime) seconds")
eggTime -= 1
}
if (eggTime == 0){
label.text = ("done")
}
}
}
``` |
29,374,553 | How can I make a countdown with an `NSTimer` using Swift? | 2015/03/31 | [
"https://Stackoverflow.com/questions/29374553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4548796/"
] | **Swift 4.1 and Swift 5.** The updatetime method will called after every second and seconds will display on UIlabel.
```
var timer: Timer?
var totalTime = 60
private func startOtpTimer() {
self.totalTime = 60
self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
}
@objc func updateTimer() {
print(self.totalTime)
self.lblTimer.text = self.timeFormatted(self.totalTime) // will show timer
if totalTime != 0 {
totalTime -= 1 // decrease counter timer
} else {
if let timer = self.timer {
timer.invalidate()
self.timer = nil
}
}
}
func timeFormatted(_ totalSeconds: Int) -> String {
let seconds: Int = totalSeconds % 60
let minutes: Int = (totalSeconds / 60) % 60
return String(format: "%02d:%02d", minutes, seconds)
}
``` | XCode 10 with Swift 4.2
```
import UIKit
class ViewController: UIViewController {
var timer = Timer()
var totalSecond = 10
override func viewDidLoad() {
super.viewDidLoad()
startTimer()
}
func startTimer() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}
@objc func updateTime() {
print(timeFormatted(totalSecond))
if totalSecond != 0 {
totalSecond -= 1
} else {
endTimer()
}
}
func endTimer() {
timer.invalidate()
}
func timeFormatted(_ totalSeconds: Int) -> String {
let seconds: Int = totalSeconds % 60
return String(format: "0:%02d", seconds)
}
}
``` |
29,374,553 | How can I make a countdown with an `NSTimer` using Swift? | 2015/03/31 | [
"https://Stackoverflow.com/questions/29374553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4548796/"
] | Swift 5 with Closure:
```
class ViewController: UIViewController {
var secondsRemaining = 30
@IBAction func startTimer(_ sender: UIButton) {
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (Timer) in
if self.secondsRemaining > 0 {
print ("\(self.secondsRemaining) seconds")
self.secondsRemaining -= 1
} else {
Timer.invalidate()
}
}
}
``` | Make Countdown app Xcode 8.1, Swift 3
```
import UIKit
import Foundation
class ViewController: UIViewController, UITextFieldDelegate {
var timerCount = 0
var timerRunning = false
@IBOutlet weak var timerLabel: UILabel! //ADD Label
@IBOutlet weak var textField: UITextField! //Add TextField /Enter any number to Countdown
override func viewDidLoad() {
super.viewDidLoad()
//Reset
timerLabel.text = ""
if timerCount == 0 {
timerRunning = false
}
}
//Figure out Count method
func Counting() {
if timerCount > 0 {
timerLabel.text = "\(timerCount)"
timerCount -= 1
} else {
timerLabel.text = "GO!"
}
}
//ADD Action Button
@IBAction func startButton(sender: UIButton) {
//Figure out timer
if timerRunning == false {
_ = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.Counting), userInfo: nil, repeats: true)
timerRunning = true
}
//unwrap textField and Display result
if let countebleNumber = Int(textField.text!) {
timerCount = countebleNumber
textField.text = "" //Clean Up TextField
} else {
timerCount = 3 //Defoult Number to Countdown if TextField is nil
textField.text = "" //Clean Up TextField
}
}
//Dismiss keyboard
func keyboardDismiss() {
textField.resignFirstResponder()
}
//ADD Gesture Recignizer to Dismiss keyboard then view tapped
@IBAction func viewTapped(_ sender: AnyObject) {
keyboardDismiss()
}
//Dismiss keyboard using Return Key (Done) Button
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
keyboardDismiss()
return true
}
}
```
<https://github.com/nikae/CountDown-> |
29,374,553 | How can I make a countdown with an `NSTimer` using Swift? | 2015/03/31 | [
"https://Stackoverflow.com/questions/29374553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4548796/"
] | In Swift 5.1 this will work:
```
var counter = 30
override func viewDidLoad() {
super.viewDidLoad()
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
}
@objc func updateCounter() {
//example functionality
if counter > 0 {
print("\(counter) seconds to the end of the world")
counter -= 1
}
}
``` | >
> Swift4
>
>
>
```
@IBOutlet weak var actionButton: UIButton!
@IBOutlet weak var timeLabel: UILabel!
var timer:Timer?
var timeLeft = 60
override func viewDidLoad() {
super.viewDidLoad()
setupTimer()
}
func setupTimer() {
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(onTimerFires), userInfo: nil, repeats: true)
}
@objc func onTimerFires() {
timeLeft -= 1
timeLabel.text = "\(timeLeft) seconds left"
if timeLeft <= 0 {
actionButton.isEnabled = true
actionButton.setTitle("enabled", for: .normal)
timer?.invalidate()
timer = nil
}
}
@IBAction func btnClicked(_ sender: UIButton) {
print("API Fired")
}
``` |
17,225,688 | I have a form that I'd like to reuse around a site, but there are times where I'd like to omit a specific field from the form. Is it possible to do this when initialising the form in the view? | 2013/06/20 | [
"https://Stackoverflow.com/questions/17225688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You may not be able to delete a field, but You can override the widget of the form in the form's `__init__` method.
```
from django import forms
class MyForm(forms.Form):
some_field=forms.CharField()
other_field=forms.CharField()
def __init__(self, my_criteria, *args,**kwrds):
super(MyForm,self).__init__(*args,**kwrds)
if my_criteria == 'this':
self.fields['some_field'].widget = forms.HiddenInput(required=False)
elif my_criteria == 'that':
self.fields['other_field'].widget=forms.HiddenInput(required=False)
#else: pass - leave it the way it is.
```
If you want to render different kinds of forms, you can pass in a parameter with specific values while declaring the form, and use that to render `HiddenInput` widget at runtime that would hide it from the form | I think there is no way only for ModelForm but what you can do is this
```
fromd django.forms import forms
class MyForm(forms.Form):
text = forms.CharField()
another_text = forms.CharField()
```
and in your view something like:
```
from myforms import MyForm
from django.shortcuts import render
def view(request):
form = MyForm(request.POST)
model = MyModel()
model.text = form.clean['text']
model.another_text = "Some value"
model.save()
return render(request, 'template.html', {'form':form})
```
and in your template.html:
```
<form action="">
{{form.text}}
</form>
```
this will only display a textfield in your template.html |
14,046,929 | I recently redesigned my website and now I have many lines of code that are not being used anymore when the website loads. Its really tedious to go through all the lines manually, is there any tool for this?
Thanks! | 2012/12/26 | [
"https://Stackoverflow.com/questions/14046929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1161412/"
] | Looks like <http://unused-css.com/> will check for unused CSS on your site.
Unused JS will be much tougher. | Found these for fixing html,
* <http://fixmyhtml.com/>
* <http://unfuckmyhtml.com/>
and these for fixing css
* <http://unused-css.com/>
* <https://github.com/giakki/uncss> (I personally recommend this. Great tool!) |
55,272,369 | I have a dictionary like
```py
{a:{b:{c:{d:2}}}, e:2, f:2}
```
How am I supposed to get the value of d and change it in python? Previous questions only showed how to get the level of nesting but didn't show how to get the value. In this case, I do not know the level of nesting of the dict. Any help will be appreciated, thank you!!!
P.S. I am using python 3 | 2019/03/21 | [
"https://Stackoverflow.com/questions/55272369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10383123/"
] | How about some recursion?
```
def unest(data, key):
if key in data.keys():
return data.get(key)
else:
for dkey in data.keys():
if isinstance(data.get(dkey), dict):
return unest(data.get(dkey), key)
else:
continue
d = {'a':{'b':{'c':{'d':25}}}, 'e':2, 'f':2}
r = unest(d, 'd')
# 25
r = unest(d, 'c')
# {'d': 25}
```
Edit: As Paul Rooney points out we don't have to use `data.keys`, we can simply iterate over the keys by doing `if key in data`
Edit 2: Given the input you provided this would find the deepest level, however this does not cover certain cases, such as where for example, key `e` is also a nested dictionary that goes `n + 1` levels where `n` is equal to the depth of key `a`.
```
def find_deepest(data):
if not any([isinstance(data.get(k), dict) for k in data]):
return data
else:
for dkey in data:
if isinstance(data.get(dkey), dict):
return find_deepest(data.get(dkey))
else:
continue
u = find_deepest(d)
# {'d': 2}
``` | I was searching for a similar solution, but I wanted to find the deepest instance of any key within a (possibly) nested dictionary and return it's value. This assumes you know what key you want to search for ahead of time. It's unclear to me if that is a valid assumption for the original question, but I hope this will help others if they stumble on this thread.
```
def find_deepest_item(obj, key, deepest_item = None):
if key in obj:
deepest_item = obj[key]
for k, v in obj.items():
if isinstance(v,dict):
item = find_deepest_item(v, key, deepest_item)
if item is not None:
deepest_item = item
return deepest_item
```
In this example, the 'd' key exists at the top level as well:
```
d = {'a':{'b':{'c':{'d':25}}}, 'd':3, 'e':2, 'f':2}
v = find_deepest_item(d, 'd')
# 25
```
Search for 'c':
```
v = find_deepest_item(d, 'c')
# {'d': 25}
``` |
15,847,920 | I have a draggable jquery popup window,now its shows a message inside its body.But i want to load a html page inside the popup how can i do this
here is the screen shot of my popup

here is my code
popup.php
```
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<style type="text/css">
#draggable { width: 200px; height: 250px; background: silver; }
</style>
<script>
$(document).ready(function() {
$("#draggable").draggable();
});
</script>
</head>
<body style="font-size:75%;">
<div id="draggable">Drag me</div>
</body>
</html>
```
Please help me ,Thanks | 2013/04/06 | [
"https://Stackoverflow.com/questions/15847920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2214797/"
] | ```
int h=10;
UILabel *lbl_headitem = [[UILabel alloc]initWithFrame:CGRectMake(3,h, 690, size_txt_overview1.height)];// See the 'h' value
lbl_headitem.text = [headItemArray objectAtIndex:k];
[lbl_headitem setTextAlignment:UITextAlignmentLeft];
[lbl_headitem setBackgroundColor:[UIColor clearColor]];
[lbl_headitem setTag:k];
lbl_headitem.numberOfLines=0;
[lbl_headitem setTextColor:[UIColor redColor]];
[lbl_headitem setFont:[UIFont fontWithName:@"Helvetica" size:18]];
[scrollAttributes addSubview:lbl_headitem];
h = h + size_txt_overview1.height;
```
**Make sure your label.numberOfLines are set to 0** | Hope the below code may work
```
CGSize size = [str sizeWithFont:lbl.font constrainedToSize:CGSizeMake(204.0, 10000.0) lineBreakMode:lbl.lineBreakMode];
```
here width or height one must be fixed.. |
15,847,920 | I have a draggable jquery popup window,now its shows a message inside its body.But i want to load a html page inside the popup how can i do this
here is the screen shot of my popup

here is my code
popup.php
```
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<style type="text/css">
#draggable { width: 200px; height: 250px; background: silver; }
</style>
<script>
$(document).ready(function() {
$("#draggable").draggable();
});
</script>
</head>
<body style="font-size:75%;">
<div id="draggable">Drag me</div>
</body>
</html>
```
Please help me ,Thanks | 2013/04/06 | [
"https://Stackoverflow.com/questions/15847920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2214797/"
] | Try it....
```
//Calculate the expected size based on the font and linebreak mode of your label
CGSize maximumLabelSize = CGSizeMake(296,9999);
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font
constrainedToSize:maximumLabelSize
lineBreakMode:yourLabel.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;
``` | ```
int h=10;
UILabel *lbl_headitem = [[UILabel alloc]initWithFrame:CGRectMake(3,h, 690, size_txt_overview1.height)];// See the 'h' value
lbl_headitem.text = [headItemArray objectAtIndex:k];
[lbl_headitem setTextAlignment:UITextAlignmentLeft];
[lbl_headitem setBackgroundColor:[UIColor clearColor]];
[lbl_headitem setTag:k];
lbl_headitem.numberOfLines=0;
[lbl_headitem setTextColor:[UIColor redColor]];
[lbl_headitem setFont:[UIFont fontWithName:@"Helvetica" size:18]];
[scrollAttributes addSubview:lbl_headitem];
h = h + size_txt_overview1.height;
```
**Make sure your label.numberOfLines are set to 0** |
15,847,920 | I have a draggable jquery popup window,now its shows a message inside its body.But i want to load a html page inside the popup how can i do this
here is the screen shot of my popup

here is my code
popup.php
```
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<style type="text/css">
#draggable { width: 200px; height: 250px; background: silver; }
</style>
<script>
$(document).ready(function() {
$("#draggable").draggable();
});
</script>
</head>
<body style="font-size:75%;">
<div id="draggable">Drag me</div>
</body>
</html>
```
Please help me ,Thanks | 2013/04/06 | [
"https://Stackoverflow.com/questions/15847920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2214797/"
] | ```
int h=10;
UILabel *lbl_headitem = [[UILabel alloc]initWithFrame:CGRectMake(3,h, 690, size_txt_overview1.height)];// See the 'h' value
lbl_headitem.text = [headItemArray objectAtIndex:k];
[lbl_headitem setTextAlignment:UITextAlignmentLeft];
[lbl_headitem setBackgroundColor:[UIColor clearColor]];
[lbl_headitem setTag:k];
lbl_headitem.numberOfLines=0;
[lbl_headitem setTextColor:[UIColor redColor]];
[lbl_headitem setFont:[UIFont fontWithName:@"Helvetica" size:18]];
[scrollAttributes addSubview:lbl_headitem];
h = h + size_txt_overview1.height;
```
**Make sure your label.numberOfLines are set to 0** | ```
func makeSizeSender(name:UILabel){
let attributes = [NSFontAttributeName : name.font]
let rect = name.text!.boundingRectWithSize(CGSizeMake(frame.size.width, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil)
name.frame = CGRectMake(contentView.frame.origin.x+30, 0, 200, rect.height+30);
self.addSubview(name)
}
``` |
15,847,920 | I have a draggable jquery popup window,now its shows a message inside its body.But i want to load a html page inside the popup how can i do this
here is the screen shot of my popup

here is my code
popup.php
```
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<style type="text/css">
#draggable { width: 200px; height: 250px; background: silver; }
</style>
<script>
$(document).ready(function() {
$("#draggable").draggable();
});
</script>
</head>
<body style="font-size:75%;">
<div id="draggable">Drag me</div>
</body>
</html>
```
Please help me ,Thanks | 2013/04/06 | [
"https://Stackoverflow.com/questions/15847920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2214797/"
] | Try it....
```
//Calculate the expected size based on the font and linebreak mode of your label
CGSize maximumLabelSize = CGSizeMake(296,9999);
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font
constrainedToSize:maximumLabelSize
lineBreakMode:yourLabel.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;
``` | Hope the below code may work
```
CGSize size = [str sizeWithFont:lbl.font constrainedToSize:CGSizeMake(204.0, 10000.0) lineBreakMode:lbl.lineBreakMode];
```
here width or height one must be fixed.. |
15,847,920 | I have a draggable jquery popup window,now its shows a message inside its body.But i want to load a html page inside the popup how can i do this
here is the screen shot of my popup

here is my code
popup.php
```
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<style type="text/css">
#draggable { width: 200px; height: 250px; background: silver; }
</style>
<script>
$(document).ready(function() {
$("#draggable").draggable();
});
</script>
</head>
<body style="font-size:75%;">
<div id="draggable">Drag me</div>
</body>
</html>
```
Please help me ,Thanks | 2013/04/06 | [
"https://Stackoverflow.com/questions/15847920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2214797/"
] | Hope the below code may work
```
CGSize size = [str sizeWithFont:lbl.font constrainedToSize:CGSizeMake(204.0, 10000.0) lineBreakMode:lbl.lineBreakMode];
```
here width or height one must be fixed.. | ```
func makeSizeSender(name:UILabel){
let attributes = [NSFontAttributeName : name.font]
let rect = name.text!.boundingRectWithSize(CGSizeMake(frame.size.width, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil)
name.frame = CGRectMake(contentView.frame.origin.x+30, 0, 200, rect.height+30);
self.addSubview(name)
}
``` |
15,847,920 | I have a draggable jquery popup window,now its shows a message inside its body.But i want to load a html page inside the popup how can i do this
here is the screen shot of my popup

here is my code
popup.php
```
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<style type="text/css">
#draggable { width: 200px; height: 250px; background: silver; }
</style>
<script>
$(document).ready(function() {
$("#draggable").draggable();
});
</script>
</head>
<body style="font-size:75%;">
<div id="draggable">Drag me</div>
</body>
</html>
```
Please help me ,Thanks | 2013/04/06 | [
"https://Stackoverflow.com/questions/15847920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2214797/"
] | Try it....
```
//Calculate the expected size based on the font and linebreak mode of your label
CGSize maximumLabelSize = CGSizeMake(296,9999);
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font
constrainedToSize:maximumLabelSize
lineBreakMode:yourLabel.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;
``` | ```
func makeSizeSender(name:UILabel){
let attributes = [NSFontAttributeName : name.font]
let rect = name.text!.boundingRectWithSize(CGSizeMake(frame.size.width, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil)
name.frame = CGRectMake(contentView.frame.origin.x+30, 0, 200, rect.height+30);
self.addSubview(name)
}
``` |
29,203 | In considering words with `-er` ending like "quandary" /ˈkwɑːn.dəɹɪ/, it seems like to me there is no difference between that IPA /ˈkwɑːn.dəɹɪ/ and /ˈkwɑːn.d.ɹɪ/, or "quand-ree". The [r] is like "rrrr" straight from the [d], as in "drrr".
There is a difference between those and "quandry", like "foundry", where the `d` and `r` *blend* together. But I don't know if there is a difference between /ˈkwɑːn.dəɹɪ/ and /ˈkwɑːn.d.ɹɪ/ ("quand-ree"). That [ə] seems like it is purely an *orthography* thing, which is spilling over into the IPA structure. But it is a silent a/u/e in the different words it appears in in English IMO, like "hurry" or "worry", those are basically "hrry" and "wrry". A word like "very" you actually *do* have an extra vowel between the `r` and the other letter, /ˈvɛɹi/ with "ai-rr" in there, not just a straight "rrrr".
It seems like the [ə] is added in the IPA purely because of the rules for syllabification in English perhaps (which I don't know much about), because if [h], [r], and [y] aren't vowels, then "hrry" can't be a grammatically correct word. But phonologically speaking, to me there is not actually an [ə] in between the [d] and [r] in "quandary".
But there also seems to be a few subtle variations in the way you could pronounce "quandary".
1. "quan-dery", with the d separated from the first syllable.
2. "quand-ery", with the d as part of the first syllable.
In (1), it seems clear there is no [ə] between the [d] and [r], but at the same time it is not a strait "drrr" *blend*. Instead there is a *shift* between the [d] and [r].
In (2), it seems it could go either way. You are essentially starting a fresh word by saying "errr". The question is if it is "errr" or "rrr". If I forcefully pronounce *just* "rrr", it starts of *smooth*. If I pronounce the more natural "errr", then it starts of with a "pop". The "pop" it seems is the reason for the [ə].
But instead of the [ə] you could do some sort of thing that is [intermediate between a *blend* and a *glottal stop*](https://linguistics.stackexchange.com/questions/29172/how-to-annotate-the-difference-between-blended-vowels-and-non-blended-vowels), which I don't know how to properly do with IPA. But maybe it would be like "'rrr", instead of "ʔrrr" or "ərrr". So the scale of pausing between the [d] and [r] would be `drrr -> d'rrr -> dʔrrr`, the "dʔrrr" being something that isn't really related to the "quandary" word. So then it would be /ˈkwɑːn.d'ɹɪ/.
So the question is if that [ə] in fact doesn't exist in the pronunciation, and it is instead carried over from the spelling/orthography of English words. And instead it is just some sort of *syllabification* of the [r], as well as a micro *separation* between the [d] and [r]. It seems that instead of "'rrr", you could do just the same writing it /ɹ̩/, or perhaps /'ɹ̩/ to capture both the "start r with a pop" and the syllabification. So we end up with /ˈkwɑːn.d'ɹ̩ɪ/.
Wondering if this is true, or what I am missing.
If the [ə] was "really" there, then I would pronounce it "quand-uh-rrrr-ee", like "quanduhrry", because the pronunciation of the [ə] is different from a straight "rrr" sound, or even from the pop at the beginning of the "errr" sound. It would be more like "uhrrrr".
Another word that seems to have this feature is `significant`. In speech you might pronounce it "sgnificant", or even "sgnificnt", or yet! "sgnifknt", where there is no vowel really between the [s] and [g], it's more like /sg/. Here since they *can't* blend (doesn't seem possible), you don't even need the pop symbol, as in /s'g/.
The word "elementary" doesn't even have this feature, it is more like "foundry", as in "elementry", but you can pronounce it if you want as "element'rry". | 2018/09/25 | [
"https://linguistics.stackexchange.com/questions/29203",
"https://linguistics.stackexchange.com",
"https://linguistics.stackexchange.com/users/3142/"
] | There really is, or really isn't, depending on the speaker. The OUP entry indicates that the schwa in "quandary" is optional for both UK and US English. The US token is pronounced with no schwa, the UK token is pronounced with one. Two versions of Jones' dictionary indicate a vowel, the Macmillan dictionary writes obligatory schwa but the recorded (US) token has no schwa, and the Websters site writes optional schwa, and the associated recording is hard to tell (those speakers over-articulate: it's not different from "laundry"). Similarly, some people have a schwa between *θ* and *l* in "athlete:, and some don't.
My recommendation is to carry a recorder with you at all times (wear a sign saying that you are taping everything, so as to not run afoul of the law), and later transcribe a day or two's worth of spontaneous speech. You may learn that 1 out of 5 tokens of your pronunciation of "quandary" has a schwa. On the other hand, everybody is capable of speech errors, so it's hard to know if an unusual token is an error or a rare variant. In this case, I think there is a US/UK factor to the difference. But it is not strict: the [Forvo repository](https://forvo.com/word/quandary/#en) suggests that it's random. It's actually rather amazing how variable pronunciations of words are even within US English and not including known dialect features. | In my dialect of American English, [r] becomes an obstruent (fricative) after [t], [d] in the same syllable, as in "dream", "drive", "trick", "trivial". This does not happen when schwa precedes the [r], or when the [r] is syllabic (which is approximately the same thing).
So, listen to the "r" in "quandary". If it's a fricative (and your dialect is like mine), that suggests there is no schwa intervening between [d] and [r]. Otherwise, there is.
It might also be interesting to observe the roundness of the [r], since [r] in the onset of a syllable is ordinarily rounded, suggesting there is no schwa, but in the offset of a syllable and unstressed, [r] is unrounded, suggesting there is a preceding schwa. |
24,659,708 | To my issue there are several similar questions but I haven't found a good one that would help me solve my problem. My problem is:
I want to convert a JQuery object into a Json String, and then post this string to a PHP webPage, This is running very good. But when I received it on the server(php page) it is full of escape characters.
Here is my code on the client:
```
var jsonRemision = JSON.stringify(remision,false);
$.post("updateremision.php",
{
rem:jsonRemision,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: false,
},
function(data,status){
if(status=="success"){
alert("Good Message");
}else{
alert("Bad Message");
}
});
```
and here is the code on the server:
```
$remision = json_decode($_POST['rem']);
```
Now, when I see whats inside of $\_POST['rem'] is full of escape characters \" . These escape character are not allowing me to jsondecode... The json full of escape characters looks like this:
```
{\"id\":\"12\",\"fecha\":\"2014-06-25\",\"ciudad\":\"Manizales\",\"camion\":\"NAQ376\",\"driver\":\"16075519\",\"cant\":\"0\",\"anticipos\":[{\"type\":\"1\",\"com\":\"Comment\",\"costo\":\"1234\"}]}
```
How can I remove the escape characters ?? thanks in advance for any comment or help :) | 2014/07/09 | [
"https://Stackoverflow.com/questions/24659708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3557746/"
] | Try this one. It is working for me.
```
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Set up the projection (we only need the ID)
String[] projection = { MediaStore.Images.Media._ID };
// Match on the file path
String selection = MediaStore.Images.Media.DATA + " = ?";
String[] selectionArgs = new String[] { imageFile.getAbsolutePath() };
// Query for the ID of the media matching the file path
Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver contentResolver = getActivity().getContentResolver();
Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);
if (c != null) {
if (c.moveToFirst()) {
// We found the ID. Deleting the item via the content provider will also remove the file
long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
Uri deleteUri = ContentUris.withAppendedId(queryUri, id);
contentResolver.delete(deleteUri, null, null);
} else {
// File not found in media store DB
}
c.close();
}
}
}, 5000);
``` | You can delete a file by using `delete()` method.
For that first you need to create a File reference in your code by specifying the path of the file as argument, then call `delete()` method to delete the file.
```
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/video1.mp4";
new File(path).delete();
``` |
24,659,708 | To my issue there are several similar questions but I haven't found a good one that would help me solve my problem. My problem is:
I want to convert a JQuery object into a Json String, and then post this string to a PHP webPage, This is running very good. But when I received it on the server(php page) it is full of escape characters.
Here is my code on the client:
```
var jsonRemision = JSON.stringify(remision,false);
$.post("updateremision.php",
{
rem:jsonRemision,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: false,
},
function(data,status){
if(status=="success"){
alert("Good Message");
}else{
alert("Bad Message");
}
});
```
and here is the code on the server:
```
$remision = json_decode($_POST['rem']);
```
Now, when I see whats inside of $\_POST['rem'] is full of escape characters \" . These escape character are not allowing me to jsondecode... The json full of escape characters looks like this:
```
{\"id\":\"12\",\"fecha\":\"2014-06-25\",\"ciudad\":\"Manizales\",\"camion\":\"NAQ376\",\"driver\":\"16075519\",\"cant\":\"0\",\"anticipos\":[{\"type\":\"1\",\"com\":\"Comment\",\"costo\":\"1234\"}]}
```
How can I remove the escape characters ?? thanks in advance for any comment or help :) | 2014/07/09 | [
"https://Stackoverflow.com/questions/24659708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3557746/"
] | Try this one. It is working for me.
```
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Set up the projection (we only need the ID)
String[] projection = { MediaStore.Images.Media._ID };
// Match on the file path
String selection = MediaStore.Images.Media.DATA + " = ?";
String[] selectionArgs = new String[] { imageFile.getAbsolutePath() };
// Query for the ID of the media matching the file path
Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver contentResolver = getActivity().getContentResolver();
Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);
if (c != null) {
if (c.moveToFirst()) {
// We found the ID. Deleting the item via the content provider will also remove the file
long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
Uri deleteUri = ContentUris.withAppendedId(queryUri, id);
contentResolver.delete(deleteUri, null, null);
} else {
// File not found in media store DB
}
c.close();
}
}
}, 5000);
``` | ```java
File file=new File(getFilePath(imageUri.getValue()));
boolean b= file.delete();
```
not working in my case. The issue has been resolved by using below code-
```java
ContentResolver contentResolver = getContentResolver ();
contentResolver.delete (uriDelete,null ,null );
``` |
24,659,708 | To my issue there are several similar questions but I haven't found a good one that would help me solve my problem. My problem is:
I want to convert a JQuery object into a Json String, and then post this string to a PHP webPage, This is running very good. But when I received it on the server(php page) it is full of escape characters.
Here is my code on the client:
```
var jsonRemision = JSON.stringify(remision,false);
$.post("updateremision.php",
{
rem:jsonRemision,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: false,
},
function(data,status){
if(status=="success"){
alert("Good Message");
}else{
alert("Bad Message");
}
});
```
and here is the code on the server:
```
$remision = json_decode($_POST['rem']);
```
Now, when I see whats inside of $\_POST['rem'] is full of escape characters \" . These escape character are not allowing me to jsondecode... The json full of escape characters looks like this:
```
{\"id\":\"12\",\"fecha\":\"2014-06-25\",\"ciudad\":\"Manizales\",\"camion\":\"NAQ376\",\"driver\":\"16075519\",\"cant\":\"0\",\"anticipos\":[{\"type\":\"1\",\"com\":\"Comment\",\"costo\":\"1234\"}]}
```
How can I remove the escape characters ?? thanks in advance for any comment or help :) | 2014/07/09 | [
"https://Stackoverflow.com/questions/24659708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3557746/"
] | Try this one. It is working for me.
```
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Set up the projection (we only need the ID)
String[] projection = { MediaStore.Images.Media._ID };
// Match on the file path
String selection = MediaStore.Images.Media.DATA + " = ?";
String[] selectionArgs = new String[] { imageFile.getAbsolutePath() };
// Query for the ID of the media matching the file path
Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver contentResolver = getActivity().getContentResolver();
Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);
if (c != null) {
if (c.moveToFirst()) {
// We found the ID. Deleting the item via the content provider will also remove the file
long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
Uri deleteUri = ContentUris.withAppendedId(queryUri, id);
contentResolver.delete(deleteUri, null, null);
} else {
// File not found in media store DB
}
c.close();
}
}
}, 5000);
``` | I tested this code on Nougat emulator and it worked:
In manifest add:
```
<application...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
</application>
```
Create empty xml folder in res folder and past in the provider\_paths.xml:
```
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
```
Then put the next snippet into your code (for instance fragment):
```
File photoLcl = new File(homeDirectory + "/" + fileNameLcl);
Uri imageUriLcl = FileProvider.getUriForFile(getActivity(),
getActivity().getApplicationContext().getPackageName() +
".provider", photoLcl);
ContentResolver contentResolver = getActivity().getContentResolver();
contentResolver.delete(imageUriLcl, null, null);
``` |
24,659,708 | To my issue there are several similar questions but I haven't found a good one that would help me solve my problem. My problem is:
I want to convert a JQuery object into a Json String, and then post this string to a PHP webPage, This is running very good. But when I received it on the server(php page) it is full of escape characters.
Here is my code on the client:
```
var jsonRemision = JSON.stringify(remision,false);
$.post("updateremision.php",
{
rem:jsonRemision,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: false,
},
function(data,status){
if(status=="success"){
alert("Good Message");
}else{
alert("Bad Message");
}
});
```
and here is the code on the server:
```
$remision = json_decode($_POST['rem']);
```
Now, when I see whats inside of $\_POST['rem'] is full of escape characters \" . These escape character are not allowing me to jsondecode... The json full of escape characters looks like this:
```
{\"id\":\"12\",\"fecha\":\"2014-06-25\",\"ciudad\":\"Manizales\",\"camion\":\"NAQ376\",\"driver\":\"16075519\",\"cant\":\"0\",\"anticipos\":[{\"type\":\"1\",\"com\":\"Comment\",\"costo\":\"1234\"}]}
```
How can I remove the escape characters ?? thanks in advance for any comment or help :) | 2014/07/09 | [
"https://Stackoverflow.com/questions/24659708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3557746/"
] | ```java
File file=new File(getFilePath(imageUri.getValue()));
boolean b= file.delete();
```
not working in my case. The issue has been resolved by using below code-
```java
ContentResolver contentResolver = getContentResolver ();
contentResolver.delete (uriDelete,null ,null );
``` | You can delete a file by using `delete()` method.
For that first you need to create a File reference in your code by specifying the path of the file as argument, then call `delete()` method to delete the file.
```
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/video1.mp4";
new File(path).delete();
``` |
24,659,708 | To my issue there are several similar questions but I haven't found a good one that would help me solve my problem. My problem is:
I want to convert a JQuery object into a Json String, and then post this string to a PHP webPage, This is running very good. But when I received it on the server(php page) it is full of escape characters.
Here is my code on the client:
```
var jsonRemision = JSON.stringify(remision,false);
$.post("updateremision.php",
{
rem:jsonRemision,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: false,
},
function(data,status){
if(status=="success"){
alert("Good Message");
}else{
alert("Bad Message");
}
});
```
and here is the code on the server:
```
$remision = json_decode($_POST['rem']);
```
Now, when I see whats inside of $\_POST['rem'] is full of escape characters \" . These escape character are not allowing me to jsondecode... The json full of escape characters looks like this:
```
{\"id\":\"12\",\"fecha\":\"2014-06-25\",\"ciudad\":\"Manizales\",\"camion\":\"NAQ376\",\"driver\":\"16075519\",\"cant\":\"0\",\"anticipos\":[{\"type\":\"1\",\"com\":\"Comment\",\"costo\":\"1234\"}]}
```
How can I remove the escape characters ?? thanks in advance for any comment or help :) | 2014/07/09 | [
"https://Stackoverflow.com/questions/24659708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3557746/"
] | I tested this code on Nougat emulator and it worked:
In manifest add:
```
<application...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
</application>
```
Create empty xml folder in res folder and past in the provider\_paths.xml:
```
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
```
Then put the next snippet into your code (for instance fragment):
```
File photoLcl = new File(homeDirectory + "/" + fileNameLcl);
Uri imageUriLcl = FileProvider.getUriForFile(getActivity(),
getActivity().getApplicationContext().getPackageName() +
".provider", photoLcl);
ContentResolver contentResolver = getActivity().getContentResolver();
contentResolver.delete(imageUriLcl, null, null);
``` | ```java
File file=new File(getFilePath(imageUri.getValue()));
boolean b= file.delete();
```
not working in my case. The issue has been resolved by using below code-
```java
ContentResolver contentResolver = getContentResolver ();
contentResolver.delete (uriDelete,null ,null );
``` |
24,659,708 | To my issue there are several similar questions but I haven't found a good one that would help me solve my problem. My problem is:
I want to convert a JQuery object into a Json String, and then post this string to a PHP webPage, This is running very good. But when I received it on the server(php page) it is full of escape characters.
Here is my code on the client:
```
var jsonRemision = JSON.stringify(remision,false);
$.post("updateremision.php",
{
rem:jsonRemision,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: false,
},
function(data,status){
if(status=="success"){
alert("Good Message");
}else{
alert("Bad Message");
}
});
```
and here is the code on the server:
```
$remision = json_decode($_POST['rem']);
```
Now, when I see whats inside of $\_POST['rem'] is full of escape characters \" . These escape character are not allowing me to jsondecode... The json full of escape characters looks like this:
```
{\"id\":\"12\",\"fecha\":\"2014-06-25\",\"ciudad\":\"Manizales\",\"camion\":\"NAQ376\",\"driver\":\"16075519\",\"cant\":\"0\",\"anticipos\":[{\"type\":\"1\",\"com\":\"Comment\",\"costo\":\"1234\"}]}
```
How can I remove the escape characters ?? thanks in advance for any comment or help :) | 2014/07/09 | [
"https://Stackoverflow.com/questions/24659708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3557746/"
] | Why don't you test this with this code:
```
File fdelete = new File(uri.getPath());
if (fdelete.exists()) {
if (fdelete.delete()) {
System.out.println("file Deleted :" + uri.getPath());
} else {
System.out.println("file not Deleted :" + uri.getPath());
}
}
```
I think part of the problem is you never try to delete the file, you just keep creating a variable that has a method call.
So in your case you could try:
```
File file = new File(uri.getPath());
file.delete();
if(file.exists()){
file.getCanonicalFile().delete();
if(file.exists()){
getApplicationContext().deleteFile(file.getName());
}
}
```
However I think that's a little overkill.
You added a comment that you are using an external directory rather than a uri. So instead you should add something like:
```
String root = Environment.getExternalStorageDirectory().toString();
File file = new File(root + "/images/media/2918");
```
Then try to delete the file. | I see you've found your answer, however it didn't work for me. Delete kept returning false, so I tried the following and it worked (For anybody else for whom the chosen answer didn't work):
```
System.out.println(new File(path).getAbsoluteFile().delete());
```
The System out can be ignored obviously, I put it for convenience of confirming the deletion. |
24,659,708 | To my issue there are several similar questions but I haven't found a good one that would help me solve my problem. My problem is:
I want to convert a JQuery object into a Json String, and then post this string to a PHP webPage, This is running very good. But when I received it on the server(php page) it is full of escape characters.
Here is my code on the client:
```
var jsonRemision = JSON.stringify(remision,false);
$.post("updateremision.php",
{
rem:jsonRemision,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: false,
},
function(data,status){
if(status=="success"){
alert("Good Message");
}else{
alert("Bad Message");
}
});
```
and here is the code on the server:
```
$remision = json_decode($_POST['rem']);
```
Now, when I see whats inside of $\_POST['rem'] is full of escape characters \" . These escape character are not allowing me to jsondecode... The json full of escape characters looks like this:
```
{\"id\":\"12\",\"fecha\":\"2014-06-25\",\"ciudad\":\"Manizales\",\"camion\":\"NAQ376\",\"driver\":\"16075519\",\"cant\":\"0\",\"anticipos\":[{\"type\":\"1\",\"com\":\"Comment\",\"costo\":\"1234\"}]}
```
How can I remove the escape characters ?? thanks in advance for any comment or help :) | 2014/07/09 | [
"https://Stackoverflow.com/questions/24659708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3557746/"
] | Why don't you test this with this code:
```
File fdelete = new File(uri.getPath());
if (fdelete.exists()) {
if (fdelete.delete()) {
System.out.println("file Deleted :" + uri.getPath());
} else {
System.out.println("file not Deleted :" + uri.getPath());
}
}
```
I think part of the problem is you never try to delete the file, you just keep creating a variable that has a method call.
So in your case you could try:
```
File file = new File(uri.getPath());
file.delete();
if(file.exists()){
file.getCanonicalFile().delete();
if(file.exists()){
getApplicationContext().deleteFile(file.getName());
}
}
```
However I think that's a little overkill.
You added a comment that you are using an external directory rather than a uri. So instead you should add something like:
```
String root = Environment.getExternalStorageDirectory().toString();
File file = new File(root + "/images/media/2918");
```
Then try to delete the file. | You can delete a file by using `delete()` method.
For that first you need to create a File reference in your code by specifying the path of the file as argument, then call `delete()` method to delete the file.
```
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/video1.mp4";
new File(path).delete();
``` |
24,659,708 | To my issue there are several similar questions but I haven't found a good one that would help me solve my problem. My problem is:
I want to convert a JQuery object into a Json String, and then post this string to a PHP webPage, This is running very good. But when I received it on the server(php page) it is full of escape characters.
Here is my code on the client:
```
var jsonRemision = JSON.stringify(remision,false);
$.post("updateremision.php",
{
rem:jsonRemision,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: false,
},
function(data,status){
if(status=="success"){
alert("Good Message");
}else{
alert("Bad Message");
}
});
```
and here is the code on the server:
```
$remision = json_decode($_POST['rem']);
```
Now, when I see whats inside of $\_POST['rem'] is full of escape characters \" . These escape character are not allowing me to jsondecode... The json full of escape characters looks like this:
```
{\"id\":\"12\",\"fecha\":\"2014-06-25\",\"ciudad\":\"Manizales\",\"camion\":\"NAQ376\",\"driver\":\"16075519\",\"cant\":\"0\",\"anticipos\":[{\"type\":\"1\",\"com\":\"Comment\",\"costo\":\"1234\"}]}
```
How can I remove the escape characters ?? thanks in advance for any comment or help :) | 2014/07/09 | [
"https://Stackoverflow.com/questions/24659708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3557746/"
] | Why don't you test this with this code:
```
File fdelete = new File(uri.getPath());
if (fdelete.exists()) {
if (fdelete.delete()) {
System.out.println("file Deleted :" + uri.getPath());
} else {
System.out.println("file not Deleted :" + uri.getPath());
}
}
```
I think part of the problem is you never try to delete the file, you just keep creating a variable that has a method call.
So in your case you could try:
```
File file = new File(uri.getPath());
file.delete();
if(file.exists()){
file.getCanonicalFile().delete();
if(file.exists()){
getApplicationContext().deleteFile(file.getName());
}
}
```
However I think that's a little overkill.
You added a comment that you are using an external directory rather than a uri. So instead you should add something like:
```
String root = Environment.getExternalStorageDirectory().toString();
File file = new File(root + "/images/media/2918");
```
Then try to delete the file. | ```java
File file=new File(getFilePath(imageUri.getValue()));
boolean b= file.delete();
```
not working in my case. The issue has been resolved by using below code-
```java
ContentResolver contentResolver = getContentResolver ();
contentResolver.delete (uriDelete,null ,null );
``` |
24,659,708 | To my issue there are several similar questions but I haven't found a good one that would help me solve my problem. My problem is:
I want to convert a JQuery object into a Json String, and then post this string to a PHP webPage, This is running very good. But when I received it on the server(php page) it is full of escape characters.
Here is my code on the client:
```
var jsonRemision = JSON.stringify(remision,false);
$.post("updateremision.php",
{
rem:jsonRemision,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: false,
},
function(data,status){
if(status=="success"){
alert("Good Message");
}else{
alert("Bad Message");
}
});
```
and here is the code on the server:
```
$remision = json_decode($_POST['rem']);
```
Now, when I see whats inside of $\_POST['rem'] is full of escape characters \" . These escape character are not allowing me to jsondecode... The json full of escape characters looks like this:
```
{\"id\":\"12\",\"fecha\":\"2014-06-25\",\"ciudad\":\"Manizales\",\"camion\":\"NAQ376\",\"driver\":\"16075519\",\"cant\":\"0\",\"anticipos\":[{\"type\":\"1\",\"com\":\"Comment\",\"costo\":\"1234\"}]}
```
How can I remove the escape characters ?? thanks in advance for any comment or help :) | 2014/07/09 | [
"https://Stackoverflow.com/questions/24659708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3557746/"
] | I see you've found your answer, however it didn't work for me. Delete kept returning false, so I tried the following and it worked (For anybody else for whom the chosen answer didn't work):
```
System.out.println(new File(path).getAbsoluteFile().delete());
```
The System out can be ignored obviously, I put it for convenience of confirming the deletion. | first call the intent
```
Intent intenta = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intenta, 42);
```
then call the result
```
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 42:
if (resultCode == Activity.RESULT_OK) {
Uri sdCardUri = data.getData();
DocumentFile pickedDir = DocumentFile.fromTreeUri(this, sdCardUri);
for (DocumentFile file : pickedDir.listFiles()) {
String pp = file.getName();
if(pp.equals("VLC.apk"))
file.delete();
String ppdf="";
}
File pathFile = new File(String.valueOf(sdCardUri));
pathFile.delete();
}
break;
}
}
``` |
24,659,708 | To my issue there are several similar questions but I haven't found a good one that would help me solve my problem. My problem is:
I want to convert a JQuery object into a Json String, and then post this string to a PHP webPage, This is running very good. But when I received it on the server(php page) it is full of escape characters.
Here is my code on the client:
```
var jsonRemision = JSON.stringify(remision,false);
$.post("updateremision.php",
{
rem:jsonRemision,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: false,
},
function(data,status){
if(status=="success"){
alert("Good Message");
}else{
alert("Bad Message");
}
});
```
and here is the code on the server:
```
$remision = json_decode($_POST['rem']);
```
Now, when I see whats inside of $\_POST['rem'] is full of escape characters \" . These escape character are not allowing me to jsondecode... The json full of escape characters looks like this:
```
{\"id\":\"12\",\"fecha\":\"2014-06-25\",\"ciudad\":\"Manizales\",\"camion\":\"NAQ376\",\"driver\":\"16075519\",\"cant\":\"0\",\"anticipos\":[{\"type\":\"1\",\"com\":\"Comment\",\"costo\":\"1234\"}]}
```
How can I remove the escape characters ?? thanks in advance for any comment or help :) | 2014/07/09 | [
"https://Stackoverflow.com/questions/24659708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3557746/"
] | Try this one. It is working for me.
```
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Set up the projection (we only need the ID)
String[] projection = { MediaStore.Images.Media._ID };
// Match on the file path
String selection = MediaStore.Images.Media.DATA + " = ?";
String[] selectionArgs = new String[] { imageFile.getAbsolutePath() };
// Query for the ID of the media matching the file path
Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver contentResolver = getActivity().getContentResolver();
Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);
if (c != null) {
if (c.moveToFirst()) {
// We found the ID. Deleting the item via the content provider will also remove the file
long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
Uri deleteUri = ContentUris.withAppendedId(queryUri, id);
contentResolver.delete(deleteUri, null, null);
} else {
// File not found in media store DB
}
c.close();
}
}
}, 5000);
``` | first call the intent
```
Intent intenta = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intenta, 42);
```
then call the result
```
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 42:
if (resultCode == Activity.RESULT_OK) {
Uri sdCardUri = data.getData();
DocumentFile pickedDir = DocumentFile.fromTreeUri(this, sdCardUri);
for (DocumentFile file : pickedDir.listFiles()) {
String pp = file.getName();
if(pp.equals("VLC.apk"))
file.delete();
String ppdf="";
}
File pathFile = new File(String.valueOf(sdCardUri));
pathFile.delete();
}
break;
}
}
``` |
926,454 | How to evaluate integral $$\int\_{0}^{\infty}\frac{\cos(2x+1)}{\sqrt[3]{x}}\text dx?$$ I tried substitution $x=u^3$ and I got $3\displaystyle\int\_{0}^{\infty}u \cos(2u^3+1)\text du$. After that I tried to use integration by parts but I don't know the integral $\displaystyle\int \cos(2u^3+1)\text du$. Any idea? Thanks in advance. | 2014/09/10 | [
"https://math.stackexchange.com/questions/926454",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/146687/"
] | Here is how. The approach is based on Mellin transform.
>
> $$I = \int\_{0}^{\infty}\frac{\cos(2x+1)}{\sqrt[3]{x}}dx = \cos(1)\int\_{0}^{\infty}\frac{\cos(2x)}{\sqrt[3]{x}}dx -\sin(1)\int\_{0}^{\infty}\frac{\sin(2x)}{\sqrt[3]{x}}dx . $$
>
>
>
To evaluate the integrals on the right hand side make the change of variables $t=2x$ and use the [Mellin transform (see tables)](http://mathworld.wolfram.com/MellinTransform.html) of $\cos(x)$ and $\sin(x)$ and then take the limit as $s \to 2/3 $. I believe you can finish the problem. See [related techniques](https://math.stackexchange.com/questions/607141/fourier-transform-of-fx-frac1exe-x2). | Hint: $\cos(2x+1) = \Re e^{i(2x+1)}$ and $\int\_0^\infty \text dx\, x^{a-1} e^{-x} = \Gamma(a)$. The latter equation can be analytically continued to complex exponentials, as long as the integral converges.
Also, why does the new Latex font look terrible? |
926,454 | How to evaluate integral $$\int\_{0}^{\infty}\frac{\cos(2x+1)}{\sqrt[3]{x}}\text dx?$$ I tried substitution $x=u^3$ and I got $3\displaystyle\int\_{0}^{\infty}u \cos(2u^3+1)\text du$. After that I tried to use integration by parts but I don't know the integral $\displaystyle\int \cos(2u^3+1)\text du$. Any idea? Thanks in advance. | 2014/09/10 | [
"https://math.stackexchange.com/questions/926454",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/146687/"
] | $$\color{blue}{\mathcal{I}=\frac{\Gamma(\frac{2}{3})\cos(1+\frac{\pi}{3})}{2^{2/3}}\approx-0.391190966503539\cdots}$$
---
\begin{align}
\int^\infty\_0\frac{\cos(2x+1)}{x^{1/3}}{\rm d}x
&=\int^\infty\_0\frac{\cos(2x+1)}{\Gamma(\frac{1}{3})}\int^\infty\_0t^{-2/3}e^{-xt} \ {\rm d}t \ {\rm d}x\tag1\\
&=\frac{1}{\Gamma(\frac{1}{3})}\int^\infty\_0t^{-2/3}\int^\infty\_0e^{-xt}\cos(2x+1) \ {\rm d}x \ {\rm d}t\\
&=\frac{\cos(1)}{\Gamma(\frac{1}{3})}\int^\infty\_0\frac{t^{1/3}}{t^2+4}{\rm d}t-\frac{2\sin(1)}{\Gamma(\frac{1}{3})}\int^\infty\_0\frac{t^{-2/3}}{t^2+4}{\rm d}t\tag2\\
&=\frac{\cos(1)}{2^{2/3}\Gamma(\frac{1}{3})}\int^\infty\_0\frac{t^{1/3}}{1+t^2}{\rm d}t-\frac{\sin(1)}{2^{2/3}\Gamma(\frac{1}{3})}\int^\infty\_0\frac{t^{-2/3}}{1+t^2}{\rm d}t\tag3\\
&=\frac{\cos(1)}{2^{5/3}\Gamma(\frac{1}{3})}\int^\infty\_0\frac{t^{-1/3}}{1+t}{\rm d}t-\frac{\sin(1)}{2^{5/3}\Gamma(\frac{1}{3})}\int^\infty\_0\frac{t^{-5/6}}{1+t}{\rm d}t\tag4\\
&=\frac{\pi\left(\cos(1)-\sqrt{3}\sin(1)\right)}{2^{2/3}\Gamma(\frac{1}{3})\sqrt{3}}\tag5\\
&=\frac{2\pi\cos(1+\frac{\pi}{3})}{2^{2/3}\frac{2\pi}{\Gamma(\frac{2}{3})\sqrt{3}}\sqrt{3}}\tag6\\
&=\frac{\Gamma(\frac{2}{3})\cos(1+\frac{\pi}{3})}{2^{2/3}}
\end{align}
---
**Explanation:**
$(1)$: $\small{\displaystyle\frac{1}{x^n}=\frac{1}{\Gamma(n)}\int^\infty\_0t^{n-1}e^{-xt}{\rm d}t}$
$(2)$: $\displaystyle\cos(a+b)=\cos(a)\cos(b)-\sin(a)\sin(b)$
$(2)$: $\small{\displaystyle\int^\infty\_0e^{-ax}\sin(bx){\rm d}x=\frac{b}{a^2+b^2}}$
$(2)$: $\small{\displaystyle\int^\infty\_0e^{-ax}\cos(bx){\rm d}x=\frac{a}{a^2+b^2}}$
$(3)$: $\displaystyle t\mapsto 2t$
$(4)$: $\displaystyle t\mapsto \sqrt{t}$
$(5)$: $\small{\displaystyle\int^\infty\_0\frac{x^{p-1}}{1+x}{\rm d}x=\pi\csc(p\pi)}$
$(6)$: $\small{\displaystyle \Gamma(z)=\frac{\pi\csc(\pi z)}{\Gamma(1-z)}}$, $\small{\displaystyle a\cos{x}-b\sin{x}=\sqrt{a^2+b^2}\cos(x+\arctan{\frac{b}{a}})}$ | Hint: $\cos(2x+1) = \Re e^{i(2x+1)}$ and $\int\_0^\infty \text dx\, x^{a-1} e^{-x} = \Gamma(a)$. The latter equation can be analytically continued to complex exponentials, as long as the integral converges.
Also, why does the new Latex font look terrible? |
926,454 | How to evaluate integral $$\int\_{0}^{\infty}\frac{\cos(2x+1)}{\sqrt[3]{x}}\text dx?$$ I tried substitution $x=u^3$ and I got $3\displaystyle\int\_{0}^{\infty}u \cos(2u^3+1)\text du$. After that I tried to use integration by parts but I don't know the integral $\displaystyle\int \cos(2u^3+1)\text du$. Any idea? Thanks in advance. | 2014/09/10 | [
"https://math.stackexchange.com/questions/926454",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/146687/"
] | $\newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
\newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
\newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
\newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
\newcommand{\dd}{{\rm d}}
\newcommand{\ds}[1]{\displaystyle{#1}}
\newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
\newcommand{\fermi}{\,{\rm f}}
\newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
\newcommand{\half}{{1 \over 2}}
\newcommand{\ic}{{\rm i}}
\newcommand{\iff}{\Longleftrightarrow}
\newcommand{\imp}{\Longrightarrow}
\newcommand{\pars}[1]{\left(\, #1 \,\right)}
\newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
\newcommand{\pp}{{\cal P}}
\newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
\newcommand{\sech}{\,{\rm sech}}
\newcommand{\sgn}{\,{\rm sgn}}
\newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
\newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
$\ds{\int\_{0}^{\infty}{\cos\pars{2x + 1} \over \root[3]{x}}\,\dd x:\ {\large ?}}$.
>
> \begin{align}
> &\color{#c00000}{\int\_{0}^{\infty}{\cos\pars{2x + 1} \over \root[3]{x}}\,\dd x}
> =\Re\bracks{\expo{\ic}\ \overbrace{\int\_{0}^{\infty}x^{-1/3}\expo{2x\ic}\,\dd x}
> ^{\ds{x \equiv \ic t/2=\expo{\pi\ic/2}t/2\ \imp\ t = -2\ic x}}}\ =\
> \\[3mm]&=\Re\bracks{\expo{\ic}\int\_{0}^{-\infty\ic}%
> \pars{\expo{\pi\ic/2}t \over 2}^{-1/3}\expo{2\pars{\ic t/2}\ic}\,{\ic \over 2}
> \,\dd t}
> \\[3mm]&=-2^{-2/3}\,\Im\bracks{\expo{\pars{1 - \pi/6}\ic}
> \int\_{0}^{-\infty\ic}t^{-1/3}\expo{-t}\,\dd t}
> \\[3mm]&=-2^{-2/3}\,\Im\braces{\expo{\pars{1 - \pi/6}\ic}
> \lim\_{R\ \to\ \infty}\bracks{-\int\_{R}^{0}t^{-1/3}\expo{-t}\,\dd t
> -\left.\int\_{-\pi/2}^{0}\,z^{-1/3}\expo{-z}\,\dd z
> \right\vert\_{z\ =\ R\expo{\ic\theta}}}}
> \end{align}
>
>
>
However,
\begin{align}
&\color{#c00000}{\large%
\verts{\int\_{-\pi/2}^{0}\,z^{-1/3}\expo{-z}\,\dd z}\_{\,z\ =\ R\expo{\ic\theta}}}
\leq \verts{\int\_{-\pi/2}^{0}R^{-1/3}\expo{-R\cos\pars{\theta}}R\,\dd\theta}
=R^{2/3}\int\_{0}^{\pi/2}\expo{-R\sin\pars{\theta}}\,\dd\theta
\\[3mm]& < R^{2/3}\int\_{0}^{\pi/2}\expo{-2R\theta/\pi}\,\dd\theta
={\pi \over 2}\,R^{-1/3}\pars{1 - \expo{-R}}
\color{#c00000}{\large\stackrel{R \to \infty}{\to} 0}
\end{align}
>
> Then,
> \begin{align}
> &\color{#66f}{\large\int\_{0}^{\infty}{\cos\pars{2x + 1} \over \root[3]{x}}\,\dd x}
> =-2^{-2/3}\sin\pars{1 - {\pi \over 6}}\int\_{0}^{\infty}t^{-1/3}\expo{-t}\,\dd t
> \\[3mm]&=\color{#66f}{\large%
> -2^{-2/3}\sin\pars{1 - {\pi \over 6}}\Gamma\pars{2 \over 3}}
> \approx {\tt -0.3911}
> \end{align}
>
>
> | Hint: $\cos(2x+1) = \Re e^{i(2x+1)}$ and $\int\_0^\infty \text dx\, x^{a-1} e^{-x} = \Gamma(a)$. The latter equation can be analytically continued to complex exponentials, as long as the integral converges.
Also, why does the new Latex font look terrible? |
926,454 | How to evaluate integral $$\int\_{0}^{\infty}\frac{\cos(2x+1)}{\sqrt[3]{x}}\text dx?$$ I tried substitution $x=u^3$ and I got $3\displaystyle\int\_{0}^{\infty}u \cos(2u^3+1)\text du$. After that I tried to use integration by parts but I don't know the integral $\displaystyle\int \cos(2u^3+1)\text du$. Any idea? Thanks in advance. | 2014/09/10 | [
"https://math.stackexchange.com/questions/926454",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/146687/"
] | $$\color{blue}{\mathcal{I}=\frac{\Gamma(\frac{2}{3})\cos(1+\frac{\pi}{3})}{2^{2/3}}\approx-0.391190966503539\cdots}$$
---
\begin{align}
\int^\infty\_0\frac{\cos(2x+1)}{x^{1/3}}{\rm d}x
&=\int^\infty\_0\frac{\cos(2x+1)}{\Gamma(\frac{1}{3})}\int^\infty\_0t^{-2/3}e^{-xt} \ {\rm d}t \ {\rm d}x\tag1\\
&=\frac{1}{\Gamma(\frac{1}{3})}\int^\infty\_0t^{-2/3}\int^\infty\_0e^{-xt}\cos(2x+1) \ {\rm d}x \ {\rm d}t\\
&=\frac{\cos(1)}{\Gamma(\frac{1}{3})}\int^\infty\_0\frac{t^{1/3}}{t^2+4}{\rm d}t-\frac{2\sin(1)}{\Gamma(\frac{1}{3})}\int^\infty\_0\frac{t^{-2/3}}{t^2+4}{\rm d}t\tag2\\
&=\frac{\cos(1)}{2^{2/3}\Gamma(\frac{1}{3})}\int^\infty\_0\frac{t^{1/3}}{1+t^2}{\rm d}t-\frac{\sin(1)}{2^{2/3}\Gamma(\frac{1}{3})}\int^\infty\_0\frac{t^{-2/3}}{1+t^2}{\rm d}t\tag3\\
&=\frac{\cos(1)}{2^{5/3}\Gamma(\frac{1}{3})}\int^\infty\_0\frac{t^{-1/3}}{1+t}{\rm d}t-\frac{\sin(1)}{2^{5/3}\Gamma(\frac{1}{3})}\int^\infty\_0\frac{t^{-5/6}}{1+t}{\rm d}t\tag4\\
&=\frac{\pi\left(\cos(1)-\sqrt{3}\sin(1)\right)}{2^{2/3}\Gamma(\frac{1}{3})\sqrt{3}}\tag5\\
&=\frac{2\pi\cos(1+\frac{\pi}{3})}{2^{2/3}\frac{2\pi}{\Gamma(\frac{2}{3})\sqrt{3}}\sqrt{3}}\tag6\\
&=\frac{\Gamma(\frac{2}{3})\cos(1+\frac{\pi}{3})}{2^{2/3}}
\end{align}
---
**Explanation:**
$(1)$: $\small{\displaystyle\frac{1}{x^n}=\frac{1}{\Gamma(n)}\int^\infty\_0t^{n-1}e^{-xt}{\rm d}t}$
$(2)$: $\displaystyle\cos(a+b)=\cos(a)\cos(b)-\sin(a)\sin(b)$
$(2)$: $\small{\displaystyle\int^\infty\_0e^{-ax}\sin(bx){\rm d}x=\frac{b}{a^2+b^2}}$
$(2)$: $\small{\displaystyle\int^\infty\_0e^{-ax}\cos(bx){\rm d}x=\frac{a}{a^2+b^2}}$
$(3)$: $\displaystyle t\mapsto 2t$
$(4)$: $\displaystyle t\mapsto \sqrt{t}$
$(5)$: $\small{\displaystyle\int^\infty\_0\frac{x^{p-1}}{1+x}{\rm d}x=\pi\csc(p\pi)}$
$(6)$: $\small{\displaystyle \Gamma(z)=\frac{\pi\csc(\pi z)}{\Gamma(1-z)}}$, $\small{\displaystyle a\cos{x}-b\sin{x}=\sqrt{a^2+b^2}\cos(x+\arctan{\frac{b}{a}})}$ | Here is how. The approach is based on Mellin transform.
>
> $$I = \int\_{0}^{\infty}\frac{\cos(2x+1)}{\sqrt[3]{x}}dx = \cos(1)\int\_{0}^{\infty}\frac{\cos(2x)}{\sqrt[3]{x}}dx -\sin(1)\int\_{0}^{\infty}\frac{\sin(2x)}{\sqrt[3]{x}}dx . $$
>
>
>
To evaluate the integrals on the right hand side make the change of variables $t=2x$ and use the [Mellin transform (see tables)](http://mathworld.wolfram.com/MellinTransform.html) of $\cos(x)$ and $\sin(x)$ and then take the limit as $s \to 2/3 $. I believe you can finish the problem. See [related techniques](https://math.stackexchange.com/questions/607141/fourier-transform-of-fx-frac1exe-x2). |
926,454 | How to evaluate integral $$\int\_{0}^{\infty}\frac{\cos(2x+1)}{\sqrt[3]{x}}\text dx?$$ I tried substitution $x=u^3$ and I got $3\displaystyle\int\_{0}^{\infty}u \cos(2u^3+1)\text du$. After that I tried to use integration by parts but I don't know the integral $\displaystyle\int \cos(2u^3+1)\text du$. Any idea? Thanks in advance. | 2014/09/10 | [
"https://math.stackexchange.com/questions/926454",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/146687/"
] | $\newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
\newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
\newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
\newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
\newcommand{\dd}{{\rm d}}
\newcommand{\ds}[1]{\displaystyle{#1}}
\newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
\newcommand{\fermi}{\,{\rm f}}
\newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
\newcommand{\half}{{1 \over 2}}
\newcommand{\ic}{{\rm i}}
\newcommand{\iff}{\Longleftrightarrow}
\newcommand{\imp}{\Longrightarrow}
\newcommand{\pars}[1]{\left(\, #1 \,\right)}
\newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
\newcommand{\pp}{{\cal P}}
\newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
\newcommand{\sech}{\,{\rm sech}}
\newcommand{\sgn}{\,{\rm sgn}}
\newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
\newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
$\ds{\int\_{0}^{\infty}{\cos\pars{2x + 1} \over \root[3]{x}}\,\dd x:\ {\large ?}}$.
>
> \begin{align}
> &\color{#c00000}{\int\_{0}^{\infty}{\cos\pars{2x + 1} \over \root[3]{x}}\,\dd x}
> =\Re\bracks{\expo{\ic}\ \overbrace{\int\_{0}^{\infty}x^{-1/3}\expo{2x\ic}\,\dd x}
> ^{\ds{x \equiv \ic t/2=\expo{\pi\ic/2}t/2\ \imp\ t = -2\ic x}}}\ =\
> \\[3mm]&=\Re\bracks{\expo{\ic}\int\_{0}^{-\infty\ic}%
> \pars{\expo{\pi\ic/2}t \over 2}^{-1/3}\expo{2\pars{\ic t/2}\ic}\,{\ic \over 2}
> \,\dd t}
> \\[3mm]&=-2^{-2/3}\,\Im\bracks{\expo{\pars{1 - \pi/6}\ic}
> \int\_{0}^{-\infty\ic}t^{-1/3}\expo{-t}\,\dd t}
> \\[3mm]&=-2^{-2/3}\,\Im\braces{\expo{\pars{1 - \pi/6}\ic}
> \lim\_{R\ \to\ \infty}\bracks{-\int\_{R}^{0}t^{-1/3}\expo{-t}\,\dd t
> -\left.\int\_{-\pi/2}^{0}\,z^{-1/3}\expo{-z}\,\dd z
> \right\vert\_{z\ =\ R\expo{\ic\theta}}}}
> \end{align}
>
>
>
However,
\begin{align}
&\color{#c00000}{\large%
\verts{\int\_{-\pi/2}^{0}\,z^{-1/3}\expo{-z}\,\dd z}\_{\,z\ =\ R\expo{\ic\theta}}}
\leq \verts{\int\_{-\pi/2}^{0}R^{-1/3}\expo{-R\cos\pars{\theta}}R\,\dd\theta}
=R^{2/3}\int\_{0}^{\pi/2}\expo{-R\sin\pars{\theta}}\,\dd\theta
\\[3mm]& < R^{2/3}\int\_{0}^{\pi/2}\expo{-2R\theta/\pi}\,\dd\theta
={\pi \over 2}\,R^{-1/3}\pars{1 - \expo{-R}}
\color{#c00000}{\large\stackrel{R \to \infty}{\to} 0}
\end{align}
>
> Then,
> \begin{align}
> &\color{#66f}{\large\int\_{0}^{\infty}{\cos\pars{2x + 1} \over \root[3]{x}}\,\dd x}
> =-2^{-2/3}\sin\pars{1 - {\pi \over 6}}\int\_{0}^{\infty}t^{-1/3}\expo{-t}\,\dd t
> \\[3mm]&=\color{#66f}{\large%
> -2^{-2/3}\sin\pars{1 - {\pi \over 6}}\Gamma\pars{2 \over 3}}
> \approx {\tt -0.3911}
> \end{align}
>
>
> | Here is how. The approach is based on Mellin transform.
>
> $$I = \int\_{0}^{\infty}\frac{\cos(2x+1)}{\sqrt[3]{x}}dx = \cos(1)\int\_{0}^{\infty}\frac{\cos(2x)}{\sqrt[3]{x}}dx -\sin(1)\int\_{0}^{\infty}\frac{\sin(2x)}{\sqrt[3]{x}}dx . $$
>
>
>
To evaluate the integrals on the right hand side make the change of variables $t=2x$ and use the [Mellin transform (see tables)](http://mathworld.wolfram.com/MellinTransform.html) of $\cos(x)$ and $\sin(x)$ and then take the limit as $s \to 2/3 $. I believe you can finish the problem. See [related techniques](https://math.stackexchange.com/questions/607141/fourier-transform-of-fx-frac1exe-x2). |
926,454 | How to evaluate integral $$\int\_{0}^{\infty}\frac{\cos(2x+1)}{\sqrt[3]{x}}\text dx?$$ I tried substitution $x=u^3$ and I got $3\displaystyle\int\_{0}^{\infty}u \cos(2u^3+1)\text du$. After that I tried to use integration by parts but I don't know the integral $\displaystyle\int \cos(2u^3+1)\text du$. Any idea? Thanks in advance. | 2014/09/10 | [
"https://math.stackexchange.com/questions/926454",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/146687/"
] | $$\color{blue}{\mathcal{I}=\frac{\Gamma(\frac{2}{3})\cos(1+\frac{\pi}{3})}{2^{2/3}}\approx-0.391190966503539\cdots}$$
---
\begin{align}
\int^\infty\_0\frac{\cos(2x+1)}{x^{1/3}}{\rm d}x
&=\int^\infty\_0\frac{\cos(2x+1)}{\Gamma(\frac{1}{3})}\int^\infty\_0t^{-2/3}e^{-xt} \ {\rm d}t \ {\rm d}x\tag1\\
&=\frac{1}{\Gamma(\frac{1}{3})}\int^\infty\_0t^{-2/3}\int^\infty\_0e^{-xt}\cos(2x+1) \ {\rm d}x \ {\rm d}t\\
&=\frac{\cos(1)}{\Gamma(\frac{1}{3})}\int^\infty\_0\frac{t^{1/3}}{t^2+4}{\rm d}t-\frac{2\sin(1)}{\Gamma(\frac{1}{3})}\int^\infty\_0\frac{t^{-2/3}}{t^2+4}{\rm d}t\tag2\\
&=\frac{\cos(1)}{2^{2/3}\Gamma(\frac{1}{3})}\int^\infty\_0\frac{t^{1/3}}{1+t^2}{\rm d}t-\frac{\sin(1)}{2^{2/3}\Gamma(\frac{1}{3})}\int^\infty\_0\frac{t^{-2/3}}{1+t^2}{\rm d}t\tag3\\
&=\frac{\cos(1)}{2^{5/3}\Gamma(\frac{1}{3})}\int^\infty\_0\frac{t^{-1/3}}{1+t}{\rm d}t-\frac{\sin(1)}{2^{5/3}\Gamma(\frac{1}{3})}\int^\infty\_0\frac{t^{-5/6}}{1+t}{\rm d}t\tag4\\
&=\frac{\pi\left(\cos(1)-\sqrt{3}\sin(1)\right)}{2^{2/3}\Gamma(\frac{1}{3})\sqrt{3}}\tag5\\
&=\frac{2\pi\cos(1+\frac{\pi}{3})}{2^{2/3}\frac{2\pi}{\Gamma(\frac{2}{3})\sqrt{3}}\sqrt{3}}\tag6\\
&=\frac{\Gamma(\frac{2}{3})\cos(1+\frac{\pi}{3})}{2^{2/3}}
\end{align}
---
**Explanation:**
$(1)$: $\small{\displaystyle\frac{1}{x^n}=\frac{1}{\Gamma(n)}\int^\infty\_0t^{n-1}e^{-xt}{\rm d}t}$
$(2)$: $\displaystyle\cos(a+b)=\cos(a)\cos(b)-\sin(a)\sin(b)$
$(2)$: $\small{\displaystyle\int^\infty\_0e^{-ax}\sin(bx){\rm d}x=\frac{b}{a^2+b^2}}$
$(2)$: $\small{\displaystyle\int^\infty\_0e^{-ax}\cos(bx){\rm d}x=\frac{a}{a^2+b^2}}$
$(3)$: $\displaystyle t\mapsto 2t$
$(4)$: $\displaystyle t\mapsto \sqrt{t}$
$(5)$: $\small{\displaystyle\int^\infty\_0\frac{x^{p-1}}{1+x}{\rm d}x=\pi\csc(p\pi)}$
$(6)$: $\small{\displaystyle \Gamma(z)=\frac{\pi\csc(\pi z)}{\Gamma(1-z)}}$, $\small{\displaystyle a\cos{x}-b\sin{x}=\sqrt{a^2+b^2}\cos(x+\arctan{\frac{b}{a}})}$ | $\newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
\newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
\newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
\newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
\newcommand{\dd}{{\rm d}}
\newcommand{\ds}[1]{\displaystyle{#1}}
\newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
\newcommand{\fermi}{\,{\rm f}}
\newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
\newcommand{\half}{{1 \over 2}}
\newcommand{\ic}{{\rm i}}
\newcommand{\iff}{\Longleftrightarrow}
\newcommand{\imp}{\Longrightarrow}
\newcommand{\pars}[1]{\left(\, #1 \,\right)}
\newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
\newcommand{\pp}{{\cal P}}
\newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
\newcommand{\sech}{\,{\rm sech}}
\newcommand{\sgn}{\,{\rm sgn}}
\newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
\newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
$\ds{\int\_{0}^{\infty}{\cos\pars{2x + 1} \over \root[3]{x}}\,\dd x:\ {\large ?}}$.
>
> \begin{align}
> &\color{#c00000}{\int\_{0}^{\infty}{\cos\pars{2x + 1} \over \root[3]{x}}\,\dd x}
> =\Re\bracks{\expo{\ic}\ \overbrace{\int\_{0}^{\infty}x^{-1/3}\expo{2x\ic}\,\dd x}
> ^{\ds{x \equiv \ic t/2=\expo{\pi\ic/2}t/2\ \imp\ t = -2\ic x}}}\ =\
> \\[3mm]&=\Re\bracks{\expo{\ic}\int\_{0}^{-\infty\ic}%
> \pars{\expo{\pi\ic/2}t \over 2}^{-1/3}\expo{2\pars{\ic t/2}\ic}\,{\ic \over 2}
> \,\dd t}
> \\[3mm]&=-2^{-2/3}\,\Im\bracks{\expo{\pars{1 - \pi/6}\ic}
> \int\_{0}^{-\infty\ic}t^{-1/3}\expo{-t}\,\dd t}
> \\[3mm]&=-2^{-2/3}\,\Im\braces{\expo{\pars{1 - \pi/6}\ic}
> \lim\_{R\ \to\ \infty}\bracks{-\int\_{R}^{0}t^{-1/3}\expo{-t}\,\dd t
> -\left.\int\_{-\pi/2}^{0}\,z^{-1/3}\expo{-z}\,\dd z
> \right\vert\_{z\ =\ R\expo{\ic\theta}}}}
> \end{align}
>
>
>
However,
\begin{align}
&\color{#c00000}{\large%
\verts{\int\_{-\pi/2}^{0}\,z^{-1/3}\expo{-z}\,\dd z}\_{\,z\ =\ R\expo{\ic\theta}}}
\leq \verts{\int\_{-\pi/2}^{0}R^{-1/3}\expo{-R\cos\pars{\theta}}R\,\dd\theta}
=R^{2/3}\int\_{0}^{\pi/2}\expo{-R\sin\pars{\theta}}\,\dd\theta
\\[3mm]& < R^{2/3}\int\_{0}^{\pi/2}\expo{-2R\theta/\pi}\,\dd\theta
={\pi \over 2}\,R^{-1/3}\pars{1 - \expo{-R}}
\color{#c00000}{\large\stackrel{R \to \infty}{\to} 0}
\end{align}
>
> Then,
> \begin{align}
> &\color{#66f}{\large\int\_{0}^{\infty}{\cos\pars{2x + 1} \over \root[3]{x}}\,\dd x}
> =-2^{-2/3}\sin\pars{1 - {\pi \over 6}}\int\_{0}^{\infty}t^{-1/3}\expo{-t}\,\dd t
> \\[3mm]&=\color{#66f}{\large%
> -2^{-2/3}\sin\pars{1 - {\pi \over 6}}\Gamma\pars{2 \over 3}}
> \approx {\tt -0.3911}
> \end{align}
>
>
> |
51,895,553 | I am trying to configure a FireDAC TFDQuery component so it fetches records on demand in batches of no more than 500, but I need it to report back what is the total record count for the query not just the number of fetched records. The `FetchOptions` are configured as follows:
```
FetchOptions.AssignedValues = [evMode, evRowsetSize, evRecordCountMode, evCursorKind, evAutoFetchAll]
FetchOptions.CursorKind = ckForwardOnly
FetchOptions.AutoFetchAll = afTruncate
FetchOptions.RecordCountMode = cmTotal
FetchOptions.RowSetSize = 500
```
This immediately returns all records in the table not just 500. I have tried setting `RecsMax` to 500, which works in limiting the fetched records, but `RecordCount` for the query shows only 500 not the total.
The FireDAC help file states that setting `RecordCountMode` to `cmTotal' causes FireDAC to issue
>
> SELECT COUNT(\*) FROM (original SQL command text).
>
>
>
Either there is a bug or I am doing something wrong!
I cannot see what other properties I can change. I am confused as to the relationship between `RowSetSize` and `RecsMax` and din't find the help file clarified.
I have tried playing with the properties of `AutoFetchAll` (Again confused as to this properties' purpose), but noting that is was set to `afAll` I set it to `afTruncate` to see if that would make a difference, but it didn't. | 2018/08/17 | [
"https://Stackoverflow.com/questions/51895553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4488342/"
] | I have tested `FetchOptions`' `fmOnDemand` `Mode` with a `FDTable` component and a `FDQuery` component. Both with identical settings for `FetchOptions` ie `RowSetSize`=50. 425,000 rows in the dataset fetched over a network server.
`FDTable` performs as expected. It loads just 50 tuples and does so almost instantly. When pressing Ctrl+End to get to the end of the DBGrid display, it loads just 100 tuples. Whilst scrolling it rarely loads more than 100 tuples. Impact on memory negligible. But it is slow in scrolling.
`FDQuery` loads 50 tuples, but takes around 35 seconds to do so and consumes over 0.5GB of memory in the process. If you press Ctrl+Home to move to the end of the connected DBGrid it does so virtually instantly and in the process loads the entire table and consumes a further 700MB of memory.
I also experimented with `CachedUpdates`. The results above where with `CachedUpdates` off. When on, there was no impact at all on the performance of `FDQuery` (still poor), but for `FDTable` it resulted in it loading the entire table at start up, taking over half a minute to do so and consuming 1.2GBs of memory.
It looks like `fmOnDemand` mode is only practically usable with `FDTable` with `CachedUpdates` off and is not suitable for use with `FDQuery` at all. | The results of my tests using `fmOnDemand` with postgreSQL and MySQL are basically the same. With FDTable `fmOnDemand` only downloads what it needs limited to the `RowSetSize`. With a `RowSetSize` of 50 it initially downloads 50 tuples and no matter where you scroll to it never downloads more than 111 tuples (though doubtless that is dependent on the size of the connected `DBGrid`. If you disconnect the `FDTable` from a data source it initially downloads 50 tuples and if you then navigate to any record in the underlying table it downloads one tuple only and discards all other data.
`FDQuery` in `fmOnDemand` downloads only the initial 50 tuples when opened, but if you navigate by `RecNo` it downloads every tuple in between. I had rather hoped it would use LIMIT and OFFSET commands to get only records that were being requested.
To recreate the test for PostGre you need the following FireDAC components:
```
object FDConnectionPG: TFDConnection
Params.Strings = (
'Password='
'Server='
'Port='
'DriverID=PG')
ResourceOptions.AssignedValues = [rvAutoReconnect]
ResourceOptions.AutoReconnect = True
end
object FDQueryPG: TFDQuery
Connection = FDConnectionPG
FetchOptions.AssignedValues = [evMode, evRowsetSize]
end
object FDTable1: TFDTable
CachedUpdates = True
Connection = FDConnectionPG
FetchOptions.AssignedValues = [evMode, evRowsetSize, evRecordCountMode]
FetchOptions.RecordCountMode = cmFetched
end
```
If you wish to recreate it with MYSQL, you will basically need the same FireDAC components, but the `FDConnection`needs to be set as follows:
```
object FDConnectionMySql: TFDConnection
Params.Strings = (
'DriverID=MySQL'
'ResultMode=Use')
ResourceOptions.AssignedValues = [rvAutoReconnect]
ResourceOptions.AutoReconnect = True
end
```
You'll need an edit box, two buttons, a checkbox, a timer and a label and the following code:
```
procedure TfrmMain.Button1Click(Sender: TObject);
begin
if not FDQueryPG.IsEmpty then
begin
FDQueryPG.EmptyDataSet;
FDQueryPG.ClearDetails;
FDQueryPG.Close;
end;
if not FDTable1.IsEmpty then
begin
FDTAble1.EmptyDataSet;
FDTable1.ClearDetails;
FDTable1.Close;
end;
lFetched.Caption := 'Fetched 0';
lFetched.Update;
if cbTable.checked then
begin
FDTable1.TableName := '[TABLENAME]';
FDTable1.Open();
lFetched.Caption := 'Fetched '+ FDTable1.Table.Rows.Count.ToString;
end
else
begin
FDQueryPG.SQL.Text := 'Select * from [TABLENAME]';
FDQueryPG.open;
lFetched.Caption := 'Fetched '+ FDQueryPG.Table.Rows.Count.ToString;
end;
timer1.Enabled:=true;
end;
procedure TfrmMain.Button2Click(Sender: TObject);
begin
if cbTable.Checked then
FDTable1.RecNo := strToInt(Edit1.Text)
else
FDQueryPG.RecNo := strToInt(Edit1.Text);
end;
procedure TfrmMain.cbTableClick(Sender: TObject);
begin
timer1.Enabled := False;
end;
procedure TfrmMain.Timer1Timer(Sender: TObject);
begin
if cbTable.checked then
lFetched.Caption := 'Fetched '+ FDTable1.Table.Rows.Count.ToString
else
lFetched.Caption:='Fetched '+FDQueryPG.Table.Rows.Count.ToString;
lFetched.Update;
end;
``` |
37,001,003 | If I calling toBytecode() method in my context it throws
>
> java.lang.RuntimeException: remaper.by.moofMonkey.Main class is frozen
> at javassist.CtClassType.checkModify(CtClassType.java:515)
> at javassist.CtClass.getClassFile(CtClass.java:524)
> at com.moofMonkey.Main.writeFile(Main.java:340)
> at com.moofMonkey.Main.saveClasses(Main.java:324)
> at com.moofMonkey.Main.main(Main.java:309)
>
>
>
My context:
```
.....
for (CtClass cl : modClasses) {
cl.stopPruning(true);
writeFile(cl, "./ModifiedClasses"); //cl.writeFile("./ModifiedClasses");
cl.stopPruning(false);
}
.....
public static void writeFile(CtClass cl, String directoryName) throws Throwable {
System.out.println(">> " + cl.getName());
byte[] bc = cl.toBytecode();
String s = cl.getClassFile().getSourceFile();
int index = new String(bc).indexOf(s);
for(int i = 0; i < s.length(); i++) //KILL SOURCEFILE (c) moofMonkey
bc[index + i] = '-';
DataOutputStream out = cl.makeFileOutput(directoryName);
out.write(bc);
out.flush();
out.close();
}
```
BUT... But. If I calling analog of writeFile() - cl.writeFile() - all works!
I can do this:
```
1. Save File
2. Read bytes from him
3. Dp what I need
4. Save File
``` | 2016/05/03 | [
"https://Stackoverflow.com/questions/37001003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6285148/"
] | Having a look into the javadoc of [CtClass](https://jboss-javassist.github.io/javassist/html/javassist/CtClass.html#toBytecode--) reveals
>
> Once this method is called, **further modifications are not possible** any more.
>
>
>
If you change the call order to
```
String s = cl.getClassFile().getSourceFile();
byte[] bc = cl.toBytecode();
```
you can call `toBytecode`. | The exception isn't coming where you call `toBytecode` but in the next source line, where you call `getClassFile`. The [documentation](http://jboss-javassist.github.io/javassist/html/index.html) says that you aren't allowed to call this on a frozen class.
There's a method called `getClassFile2` which seems intended to work around this problem:
>
> Returns a class file for this class (read only). Normal applications do not need calling this method. Use getClassFile().
>
>
> The ClassFile object obtained by this method is read only. Changes to this object might not be reflected on a class file generated by toBytecode(), toClass(), etc.
>
>
> This method is available even if isFrozen() is true. However, if the class is frozen, it might be also pruned.
>
>
>
The first paragraph suggests that if there's some way to restructure your code so it doesn't need to get a class file for a frozen class, that might be better (or at least better-thought-of by the creators of Javassist). |
11,030,273 | I'm trying to produce a conditional sum in SQL Server Report Builder 3.0.
My expression looks like this:
```
=Sum(Iif(Fields!ProjectTypeID.Value=2,Fields!kWp.Value,0))
```
I'd hoped that this expression would produce a sum of the kWp of all projects of type 2.
Unfortunately, it is not to be. And I can't seem to work out why. It just returns a 0 result, even though I know that there are non-zero values in the kWp column, and the column does not contain nulls.
A colleague did manage to get a positive result by replacing the
```
Fields!kWp.Value
```
with
```
1 * Fields!kWp.Value
```
But we have no idea why this works, and therefore, can't really trust the answer.
How can I get this conditional sum to behave itself? | 2012/06/14 | [
"https://Stackoverflow.com/questions/11030273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1037491/"
] | The data type of the column 'kWp' is Decimal so you need to either convert the default value to 0.00 or cast the column to double
```
SUM(iif(Fields!ProjectTypeID.Value = 2,cdbl(Fields!kWp.Value),0.00))
``` | To get the `sum` of the **kWp** of all projects of type **2**, the expression is as follows,
```
=IIf(Fields!ProjectTypeID.Value=2,sum(Fields!kWp.Value),0)
```
I hope this will help u. |
11,030,273 | I'm trying to produce a conditional sum in SQL Server Report Builder 3.0.
My expression looks like this:
```
=Sum(Iif(Fields!ProjectTypeID.Value=2,Fields!kWp.Value,0))
```
I'd hoped that this expression would produce a sum of the kWp of all projects of type 2.
Unfortunately, it is not to be. And I can't seem to work out why. It just returns a 0 result, even though I know that there are non-zero values in the kWp column, and the column does not contain nulls.
A colleague did manage to get a positive result by replacing the
```
Fields!kWp.Value
```
with
```
1 * Fields!kWp.Value
```
But we have no idea why this works, and therefore, can't really trust the answer.
How can I get this conditional sum to behave itself? | 2012/06/14 | [
"https://Stackoverflow.com/questions/11030273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1037491/"
] | To get the `sum` of the **kWp** of all projects of type **2**, the expression is as follows,
```
=IIf(Fields!ProjectTypeID.Value=2,sum(Fields!kWp.Value),0)
```
I hope this will help u. | To get the conditional sum you can try this expression
```
=sum(IIf(Fields!balance.Value > 0,(Fields!balance.Value),0))
```
It sums only positive numbers otherwise it adds 0 to the total, you can do it wise versa. |
11,030,273 | I'm trying to produce a conditional sum in SQL Server Report Builder 3.0.
My expression looks like this:
```
=Sum(Iif(Fields!ProjectTypeID.Value=2,Fields!kWp.Value,0))
```
I'd hoped that this expression would produce a sum of the kWp of all projects of type 2.
Unfortunately, it is not to be. And I can't seem to work out why. It just returns a 0 result, even though I know that there are non-zero values in the kWp column, and the column does not contain nulls.
A colleague did manage to get a positive result by replacing the
```
Fields!kWp.Value
```
with
```
1 * Fields!kWp.Value
```
But we have no idea why this works, and therefore, can't really trust the answer.
How can I get this conditional sum to behave itself? | 2012/06/14 | [
"https://Stackoverflow.com/questions/11030273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1037491/"
] | I had similar problem, this worked for me:
```
=Sum(iif(Fields!date_break.Value = "0001-01-01",Fields!brkr_fee.Value, nothing))
```
zb | To get the `sum` of the **kWp** of all projects of type **2**, the expression is as follows,
```
=IIf(Fields!ProjectTypeID.Value=2,sum(Fields!kWp.Value),0)
```
I hope this will help u. |
11,030,273 | I'm trying to produce a conditional sum in SQL Server Report Builder 3.0.
My expression looks like this:
```
=Sum(Iif(Fields!ProjectTypeID.Value=2,Fields!kWp.Value,0))
```
I'd hoped that this expression would produce a sum of the kWp of all projects of type 2.
Unfortunately, it is not to be. And I can't seem to work out why. It just returns a 0 result, even though I know that there are non-zero values in the kWp column, and the column does not contain nulls.
A colleague did manage to get a positive result by replacing the
```
Fields!kWp.Value
```
with
```
1 * Fields!kWp.Value
```
But we have no idea why this works, and therefore, can't really trust the answer.
How can I get this conditional sum to behave itself? | 2012/06/14 | [
"https://Stackoverflow.com/questions/11030273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1037491/"
] | The data type of the column 'kWp' is Decimal so you need to either convert the default value to 0.00 or cast the column to double
```
SUM(iif(Fields!ProjectTypeID.Value = 2,cdbl(Fields!kWp.Value),0.00))
``` | To get the conditional sum you can try this expression
```
=sum(IIf(Fields!balance.Value > 0,(Fields!balance.Value),0))
```
It sums only positive numbers otherwise it adds 0 to the total, you can do it wise versa. |
11,030,273 | I'm trying to produce a conditional sum in SQL Server Report Builder 3.0.
My expression looks like this:
```
=Sum(Iif(Fields!ProjectTypeID.Value=2,Fields!kWp.Value,0))
```
I'd hoped that this expression would produce a sum of the kWp of all projects of type 2.
Unfortunately, it is not to be. And I can't seem to work out why. It just returns a 0 result, even though I know that there are non-zero values in the kWp column, and the column does not contain nulls.
A colleague did manage to get a positive result by replacing the
```
Fields!kWp.Value
```
with
```
1 * Fields!kWp.Value
```
But we have no idea why this works, and therefore, can't really trust the answer.
How can I get this conditional sum to behave itself? | 2012/06/14 | [
"https://Stackoverflow.com/questions/11030273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1037491/"
] | The data type of the column 'kWp' is Decimal so you need to either convert the default value to 0.00 or cast the column to double
```
SUM(iif(Fields!ProjectTypeID.Value = 2,cdbl(Fields!kWp.Value),0.00))
``` | I had similar problem, this worked for me:
```
=Sum(iif(Fields!date_break.Value = "0001-01-01",Fields!brkr_fee.Value, nothing))
```
zb |
11,030,273 | I'm trying to produce a conditional sum in SQL Server Report Builder 3.0.
My expression looks like this:
```
=Sum(Iif(Fields!ProjectTypeID.Value=2,Fields!kWp.Value,0))
```
I'd hoped that this expression would produce a sum of the kWp of all projects of type 2.
Unfortunately, it is not to be. And I can't seem to work out why. It just returns a 0 result, even though I know that there are non-zero values in the kWp column, and the column does not contain nulls.
A colleague did manage to get a positive result by replacing the
```
Fields!kWp.Value
```
with
```
1 * Fields!kWp.Value
```
But we have no idea why this works, and therefore, can't really trust the answer.
How can I get this conditional sum to behave itself? | 2012/06/14 | [
"https://Stackoverflow.com/questions/11030273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1037491/"
] | I had similar problem, this worked for me:
```
=Sum(iif(Fields!date_break.Value = "0001-01-01",Fields!brkr_fee.Value, nothing))
```
zb | To get the conditional sum you can try this expression
```
=sum(IIf(Fields!balance.Value > 0,(Fields!balance.Value),0))
```
It sums only positive numbers otherwise it adds 0 to the total, you can do it wise versa. |
131,110 | In the new setting I'm making, I found an opportunity to make a species of humanoids that I simply couldn't resist. So I got to work, making the tribal herdsmen and hunters of the predominantly carnivorous **Luugitsu**. Though I've come to an impasse.
They are a species with a rare trait--which I call *polythermy*--that causes them to be able to change whether they are endothermic or ectothermic based on changing ambient temperatures, and are highly effective at comfortably surviving under a wider range of natural temperatures. Whether this will affect the answer or not I have no idea. Hell, it could cause them to have changing skin colours like Space Marines from *Warhammer 40k*. But they're also very skilled hunters and, when at war, guerrilla warriors, which I'm certain will most definitely affect their skin colour, or may possibly add patterns of contrasting colours to their skin. But with these in mind, what would be the most likely skin colour--and possibly coloured patterns--that they would select for? | 2018/11/23 | [
"https://worldbuilding.stackexchange.com/questions/131110",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/48443/"
] | Consider that homo sapiens is a highly adaptable hunter humanoid, and you will see that within our own biochemistry the range is from nearly black to nearly white - essentially any color that can be created by density of melanin over unpigmented flesh and blood | Consider camouflage colors, for desert, forest, water, city, or whatever environment they do most of their hunting in. Splotches of the most common colors found in such environments. Although splotches are common in natural settings, urban camo may involve straight lines and shadow; due to straight lines being most prevalent in man-made structures.
Perhaps like [cuttlefish,](https://www.huffingtonpost.com/2015/06/25/cuttlefish-changing-color_n_7656674.html) (or google cuttlefish for many other videos) they could change color dynamically on the fly, to match any background. That is from real-life; and although cuttlefish use it to hide from predators, it would be equally useful in attack or subterfuge for soldiers. |
131,110 | In the new setting I'm making, I found an opportunity to make a species of humanoids that I simply couldn't resist. So I got to work, making the tribal herdsmen and hunters of the predominantly carnivorous **Luugitsu**. Though I've come to an impasse.
They are a species with a rare trait--which I call *polythermy*--that causes them to be able to change whether they are endothermic or ectothermic based on changing ambient temperatures, and are highly effective at comfortably surviving under a wider range of natural temperatures. Whether this will affect the answer or not I have no idea. Hell, it could cause them to have changing skin colours like Space Marines from *Warhammer 40k*. But they're also very skilled hunters and, when at war, guerrilla warriors, which I'm certain will most definitely affect their skin colour, or may possibly add patterns of contrasting colours to their skin. But with these in mind, what would be the most likely skin colour--and possibly coloured patterns--that they would select for? | 2018/11/23 | [
"https://worldbuilding.stackexchange.com/questions/131110",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/48443/"
] | Something you need to take into account is the visual system of these people and their prey & predators. Most placental mammals are dichromats <https://en.wikipedia.org/wiki/Dichromacy#Animals_that_are_dichromats> rather than trichromats like humans and some other primates, which probably goes a long way towards explaining the rather muted color schemes of mammals: variations on black, white, and reddish-brown. There's little point in evolving colors if they can't be seen.
Many birds (and reptiles!), by contrast, are tetrachromats, being able to see ultraviolet as well as what humans see. Even birds that are rather drab to human eyes are often strongly colored in the ultraviolet: <https://www.nwf.org/Magazines/National-Wildlife/2012/AugSept/Animals/Bird-Vision>
So if your people, and their evolutionary ancestors, can distinguish a variety of wavelengths, they might evolve colorful integuments like the feathers of parrots or peafowl. Or they might become like chameleons, able to change colors depending on their environment: <https://en.wikipedia.org/wiki/Chameleon#Change_of_color> | Consider camouflage colors, for desert, forest, water, city, or whatever environment they do most of their hunting in. Splotches of the most common colors found in such environments. Although splotches are common in natural settings, urban camo may involve straight lines and shadow; due to straight lines being most prevalent in man-made structures.
Perhaps like [cuttlefish,](https://www.huffingtonpost.com/2015/06/25/cuttlefish-changing-color_n_7656674.html) (or google cuttlefish for many other videos) they could change color dynamically on the fly, to match any background. That is from real-life; and although cuttlefish use it to hide from predators, it would be equally useful in attack or subterfuge for soldiers. |
131,110 | In the new setting I'm making, I found an opportunity to make a species of humanoids that I simply couldn't resist. So I got to work, making the tribal herdsmen and hunters of the predominantly carnivorous **Luugitsu**. Though I've come to an impasse.
They are a species with a rare trait--which I call *polythermy*--that causes them to be able to change whether they are endothermic or ectothermic based on changing ambient temperatures, and are highly effective at comfortably surviving under a wider range of natural temperatures. Whether this will affect the answer or not I have no idea. Hell, it could cause them to have changing skin colours like Space Marines from *Warhammer 40k*. But they're also very skilled hunters and, when at war, guerrilla warriors, which I'm certain will most definitely affect their skin colour, or may possibly add patterns of contrasting colours to their skin. But with these in mind, what would be the most likely skin colour--and possibly coloured patterns--that they would select for? | 2018/11/23 | [
"https://worldbuilding.stackexchange.com/questions/131110",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/48443/"
] | Consider that homo sapiens is a highly adaptable hunter humanoid, and you will see that within our own biochemistry the range is from nearly black to nearly white - essentially any color that can be created by density of melanin over unpigmented flesh and blood | Earth humans living near the poles have evolved to be pale. Humans living near the equator tend to have darker skin. This is a response to the level of sunlight and the need to synthesise vitamin D.
Your humanoids could turn pale when they are in cold conditions and dark when they are in hot conditions.
When they are partly in shade then their bodies have patches of each colour. |
131,110 | In the new setting I'm making, I found an opportunity to make a species of humanoids that I simply couldn't resist. So I got to work, making the tribal herdsmen and hunters of the predominantly carnivorous **Luugitsu**. Though I've come to an impasse.
They are a species with a rare trait--which I call *polythermy*--that causes them to be able to change whether they are endothermic or ectothermic based on changing ambient temperatures, and are highly effective at comfortably surviving under a wider range of natural temperatures. Whether this will affect the answer or not I have no idea. Hell, it could cause them to have changing skin colours like Space Marines from *Warhammer 40k*. But they're also very skilled hunters and, when at war, guerrilla warriors, which I'm certain will most definitely affect their skin colour, or may possibly add patterns of contrasting colours to their skin. But with these in mind, what would be the most likely skin colour--and possibly coloured patterns--that they would select for? | 2018/11/23 | [
"https://worldbuilding.stackexchange.com/questions/131110",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/48443/"
] | Consider that homo sapiens is a highly adaptable hunter humanoid, and you will see that within our own biochemistry the range is from nearly black to nearly white - essentially any color that can be created by density of melanin over unpigmented flesh and blood | If the Luugitsu want to take advantage of natural sunlight their skins would have to be green. Plants are green because they absorb the sun's energy in the blue and red wavelengths, while reflecting the green wavelengths. In cold climates though the skin color isn't as important as having thermal insulation layers, such as fur or downy feathers. Human backpackers wear jackets with SILVER reflective lining to bounce heat back to their bodies, while some athletes train in hot climates with artificial cooling systems because body temperature matters more than skin temperature, so the skin color of the Luugitsu may not be much of an advantage against a moderately advanced population of human colonists.
<https://www.ezcooldown.com/us/shop-by-use/athletes-sports-cooling-vests> |
131,110 | In the new setting I'm making, I found an opportunity to make a species of humanoids that I simply couldn't resist. So I got to work, making the tribal herdsmen and hunters of the predominantly carnivorous **Luugitsu**. Though I've come to an impasse.
They are a species with a rare trait--which I call *polythermy*--that causes them to be able to change whether they are endothermic or ectothermic based on changing ambient temperatures, and are highly effective at comfortably surviving under a wider range of natural temperatures. Whether this will affect the answer or not I have no idea. Hell, it could cause them to have changing skin colours like Space Marines from *Warhammer 40k*. But they're also very skilled hunters and, when at war, guerrilla warriors, which I'm certain will most definitely affect their skin colour, or may possibly add patterns of contrasting colours to their skin. But with these in mind, what would be the most likely skin colour--and possibly coloured patterns--that they would select for? | 2018/11/23 | [
"https://worldbuilding.stackexchange.com/questions/131110",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/48443/"
] | Something you need to take into account is the visual system of these people and their prey & predators. Most placental mammals are dichromats <https://en.wikipedia.org/wiki/Dichromacy#Animals_that_are_dichromats> rather than trichromats like humans and some other primates, which probably goes a long way towards explaining the rather muted color schemes of mammals: variations on black, white, and reddish-brown. There's little point in evolving colors if they can't be seen.
Many birds (and reptiles!), by contrast, are tetrachromats, being able to see ultraviolet as well as what humans see. Even birds that are rather drab to human eyes are often strongly colored in the ultraviolet: <https://www.nwf.org/Magazines/National-Wildlife/2012/AugSept/Animals/Bird-Vision>
So if your people, and their evolutionary ancestors, can distinguish a variety of wavelengths, they might evolve colorful integuments like the feathers of parrots or peafowl. Or they might become like chameleons, able to change colors depending on their environment: <https://en.wikipedia.org/wiki/Chameleon#Change_of_color> | Earth humans living near the poles have evolved to be pale. Humans living near the equator tend to have darker skin. This is a response to the level of sunlight and the need to synthesise vitamin D.
Your humanoids could turn pale when they are in cold conditions and dark when they are in hot conditions.
When they are partly in shade then their bodies have patches of each colour. |
131,110 | In the new setting I'm making, I found an opportunity to make a species of humanoids that I simply couldn't resist. So I got to work, making the tribal herdsmen and hunters of the predominantly carnivorous **Luugitsu**. Though I've come to an impasse.
They are a species with a rare trait--which I call *polythermy*--that causes them to be able to change whether they are endothermic or ectothermic based on changing ambient temperatures, and are highly effective at comfortably surviving under a wider range of natural temperatures. Whether this will affect the answer or not I have no idea. Hell, it could cause them to have changing skin colours like Space Marines from *Warhammer 40k*. But they're also very skilled hunters and, when at war, guerrilla warriors, which I'm certain will most definitely affect their skin colour, or may possibly add patterns of contrasting colours to their skin. But with these in mind, what would be the most likely skin colour--and possibly coloured patterns--that they would select for? | 2018/11/23 | [
"https://worldbuilding.stackexchange.com/questions/131110",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/48443/"
] | Something you need to take into account is the visual system of these people and their prey & predators. Most placental mammals are dichromats <https://en.wikipedia.org/wiki/Dichromacy#Animals_that_are_dichromats> rather than trichromats like humans and some other primates, which probably goes a long way towards explaining the rather muted color schemes of mammals: variations on black, white, and reddish-brown. There's little point in evolving colors if they can't be seen.
Many birds (and reptiles!), by contrast, are tetrachromats, being able to see ultraviolet as well as what humans see. Even birds that are rather drab to human eyes are often strongly colored in the ultraviolet: <https://www.nwf.org/Magazines/National-Wildlife/2012/AugSept/Animals/Bird-Vision>
So if your people, and their evolutionary ancestors, can distinguish a variety of wavelengths, they might evolve colorful integuments like the feathers of parrots or peafowl. Or they might become like chameleons, able to change colors depending on their environment: <https://en.wikipedia.org/wiki/Chameleon#Change_of_color> | If the Luugitsu want to take advantage of natural sunlight their skins would have to be green. Plants are green because they absorb the sun's energy in the blue and red wavelengths, while reflecting the green wavelengths. In cold climates though the skin color isn't as important as having thermal insulation layers, such as fur or downy feathers. Human backpackers wear jackets with SILVER reflective lining to bounce heat back to their bodies, while some athletes train in hot climates with artificial cooling systems because body temperature matters more than skin temperature, so the skin color of the Luugitsu may not be much of an advantage against a moderately advanced population of human colonists.
<https://www.ezcooldown.com/us/shop-by-use/athletes-sports-cooling-vests> |
20,193,067 | I have environmental transect data for three environmental variables. I have performed a PCA in R on my three environmental variables. I would like to plot my points (sites on my transect) along a single principal compoent. If I use the `plot()` function in R it generates a 2d biplot.
How do I create a 1D plot of my PCA?
Here is what I have done:
```
pca1= princomp(~ X250 + X500 + shear, data=data, scores=TRUE, cor=TRUE)
plot(pca1)
``` | 2013/11/25 | [
"https://Stackoverflow.com/questions/20193067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3032264/"
] | >
> How do I create a 1D plot of my PCA?
>
>
>
You can use the `linestack()` function in the **vegan** package for a plot of a single PCA axis (others have pointed out the error that led to you only getting a single component in this case).
E.g.:
```
library("vegan")
data(dune)
## fit PCA
pca <- rda(dune, scale = TRUE)
## 1D plot
linestack(scores(pca, choices = 1, display = "species"))
linestack(scores(pca, choices = 1, display = "sites"), side = "left", add = TRUE)
```
which gives

The argument `choices` selects the dimension you wish to plot. In the above example this was component `1`, but any of the components can be selected this way. | Actually, `vegan::ordiplot()` knows `prcomp` and `princomp` results and will produce a `linestack` graph if only one axis is requested. This should work:
```
pca1 <- princomp(~ X250 + X500 + shear, data=data, scores=TRUE, cor=TRUE)
ordiplot(pca1, choices = 1)
```
The scaling of row and column scores can be odd with respect to each other, though (`rda` scales more equally). |
199,898 | Let's face it, mankind is evil. We invented means to destroy one another under the guidance of mages since the dawn of time. We shed off the yoke of the werebeasts during the Impergium and made them pariahs. We launched the first and second Inquisition to drive out the undead. We fortified our holdings with the works of the Order of Leopold. Then the Order of Reason took their teachings and went rampant to fortify its hold on Reality. Humans under the guidance of defectors beat them and their puppets to a pulp in 1945. And Resistance against any such overlords, be they Lycanthrope, Undead or Realitywarper is strong in the social experiment that we call "America".
Anyway. We have come a long way, and our weapons are honed and refined to a point where Norway produces one of the best rounds to go hunting for any supernatural being: The [Raufos Mk.211](https://en.wikipedia.org/wiki/Raufoss_Mk_211) in .50 BMG, loaded in any compatible Anti-materiel Rifle, is the ultimate weapon for this...
Well, wait, the weapons tables in 20th Anniversary only go up to *Rifle* using a *(30.06)* cartridge as their 8-Damage entry 1, and the only mention I can find for an Anti-materiel rifle is in Hunters Hunted II, but no damage values for it.
The only other weapon in this caliber, the .50 caliber Heavy Machine gun (most likely the venerable [M2 Browning](https://en.wikipedia.org/wiki/M2_Browning)), is listed with a damage code of 16. 2
The best rules inspiration for HEIAP I can find is actually in Mage: it lists Flechette (which is akin to the armor penetrator) and Incendiary Rounds 3, which are doing some aggravated damage, but describes them also as "phosphorous" in a table of hypertech weaponry ammo, so possibly not the [best analog for a round that punches a neat hole, then detonates in the target.](https://youtu.be/1bYMuvtpJF4) Let alone for being a gun chambered in a cartridge that even without this specialty ammunition is used to shoot straight through a normal vehicle's body, destroy engines and shoot down aircraft. There have been [tests of shooting Raufoss Mk.211 it on replica bodies](https://youtu.be/UwQ2ks9Gl5A?t=1112) showing it'd detonate *inside* bodies.
Do I miss something that would help in estimating the damage?
As a result, I estimate an Anti-materiel Rifle to have a damage of roughly the following stats:
>
> Anti-materiel Rifle ([PGM Hecate II](https://en.wikipedia.org/wiki/PGM_H%C3%A9cate_II), .50 BMG)- Damage: 14/L - Range 2000 yards (1800 m) - Rate 1 - Clip: 7 - Conceal N/A - Notes: N/A
>
>
> Raufoss Mk211 - Damage: - Effects: Reduce any body armor by -4. If a present armor is totally negated: Treat all damage also as fire damage.
>
>
>
Is this loadout *balanced* compared to other weapons available in the circumstances of a **Hunter**, or did I overdo it to get to the vehicle-stopping properties and a somewhat good representation of the gun and ammo?
---
1 - V20 p.280 ; M20 p.452 ; W20 p.303 ; C20 p.287
2 - M20 p.453
3 - M20 p.454 | 2022/07/12 | [
"https://rpg.stackexchange.com/questions/199898",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/30306/"
] | ### Bombs fall, everybody dies.
Vampire isn't supposed to be a game where human militaries play a large role. That's part of the point of the Masquerade - vampires are afraid that humans will wipe them out if their existence becomes widely known.
If things degenerate to the point where vampires are getting shot at by miltary heavy weapons, just kill them. If you want to use mechanics, just pull out a big pile of dice and roll them, with every success doing a point of lethal damage. Vampires typically only have 7 health levels, so 20 or 30 dice should be enough to ensure the true deaths of whatever vampire was dumb enough to pick a fight with the full force of the military.
There are rules for military vehicles in M20, and honestly, they're so powerful that a squad of dudes in a tank can fight multiple vampire Methuselahs and win - so much so that one of White Wolf's former designers (unofficially) rewrote nerfed versions of them for games where fighting them isn't meant to be either instant death or a boring grindfest where neither party is capable of harming the other.
Of course, if the PC'S haven't been stupid, and you want to use a hunt by military forces as a part of the game, I'd suggest maybe showing a powerful vampire openly fight the military and getting obliterated, and then running a session of the PC's running and hiding from military vehicles and maybe fighting a squad or two of soldiers with rifles - with the tension of having to take out the soldiers before they can alert their comrades to the PCs' location. | In your question you mention M20 having Flechettes and Incendiary rounds. The same table (p453) also lists explosive shells. Additionally, there's an explosives chart two pages later (455) that includes small rockets and artillery shells.
While maybe not the most directly applicable answer, I also recommend taking a glance at Scion 1e's Companion book, specifically p266-269. While the action tracking (Tick System) is slightly different, the stats are quite comparable to WoD, including that Epic Strength and Stamina can act like Potence and Fortitude respectively. The main consideration is that comparable weapons at military grade levels appear to float a bit higher for damage. Otherwise, it is still a d10 system based on success counting, deals damage in bashing/lethal/aggravated increments, and separates hitting from damage. |
147,193 | I'm writing planet generator, using [pico8](http://lexaloffle.com/pico-8.php). I got surface generation done:
[](https://i.stack.imgur.com/wjWnP.png)
[](https://i.stack.imgur.com/bVwUn.png)
And the last thing to do is to map the texture onto a sphere.
Pico8 has no triangle function. So my question is, how do I make a sphere in my 2d space, and how do I apply a texture on it?
Looking for an effect like this (with no lighting, of course!):
[](https://i.stack.imgur.com/r2MaJ.jpg)
I have really bad knowledge of 3d space manipulations.
The full list of available API functions can be found **[here](https://neko250.github.io/pico8-api/)**.
**Update 4:**
Solved!
[](https://i.stack.imgur.com/nK0P1.gif)
[Try it live here.](http://egordorichev.itch.io/planet-generator) | 2017/08/15 | [
"https://gamedev.stackexchange.com/questions/147193",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/-1/"
] | Here's a rundown of a few different ways we can sample a panning texture to make it look like a globe...
[](https://i.stack.imgur.com/Tk86w.gif)
Since I'm not deeply familiar with Pico-8 syntax & conventions, I'll try to present these as pseudo-code that should be reasonably straightforward to translate / token-reduce as needed.
```
// iterate over each pixel in the discSize x discSize bounding square
for x = left...left + discSize
for y = top...top + discSize
// convert pixel position into a vector relative to the center,
// normalized into the range -1...1
px = (x - left) * 2/discSize - 1
py = (y - top) * 2/discSize - 1
// get the squared magnitude of this vector
magSq = px * px + py * py
// if we're outside the circle, draw black/background and skip ahead
if ( magSq > 1 )
plotPixel(x, y, BLANK)
continue
// TODO: warp our local offset vector px py to imitate 3D bulge
// convert our local offsets into lookup coordinates into our map texture
u = time * rotationSpeed + (px + 1) * (mapHeight/2)
v = (py + 1) * (mapHeight/2)
// wrap the horizontal coordinate around our map when it goes off the edge
u = u % (2 * mapHeight)
// look up the corresponding colour from the map texture & plot it
color = lookupFromMap(u, v)
plotPixel(x, y, color)
```
If you just use this as-is, you'll get the left version: it's cropped to a circle and wraps around, but it's very flat-looking.
By tweaking `px` and `py` where it says "`TODO`" we can get different bending effects.
Here's an equivalent implementation of **Bálint's suggestion** in this form:
```
widthAtHeight = sqrt(1 - py * py)
px = px / widthAtHeight
```
If we want an exactly correct sphere as viewed by an orthographic camera, we can use inverse trig functions to convert to **latitude & longitude**:
```
widthAtHeight = sqrt(1 - py * py)
px = asin(px / widthAtHeight) * 2/3.141592653589
py = asin(py) * 2/3.141592653589
```
(This assumes asin's return value is in radians. If using another unit, divide by whatever value corresponds to 90 degrees, instead of by pi/2. The idea is to map asin(-1)...asin(1) back into the range -1...1)
This gives the version second from the right, which you can see is a very good match for rendering a real 3D sphere (far right). The downside is that transcendentals like the arcsine function can be expensive. This may or may not be an issue in your case.
If you're looking for something to give a more bulgy look without the trig, you can use something like a **lens distortion** for a cheap hack:
```
scale = 0.35 * magSq + (1 - 0.35)
px = px * scale
py = py * scale
```
At the edges of the disc, scale is 1 so there's no difference versus the flat version. Closer to the center, this shrinks the length of our local offset vector (down to a controllable minimum set by the 0.35 linear interpolation constant), which has the effect of magnifying features close to the middle.
Of course these are just a few different ways you could get a bulged look. You could try all kinds of other formulae, or even go for a perspective camera look instead of the orthographic version I've shown here. | First of all, this is going to cut corners, as this API is very small (I have concerns about the maximum 8192 tokens rule, which technically makes this non-turing-complete). The algorithms you need to use are the pythagorean theorem (`√(x² + y²)`) and the width of a circle at a specific height (`2√(r² + |y - cy|²)` where cy is the y coordinate of the circle).
So, you need to loop through the square that contains the circle. If the radius of the sphere is `r` and the center of it is `(cx; cy)`, then you need to loop through the coordinates between `(cx - r; cy - r)` and `(cx + r; cy + r)`. Let the coordinates of the current pixel be `(x; y)`.
If `√((x - cx)² + (y - cy)²)` is less then or equal to the radius of the sphere, then the pixel is inside the 2d projection of the sphere.
Next we need to map this coordinate to a coordinate on the texture. Here we use the circle width formula. Get the width of the circle at the current position, let's name it `segmentWidth` Because we usually see around half of a sphere, we can just say that the coordinates of the pixel on the texture is
```
x = round(((x - cx) / segmentWidth + 0.5) * textureWidth / 2)
y = round(((y - cy) / r / 2 + 0.5) * textureHeight)
``` |
301,422 | consider an insteresting question:
given Banach Space $ \mathcal{B}$, independent identical distribution random operator on $ \mathcal{B}$: $ (T\_i)\_{i \ge 1} $, where operator space is endowed with operator norm $ || T\_i||= \sup\_{v \in \mathcal{B},||v||=1}||T\_iv||$.
assume $ \sup\_i||T\_i|| < \infty $, spectrum radius $ \rho(T\_i)<1 $ which is i.i.d random variables.
can we show: $ ||\prod\_{i=1}^n T\_i|| $ has exponential decay almost surely?
take matrix as example: let $T\_i$ be
\begin{pmatrix}
\lambda\_i & 1 \\
0 & \lambda\_i
\end{pmatrix}
where $ \lambda\_i <1 $ is i.i.d random variable.
so $ \prod\_{i=1}^n T\_i=$
\begin{pmatrix}
\prod\_{i=1}^n\lambda\_i & (\prod\_{i=1}^n\lambda\_i)(\prod\_{i=1}^n\frac{1}{\lambda\_i}) \\
0 & \prod\_{i=1}^n\lambda\_i
\end{pmatrix}
then by law of large number when $ n \to \infty $, it is almost surely:
\begin{pmatrix}
\exp(n\mathbb{E}\log \lambda\_1) & \exp(n\mathbb{E}\log \lambda\_1)\cdot n \cdot \mathbb{E}\frac{1}{\lambda\_1} \\
0 & \exp(n\mathbb{E}\log \lambda\_1)
\end{pmatrix}
so $ ||\prod\_{i=1}^n T\_i|| $ has exponential decay almost surely if $ \mathbb{E}\frac{1}{\lambda\_1} < \infty, \mathbb{E}\log \lambda\_1 > -\infty$.
From my example, we have to add some conditions to my problem, otherwise it is not true. But If you know some reference about iid random operator and its spectrum, pls let me know, very appreciate!!! | 2018/05/29 | [
"https://mathoverflow.net/questions/301422",
"https://mathoverflow.net",
"https://mathoverflow.net/users/124254/"
] | Let $\mathbb{P}$ be a Borel probability measure on the space of bounded operators on $\mathcal{B}$, equipped with the operator norm topology. By the subadditive ergodic theorem, the limit
$$\lim\_{n \to \infty} \frac{1}{n}\log \|T\_{\omega\_n}\cdots T\_{\omega\_1}\|$$
exists a.s., where the operators $T\_{\omega\_i}$ are chosen IID according to the law $\mathbb{P}$. (This is also true if the sequence $(\omega\_k)$ is chosen according to a stationary ergodic process.) The limit
is a.s. equal to
$$\lim\_{n \to \infty} \frac{1}{n}\int \log\|T\_{\omega\_n}\cdots T\_{\omega\_1}\|d\mathbb{P}(\omega\_n)\cdots d\mathbb{P}(\omega\_1)$$
in the IID case, and a related property holds in the stationary ergodic case. This limit is conventionally called the *(top) Lyapunov exponent*.
Here is an example to illustrate that the criterion $\rho(T\_i)<1$ a.s. is insufficient to guarantee that the top Lyapunov exponent is negative even if $\mathcal{B}$ is two-dimensional. It is sufficient to find a probability measure supported on a pair of $2 \times 2$ matrices with spectral radius $1$ for which the top Lyapunov exponent is positive, since then we can divide both matrices by $e$ to the power of the top Lyapunov exponent and obtain something with spectral radii $<1$ but with the IID products not exponentially decaying. So, consider
$$A\_1=\begin{pmatrix}0&-1\\1&0\end{pmatrix},\qquad A\_2=\begin{pmatrix}1&-\frac{1}{2}\\2&0\end{pmatrix}$$
each with probability $\frac{1}{2}$. One may check that the two matrices have spectral radius $1$, have determinant $1$, do not preserve a finite union of one-dimensional subspaces of $\mathbb{R}^2$, and have the property that $\rho(A\_1A\_2)>1$. By Furstenberg's Theorem on random matrix products (see for example Viana's book *Lectures on Lyapunov exponents*, or Bougerol and Lacroix's *Products of Random Matrices with Applications to Schrödinger Operators*) it follows from these observations that the top Lyapunov exponent is positive. Thus, the desired implication is false even for $2 \times 2$ matrices.
However, the stronger condition
$$\rho(T\_{\omega\_n}\cdots T\_{\omega\_1})<(1-\varepsilon)^n$$
for $\mathbb{P}\times \cdots \times \mathbb{P}$ almost every $\omega\_1,\ldots,\omega\_n$, for all $n \geq 1$, is sufficient if $\mathbb{P}$ has bounded support and $\mathcal{B}$ is finite-dimensional. Indeed, this condition implies
$$\limsup\_{n \to \infty} \sup\_{\omega\_1,\ldots,\omega\_n \in \mathrm{supp} \mathbb{P}}\|T\_{\omega\_n}\cdots T\_{\omega\_1}\|^{\frac{1}{n}}\leq 1-\varepsilon $$
and the almost sure result follows trivially. This result is sometimes referred to as the Berger-Wang formula for the joint spectral radius. This result also holds in infinite dimensions if the operators are compact, or satisfy a more complicated condition involving their approximability by compact operators. A while ago I wrote a paper on this, "The generalised Berger-Wang formula and the spectral radius of linear cocycles", and you might find some of the references therein helpful.
You would probably also be interested in reading about Oseledec's multiplicative ergodic theorem and its infinite-dimensional generalisations. Anthony Quas has (co-)written numerous papers on infinite-dimensional multiplicative ergodic theorems and those would probably give you some insight into the state of the art in this area as well as a good source of contemporary and historical references. | You should have a look on the book "Product of random matrices and application to Schrodinger operators" (Lacroix, Bougerol) <http://fr.booksc.org/book/32773481/48bc02>
or the paper of Le Page "Théorèmes limites pour les produits de matrices aléatoires" (in French).
I am not sure that the spectral radius condition is very appropriate because we can't estimate $\rho(AB)$ with $\rho(A)$ and $\rho(B)$.
In a nutshell what is done in the literature is the following :
1-Almost surely we have the Lyapunov exponent : $$ \frac{1}{N}\log \|\prod\_i T\_i \|\rightarrow \gamma$$
2-Assuming $\det(T\_i)=1$, then in many cases you can show that $\gamma>0$ ( $\|\prod T\_i \|$ is exponentially increasing).
Therefore, you have exponentially decreasing if $\gamma\_1<-\frac{1}{d}\mathbb{E}(\log(\det(T)))$ where $\gamma\_1$ is the Lyapunov exponent of $\frac{1}{\det(T\_i)^{1/d}}T\_i$ and $d$ the size of the matrices. |
73,479,875 | I'm writing an API in Next.js to insert data into a MySQL database. The error I'm experiencing relates to a circular reference, but I'm having trouble finding it. Please be aware that I am also using Axios to write this API.
I'm running into the following error:
```
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Query'
| property '_timer' -> object with constructor 'Timer'
--- property '_object' closes the circle
```
Here is my API:
```
import type { NextApiRequest, NextApiResponse } from "next";
import * as pool from "../../../src/utils/dbConnection";
import console from "console";
export default async (req: NextApiRequest, res: NextApiResponse) => {
const { email, password, firstname, lastname } = req.body as any;
let conn;
try {
conn = await pool.getConnection();
const rows = await conn.query(
`INSERT INTO Users(email, password, firstname, lastname) VALUES(?, ?, ?, ?)`,
[email, password, firstname, lastname]
);
res.status(200).json(JSON.stringify(rows));
} catch (err) {
console.log(err);
} finally {
if (conn) conn.end(); // close connection
}
};
``` | 2022/08/24 | [
"https://Stackoverflow.com/questions/73479875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13844056/"
] | I guess your problem is here: `res.status(200).json(JSON.stringify(rows));`. So, from the docs of [`res.json`](https://expressjs.com/de/api.html#res.json):
>
> Sends a JSON response. This method sends a response (with the correct
> content-type) that is the parameter converted to a JSON string using
> [JSON.stringify()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify).
>
>
>
Therefore you just need `res.json(rows);` or maybe `res.status(201).json(rows);`, where `201` means [Created](https://developer.mozilla.org/de/docs/Web/HTTP/Status/201).
**Edit:**
I think there might be another problem. The query to insert data does not return the inserted rows (if you use [mysql](https://www.npmjs.com/package/mysql)). So, please log `rows` to check its content - and as mentioned by @jfriend00 there could be and properly are some circular references.
However, you can get the [id of the inserted row](https://www.npmjs.com/package/mysql#getting-the-id-of-an-inserted-row) or [the number of affected rows](https://www.npmjs.com/package/mysql#getting-the-number-of-affected-rows) for example. | I personally use `safe-json-stringify` which has a method to modify objects without stringifying, in case you want a circular-safe object.
<https://www.npmjs.com/package/safe-json-stringify>
```
res.status(200).json(safeJsonStringify.ensureProperties(data));
```
Otherwise, you can look at many other posts on the subject:
[Stringify (convert to JSON) a JavaScript object with circular reference](https://stackoverflow.com/questions/10392293/stringify-convert-to-json-a-javascript-object-with-circular-reference)
About natively removing circulars. |
13,265 | I'm trying to figure out if I should be filtering out GWAS hits that have high standard error and I'm not quite sure what to do. It seems like it might not matter, because the standard error is used to calculate the t-statistic, which is then used to calculate the p-value. So in a way it's already built in. But reporting SNPs that have very high standard error doesn't seem quite right. What's the best way to handle this? | 2020/05/12 | [
"https://bioinformatics.stackexchange.com/questions/13265",
"https://bioinformatics.stackexchange.com",
"https://bioinformatics.stackexchange.com/users/59/"
] | I am curious about the relationship between your p-value (or effect sizes) and standard error. I would expect the significant signals to have smaller stand error compared to the non-significant, background signals. If this is the case, there is no need to do filter. | I think the effect size is more of an issue than the standard error.
If the standard error suggests that the effect direction could change sign, then it might be a good idea to filter it out. Otherwise, if the effect size remains large (or at least positive) even after accounting for a large error, then [to me] that would attach more weight to the likelihood that the association is valid.
I did a very quick analysis of the results of one UK Biobank study on Twitter, where I used the statistic of "the least extreme value in a 95% confidence interval" in a Manhattan plot instead of the more commonly-used p-value:
<https://twitter.com/gringene_bio/status/1207617723586371584> |
6,907,423 | I have a module called 'admin' in my application, which is accessible at /mysite/admin. To improve the site security I want to change this URL to something more difficult to guess to the normal users and only the site admin will know.
I tried urlManager rules but couldn't get the desired result, for example:
```
'admin-panel'=>'admin/default/index',
'admin-panel/login'=>'admin/default/login'
```
But this will only work for those two URLs.
So the only thing I can think of now is to rename the actual module. The module name is referenced a lot throughout the app so that it is too difficult to do. anyone have any other suggestions? | 2011/08/02 | [
"https://Stackoverflow.com/questions/6907423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/238784/"
] | ```
rules=>array(
'admin-panel' =>'admin',
'admin-panel/<_c:\w+>/<_a:\w+>/<id:\d+>' =>'admin/<_c>/<_a>/<id>',
'admin-panel/<_c:\w+>/<_a:\w+>' =>'admin/<_c>/<_a>',
'admin-panel/<_c:\w+>' =>'admin/<_c>',
)
```
But it's just alias - your admin module still will be available by /admin/ URL. Actually you must check access for users, don't try to hide your admin panel. | Take a look at [URL Management (Parameterizing Routes)](http://www.yiiframework.com/doc/guide/1.1/en/topics.url#parameterizing-routes) from the Definitive Guide.
Something like this should do the job:
```
array(
'<_c:(admin\-panel)>/<_a>' => 'admin/default/<_a>',
)
```
But you're just 'renaming' your default controller in the admin module and it will still be accessible under your old URL. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.