text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Is it possible to have a inputbox require 5 digits?
I am currently designing a macro that will require 3 inputs from a user, I want to know if I could somehow require the numeric inputs to require a 5 digit serial number. And restrict anything that is more or less then five digits. This is my code so far:
Sub MRN_numbers()
Dim s, e As Integer
Dim m As String
s = InputBox("Please enter the starting 5 digit MRN number")
m = InputBox("please enter the material type")
If Not m = "ebara" Or m = "mirra" Or m = "300mm" Then
MsgBox ("Please enter valid material name!")
m = InputBox("Please enter the material type")
End If
e = InputBox("pleae enter the ending 5 digit MRN number")
Range("D1").Activate
Range("D65536").End(xlUp).Offset(1, 0).Activate
For i = s To e
If m = "ebara" Or m = "mirra" Or m = "300mm" Then
If m = "ebara" Then
For l = 1 To 5
ActiveCell.Value = i & "-" & l
ActiveCell.Offset(1, 0).Activate
ActiveCell.Offset(-1, -1).Value = "Ebara"
Next l
End If
If m = "mirra" Then
For r = 1 To 6
ActiveCell.Value = i & "-" & r
ActiveCell.Offset(1, 0).Activate
ActiveCell.Offset(-1, -1).Value = "Mirra"
Next r
End If
If m = "300mm" Then
For y = 1 To 4
ActiveCell.Value = i & "-" & y
ActiveCell.Offset(1, 0).Activate
ActiveCell.Offset(-1, -1).Value = "300mm"
Next y
End If
End If
Range("D65536").End(xlUp).Offset(1, 0).Activate
Next i
End Sub
I am not sure where to start on this, I watched videos but didn't find anything that helped, I am going to keep looking and trying different ways in the mean time, but any help on this would be appreciated.
A:
Wrap each entry in a Do Loop:
Do
s = InputBox("Please enter the starting 5 digit MRN number")
If Not (IsNumeric(s) And Len(s) = 5) Then MsgBox s & " is not a 5 digit number"
Loop Until IsNumeric(s) And Len(s) = 5
So for e
Do
e = InputBox("Please enter the ending 5 digit MRN number")
If Not (IsNumeric(e) And Len(e) = 5) Then MsgBox e & " is not a 5 digit number"
Loop Until IsNumeric(e) And Len(e) = 5
| {
"pile_set_name": "StackExchange"
} |
Q:
How to overwrite the values of the first column in every rows in a HTML tbody table with JavaScript and with jQuery?
Here is a table example:
<table id="tableId">
<thead>
<tr>
<th>line number</th>
<th>value</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>value 1</td>
</tr>
<tr>
<td>3</td>
<td>value 2</td>
</tr>
<tr>
<td>1</td>
<td>value 3</td>
</tr>
</tbody>
</table>
<input type="button" value="relineing" onclick="reLineNumbering('tableId')"/>
I want only the "line number"s to be in sequence like this:
<table id="tableId">
<thead>
<tr>
<th>line number</th>
<th>value</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>value 1</td>
</tr>
<tr>
<td>2</td>
<td>value 2</td>
</tr>
<tr>
<td>3</td>
<td>value 3</td>
</tr>
</tbody>
</table>
<input type="button" value="relineing" onclick="reLineNumbering('tableId')"/>
I've tried both of the snippets below:
function reLineNumbering(tableId) {
$('#'+tableId+' tbody').each(function (i) {
this.rows[i].cells[0].text('i');
});
}
function reLineNumbering(tableId) {
var rowCount = $('#'+tableId+' tbody tr').length;
for (var i=0; i<rowCount; i++) {
$('#'+tableId+' tbody').rows[i].cells[0].text(i);
}
}
Could someone help me?
A:
This will change the first column to a sequential number starting from 1:
function reLineNumbering(tableId){
$('#' + tableId + ' > tbody > tr').each(function(i, val){
$('td:first', this).text(i+1);
});
}
Fiddle
Plain Javascript - Fiddle:
function reLineNumbering(tableId){
var table = document.getElementById(tableId);
var total = table.rows.length;
for(var i=0; i<total; i++){
if(i > 0){
table.rows[i].cells[0].innerHTML = i;
}
}
}
Or by creating the text node instead of setting innerHTML. In this simple scenario the use of innerHTML isn't a problem, but usually you will want to work with DOM elements and set the text node instead of setting the HTML:
function reLineNumbering(tableId){
var table = document.getElementById(tableId);
var total = table.rows.length, text, cell;
for(var i=0; i<total; i++){
if(i > 0){
text = document.createTextNode(i);
cell = table.rows[i].cells[0];
cell.removeChild(cell.firstChild);
cell.appendChild(text);
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Subclass calling its superclass method
please I have a class WN that is a subclass of N. N has a method create_nl() that appends the keys and values in the pos dictionary to two empty lists nl and nv. My question is how can I write a method in the subclass to call the create_nl() method in class N such that A and B in wr(), gets assigned random values from the nl list in the superclass method create_nl().I have written a code for that below but it generates an error. Thanks
import random as rand
pos = {1:(0, 0.1), 2:(0, 0.), 3:(0, 0.3), 4:(0, 0.4), 5:(0, 0.5), 6:(0, 0.6) }
class N(object):
def __init__(self, name):
self.name = name
def create_nl(self):
nv = []
nl = []
for key, value in pos.iteritems():
nl.append(key)
nv.append(value)
return nl
nn = N("CT")
nn.create_nl()
class WN(N):
def n(self):
return super(WN, self).create_nl()
def wr(self):
count = 0
while count < 1:
A = int(rand.choice(self.n))
B = int(rand.choice(self.n))
count += 1
A:
You can call superclass methods directly on subclass instances. You only need to use super if you've overridden the method in the subclass and you want to access the superclass version instead of the override.
class WN(N):
def wr(self):
nl = self.create_nl() # calls superclass method, which we have not overridden
A = random.choice(nl) # use the return value
B = random.choice(nl)
Note that it's a bit strange to be using a method like create_nl to access global data, rather than instance data. Your random.choice calls could just as easily be done directly on pos directly!
| {
"pile_set_name": "StackExchange"
} |
Q:
Revi'a - mi yodeya?
Who knows a quarter?
?רביע - מי יודע
In the spirit of the song "Echad - mi yodeya", please post interesting and significant Jewish facts about the number 0.25.
Lazy gematria may be worthy of discission, but perhaps not of a full-fledged answer. [This may not apply in the conventional sense, but, e.g., saying x is a quarter of y is just not keeping in the spirit. However, there maybe be examples that the Arizal, Baal Haturim, etc., mention and they are perfect for comments.]
Check out mi-yodeya-series for the previous three hundred fifty entries in this ongoing series.
Please include sources for your information wherever possible, as with all other answers on this site.
A:
A quarter (reviit) of a log is a measure frequently found in halacha, particulrly for drinking such as wine. In most (all?) cases a cup of blessing must hold a reviit. Similarly, the cup used for washing one's hands must hold a reviit.
A:
The Sof Zman Kriyas Shema in the morning is (three hours) or a quarter of the day.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to obtain command return value in script
I have the following script:
serverip=$1
key=$2
linenumber=0
##CHeck If server IP exists
if grep -wq $serverip server; then
echo "IP exists"
linenumber=`awk '$0 ~ "$serverip" {print NR}' file`
echo "$linenumber"
fi
The file contains:
192.168.18.2 testing123 3
./radius_adt.sh 192.168.18.2 nevis
Does not print the line number.
The awk command works outside the script.
awk '$0 ~ "192.168.18.4" {print NR}' file
output: 1
WHy is the command does not run inside the script and its return value copied into linenumber.
A:
This line is the problem:
linenumber=`awk '$0 ~ "$serverip" {print NR}' file`
And shell won't be able to expand $serverip inside single quotes and awk will treat it literally. You should use it like this to pass shell variable to awk:
linenumber=$(awk -v serverip="$serverip" '$0 ~ serverip {print NR}' file)
| {
"pile_set_name": "StackExchange"
} |
Q:
D3 tooltip inside custom sparkline chart in an 'ag-grid' table cell not visible outside of table cell boundary
I have an angular.js app with d3 and ag grid javascript grid libary (https://www.ag-grid.com/) to generate a tooltip for providing point data on a waterfall chart inside the table.
When I hover to a lower poin on a particular chart I get a tooltip but is clipped if it extends beyond the table cell boundary.
Cell/Chart width height is 300px by 150px.
What I have tried (with partial success):
<div tabindex="-1" unselectable="on" role="gridcell" comp-id="51" col-id="CloseTrends_1"
class="ag-cell ag-cell-not-inline-editing ag-cell-with-height ag-cell-value ag-cell-focus"
style="width:500px;left: 915px;">
width 500px works to only eliminate horizontal clipping value for each cell modified but vertical portion clipping is still occuring when tooltip goes below the cell boundary on y axis.
What I want:
Each chart to have tooltips visible above and throughtout cell no matter of location of tooltip on cell chart.
overflow: visible on the svg element and the above modification partially helped but still is producing an incomplete solution
Open the fiddle and scroll table to right to see the charts. Hover with mouse to observe effect.
https://next.plnkr.co/edit/6m3EoZ2RN1bWMOiP?preview
A:
You can create an html tooltip that appears based on its activated position. This should eliminate the issue of the tooltip getting cut off.
//function to append the tooltip; this is assuming only one tooltip will show at a time
appendTooltip() {
var target = document.getElementById("app");
var tooltip = d3.select(target).selectAll(".tool-tip");
if (tooltip.empty()) {
tooltip = d3.select(target).append("div")
.attr("class", "tool-tip")
.style("opacity", 0);
}
return tooltip
},
//function to show the tooltip
showTooltip(tooltip, d) {
tooltip.transition()
.duration(200)
.style("opacity", 0.8);
var html = `<div>date<div>${d.date}`
tooltip.html(html);
tooltip.style("left", (d3.event.pageX + 10) + "px)
tooltip.style("top", d3.event.pageY + "px")
},
//function to remove the tooltip
removeTooltip(tooltip) {
tooltip.transition()
.duration(100)
.style("opacity", 0);
}
You can style the tooltip however you want. Make sure to add appropriate z-index if necessary.
.tooltip {
fill: white;
stroke: #000;
opacity: 0.75;
}
// Append the tooptip when you first draw the d3 graph, and call the tooltip to add new HTML element on mouseover.
var tooltip = appendTooltip();
element.on("mouseover", d => showtooltip(tooltip, d);)
| {
"pile_set_name": "StackExchange"
} |
Q:
Do I need to call VariantClear after VariantChangeType
I have the following code in C++. Do I need to free 'varDest' variable?
VARIANT val;
if(SUCCEEDED(classObj->Get(pwPropName, 0, &val, NULL, 0))) //WMI property retrieval
{
//Then at some point
VARIANT varDest;
varDest.vt = VT_EMPTY;
if(SUCCEEDED(::VariantChangeType(&varDest,
const_cast<VARIANT *>(&val), 0, VT_BSTR)))
{
//Do I need to call the following?
VariantClear(&varDest);
}
VariantClear(&val);
}
A:
Yes you must call VariantClear. The VariantChangeType method if successful will essentially coerce a copy of the source into the destination. This copy in the destination is now independently tracked and must be independently cleared.
| {
"pile_set_name": "StackExchange"
} |
Q:
Picasso not loading image from file
I really don't know what I am doing wrong.
onPostExecute, the I loaded the ImageView with the file I just created from bitmap:
public class ComicFragment extends Fragment
{
private final static String URL1 = "http://192.168.1.143/jerson/sample_comic.jpg";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_comic, parent, false);
ImageView imageView = (ImageView) view.findViewById(R.id.imageview_comic);
Point point = getScreenSize();
new DownloadImageTask(getActivity(), imageView, point.x, point.y).execute(URL1);
//Uri uri = Uri.parse("http://192.168.1.143/jerson/sample_comic.jpg");
//simpleDraweeView.setImageURI(uri);
return view;
}
private Point getScreenSize()
{
Point point = new Point();
WindowManager manager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
display.getSize(point);
return point;
}
private byte [] getBitmapByteArray(Bitmap bitmap)
{
int bytes = bitmap.getByteCount();
ByteBuffer buffer = ByteBuffer.allocate(bytes);
bitmap.copyPixelsToBuffer(buffer);
return buffer.array();
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
}
private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
{
// From https://developer.android.com/training/displaying-bitmaps/load-bitmap.html#read-bitmap
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth)
{
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth)
{
inSampleSize *= 2;
}
}
return inSampleSize;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap>
{
private Context context;
private int viewWidth;
private int viewHeight;
private ImageView canvas;
public DownloadImageTask(Context context, ImageView view, int viewWidth, int viewHeight)
{
this.context = context;
this.viewWidth = viewWidth;
this.viewHeight = viewHeight;
canvas = view;
}
@Override
protected Bitmap doInBackground(String ... urls)
{
String url = urls[0];
Bitmap comicBitmap = null;
FileOutputStream out = null;
File root = Environment.getExternalStorageDirectory();
File directory = new File(root.getAbsolutePath() + "/DCIM/tmpimg/cached/");
directory.mkdirs();
File file = new File(directory, "tmp.png");
try
{
InputStream forGettingSizeOnly = new BufferedInputStream(new URL(url).openStream());
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(forGettingSizeOnly, null, options);
int outWidth = options.outWidth;
int outHeight = options.outHeight;
options.inSampleSize = calculateInSampleSize(options, viewWidth, viewHeight);
options.inJustDecodeBounds = false;
// Make this not load another image from network the second time...
InputStream actualImage = new BufferedInputStream(new URL(url).openStream());
Bitmap decodedImage = BitmapFactory.decodeStream(actualImage);
out = new FileOutputStream(file);
comicBitmap = Bitmap.createBitmap(decodedImage, 0, 0, outWidth, 400);
comicBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
Log.i(ComicApplication.TAG, "****File saved at : " + file.getAbsolutePath() + "WxH" + outWidth + " x " + comicBitmap.getHeight());
}
catch(Exception e)
{
e.printStackTrace();
Log.i(ComicApplication.TAG, "ERROR : " + e.getMessage());
}
return comicBitmap;
}
@Override
protected void onPostExecute(Bitmap result)
{
File root = Environment.getExternalStorageDirectory();
File file = new File(root.getAbsolutePath() + "/DCIM/tmpimg/cached/tmp/tmp.png");
Picasso.with(context).load(file).into(canvas);
Log.i(ComicApplication.TAG, "FILE LOADED FROM : " + file.getAbsolutePath());
}
}
}
I am able to see the tmp.png from the phone's image viewer. I am not receiving any exceptions, error, whatsoever from Picasso's end?
Can someone help me out on why is Picasso not loading my image from file?
A:
first, make sure that you are giving Picasso the correct file path,
then you have to add the permission of READ_EXTERNAL_STORAGE in the app Manifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
put this line in the manifest level
| {
"pile_set_name": "StackExchange"
} |
Q:
Parenthesis/Brackets Matching using Stack algorithm
For example if the parenthesis/brackets is matching in the following:
({})
(()){}()
()
and so on but if the parenthesis/brackets is not matching it should return false, eg:
{}
({}(
){})
(()
and so on. Can you please check this code? Thanks in advance.
public static boolean isParenthesisMatch(String str) {
Stack<Character> stack = new Stack<Character>();
char c;
for(int i=0; i < str.length(); i++) {
c = str.charAt(i);
if(c == '{')
return false;
if(c == '(')
stack.push(c);
if(c == '{') {
stack.push(c);
if(c == '}')
if(stack.empty())
return false;
else if(stack.peek() == '{')
stack.pop();
}
else if(c == ')')
if(stack.empty())
return false;
else if(stack.peek() == '(')
stack.pop();
else
return false;
}
return stack.empty();
}
public static void main(String[] args) {
String str = "({})";
System.out.println(Weekly12.parenthesisOtherMatching(str));
}
A:
Your code has some confusion in its handling of the '{' and '}' characters. It should be entirely parallel to how you handle '(' and ')'.
This code, modified slightly from yours, seems to work properly:
public static boolean isParenthesisMatch(String str) {
if (str.charAt(0) == '{')
return false;
Stack<Character> stack = new Stack<Character>();
char c;
for(int i=0; i < str.length(); i++) {
c = str.charAt(i);
if(c == '(')
stack.push(c);
else if(c == '{')
stack.push(c);
else if(c == ')')
if(stack.empty())
return false;
else if(stack.peek() == '(')
stack.pop();
else
return false;
else if(c == '}')
if(stack.empty())
return false;
else if(stack.peek() == '{')
stack.pop();
else
return false;
}
return stack.empty();
}
A:
This code is easier to understand:
public static boolean CheckParentesis(String str)
{
if (str.isEmpty())
return true;
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < str.length(); i++)
{
char current = str.charAt(i);
if (current == '{' || current == '(' || current == '[')
{
stack.push(current);
}
if (current == '}' || current == ')' || current == ']')
{
if (stack.isEmpty())
return false;
char last = stack.peek();
if (current == '}' && last == '{' || current == ')' && last == '(' || current == ']' && last == '[')
stack.pop();
else
return false;
}
}
return stack.isEmpty();
}
A:
public static boolean isValidExpression(String expression) {
Map<Character, Character> openClosePair = new HashMap<Character, Character>();
openClosePair.put(')', '(');
openClosePair.put('}', '{');
openClosePair.put(']', '[');
Stack<Character> stack = new Stack<Character>();
for(char ch : expression.toCharArray()) {
if(openClosePair.containsKey(ch)) {
if(stack.pop() != openClosePair.get(ch)) {
return false;
}
} else if(openClosePair.values().contains(ch)) {
stack.push(ch);
}
}
return stack.isEmpty();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
REST HTTP response code for missing parent resource
My question is, should I return a HTTP response code of 400 Bad Request, 404 Not Found or 410 Gone when a parent resource, or higher, does not exist / has been deleted?
Looking for some guidance around how to handle a missing links in a RESTful resource tree, as I've read quite a bit but not a whole lot of personal experience.
Say we have the resources structure below:
/users/{userId}/accounts/{accoundId}/logs/{logId}
One user can have many accounts, which in turn can have many orders, which in turn can have many logs. Logs only exist against a single account, and accounts only exist against a single user. Logs cannot exist without an account, and accounts cannot exist without a user.
My problem comes when I try to resolve the below:
/users/123/accounts/321/logs - POST
/users/123/accounts/321/logs/987 - GET
/users/123/accounts/321/logs/987 - PUT
/users/123/accounts/321/logs/987 - DELETE
/users/123/accounts/321/logs/987 - PATCH
/users/123/accounts/321/logs/987 - HEAD
But this resource does not, or no longer, exists:
/users/123/accounts/321
or this resource does not, or no longer, exists:
/users/123
I could argue it's a 400 Bad Request, which as per RFC7231:
6.5.1. 400 Bad Request
The 400 (Bad Request) status code indicates that the server cannot
or will not process the request due to something that is perceived
to be a client error (e.g., malformed request syntax, invalid
request message framing, or deceptive request routing).
Would be by definition true, except in the scenario that a cache hadn't expired, meaning the application had yet to re-traverse the hierarchy, and another application had deleted the parent resource. By providing a relevant oplock, the client will have proven that as per its last knowledge, it was making a semantically correct request.
I instinctively would have lent towards 404 Not Found or 410 Gone even if this wasn't a cache thing, as the cause of the failure was literally a missing/unavailable resource. However as per the spec RFC7231:
6.5.4. 404 Not Found
The 404 (Not Found) status code indicates that the origin server
did not find a current representation for the target resource or is
not willing to disclose that one exists. A 404 status code does
not indicate whether this lack of representation is temporary or
permanent; the 410 (Gone) status code is preferred over 404 if the
origin server knows, presumably through some configurable means, that
the condition is likely to be permanent.
or
6.5.9. 410 Gone
The 410 (Gone) status code indicates that access to the target
resource is no longer available at the origin server and that this
condition is likely to be permanent.
These would appear to give the lie to that instinct.
Does anyone have any experience in dealing with this, or similar, scenarios and good approaches? I feel I should go with what feels right and what I'd expect to see if consuming this service, rather than the letter of the text.
A:
A thing to keep in mind: the HTTP response, including the metadata, which includes the status code, are specific to the requested resource, not some implicit hierarchy of things.
Which is to say
GET /users/{userId}/accounts/{accoundId}/logs/{logId}
requests: a current selected representation for the target resource. See RFC 7231; in particular, the request doesn't ask about representations of any of these:
/users/{userId}/accounts/{accoundId}/logs/
/users/{userId}/accounts/{accoundId}/
/users/{userId}
...
It's much simpler than that - can I have what I asked for? And the origin server provides a response, which may be a current representation, or it may be a message explaining that no such representation is available.
The fact that no representation of /users/{userId}/accounts/{accoundId}/logs/{logId} is available because /users/{userId}/accounts/{accoundId} does not exist is an implementation detail.
404 is normally what you would want to use as a status code to announce that no current representation of the target resource is available. Any explanation for why this is the case would normally go into the message body. For instance, you might describe it using problem details.
The server is not obligated to send an expired representation of a resource just because it happens to have one lying around (again, the cache is an implementation detail).
410 is almost the same thing; it's effectively an advisory that the client can mark its bookmarks as deprecated.
400 is a perfectly reasonable way to punt if you can't find a status code that better fits the semantics of the message in the payload. But I wouldn't use if for this case where 404 does actually fit your needs.
A:
NO: Rule out the 400 Bad Request as all the requests, which you have mentioned, are valid.
NO: To add some spice: I've seen a 409 Conflict being returned in similar cases. It appears inappropriate in your situation though as you clearly indicated that a resource is missing.
YES: A 404 Not Found is the most appropriate response if your resource does not exist. It doesn't matter if it ever existed or not. The 404 indicates a "sorry, resource unavailable". I would add an error message to be precise about which resource is missing so that your API consumers can handle the situation better.
MAYBE: A 410 Gone is a specific case of a 404. It should be raised if the resource is unavailable and it existed before and it will (practically) never exist again. So no matter how often and when you try to get the resource, you'll never get it again, but in the past, you may have been able to get it. Same thing here: if you decided on a 410 consider adding a precise error message.
On a personal note:
I have never seen a practical useful situation of a 410 Gone hence I avoid it and recommend my teams not to use it unless they can come up with a real good reason. It appears a little academic. In most cases, a 404 and 410 will be dealt with identically by your API consumers. They most often don't mind/care. I can only see rare edge cases to make valuable sense of a differentiation.
A DELETE often doesn't delete a resource. They get inactivated (made unavailable), but they are still available technically. If there's any chance that a resource may become available again, such as via a new feature called "return all recently deleted resources", a 410 would be already misleading.
A 410 also states that that resource did exist in the past indeed. From a data securities point of view, you could argue that information should kept internal and should not be exposed. In these cases, a 410 becomes a general no-no for your API.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mahalanobis distance in Matlab
I am trying to find the Mahalanobis distance of some points from the origin.The MATLAB command for that is mahal(Y,X)
But if I use this I get NaN as the matrix X =0 as the distance needs to be found from the origin.Can someone please help me with this.How should it be done
A:
I think you are a bit confused about what mahal() is doing. First, computation of the Mahalanobis distance requires a population of points, from which the covariance will be calculated.
In the Matlab docs for this function it makes it clear that the distance being computed is:
d(I) = (Y(I,:)-mu)*inv(SIGMA)*(Y(I,:)-mu)'
where mu is the population average of X and SIGMA is the population covariance matrix of X. Since your population consists of a single point (the origin), it has no covariance, and so the SIGMA matrix is not invertible, hence the error where you get NaN/Inf values in the distances.
If you know the covariance structure that you want to use for the Mahalanobis distance, then you can just use the formula above to compute it for yourself. Let's say that the covariance you care about is stored in a matrix S. You want the distance w.r.t. the origin, so you don't need to subtract anything from the values in Y, all you need to compute is:
for ii = 1:size(Y,1)
d(ii) = Y(ii,:)*inv(S)*Y(ii,:)'; % Where Y(ii,:) is assumed to be a row vector.'
end
| {
"pile_set_name": "StackExchange"
} |
Q:
Is hooking in iOS/Mac possible?
Is it possible to develop apps in iOS/Mac-OSx which needs hooking in iOS/Mac (similar to what we have in windows)? and how complex is it?
A:
If you want to hook a third-party app in MacOSX, it is possible thru InputManager.
See the SIMBL plugin that helps doing this by managing the InputManagers for you, or ApplicationEnhencer.
More info here
If you want to intercept a call inside your own app, e.g. when a call to a method (possibly a system method), you can do class posing (obsolete) or method swizzling using objc_exchangeImplementations. This also works on iOS apps. More info here.
Be careful anyway with this, this can potentially be dangerous, you have to know what you are doing (avoid infinite call loops, etc)
On MacOSX, you can also do C interception like on any UNIX system, to intercept system calls. But it is a bit more tricky and low-level (and system-wide)
| {
"pile_set_name": "StackExchange"
} |
Q:
MVC 6 Anchor Tag Helper not producing the expected href
Fairly straightforward issue.
<a asp-controller="Guide" asp-action="Index" asp-route-title="@Model.Title">Read more</a>
produces the link /Guide?title=Guide_no_1 but it is supposed to produce the link /Guide/Guide_no_1/
The documentation i can find all specify that its supposed to output /Guide/Guide_no_1/ so I have the feeling there is something i missed, a setting or some attribute somewhere.
the routes i have are like this, just incase they have an impact on link creation
[Route("/Guide/")]
public IActionResult Index() { ... }
[Route("/Guide/{title}/{page?}/")]
public IActionResult Index(string title, int page = 0) { ... }
[Route("/Guide/OnePage/{title}/")]
public IActionResult Index(string title) { ... }
A:
You need to specify the ordering of your attribute routes.
Otherwise they will be evaluated in the default order, which is probably based on reflection. The first one evaluated is the route /Guide/ which matches your specified controller and action, and since it is a match, no further routes are examined.
You need to order your routes so you evaluate first the most specific routes. In the case of attribute routing, you will do that using the Order parameter:
[Route("Guide/OnePage/{title}/", Order = 1)]
public IActionResult Index(string title) { ... }
[Route("Guide/{title}/{page?}/", Order = 2)]
public IActionResult Index(string title, int page = 0) { ... }
[Route("Guide/", Order = 3)]
public IActionResult Index() { ... }
Please note the order in which they appear in the file doesn't matter, the evaluation order is based just in the Order parameter of the attribute. I just wrote them so the order of evaluation is clear.
Now you will notice that you also have a problem with the 2 routes with parameters Guide/OnePage/{title}/ and Guide/{title}/{page?}/. Since they have the same controller, action and required parameters, there is no way MVC can differentiate them and the one ordered first will always win!
Either use a different action name for one of those routes
Or assign a specific route name to the one that will always lose, so you can create links using that name:
[Route("Guide/{title}/{page?}/", Name = "titleAndPage", Order = 2)]
public IActionResult Index(string title, int page = 0) { ... }
<a asp-route="titleAndPage" asp-route-title="fooTitle">Read more</a>
| {
"pile_set_name": "StackExchange"
} |
Q:
Underlying topological space of a CW complex
I'm reading a paper which has this sentence: if $X$ is a CW complex then $|X|$ denotes its underlying topological space.
I'm confused about what this underlying topological space is.
A:
When talking about a CW complex, the complex itself has more structure than a simple topological space. Each point is partitioned into a particular cell of the complex. However, CW complexes are mostly important because they allow us to manipulate topological spaces in an efficient manner. Some good examples of CW complexes are the surfaces of a cube, or a tetrahedron, or an octahedron, but all of these have the same underlying topological structure, homeomorphic to the surface of a sphere.
| {
"pile_set_name": "StackExchange"
} |
Q:
Prove this inequality $1+x+\frac{x^2}{2!}+\frac{x^3}{3!}+\cdots+\frac{x^n}{n!}>\frac{e^x}{2}$
let $0<x\le n$,prove that
$$1+x+\dfrac{x^2}{2!}+\dfrac{x^3}{3!}+\cdots+\dfrac{x^n}{n!}>\dfrac{e^x}{2}$$
Now I have prove $x=n$ case and my methods is very ugly,but $x\in(0,n]$,I can't prove it
Thank you
the following it's $x=n$ solution
show that
$$1+\dfrac{n}{1!}+\dfrac{n!}{2!}+\cdots+\dfrac{n^n}{n!}>\dfrac{e^n}{2},n\ge 0,n\in Z$$
use this
$$e^n=\sum_{k=0}^{n}\dfrac{n^k}{k!}+\dfrac{1}{n!}\int_{0}^{n}(n-t)^ne^tdt$$
then
$$\Longleftrightarrow n!>2e^{-n}\int_{0}^{n}(n-t)^ne^tdt$$
$$\Longleftrightarrow \int_{0}^{\infty}t^ne^{-t}dt>2e^{-n}\int_{0}^{n}(n-t)^ne^tdt$$
let $u=n-t$
$$\Longleftrightarrow \int_{0}^{\infty}t^ne^{-t}dt>2\int_{0}^{n}u^ne^{-u}du$$
$$\Longleftrightarrow \int_{n}^{\infty}u^ne^{-u}du>\int_{0}^{n}u^ne^{-u}du$$
let $f(u)=u^ne^{-u}$
$$\Longleftrightarrow f(n+h)\ge f(n-h),0\le h\le n$$
This is very easy.
A:
Here is a reduction to the case $x=n$.
Notice that by integration by parts we have
$$\int_x^\infty \frac{t^n}{n!} e^{-t} \, dt = e^{-x}\left(1 + x + \frac{x^2}{2!} + \dots + \frac{x^n}{n!}\right).$$
Thus it is enough to show that
$$\int_x^\infty \frac{t^n}{n!} e^{-t} \, dt > \frac{1}{2}.$$
But clearly $\int_x^\infty \frac{t^n}{n!} e^{-t} \, dt \ge \int_n^\infty \frac{t^n}{n!} e^{-t} \, dt$ when $0 < x \le n$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Drop trigger if exists in MySQL
I need to execute a command similar to the following not inside a procedure but inside a simple sql file for mysql 5.xx
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TRIGGERS WHERE TRIGGER_NAME = 'tr_fnninio_censopersona_ins') THEN
DROP TRIGGER tr_fnninio_censopersona_ins;
END IF;
A:
Why not just
DROP TRIGGER IF EXISTS tr_fnninio_censopersona_ins;
MySQL drop trigger doc
| {
"pile_set_name": "StackExchange"
} |
Q:
Array of Char in C
I'm trying to create a function that get a string, taking char by char:
char * GetString (int dim) // dim is the size of the string
{
char c, *S;
int i = 0;
S = (char*)malloc(dim*(sizeof(char));
while ((c=getchar() != '\n') && (i < dim) && (c != EOF))
{
S[i] = c;
i++;
}
S[i] = '/0';
return S;
}
The problem is when i try to use a "printf" in this function, trying to see if the input was taken correctly, it shows me strange characters, not the ones i inserted. I don't know what i'm missing.
Thanks very much.
A:
This should be a backslash:
S[i] = '\0';
Make sure your compiler warnings are turned on and you're paying attention to them. '/0' is a non-standard multi-character integer literal.
Backslash zero '\0' is the C string NUL-terminator you're after.
Also, in the case where your input is larger than dim, you are overrunning your buffer, writing one byte more than you allocated. I would suggest allocating dim+1 bytes.
Finally, there's no point in multiplying by sizeof(char) - it is 1 by definition.
P.S. Now is an excellent time to learn how to use a debugger. If you're using GNU tools: gcc -Wall -Werror main.c then gdb a.out, and type r to run.
A:
This '/0' is a character constant which value is implementation defined. So you have to replace it with escape character '\0'.
Also you have to allocate dim + 1 bytes if you want to append exactly dim characters with the terminating zero.
The function can look like
char * GetString( int dim )
{
char *s;
int i;
s = ( char* )malloc( ( dim + 1 ) *( sizeof( char ) );
i = 0;
while ( i < dim && ( ( c = getchar() ) != '\n') && ( c != EOF ) )
{
s[i++] = c;
}
s[i] = '\0';
return s;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Where I can find high-res public domain images of Countries or Continents on the web
I found this one of Africa:
That one is nice because it's > 3000x3000px which is large enough. I have looked around a bit for ones of these countries but haven't found anything that is large/high quality, free/public domain, and free of clouds/weather like the Africa image:
United States
Russia
China
India
Mexico/Central America
South America
Canada
Greenland/Iceland/Arctic
Europe
Australia
Southeast Asia
Japan
I would like to find these broad areas as images on a high quality satellite image similar to this Africa one.
A:
You can find satellite images free of clouds at chinesse version of google maps.
Under the rigth toolbar, top icon, you need to uncheck the first layer with the geographical names and click on the satellite image button, and you can place the view to see maps as this one of Southamerica.
| {
"pile_set_name": "StackExchange"
} |
Q:
"Move will not work across volumes" - Why? And how to overcome?
Why is it that File.Move(sourceFileName, destFileName) works fine when the source file and destination files are in different partitions, but Directory.Move(sourceDirName, destDirName) don't? It throws
System.IO.IOException: "Source and destination path must have
identical roots. Move will not work across volumes."
I even tried to create a DirectoryInfo instance and use the MoveTo(destDirName) method but without success.
Am I missing something? Do I really have to implement a "move" functionality myself? (the directory I want to move is very large btw).
A:
You should Use Copy Function followed by a remove. As Move only works in the same drive.
Directory.Move has a condition that states that :
IO Exception will be thrown if an attempt was made to move a directory to a different volume.
A:
Another option is, to add a reference to the Microsoft.VisualBasic namespace and use the MoveDirectory method, which can move across volumes.
Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(sourceDirName, destDirName);
A:
You can also p/invoke SHFileOperation which is the same function Windows Explorer uses to move directories around. It will either perform a true move or recursive-copy-then-delete, as appropriate.
It can also show the same progress UI as explorer, just by setting a flag.
| {
"pile_set_name": "StackExchange"
} |
Q:
add polylines from web service to R leaflet map
I am trying to add polylines from a web service to an R leaflet map. I tried using addWMSTiles. I didn't get an error, but also the lines didn't show up.
Info on the web service source is here: https://mapcase.deq.idaho.gov/arcgis/rest/services/ID305B_2016_WMS/MapServer/14
library(dplyr)
library(leaflet)
leaflet() %>%
setView(lat = 46.2271, lng = -116.00293, zoom = 7) %>%
addProviderTiles("Esri.WorldTopoMap") %>%
addWMSTiles("https://mapcase.deq.idaho.gov/arcgis/rest/services/ID305B_2016_WMS/MapServer/14", layers = "2016 305(b) Lakes (Final) (ID:14)", options = WMSTileOptions(format = "image/png", transparent = TRUE))
A:
Figured it out. R package leaflet.esri provides tools for mapping ESRI web services data with leaflet. A minimal example:
library(dplyr)
library(leaflet)
library(leaflet.esri)
leaflet() %>%
setView(lat = 46.2271, lng = -116.00293, zoom = 7) %>%
addProviderTiles("Esri.WorldTopoMap") %>%
addEsriFeatureLayer(url = paste0("https://mapcase.deq.idaho.gov/arcgis/rest/services/ID305B_2016_WMS/MapServer/14"),
useServiceSymbology = TRUE, weight = 1, fill = FALSE,
labelProperty = "ENTITY_ID", labelOptions = labelOptions(textsize = "12px"), options = featureLayerOptions(useCors = FALSE))
| {
"pile_set_name": "StackExchange"
} |
Q:
Does python have an equivalent to C#'s Enumerable.Aggregate?
In C#, if I have a collection of strings, and I want to get a comma-separated string representing of the collection (without extraneous comments at the beginning or end), I can do this:
string result = collection.Aggregate((s1, s2) => String.Format("{0}, {1}", s1, s2));
I could do something like
result = collection[0]
for string in collection[1:]:
result = "{0}, {1}".format(result, string)
But this feels like a cludge. Does python have an elegant way to accomplish the same thing?
A:
Use str.join:
result = ', '.join(iterable)
If not all the items in the collection are strings, you can use map or a generator expression:
result = ', '.join(str(item) for item in iterable)
A:
The Equivalent of the C# Enumerable.Aggregate method is pythons built in "reduce" method.
For example,
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
Calculates ((((1+2)+3)+4)+5). which is 15
This means you could achieve the same with
result = reduce(lambda s1, s2: "{0}, {1}".format(s1, s2), collection)
Or with
result = reduce(lambda s1, s2: s1 + ", " + s2, collection)
In your Case it would be better to use ', '.join as others have suggested because of pythons immutable strings.
For completeness the C# Enumerable.Select method in python is "map".
Now if anyone asks you can say you know MapReduce :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Integral from zero to infinity of $\int_0^{\infty}\frac{(1-e^{-\lambda z})}{\lambda^{a+1}} d \lambda$
I know that the value of the integral is as follows
$$\int_0^{\infty}\frac{(1-e^{-\lambda z})}{\lambda^{a+1}} d \lambda =z^a \frac{\Gamma(1-a)}{a}$$
However, how exactly the integral is calculated? How one proves that the integral even exists? Why does the integral only exist for $0<a<1$?
A:
Existence: at $\lambda=\infty$, $a>0$ guarantees that the integrand is below $1/\lambda{1+a}$ which is integrable. At $\lambda=0$,
$$
\int_0^\delta\frac{(1-e^{-\lambda z})}{\lambda^{a+1}}\,d\lambda=\int_0^\delta\frac{\lambda z+O(\lambda^2)}{\lambda^{a+1}}\,d\lambda=\int_0^\delta\frac{z}{\lambda^a}+O(\lambda^{1-a})\,d\lambda.
$$
The first term requirest $a<1$ for convergence, and the second one $a<2$. So $0<a<1$ are precisely the values of $a$ for which your integral exists.
Regarding the calculation, I wouldn't know how to find the formula, but here is a way to justify it. It suffices to use differentiation under the integral sign: we have
$$
\frac d{dz}\,\int_0^\infty\frac{(1-e^{-\lambda z})}{\lambda^{a+1}}\,d\lambda=\int_0^\infty\frac{\lambda\,e^{-\lambda z}}{\lambda^{a+1}}\,d\lambda=\int_0^\infty\lambda^{-a}\,e^{-\lambda z}\,d\lambda=\int_0^\infty z^{a-1}\,t^{-a}\,e^{-t}\,dt=z^{a-1}\Gamma(1-a)=\frac d{dz}\,\left(\frac{z^a}a\,\Gamma(1-a)\right).
$$
So the two sides of your equality differ by a constant $c$. When $z=0$ both sides equal to $0$, so $c=0$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Truth is singular. Its "versions" are mistruths
In the beginning of the legendary movie called Cloud Atlas... Somni 541 is sitting in a room, and an "Archivist" comes in. The conversation starts...
Archivist:
On behalf of my Ministry and the future of Unanimity, I want to thank you for the final interview. Remember, this isn't an interrogation or trial. Your version of the truth is all that matters.
Sonmi 541:
Truth is singular. Its "versions" are mistruths.
I am stuck on her statement of what she actually means... is it that each version of the truth is actually the truth, is hers the truth? Or is someone elses the truth?
A few friends and I have tried to analyze what she is meaning, but we are clueless.
A:
Here's one way of analyzing it. Consider the predicate 'Thinks(α, φ)', which is true just in case agent α thinks that φ is true. Let A be the Archivist, and A Sonmi 541. Let's begin by looking at what A says:
Ω = { φ : Thinks(S, φ) }.
Ω stands for the set of "things that matter", which according to A is the set of all those propositions φ (about events and so on) that S thinks to be true. We can assume that there is another set Σ s.t.:
Σ = { φ : True(φ) }.
This is the set of those propositions φ that are actually true. Depending on which set-theoretic relations hold between Ω and Σ (e.g. Ω ⊂ Σ, Ω ∩ Σ = ∅, etc.), Sonmi's version of the truth may or may not coincide with the actual truth. Now let's look at the things S says:
(1) Truth is singular.
(2) 'Versions' of the truth are mistruths.
I take it that (1) means that:
(1) ∀φ, α, β( [φ &in Ωα ≡ φ &in Ωβ] → Ωα = Ωβ).
This says that given any two agents α and β, if a proposition φ is among the truths recognized by α (Ωα) if and only if φ is among the truths recognized by β (Ωβ), then the truths recognized by α are β are the same. So for any two different 'versions' of the truth, there must be a φ that belongs to one but not to the other. If one of these guys is right, then both are and their Ωs coincide with Σ (the set of all truths).
From that reasoning, (2) doesn't follow; what follows is this:
(*) ∀α, β ( ¬[Ωα = Ωβ] → ∃φ[φ &in Ωα ∧ ¬(φ &in Ωβ)] ).
Which says that if two agents have different 'versions' of the truth, then there is some proposition that one thinks to be true while the other thinks to be false. But (2) says that in that case both Ωs are 'mistruth's, i.e., neither Ωα nor Ωβ is a subset of Σ:
(2) ∀α, β ( ¬[Ωα = Ωβ] → ¬[Ωα &subset Σ ∨ Ωβ &subset Σ] ).
This, of course, doesn't follow from previous reasoning, because it's possible that one of the Ωs coincides with Σ. All we can conclude is that at most one can, because of the disagreement, because of the fact that they are genuinely different 'versions' of what happened.
As I said, 'versions' in that context seems to me to contain assumptions that we might want to reject, so that, for example, we'll be able to say that two 'versions' of what happened yesterday may both be true.
| {
"pile_set_name": "StackExchange"
} |
Q:
Failure [INSTALL_FAILED_MISSING_SHARED_LIBRARY] on Glass XE16 KitKat
I have a Glass GDK app (open-source on Github) that works fine on XE12.
I got the XE16 update yesterday, and now when I run gradlew installDebug to deploy to Glass, I get the message:
:onebusaway-android:installDebug
pkg: /data/local/tmp/onebusaway-android-debug-unaligned.apk
Failure [INSTALL_FAILED_MISSING_SHARED_LIBRARY]
Here are the changes I've made to update to XE16:
I've changed my compileSdkVersion to "Google Inc.:Glass Development Kit Preview:19"
I've updated the gdk.jar in the /libs folder to the file from <android-sdk>/add-ons/addon-google_gdk-google-19/libs
Added <uses-permission android:name="com.google.android.glass.permission.DEVELOPMENT"/> to manifest for pre-production voice commands
(I actually made these changes prior to receiving the XE16 update myself, based on reports of it failing on XE16 from others - so I can confirm that with the above changes the app still works fine on XE12).
I'm using this third-party progress bar library, but from what I can tell from the release notes nothing has changed with the GestureDetector or Gesture Glass classes, which are the only Glass-specific classes it relies on.
My Glassware is an immersive Activity, so I'm not relying on TimelineManager or Cards (which changed in XE16).
EDIT
I've tried removing the third-party progress bar, but that doesn't seem to have any affect - still the same error.
I've also updated to Android Studio 0.5.5, no luck deploying from there either (as opposed to running gradlew installDebug from command-line). Also tried removing /libs/gdk.jar since this isn't required in Android Studio 0.5.5, still no change.
A:
If you have any <uses-library> elements that aren't supported by Glass in your AndroidManifest.xml, you must include the android:required="false" attribute, or remove the element completely, for your app to install on XE16. This is a change in behavior from XE12.
According to the Android docs:
If <uses-library> element is present and its android:required attribute is set to true, the PackageManager framework won't let the user install the application unless the library is present on the user's device...The default android:required value is "true".
I borrowed code from a normal Android app for my Glass app, and I had a leftover element buried in the manifest:
<uses-library android:name="com.google.android.maps"/>
Since I didn't include the android:required="false", XE 16 is correctly preventing the app from installing.
Apparently XE12 didn't enforce this, and installed the app anyway.
After either adding the android:required="false"attribute:
<uses-library android:name="com.google.android.maps"
android:required="false"/>
...or removing this <uses-library> element completely, the app now installs correctly on XE16.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to avoid file duplication in Visual Studio project when dealing with path issue?
Our vendor-created platform is asp.net based and I am developing customizations in the form of web user controls (ascx) that the product will host.
I have the web portion of this web product on my dev pc and it looks something like this generic representation:
C:\Inetpub\wwwroot\VendorApp\WebParts\ServiceModule [ascx files here]
C:\Inetpub\wwwroot\VendorApp\WebParts\ServiceModule\Scripts [js files here]
C:\Inetpub\wwwroot\VendorApp\WebParts\ServiceModule\StyleSheets[css files here]
I decided to create my VS 2010 project like this:
C:\Inetpub\wwwroot\VendorApp\WebParts\CustomControls.sln
C:\Inetpub\wwwroot\VendorApp\WebParts\ServiceModule\CustomControls.csproj
C:\Inetpub\wwwroot\VendorApp\WebParts\ServiceModule\ [custom ascx and code behind]
I created it as a web application so that VS plays nice with ascx designer/intellisense although I deleted web.config etc since I actually test and debug through the vendor's site in IIS
This works reasonably well however I must reference js and css relative to this path:
<script type="text/javascript" src="WebParts/ServiceModule/Scripts/jquery-1.6.2.min.js"></script>
The problem is that VS complains that the path is invalid and refuses to allow jquery intellisense.
My current fix is to create sub folders below the project to mimic the path the VS is seeing. Jquery intellisense works and VS stops complaining. The downside is file duplication:
C:\Inetpub\wwwroot\VendorApp\WebParts\ServiceModule\WebParts\ServiceModule\Scripts\ [copy of any js I use]
C:\Inetpub\wwwroot\VendorApp\WebParts\ServiceModule\WebParts\ServiceModule\StyleSheets\ [copy of any css I use]
Is there a better way to solve this problem? It isn't a huge deal since only one copy of the scripts/css will actually deploy to production but this is still seems untidy from project/TFS point of view.
I've looked into the jquery vsdoc files but I don't think I need them since intellisense works perfectly as long as VS thinks the path is correct. I also considered sym links but I am on XP at least until later this year.
A:
I didn't find a way to avoid the duplication, but I realized that I can make it a bit more tolerable by adding a post build event to robocopy to the other location.
| {
"pile_set_name": "StackExchange"
} |
Q:
Algebraic integers of a cubic extension
Apparently this should be a straightforward / standard homework problem, but I'm having trouble figuring it out.
Let $D$ be a square-free integer not divisible by $3$. Let $\theta = \sqrt[3]{D}$, $K = \mathbb{Q}(\theta)$. Let $\mathcal{O}_K$ be the ring of algebraic integers inside $K$. I need to find explicitly elements generating $\mathcal{O}_K$ as a $\mathbb{Z}$-module.
It is reasonably clear that $\theta$ is itself an algebraic integer and that $\mathbb{Z}[\theta] \le \mathcal{O}_K$, but I strongly suspect it isn't the whole ring. I'm not sure where the hypotheses on $D$ come in at all... any hints would be much appreciated.
A:
A very belated answer: This is (part) of the content of Exercise 1.41 of Marcus' Number Fields (a great source of exercises in basic number theory). In it, one proves that, for $K = \mathbf{Q}(m^{1/3})$, $m$ squarefree, an integral basis is given by
$\begin{cases} 1, m^{1/3}, m^{2/3},& m \not \equiv \pm 1 \pmod 9 \\
1, m^{1/3}, \frac{m^{2/3} \pm m^{1/3} + 1}{3},& m \equiv \pm 1 \pmod 9
\end{cases}$
This is leveraged out of his Theorem 13 (among other things).
A:
I thought this was a fun problem. Let $z = a + b \theta + c \theta^2$ be an algebraic integer, $a, b, c \in \mathbb{Q}$. Then the coefficients of the characteristic polynomial of $z$ must be integers. This tells you, for example, that $\text{tr}(z) = 3a$ is an integer. The other two coefficients are slightly harder to work with, but here's a start: since $\theta z$ and $\theta^2 z$ are algebraic integers, their traces are also integers, so...? And then you work with the other coefficients of the minimal polynomial.
The hypotheses on $D$ come from some divisibility arguments you will need to make later; without them the problem is harder. Note that the discriminant of $\mathbb{Z}[\theta]$ has absolute value $27D^2$, which means that the index of $\mathbb{Z}[\theta]$ in $\mathcal{O}_K$ divides $3D$. (Actually it will turn out to divide $3$.)
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP - String pattern matching
I need to know if there is any way I can do the following using regular expressions (or otherwise) in PHP
aaBaa BBB -> aa Baa BBB
ie, I want to introduce a space before a capital letter only if a Capital letter occurs before and after a small letter.
The best I could come up with was something like this
$string = preg_replace('/(\w+)([A-Z])/U', '\\1 \\2', $string);
but that would only give me something like
aaBaa BBB -> aa Baa B B B
Thanks in advance.
A:
Here: http://rubular.com/r/3xqbuWuiLD
([a-z]+)([A-Z]+)
| {
"pile_set_name": "StackExchange"
} |
Q:
Undefined reference in Code::Blocks with SFML 2,4
I am currently trying to build a small game using C++ along with SFML following instructions from this page: http://www.gamefromscratch.com/page/Game-From-Scratch-CPP-Edition-The-Introduction.aspx.
I keep running into the following errors:
||=== Build: Debug in Pong (compiler: GNU GCC Compiler) ===|
G:\Ashwin\WIP\Pong\Game.cpp|34|warning: enumeration value 'Uninitialized' not handled in switch [-Wswitch]|
G:\Ashwin\WIP\Pong\Game.cpp|34|warning: enumeration value 'ShowingSplash' not handled in switch [-Wswitch]|
G:\Ashwin\WIP\Pong\Game.cpp|34|warning: enumeration value 'Paused' not handled in switch [-Wswitch]|
G:\Ashwin\WIP\Pong\Game.cpp|34|warning: enumeration value 'ShowingMenu' not handled in switch [-Wswitch]|
G:\Ashwin\WIP\Pong\Game.cpp|34|warning: enumeration value 'Exiting' not handled in switch [-Wswitch]|
obj\Debug\Game.o||In function `ZN4Game5startEv':|
G:\Ashwin\WIP\Pong\Game.cpp|6|undefined reference to `Game::gameState'|
G:\Ashwin\WIP\Pong\Game.cpp|9|undefined reference to `Game::mainWindow'|
G:\Ashwin\WIP\Pong\Game.cpp|10|undefined reference to `Game::gameState'|
G:\Ashwin\WIP\Pong\Game.cpp|17|undefined reference to `Game::mainWindow'|
obj\Debug\Game.o||In function `ZN4Game9isExitingEv':|
G:\Ashwin\WIP\Pong\Game.cpp|22|undefined reference to `Game::gameState'|
obj\Debug\Game.o||In function `ZN4Game8gameLoopEv':|
G:\Ashwin\WIP\Pong\Game.cpp|34|undefined reference to `Game::gameState'|
G:\Ashwin\WIP\Pong\Game.cpp|38|undefined reference to `Game::mainWindow'|
G:\Ashwin\WIP\Pong\Game.cpp|39|undefined reference to `Game::mainWindow'|
G:\Ashwin\WIP\Pong\Game.cpp|43|undefined reference to `Game::gameState'|
G:\Ashwin\WIP\Pong\Game.cpp|31|undefined reference to `Game::mainWindow'|
||error: ld returned 1 exit status|
||=== Build failed: 11 error(s), 5 warning(s) (0 minute(s), 1 second(s)) ===|
Here is a list of all the source files:
Pong.cpp
#include <iostream>
#include "Game.h"
int main(int argc, char** argv)
{
Game::start();
return 0;
}
Game.cpp
#include <iostream>
#include "Game.h"
void Game::start(void)
{
if(gameState != Uninitialized)
return;
mainWindow.create(sf::VideoMode(1024,768,32),"Pang!");
gameState = Game::Playing;
while(!isExiting())
{
gameLoop();
}
mainWindow.close();
}
bool Game::isExiting()
{
if(gameState == Game::Exiting)
return true;
else
return false;
}
void Game::gameLoop()
{
sf::Event currentEvent;
while(mainWindow.pollEvent(currentEvent))
{
switch(gameState)
{
case Game::Playing:
{
mainWindow.clear(sf::Color(255,0,0));
mainWindow.display();
if(currentEvent.type == sf::Event::Closed)
{
gameState = Game::Exiting;
}
break;
}
}
}
}
Game.h
#ifndef GAME_H_INCLUDED
#define GAME_H_INCLUDED
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
class Game
{
public:
static void start();
private:
static bool isExiting();
static void gameLoop();
enum GameState {Uninitialized,ShowingSplash,Paused,ShowingMenu,Playing,Exiting};
static GameState gameState;
static sf::RenderWindow mainWindow;
};
#endif // GAME_H_INCLUDED
How could I correct these errors?
A:
Let me put this answer from the comments here. As @DeiDei already pointed out that the gameState and mainWindow are missing.
Actually they are mentioned on the Part 2 page of the tutorial, right at the bottom of the game.cpp section:
Game::GameState Game::_gameState = Uninitialized;
sf::RenderWindow Game::_mainWindow;
I had to remove the underscores in order to get this to work.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to compress a Video file(.wmv,.avi,.flv) without affecting its video quality
I am doing a process in which i compress files of all types,for compression/decompression i used GZipStream class ,i easily compress all types of files but when it comes to a video file the compressed filesize is more than the original filesize
so the purpose of compressing gets spoiled.how to compress a video file without losing the
quality of the video successfully.
ok i accept this.but what about the winrar
A:
Most of the formats are already compressed. Just by converting from format to format you most likely will kill the quality without gaining much in limiting the size
| {
"pile_set_name": "StackExchange"
} |
Q:
nested query not running, always returns null.
I have am working on a mobile app, when a user logs in against a php/mysql webserver the users details are stored in the local sqlite db via json.
This works fine. Next, I am trying to have a second sqlite table update from another table in the mysql DB.
The returned json is always null for the second query. (the query is fine if run alone)
Can I run two queries like this ?? Any ideas ?
Thanks.
<?php
include 'DB_Connect.php';
// get tag
if (isset($_POST['email']) && $_POST['email'] != '') {
$tag = 'login';
//json response array
$response = array();
// check for tag type
if ($tag == 'login') {
$email = $_POST['email'];
$password = $_POST['password'];
//check user exists
$qry = "SELECT uid, name, email, registration_date, updated_at FROM users WHERE email = ? AND password = ? ";
$stmt = $mysqli->prepare($qry);
$stmt->bind_param('ss', $email, $password);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($uid, $name, $email, $registration_date, $updated_at); // get variables from result.
$stmt->fetch();
if ($stmt->num_rows == 1){
// if user exists, set json values
$response["success"] = 1;
$response["uid"] = $uid;
$response["user"]["name"] = $name;
$response["user"]["email"] = $email;
$response["user"]["registration_date"] = $registration_date;
$response["user"]["updated_at"] = $updated_at;
echo json_encode($response);
$stmt->close();
if ($response["success"] = 1 ){
$qry = "SELECT device_name, device_registration_date FROM devices WHERE parent_id =?";
$stmt = $mysqli->prepare($qry);
$stmt->bind_param('s',$uid);
$stmt->store_result();
$stmt->bind_result($device_name, $device_registration_date); // get variables from result.
$stmt->fetch();
$response2["device"]["device_name"] = $device_name;
$response2["device"]["device_registration_date"] = $device_registration_date;
echo json_encode($response2);
}
else if ($tag = 'register' ... blah blah blah .....
A:
Query both tables at once with a JOIN:
SELECT u.uid, u.name, u.email, u.registration_date, u.updated_at,
d.device_name, d.device_registration_date
FROM users u
LEFT JOIN devices d ON d.parent_id = u.uid
WHERE u.email = ? and u.password = ?
| {
"pile_set_name": "StackExchange"
} |
Q:
Laravel - Delete data record from Database
I want to delete record Photo and Photo_list from Database but give me error
This is my Code in Controller
public function deletephoto($id)
{
$product = $this->productRepository->findWithoutFail($id);
Product::select('photo','photo_list')->delete($product->id);
return redirect(route('stores.index'));
}
A:
You can try this :
public function deletephoto($id)
{
$product = $this->productRepository->findWithoutFail($id);
if($product){
$product->photo= null;
$product->photo_list= null;
$product->save();
}
return redirect(route('stores.index'));
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Call a function later
I'm parsing user input and doing, as an example, the following in response:
User Input 1:
Array<int> a;
Populate()(a);
int v = 10;
a.append(v);
User Input 2:
Array<bool> a;
Populate()(a);
int v = true;
a.remove(v);
User Input 3:
Array<bool> a;
Populate()(a);
a.removeAll();
Now lets say I wish to execute the functions at a later stage, such that the parse creates the Array object, establishes the command to execute for this Array(removeAll etc.) as well as the arguments, but doesn't actually call the command - this calling occurs at a later stage.
Is there a std or boost library which might help me to do achieve such a behaviour?
A:
In C++11 you can remember the action in std::function:
std::function<void()> action;
Array<int> a;
Populate()(a);
int v = 10;
action = [&a,v] () { a.append(v); };
Note, that when you call the action, it will work on the exact Array you gave it (it is captured by reference), so make sure the object still exists!
A:
In C++11 you can use std::function and std::bind to store function objects that you can call later. In C++03 you can use boost::function and boost::bind.
| {
"pile_set_name": "StackExchange"
} |
Q:
Check if matrix elements are continuous
I've been trying to solve this for days and I haven't been able to solve it.
I need to check if elements in a matrix are continuous or not. For example:
1 0 1 0 0 0
0 1 0 0 1 0
0 0 1 1 0 0
In this case, the 1 are connected because they are continuous.
Check this example:
1 0 0 0 1
0 1 0 0 1
1 0 0 0 1
0 0 1 0 0
In this case, the 1 are not continuous because they are not connected.
As you can see, the matrix size varies.
A:
A bit of recursion will do the trick.
Here is a description of the algorithm:
find a 1
mark it as 0
move to all adjacent cells
in all of the adjacent cells that are a 1, repeat from point 2.
when there is nowhere to go, find a 1 again - if found then matrix is not connected
To clarify last point - if there are any 1s remaining in the matrix, that means that our algorithm didn't reach it. And since it's moving only to adjacent cells, we conclude that the remaining 1 was not connected to initial 1 from step 1.
Here is the code:
def find_a_1():
for row_i, row in enumerate(matrix):
if '1' in row:
return {
'row': row_i,
'col': row.index('1'),
}
def walk_the_matrix(point):
""" Clear current point and move to adjacent cells that are "1s" """
# check if this is a valid cell to work on:
try:
if point['row'] < 0 or point['col'] < 0:
raise IndexError # prevent negative indexes
if matrix[point['row']][point['col']] == '0':
return # nothing to do here, terminate this recursion branch
except IndexError:
return # we're outside of the matrix, terminate this recursion branch
# clear this cell:
matrix[point['row']][point['col']] = '0'
# recurse to all 8 directions:
for i in (-1, 0, 1):
for j in (-1, 0, 1):
if (i, j) == (0, 0):
continue
walk_the_matrix({
'row': point['row'] + i,
'col': point['col'] + j,
});
Example:
matrix = [
list('001001'),
list('010000'),
list('001110'),
list('110000'),
]
starting_point = find_a_1()
walk_the_matrix(starting_point)
if find_1() is None:
print("The matrix is connected")
else:
print("The matrix is not connected")
Note that this mutates the matrix list.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use yield and Iron-router?
So I am trying to do a basic meteor app at the moment.. here are the three files.
router.js:
Router.configure({
layoutTemplate : 'layout',
loadingTemplate : 'loading',
notFoundTemplate : 'notFound'
});
Router.route("/", {
name : "homeIndex",
data : function() {
return {
message : "Welcome to the Rocket Shop"
}
}
});
index.html:
<template name="homeIndex">
<h1>{{message}}</h1>
</template>
layout.html:
<template name="layout">
{{> nav}}
<div class="container">
{{>yield}}
</div><!-- /.container -->
</template>
When I go to localhost:3000 after starting the app I get a long stacktrace in my browser console and the body of the page does not load up.
22:35:57.444 Exception in callback of async function: MiddlewareStack.prototype.concat@http://localhost:3000/packages/iron_middleware-stack.js?ff70621b6c5f6a406edc60600c4b76126dae21d6:303:7
RouteController.prototype._runRoute@http://localhost:3000/packages/iron_router.js?dd5fa02859b6335661b94134bd9903be8eecf44d:542:11
Route.prototype.dispatch@http://localhost:3000/packages/iron_router.js?dd5fa02859b6335661b94134bd9903be8eecf44d:856:10
Route/route@http://localhost:3000/packages/iron_router.js?dd5fa02859b6335661b94134bd9903be8eecf44d:713:5
boundNext@http://localhost:3000/packages/iron_middleware-stack.js?ff70621b6c5f6a406edc60600c4b76126dae21d6:425:16
Meteor.bindEnvironment/<@http://localhost:3000/packages/meteor.js?5deab0885176b44ccbbbf0b5101b065971c8f283:999:17
dispatch@http://localhost:3000/packages/iron_middleware-stack.js?ff70621b6c5f6a406edc60600c4b76126dae21d6:449:3
RouteController.prototype.dispatch/</<@http://localhost:3000/packages/iron_router.js?dd5fa02859b6335661b94134bd9903be8eecf44d:393:7
Tracker.Computation.prototype._compute@http://localhost:3000/packages/tracker.js?9309a5697855cef52b32921fbc9dcb1017c58b39:349:5
Tracker.Computation@http://localhost:3000/packages/tracker.js?9309a5697855cef52b32921fbc9dcb1017c58b39:237:5
Tracker.autorun@http://localhost:3000/packages/tracker.js?9309a5697855cef52b32921fbc9dcb1017c58b39:588:11
RouteController.prototype.dispatch/<@http://localhost:3000/packages/iron_router.js?dd5fa02859b6335661b94134bd9903be8eecf44d:391:5
Tracker.nonreactive@http://localhost:3000/packages/tracker.js?9309a5697855cef52b32921fbc9dcb1017c58b39:615:12
RouteController.prototype.dispatch@http://localhost:3000/packages/iron_router.js?dd5fa02859b6335661b94134bd9903be8eecf44d:390:3
Router.prototype.dispatch@http://localhost:3000/packages/iron_router.js?dd5fa02859b6335661b94134bd9903be8eecf44d:1700:3
onLocationChange@http://localhost:3000/packages/iron_router.js?dd5fa02859b6335661b94134bd9903be8eecf44d:1784:20
Tracker.Computation.prototype._compute@http://localhost:3000/packages/tracker.js?9309a5697855cef52b32921fbc9dcb1017c58b39:349:5
Tracker.Computation@http://localhost:3000/packages/tracker.js?9309a5697855cef52b32921fbc9dcb1017c58b39:237:5
Tracker.autorun@http://localhost:3000/packages/tracker.js?9309a5697855cef52b32921fbc9dcb1017c58b39:588:11
Router.prototype.start@http://localhost:3000/packages/iron_router.js?dd5fa02859b6335661b94134bd9903be8eecf44d:1777:31
Router/</<@http://localhost:3000/packages/iron_router.js?dd5fa02859b6335661b94134bd9903be8eecf44d:980:9
.withValue@http://localhost:3000/packages/meteor.js?5deab0885176b44ccbbbf0b5101b065971c8f283:971:17
withoutInvocation/<@http://localhost:3000/packages/meteor.js?5deab0885176b44ccbbbf0b5101b065971c8f283:428:26
Meteor.bindEnvironment/<@http://localhost:3000/packages/meteor.js?5deab0885176b44ccbbbf0b5101b065971c8f283:999:17
onGlobalMessage@http://localhost:3000/packages/meteor.js?5deab0885176b44ccbbbf0b5101b065971c8f283:365:11
1 meteor.js:880:11
Does anyone possibly know what I am doing wrong? I am just following a pluralsight tutorial and have followed all of the directions.
A:
I figured out the answer to my own question after searching around stackoverflow at other iron-router questions.. I have no idea why it worked, but it solved the issue. All I had to do was run:
meteor add ejson
and I no longer got my error.
Here is the question that answered my question (which was posted AFTER my question):
Iron:router 1.0.9 Not working
| {
"pile_set_name": "StackExchange"
} |
Q:
Need to get rid of lang version in url
Have a project on Contao CMS 3.3.6.
Main page adress has url: sitename.com/en/
Even try sitename.com, whatever redirecting to sitename.com/en/
I have tried fix it by using htaccess but it is not works: too many redirects.
Also I didn`t find redirects type of
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://sitename.com/xx");
How can fix it? Or where I need to see?
A:
You don't need .htaccess to do that. Go to the backend settings. Uncheck 'add language to url' in the front end configuration fieldset. That should do it. First reverse what you have done with the htaccess file
| {
"pile_set_name": "StackExchange"
} |
Q:
Installing spatialite-gui using ubuntugis
I am unable to install spatialite-gui using the ubuntugis unstable ppa. There appears to be a conflict between the GEOs libraries required by QGIS, which I installed first successfully (GEOS 3.5.0 automatically installed as a dependency), and the GEOS libraries required by spatialite-gui. Here is the error I receive when trying to install spatialite-gui:
The following packages have unmet dependencies:
spatialite-gui : Depends: libgeos-c1 (>= 3.4.2) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
When I try to install libgeos-c1, I see that this install would remove my QGIS install. Is is possible to have both QGIS and spatialite-gui installed from ubuntugis ppa, either w/ GEOS 3.5 or another version?
Edit:
Ubuntu 14.04.4
QGIS 2.16.0
A:
The maintainer of ubuntugis has been rebuilding all packages related to gdal and the new geos libraries. Spatialite_gui should be available soon. Here's his message:
Thanks for reporting this issue, I've rebuilt spatialite-gui for the
geos transition in ubuntugis-unstable and uploaded the new revision
(1.7.1-5~trusty3) to my staging PPA.
I've copied the packages to the ubuntugis-unstable PPA after the
builds were confirmed successful in my staging PPA.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to post data with jQuery and process it with Spring controller
I am getting for values from Form on button click and I want to post these values to controller to store into database.
function PostData() {
var form = $('#myFormID')[0];
var data = {};
var dataString = "";
for(var i=1; i<form.elements.length-1; i++) {
var element = form.elements[i];
alert(element.value);
data[element.name] = element.value; //assuming the name is set on each element
dataString = (i>0 ? ";" : "") + element.value;
}
//var contextPath = "<c:url value="/checkEmailInDB"/>"; //How to send on this url
$.post("saveContact", data); //OR
}
I am not getting how can I get these value in store into database.
Without using jquery I was sending object and getting values from object like this:
@RequestMapping(value = "/saveContact", method = RequestMethod.POST)
public ModelAndView saveContact(@ModelAttribute Contact contact) {
insertDAO.saveOrUpdate(contact); //FRom this contact object I was able store values into database
return new ModelAndView("redirect:/");
}
Can someone please tell me how can I receive post response from jquery and store into database?
A:
function PostData() {
var form = $('#myFormID')[0];
var data ;
var dataString = "";
for(var i=1; i<form.elements.length-1; i++) {
var element = form.elements[i];
alert(element.value);
//assuming the name is set on each element
var obj = {element.name : element.value};
data.push(obj);
}
//var contextPath = "<c:url value="/checkEmailInDB"/>"; //How to send on this url
$.post("saveContact", data); //OR
}
try above
| {
"pile_set_name": "StackExchange"
} |
Q:
How to recover a dog from maggots?
My pet is a Labrador breed and he is suffering from maggots. He is too aggressive and does not let any of my family members touch his wound. He has maggots in his right leg at his palm and it's increasing day by day. I have tried using the spray to cure it but he won't let me apply the spray on his wound. What can I do so that I can apply the medicines?
A:
He needs to go to a veterinarian to assess the damage, you will need a prescription antiparasitic as well as antibiotics and pain meds.
They will be able to handle an aggressive dog.
| {
"pile_set_name": "StackExchange"
} |
Q:
Scene transition image drawn in tiles during transition
I'm facing weird drawing issue with scene transitions (running with Nexus 5x 6.0.1 platform)
I found out that <item name="android:windowBackground">@null</item> has some relation to the issue.
Anyone know why this happens and what can be possible places to check in order to fix this?
Here is my test project setup to reproduce the problem:
minSdkVersion 16 and targetSdkVersion 23 using:
com.android.support:appcompat-v7:23.3.0
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".NextActivity"/>
</application>
styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowActionBar">false</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowBackground">@null</item>
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final View iv = findViewById(R.id.iv_test);
ViewCompat.setTransitionName(iv, "test");
findViewById(R.id.b_go).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(MainActivity.this,
android.support.v4.util.Pair.create(iv, "test")).toBundle();
startActivity(new Intent(MainActivity.this, NextActivity.class), bundle);
}
});
}
}
NextActivity.java
public class NextActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
final View iv = findViewById(R.id.iv_test);
ViewCompat.setTransitionName(iv, "test");
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.test.scenetransitions.MainActivity">
<ImageView
android:id="@+id/iv_test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/ic_dialog_email"
android:tint="@color/colorAccent"/>
<Button
android:id="@+id/b_go"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:background="@color/colorAccent"
android:padding="20dp"
android:text="GO"/>
</RelativeLayout>
activity_next.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.test.scenetransitions.MainActivity">
<ImageView
android:id="@+id/iv_test"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerInParent="true"
android:src="@android:drawable/ic_dialog_email"
android:tint="@color/colorAccent"/>
</RelativeLayout>
And here is screenshot took in proper time during the transition:
A:
The issue is with <item name="android:windowBackground">@null</item> you should never ever use null for window background. Replace it with <item name="android:windowBackground">@android:color/transparent</item>
When you set it to null Android doesn't know what to draw and it could draw any garbage from GPU. So you should explicitly specify transparent background.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the differences between class and instance declarations?
I am currently reading this, but if I am honest I am struggling to see what
class Eq a where
(==) :: a -> a -> Bool
achieves, which
instance Eq Integer where
x == y = x `integerEq` y
doesnt achieve. I understand the second code defines what the result of performing equality on two Integer types should be. What is the purpose of the first then??
A:
The class declaration says "I'm going to define a bunch of functions now which will work for several different types". The instance declaration says "this is how these functions work for this type".
In your specific example, class Eq says that "Eq means any type that has a function named ==", whereas the instance Eq Integer says "this is how == works for an Integer".
A:
The first defines what operations must be provided for a type to be comparable for equality. You can then use that to write functions that operate on any type that is comparable for equality, not just integers.
allSame :: Eq a => [a] -> Bool
allSame [] = []
allSame (x:xs) = foldr True (==x) xs
This function works for integers because instances for Eq Integer exists. It also works for strings ([Char]) because an instance for Eq Char exists, and an instance for lists of types that have instances of Eq also exists (instance Eq a => Eq [a]).
| {
"pile_set_name": "StackExchange"
} |
Q:
Xcode Workspace - Not finding imports from framework development pod
I've set up a workspace with two Swift projects in it: one a framework I'm developing, the other a demo app for the framework.
Podfile looks like this:
platform :ios, '9.0'
workspace 'foo.xcworkspace'
target 'framework' do
project 'framework.xcodeproj'
end
target :'demo' do
project 'demo/demo.xcodeproj'
pod 'framework', :path => 'framework.podspec'
end
the .podspec file looks like this:
Pod::Spec.new do |s|
s.name = 'framework'
s.authors = { "foo author" }
s.version = '0.1.0'
s.summary = 'foo summary.'
s.homepage = 'foo homepage'
s.platform = :ios, '9.0'
s.license = {
:type => "Proprietary",
:file => "LICENSE"
}
s.source = {
:git => 'https://url.to/foo.git',
:tag => s.version.to_s
}
s.source_files = 'framework/framework/**/*.{swift,h,m}'
s.requires_arc = true
s.weak_framework = "XCTest"
s.pod_target_xcconfig = {
'FRAMEWORK_SEARCH_PATHS' => '$(inherited) "$(PLATFORM_DIR)/Developer/Library/Frameworks"',
}
end
After running pod install, Xcode/AppCode can still not see the classes from the framework project. So if I add a manual import to a class in the demo app and try to compile, it fails with:
Error:(13, 21) use of undeclared type 'FooClass'
What do I have to do to properly have the demo app project see the classes from the framework project generated pod?
A:
I finally resolved this issue:
Make sure the min. required iOS is defined in Podfile, e.g.:
platform :ios, '10.0'
Add any third-party pods also to the podspec file, e.g.:
spec.dependency 'Alamofire', '~> 4.5'
spec.dependency 'Serpent', '~> 1.0'
If doing pod install without the use_frameworks! it will mess up some things (see this answer: ld: framework not found Pods). So in between I got these invalid Pod xconfigs that I had to delete and then do a clean and pod install.
Make sure to build the framework project at least once and then the demo source should find the import to the framework pod name!
Make sure that all classes are correctly added to their target, especially classes in the test target should not have been added to the app target accidentally.
After all is said and done, having worked with a multitude of IDEs and development technologies, Xcode and Cocoapods can only be summed up as one giant clusterf*** of an accident!
| {
"pile_set_name": "StackExchange"
} |
Q:
Active directory on mac server
Can an apple server run Active directory instead of open directory or Active directory is just an addon feature for the server?
A:
currently Snow Leopard Server cannot run active directory server, unless you run windows server in a VM on it.
you can however use the old PDC method however this wont work out of the box with windows 7 clients and it will provide some basic windows logon functionality, however the server has to be an open directory master or connected to one in some way
the server can only bind to an active directory network to integrate mac client management in an AD network and obtain authentication info from the AD servers it cant be the AD master
for more info try here or here
| {
"pile_set_name": "StackExchange"
} |
Q:
Should I always specify which IFormatProvider to use?
I tried running FxCop on a few assemblies of our product, and I get lots and lots of matches of the "Specify IFormatProvider" rule.
As it happens, some of those are legitimate, but it also matches code like this:
Logger.DebugFormat("Appending file {0}", fileName);
Which can be written as
Logger.DebugFormat(CultureInfo.InvariantCulture, "Appending file {0}", fileName);
The second variant is much harder to read.
So, is it actually recommended to always specifiy the IFormatProvider or is it "just" a limitation of the heuristic used in the rule?
A:
It only applies to methods with an IFormatProvider overload.
To deal with this problem, I have two static classes, InvariantText and CulturedText, that work with strings in the invariant culture and current culture, respectively. For example, I have a Format method in each class. This way, I can do culture-neutral and culture-aware formatting without having to specify an IFormatProvider each time.
Example:
InvariantText.Format("0x{0:X8}",value);
CulturedText.Format("Appending file {0}",file);
InvariantText.Format and CulturedText.Format are simply wrappers to the String.Format method, and accordingly likewise return strings.
You can even use this pattern to wrap other functions that require culture-neutral and culture-specific strings. For example, create two methods, InvariantLog and CulturedLog that wrap calls to Logger.DebugFormat in your question and take the appropriate IFormatProvider in each case.
| {
"pile_set_name": "StackExchange"
} |
Q:
Decimal Generate Random Number within a range including negatives?
I have the below function to generate a random number within a min, max range:
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
//..
int GenerateRandom(int min, int max) //range : [min, max)
{
static bool first = true;
if (first)
{
srand(time(NULL)); //seeding for the first time only!
first = false;
}
return min + rand() % (max - min); // returns a random int between the specified range
}
I want to include c++ create a random decimal between 0.1 and 10 functionality or/and create a random decimal number between two other numbers functionality into the above function without excluding negatives. So I want to get the decimal between "any" range: [negative, negative], [negative, positive] and [positive, positive]
A:
You just need to make sure that min, max are ordered correctly, and use floating point rather than integers, e.g.
double GenerateRandom(double min, double max)
{
static bool first = true;
if (first)
{
srand(time(NULL));
first = false;
}
if (min > max)
{
std::swap(min, max);
}
return min + (double)rand() * (max - min) / (double)RAND_MAX;
}
LIVE DEMO
| {
"pile_set_name": "StackExchange"
} |
Q:
What are the trade-offs of weight versus repetition?
When doing work out with weights, what is the impact of trade-off between
amount of weights working with
number of times an exercise is repeated
For example, I can repeat an exercise 10x3 times with 20kg weights but only 7X3 times with 25kg weights. What will be the difference of these two exercises on the body?
A:
Your goals and your current level of progress determine the number of sets and reps.
Possible Goals
Training for strength, power, endurance and hypertrophy all require a different number of sets and reps:
Strength (how much weight your muscle can move) is best developed by lifting as much weight as possible. This is probably best achieved with 5 or less reps. Strength is expressed in how much you can lift one time, so the closer you train to 1 rep at a time, the more specific you are training for strength.
Power (how much your muscle can move quickly) is best developed by moving heavy weights very fast. This is best achieved with very few reps, something like 2 or 3 in a set, but you have to use slightly less weight so that you can move it faster.
Endurance (how long your muscle can keep doing its job) is best developed by lifting a weight many times, which requires many, many more reps: at least 15. You'll have to use a lot less weight in order for this to be possible.
Hypertrophy (how big your muscles are) is best developed by achieving momentary muscular failure, and with overall training volume. Moderate weight works best for this purpose, since it is heavy enough to quickly make one unable to lift it, but not so heavy that failure to lift is dangerous. Most people use 6-12 reps for this purpose, but there may or may not be anything special about this range. Multiple sets and exercises are useful for achieving high total workout volume.
This is well explained by a chart in the article I linked to:
Three sets of 7 at 25kg will demand and develop more strength than three sets of 10 at 20kg would. The sets of 10 would promote greater hypertrophy and require more strength-endurance and conditioning. The difference is not going to be terribly significant, however, since 7 and 10 aren't too far apart.
Doing fewer reps with heavier weights requires and develops more strength and less conditioning than more reps with somewhat lighter weights. Doing more reps with slightly lighter weights may, in some circumstances, for some exercises, produce more hypertrophy (mass gain). Fewer heavier reps is better for strength; more reps (but still as heavy as possible) is better for size.
Though the original on page 60 of Rippetoe & Kilgore's Practical Programming is better (the gradations from range to range are less stark) this chart from reddit does an excellent job explaining the effects of different rep schemes:
Doing fewer repetitions with heavier weights builds strength most effectively. Doing more repetitions (circa 4 to 12), with weight that is still challenging, builds mass most efficiently. Doing more than 12 repetitions in a single set is generally best for endurance as opposed to strength. (See this answer for more information.) Does this mean that someone who is diligent with a 12-rep program can't get strong? Heck no! People get strong with 12-rep sets all the time. But if raw strength is their goal, they could probably achieve that goal faster with sets of, say, 3 or 6.
A novice generally does best with a focus on strength and some hypertrophy. Three sets of five or five sets of five are the two most common set/rep schemes. The weight must be heavy enough to make more than 5 sets very difficult.
Note that there is very little about these rep ranges in and of themselves that produces desired attributes. It is how these rep ranges relate to elements of training such as volume, intensity (that is, proximity to 1RM), and muscular exhaustion that determines the effects of training. Notice also that hypertrophy produces strength and power, and strength and endurance enable hypertrophy.
The following "map", from the Starting Strength site, explains the relationship of this volume-to-purpose relationship to sports. It refers to the three metabolic pathways: phosphagenic, glycolytic, and oxidative. The phosphagenic pathway is used when we do a very small number of reps in a set (3 or less, whereas higher-rep sets use the glycolytic pathway (approximately 4 to 12, though it depends on how vigorously one is working out). The oxidative pathway is for even higher rep ranges (e.g. 20), and is more commonly associated with longer duration, repetitive exercise like distance running or bicycling. It is explained in more detail in this article.
| {
"pile_set_name": "StackExchange"
} |
Q:
Right Join not returning all expected rows
I have two queries which I am running in HP ALM (formally Quality Center):
Query 1:
SELECT
TEST.TS_NAME
FROM CYCLE
JOIN TESTCYCL ON (TESTCYCL.TC_CYCLE_ID = CYCLE.CY_CYCLE_ID)
JOIN TEST ON TEST.TS_TEST_ID = TESTCYCL.TC_TEST_ID)
WHERE CYCLE.CY_CYCLE_ID = 44451
This returns 38 rows with all the test names I want to report on.
Query 2:
SELECT
STEP.ST_RUN_ID as "RunId" /*Test Step.Run No*/ ,
TEST.TS_NAME as "Test Name",
STEP.ST_STATUS as "Run Status",
STEP.ST_STEP_NAME as "Step Name",
CYCLE.CY_CYCLE as "TestSet",
CYCL_FOLD.CF_ITEM_NAME as "Test Lab Folder Name"
FROM RUN, CYCL_FOLD, CYCLE, STEP, TEST
WHERE RUN.RN_CYCLE_ID = CYCLE.CY_CYCLE_ID
AND CYCLE.CY_FOLDER_ID = CYCL_FOLD.CF_ITEM_ID
AND CYCLE.CY_CYCLE_ID = 44451
AND STEP.ST_RUN_ID = RUN.RN_RUN_ID
AND RUN.RN_TEST_ID = TEST.TS_TEST_ID
AND RUN.RN_RUN_ID in (select MAX(RUN.RN_RUN_ID) FROM RUN
GROUP BY RN_TESTCYCLE_ID)
This query returns all of the tests with the individual steps and their status. The MAX statement returns the latest run of that test.
When a test is run, a RUN_ID is assigned in the STEP table. The issue is that if a test has not been run, it won't have a RUN_ID and therefore won't be included in the results.
So I created the below query 3:
SELECT
STEP.ST_RUN_ID as "RunId" /*Test Step.Run No*/,
TEST.TS_NAME as "Test Name",
STEP.ST_STATUS as "Run Status",
STEP.ST_STEP_NAME as "Step Name",
CYCLE.CY_CYCLE as "TestSet",
CYCL_FOLD.CF_ITEM_NAME as "Test Lab Folder Name"
FROM RUN, CYCL_FOLD, CYCLE, STEP, TEST
RIGHT JOIN (
SELECT
TEST.TS_NAME
FROM CYCLE
JOIN TESTCYCL ON (TESTCYCL.TC_CYCLE_ID = CYCLE.CY_CYCLE_ID)
JOIN TEST ON TEST.TS_TEST_ID = TESTCYCL.TC_TEST_ID)
WHERE CYCLE.CY_CYCLE_ID = 44451) alltest
ON alltest.TS_NAME = TEST.TS_NAME
WHERE RUN.RN_CYCLE_ID = CYCLE.CY_CYCLE_ID
AND CYCLE.CY_FOLDER_ID = CYCL_FOLD.CF_ITEM_ID
AND STEP.ST_RUN_ID = RUN.RN_RUN_ID
AND RUN.RN_TEST_ID = TEST.TS_TEST_ID
AND RUN.RN_RUN_ID in (select MAX(RUN.RN_RUN_ID) FROM RUN GROUP BY rn_testcycl_id)
I wanted to RIGHT JOIN on all the tests and populate the rows which have a run recorded but it's still not returning the NULL rows. There is no difference between running query 2 or 3.
A:
It is not returning the rows because the where clause is filtering them out.
Use ANSI standard join syntax (an on clause) and put the conditions in the on clause. The result is something like this:
SELECT s.ST_RUN_ID as "RunId" /*Test Step.Run No*/, t.TS_NAME as "Test Name",
s.ST_STATUS as "Run Status", s.ST_STEP_NAME as "Step Name", c.CY_CYCLE as "TestSet",
cf.CF_ITEM_NAME as "Test Lab Folder Name"
FROM RUN r join
CYCL_FOLD cf
on c.RN_CYCLE_ID = cf.CY_CYCLE_ID join
CYCLE c
on c.CY_FOLDER_ID = cf.CF_ITEM_ID join
STEP s
on s.ST_RUN_ID = r.RN_RUN_ID join
TEST t
on r.RN_TEST_ID = t.TS_TEST_ID right join
(SELECT TEST.TS_NAME
FROM CYCLE JOIN
TESTCYCL
ON TESTCYCL.TC_CYCLE_ID = CYCLE.CY_CYCLE_ID JOIN
TEST
ON TEST.TS_TEST_ID = TESTCYCL.TC_TEST_ID
WHERE CYCLE.CY_CYCLE_ID = 44451
) alltest
ON alltest.TS_NAME = t.TS_NAME and
r.RN_RUN_ID in (select MAX(RUN.RN_RUN_ID) FROM RUN GROUP BY rn_testcycl_id);
| {
"pile_set_name": "StackExchange"
} |
Q:
How to calculate X.509 certificate's SHA-1 fingerprint?
I'm trying to implement an X.509 certificate generator from scratch (I know about the existing ones, but I need yet another one). What I cannot understand is how to calculate the SHA-1 (or any other) fingerprint of the certificate.
The RFC5280 says that the input to the signature function is the DER-encoded tbsCertificate field. Unfortunately, the hash that I calculate differs from the one produced by OpenSSL. Here's a step-by-step example.
generate a certificate using OpenSSL's x509 tool (in a binary DER form, not the ASCII PEM)
calculate its SHA-1 hash using openssl x509 -fingerprint
extract the TBS field using dd (or anything else) and store it in a separate file; calculate its hash using the sha1sum utility
Now, the hashes I get at steps 2 and 3 are different. Can someone please give me a hint what I may be doing wrong?
A:
Ok, so it turned out that the fingerprint calculated by OpenSSL is simply a hash over the whole certificate (in its DER binary encoding, not the ASCII PEM one!), not only the TBS part, as I thought.
For anyone who cares about calculating certificate's digest, it is done in a different way: the hash is calculated over the DER-encoded (again, not the PEM string) TBS part only, including its ASN.1 header (the ID 0x30 == ASN1_SEQUENCE | ASN1_CONSTRUCTED and the length field). Please note that the certificate's ASN.1 header is not taken into account.
A:
The finger print is similar to term "Thumbprint" in .net. Below code snippet should help you to compute finger print :
public String generateFingerPrint(X509Certificate cert) throws CertificateEncodingException,NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
byte[] hash = digest.digest(cert.getEncoded[]);
final char delimiter = ':';
// Calculate the number of characters in our fingerprint
// ('# of bytes' * 2) chars + ('# of bytes' - 1) chars for delimiters
final int len = hash.length * 2 + hash.length - 1;
// Typically SHA-1 algorithm produces 20 bytes, i.e. len should be 59
StringBuilder fingerprint = new StringBuilder(len);
for (int i = 0; i < hash.length; i++) {
// Step 1: unsigned byte
hash[i] &= 0xff;
// Steps 2 & 3: byte to hex in two chars
// Lower cased 'x' at '%02x' enforces lower cased char for hex value!
fingerprint.append(String.format("%02x", hash[i]));
// Step 4: put delimiter
if (i < hash.length - 1) {
fingerprint.append(delimiter);
}
}
return fingerprint.toString();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
HashMap returned by Maps.newHashMap vs new HashMap
I am trying Guava for the first time and I find it really awesome.
I am executing few parameterized retrieve queries on a Spring jdbc template. The method in the DAO (AbstractDataAccessObject) goes like this. No problem here.
public Map<String,Object> getResultAsMap(String sql, Map<String,Object> parameters) {
try {
return jdbcTemplate.queryForMap(sql, parameters);
} catch (EmptyResultDataAccessException e) {
//Ignore if no data found for this query
logger.error(e.getMessage(), e);
}
return null;
}
Here's the problem :
When I call this method using
getResultAsMap(query, new HashMap<String,Object>(ImmutableMap.of("gciList",gciList)));
it works great.
But when I do this
getResultAsMap(query, Maps.newHashMap(ImmutableMap.of("gciList",gciList)));
the compiler gets upset saying
The method getResultAsMap(String, Map<String,Object>) in the type AbstractDataAccessObject is not applicable for the arguments (String, HashMap<String,List<String>>)
Am I doing something wrong or what could be the reason for this complaint?
A:
This is type inference failing. Maps.newHashMap is a static parameterized method. It allows you to use
Map<String,Integer> map = Maps.newHashMap()
instead of
Map<String,Integer> map = new HashMap<String,Integer>()
saving you from having to type <String,Integer> twice. In Java 7, the diamond operator allows you to use
Map<String,Integer> map = new HashMap<>()
so the method is then redundant.
To answer your question, just use the new HashMap version, since type inference doesn't work for method parameters. (You could use Maps.<String,Object>newHashMap() but that defeats the point of using the method)
A:
The problem here is that your method takes Map<String, Object>, but that's not actually what you want. You want a Map of String keys to any kind of values. That's not Map<String, Object>, it's Map<String, ?>.
A:
Adding a late answer here:
Most of the benefit is gone before type inference came to java. (yay) but I was wondering about any performance differences. Here is the code for google.common.collect.maps
/**
* Creates a <i>mutable</i>, empty {@code HashMap} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableMap#of()} instead.
*
* <p><b>Note:</b> if {@code K} is an {@code enum} type, use {@link
* #newEnumMap} instead.
*
* @return a new, empty {@code HashMap}
*/
public static <K, V> HashMap<K, V> newHashMap() {
return new HashMap<K, V>();
}
Its the same code.
| {
"pile_set_name": "StackExchange"
} |
Q:
Who is the good and beautiful person in Zechariah 9:17?
There seem to be two main variants of English translations of Zechariah 9:17a:
The newer one, of which the NLT is a prime representative:
16On that day the Lord their God will rescue his people,
just as a shepherd rescues his sheep.
They will sparkle in his land
like jewels in a crown.
17How wonderful and beautiful they will be!
The young men will thrive on abundant grain,
and the young women will flourish on new wine.
The older one, of which the new ESV translation represents well:
16On that day the Lord their God will save them,
as the flock of his people;
for like the jewels of a crown
they shall shine on his land.
17For how great is his goodness, and how great his beauty!
Grain shall make the young men flourish,
and new wine the young women.
The meanings of 17a are significantly different in these two renderings. Is he talking about wonderful people, or a great, good God? What clues do we have from the structure of these verses or the grammar of the Hebrew? In particular, is 17a in a different tense and number than 16b and 17b, and how significant is this?
A:
tl;dr The Hebrew is also ambiguous.
In the Hebrew:
(16) וְֽהוֹשִׁיעָ֞ם יְהוָ֧ה אֱלֹהֵיהֶ֛ם בַּיּ֥וֹם הַה֖וּא כְּצֹ֣אן עַמּ֑וֹ כִּ֚י אַבְנֵי־נֵ֔זֶר מִֽתְנוֹסְס֖וֹת עַל־אַדְמָתֽוֹ׃ (17) כִּ֥י מַה־טּוּב֖וֹ וּמַה־יָפְי֑וֹ דָּגָן֙ בַּֽחוּרִ֔ים וְתִיר֖וֹשׁ יְנוֹבֵ֥ב בְּתֻלֽוֹת׃ (Westminster Leningrad Codex)
The words translated "How wonderful and beautiful they will be" / "For how great is his goodness, and how great his beauty" are "כִּ֥י מַה־טּוּב֖וֹ וּמַה־יָפְי֑וֹ". These words mean "what is his goodness and what is his beauty", in singular-male. Thus, the ambiguity is already in the Hebrew: the goodness and beauty may refer to God, the people, or even the crown jewels.
| {
"pile_set_name": "StackExchange"
} |
Q:
When Using UITabBarController, all view controllers receive shouldAutoRotate or just the displayed one?
If I have a UITabBarController, displayed 4 view controllers: vc1, vc2, vc3, vc4.
when vc1 is displayed, I rotate the device.
Will all the view controllers receive and run the AutoRotate methods (shouldAutoRotate, willAutoRotate) or just vc1?
If only vc1: should I just send a notification and register all the vc's for it in order so they'll rotate as well? Because I don't want to rotate vc1 to landscape, then go to vc2 and it'll still be on landscape.
Btw - if it matters - I use a different xib for portrait&landscape.
Tnx!
A:
It depends of how your app is constructed. You should have some kind of ViewController that would hold your other viewControllers. So you could do something like this:
-(void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
NSLog(@"Main will rotate");
[view1 willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
[view2 willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
[view3 willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
[view4 willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
}
In this case, all your UIViewControllers would rotate because the one who hold them is rotating and making his children rotate. :)
I really like this approach because you don't need to have references to the others viewControllers from each viewController. (view1 doesn't need to know that there is view2,view3 and a view4).
| {
"pile_set_name": "StackExchange"
} |
Q:
How to redirect pages after stored data on mysql
I am trying to redirect to thanks webpage after stored on data on mysql using header("Location: success.html");
exit;
but when i open that link it will automatically goes into success.html page without entering or Storing any data on form and mysql.
<?php
$con=mysqli_connect("localhost","root","","vdl");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])) // Fetching variables of the form which travels in URL
{
$company_name = $_POST['company_name'];
$since = $_POST['since'];
$strength = $_POST['strength'];
$head_quarter = $_POST['head_quarter'];
if($company_name !=''||$since !='')
{
mysqli_query($con,"insert into digital_library(company_name, since, strength, head_quarter) values ('$company_name', '$since', '$strength', '$head_quarter')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
mysqli_close($con);
}
else
{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
header("Location: success.html");
exit;
?>
A:
$con=mysqli_connect("localhost","root","","libro");
// Check connection
if (mysqli_error($con))
{
echo "Failed to connect to MySQL: " . mysqli_error($con);
exit();
}
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$company_name = $_POST['company_name'];
$since = $_POST['since'];
$strength = $_POST['strength'];
$head_quarter = $_POST['head_quarter'];
if($company_name !== ''||$since !== ''){
mysqli_query($con,"insert into digital_library(company_name, since, strength, head_quarter) values ('$company_name', '$since', '$strength', '$head_quarter')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
header("Location: success.html");
exit();
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
exit();
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Insert into table, return id and then insert into another table with stored id
I have the following three tables:
Please note that the below DDL came models generated by Django then grabbed out of Postgresql after they were created. So modifying the tables is not an option.
CREATE TABLE "parentTeacherCon_grade"
(
id INTEGER PRIMARY KEY NOT NULL,
"currentGrade" VARCHAR(2) NOT NULL
);
CREATE TABLE "parentTeacherCon_parent"
(
id INTEGER PRIMARY KEY NOT NULL,
name VARCHAR(50) NOT NULL,
grade_id INTEGER NOT NULL
);
CREATE TABLE "parentTeacherCon_teacher"
(
id INTEGER PRIMARY KEY NOT NULL,
name VARCHAR(50) NOT NULL
);
CREATE TABLE "parentTeacherCon_teacher_grade"
(
id INTEGER PRIMARY KEY NOT NULL,
teacher_id INTEGER NOT NULL,
grade_id INTEGER NOT NULL
);
ALTER TABLE "parentTeacherCon_parent" ADD FOREIGN KEY (grade_id) REFERENCES "parentTeacherCon_grade" (id);
CREATE INDEX "parentTeacherCon_parent_5c853be8" ON "parentTeacherCon_parent" (grade_id);
CREATE INDEX "parentTeacherCon_teacher_5c853be8" ON "parentTeacherCon_teacher" (grade_id);
ALTER TABLE "parentTeacherCon_teacher_grade" ADD FOREIGN KEY (teacher_id) REFERENCES "parentTeacherCon_teacher" (id);
ALTER TABLE "parentTeacherCon_teacher_grade" ADD FOREIGN KEY (grade_id) REFERENCES "parentTeacherCon_grade" (id);
CREATE UNIQUE INDEX "parentTeacherCon_teacher_grade_teacher_id_20e07c38_uniq" ON "parentTeacherCon_teacher_grade" (teacher_id, grade_id);
CREATE INDEX "parentTeacherCon_teacher_grade_d9614d40" ON "parentTeacherCon_teacher_grade" (teacher_id);
CREATE INDEX "parentTeacherCon_teacher_grade_5c853be8" ON "parentTeacherCon_teacher_grade" (grade_id);
My Question is: How do I write an insert statement (or statements) where I do not have keep track of the IDs? More specifically I have a teacher table, where teachers can teach relate to more than one grade and I am attempting to write my insert statements to start populating my DB. Such that I am only declaring a teacher's name, and grades they relate to.
For example, if I have a teacher that belong to only one grade then the insert statement looks like this.
INSERT INTO "parentTeacherCon_teacher" (name, grade_id) VALUES ('foo bar', 1 );
Where grades K-12 are enumerated 0,12
But Need to do something like (I realize this does not work)
INSERT INTO "parentTeacherCon_teacher" (name, grade_id) VALUES ('foo bar', (0,1,3) );
To indicate that this teacher relates to K, 1, and 3 grades
leaving me with this table for the parentTeacherCon_teacher_grade
+----+------------+----------+
| id | teacher_id | grade_id |
+----+------------+----------+
| 1 | 3 | 0 |
| 2 | 3 | 1 |
| 3 | 3 | 3 |
+----+------------+----------+
This is how I can currently (successfully) insert into the Teacher Table.
INSERT INTO public."parentTeacherCon_teacher" (id, name) VALUES (3, 'Foo Bar');
Then into the grade table
INSERT INTO public.parentTeacherCon_teacher_grade (id, teacher_id, grade_id) VALUES (1, 3, 0);
INSERT INTO public.parentTeacherCon_teacher_grade (id, teacher_id, grade_id) VALUES (2, 3, 1);
INSERT INTO public.parentTeacherCon_teacher_grade (id, teacher_id, grade_id) VALUES (3, 3, 3);
A bit more information.
Here is a diagram of the database
Other things I have tried.
WITH i1 AS (INSERT INTO "parentTeacherCon_teacher" (name) VALUES ('foo bar')
RETURNING id) INSERT INTO "parentTeacherCon_teacher_grade"
SELECT
i1.id
, v.val
FROM i1, (VALUES (1), (2), (3)) v(val);
Then I get this error.
[2016-08-10 16:07:46] [23502] ERROR: null value in column "grade_id" violates not-null constraint
Detail: Failing row contains (6, 1, null).
A:
If you want to insert all three rows in one statement, you can use:
INSERT INTO "parentTeacherCon_teacher" (name, grade_id)
SELECT 'foo bar', g.grade_id
FROM (SELECT 0 as grade_id UNION ALL SELECT 1 UNION ALL SELECT 3) g;
Or, if you prefer:
INSERT INTO "parentTeacherCon_teacher" (name, grade_id)
SELECT 'foo bar', g.grade_id
FROM (VALUES (0), (2), (3)) g(grade_id);
EDIT:
In Postgres, you can have data modification statements as a CTE:
WITH i as (
INSERT INTO public."parentTeacherCon_teacher" (id, name)
VALUES (3, 'Foo Bar')
RETURNING *
)
INSERT INTO "parentTeacherCon_teacher" (name, teacher_id, grade_id)
SELECT 'foo bar', i.id, g.grade_id
FROM (VALUES (0), (2), (3)) g(grade_id) CROSS JOIN
i
| {
"pile_set_name": "StackExchange"
} |
Q:
how to pass an object value to 2 jsp pages via spring controller
i have 2 model class
public class Abcd {
private String name;
private String familyName;
// getters and setters
}
public class Bcd {
private String color;
// getters and setters
}
i want that 1st jsp page takes input for Abcd, and then pass it to 2nd jsp page, where i also take input for the BCD class and then i show both objects input data to the 3rd page
please suggest the way to do this
A:
You could put the Abcd's name and family in hidden fields on the second page. The action calling the third page would be able to access to Abcd's and Bcd's attributes and show them in the third JSP.
| {
"pile_set_name": "StackExchange"
} |
Q:
Recharts render pie chart vertically
I am using recharts library for pie charts.
I want to load pie chart for two values always.The chart is loading horizantally as you can see here starting from angle 0.
But i want it to be starting from angle 90 looking as below.
PS: Tried changing startAngle and endAngle values.
A:
Well I guess it's still related with props startAngle and endAngle
It starts counting at degree 90. (It may be kind of counterintuitive)
If you try another value as below, it would become a vertical start pie
startAngle={-270}
Notice according to the document, the default value:
startAngle: 0
endAngle: 360
The diff equals 360 would show a full circle pie. You can try out other pairs, like
[-270, 90], [90, -270], [45, 405]
| {
"pile_set_name": "StackExchange"
} |
Q:
Palindrome checker - What am i doing wrong?
I am to create a program that checks for palindromes in a sentence and display the palindromes that have been found. My following code keeps giving me a "String is out of bounds" error. What am i doing wrong?
My Program:
import javax.swing.JOptionPane;
public class Palindromechkr {
public static void main(String[] args) {
//Declare Variables
String Palin, input, Rinput = "";
int wordlength, spacePos;
//Ask for sentance
input = JOptionPane.showInputDialog("enter a sentance");
//Split string
spacePos = input.indexOf(" ");
String word = input.substring(0, spacePos);
//Get palindromes
System.out.println("Your Palindromes are:");
for (int counter = 0; counter < input.length(); counter++) {
//Reverse first word
wordlength = word.length();
for (int i = wordlength - 1; i >= 0; i--) {
Rinput = Rinput + word.charAt(i);
//Add word to An array of Palindromes
if (Rinput.equalsIgnoreCase(word)) {
Palin = word;
System.out.println("Palin:" + Palin);
break;
}
//Move on to the next word in the string
input = input.substring(input.indexOf(" ") + 1) + " ";
word = input.substring(0, input.indexOf(" "));
}
}
}
}
A:
If you know functions you can use a recursive function to build the palindrome version of a string (it's a common example of how recursion works).
Here's an example:
import javax.swing.JOptionPane;
public class Palindromechkr {
public static void main(String[] args) {
//Declare Variables
String Palin, input, Rinput = "";
int wordlength, spacePos;
//Ask for sentance
input = JOptionPane.showInputDialog("enter a sentance");
String[] words = input.split(" +"); // see regular expressions to understand the "+"
for(int i = 0; i < words.length; i++) { // cycle through all the words in the array
Rinput = makePalindrome(words[i]); // build the palindrome version of the current word using the recursive function
if(Rinput.equalsIgnoreCase(words[i])) {
Palin = words[i];
System.out.println("Palin: " + Palin);
}
}
}
// this is the recursive function that build the palindrome version of its parameter "word"
public static String makePalindrome(String word) {
if(word.length() <= 1) return word; // recursion base case
char first = word.charAt(0); // get the first character
char last = word.charAt(word.length()-1); // get the last character
String middle = word.substring(1, word.length()-1); // take the "internal" part of the word
// i.e. the word without the first and last characters
String palindrome = last + makePalindrome(middle) + first; // recursive call building the palindrome
return palindrome; // return the palindrome word
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Select first element of nested list
Let's say I have a list like this:
x = list(list(1,2), list(3,4), list(5,6))
I would like a list that contains only the first elements of the nested list. I can do this by returning another list like so
x1 = lapply(x, function(l) l[[1]])
Is there shortcut notation for this?
A:
Not much of a shortcut, but you can do this:
lapply(x, `[[`, 1)
# [[1]]
# [1] 1
#
# [[2]]
# [1] 3
#
# [[3]]
# [1] 5
A:
Another possibility uses the nice purrr library:
library(purrr)
map(x, 1)
A:
For your example list you can just do:
unlist(x)[ c(TRUE,FALSE) ]
but that depends on each sublist having exactly 2 elements.
If there are different numbers of elements then you could first do an sapply to calculate the lengths, then compute the corresponding 1st element positions (see cumsum), then select those values from the unlisted list. But by that time the accepted answer is probably much simpler.
If all the sublists have the same length (but could be different from 2) then you could do something like:
do.call( rbind, x)[,1]
or some other cast to a common object. But I doubt that this would be as efficient as the lapply approach.
| {
"pile_set_name": "StackExchange"
} |
Q:
Crossdomain xml and flash
I have a web server application (based on python). Flash applications which are located at this server should connect to the server. The trouble is in crossdomain.xml.
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="*" to-ports="*"/>
</cross-domain-policy>
Here is this file (it's in the root directory).
The exact problem is that flash-applications don't load this file. Are there any ways to do this manually? For example, load it directly from flash-script or make up a new application at given port which will send this file to any connected socket.
A:
you're not closing the <cross-domain-policy> tag with </cross-domain-policy> - have you just forgot to copy/paste the last line? otherwise try that. also you might not need the DOCTYPE line and the to-ports="*" either.
we use this crossdomain.xml file and as long as it's in the root folder, it's worked fine for us every time
<?xml version="1.0"?>
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>
if it's an https domain and you want flash on non-https domains to access it you'll need to change the allow-access-from line to this
<allow-access-from domain="*" secure="false" />
one final thing worth trying is adding this line :
<allow-http-request-headers-from domain="*" headers="*"/>
but we've never had to use that for standard flash loading/saving via http.
| {
"pile_set_name": "StackExchange"
} |
Q:
PL / SQL Trigger to format information with compilation errors
this is my very first question, I'm new here so I hope I'm asking well in the right topic... etc.
I'm trying with a trigger wich catch information from one table, compares some data from this table and if a condition is true then the trigger have to store the information changing some values. There are my tables and the trigger. I need this trigger to store larger tables with a lot of columns and a lot more information but this is just a test, please help! :'(
create table datos_prueba(
nombre varchar2(10) primary key,
numero number(3),
mensaje varchar(30),
fecha date);
create table store_datos_prueba(
nombre varchar(20) primary key,
numero number(5),
mensaje varchar(30),
fecha date);
And this is the trigger, I worte it but it's wrong...
create or replace trigger tgr_trigger_prueba
after insert on datos_prueba
for each row
declare
cambio_numero number;
begin
if :datos_prueba.numero <= 5 then
insert into store_datos_prueba (nombre,numero,mensaje,fecha) values(:datos_prueba.nombre,666,:datos_prueba.mensaje,:datos_prueba.fecha);
else
insert into store_datos_prueba (nombre,numero,mensaje,fecha) values(:datos_prueba.nombre,777,:datos_prueba.mensaje,:datos_prueba.fecha);
end if;
end;
A:
You have to use old or new to refer the row value. Not the table name.
create or replace trigger tgr_trigger_prueba
after insert on datos_prueba
for each row
declare
cambio_numero number;
begin
if :new.numero <= 5 then
insert into store_datos_prueba (nombre,numero,mensaje,fecha) values(:new.nombre,666,:new.mensaje,:new.fecha);
else
insert into store_datos_prueba (nombre,numero,mensaje,fecha) values(:new.nombre,777,:new.mensaje,:new.fecha);
end if;
end;
/
More on Triggers
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't center a div
I can't center this div for the life of me. I'm going a bit crazy here. I've tried auto margin, text-align center. I've got it in an unordered list.
js fiddle http://jsfiddle.net/8V3Tr/
#logoWrap {
background:#F0F0F0;
text-align:center;
}
#logowrapInner {
width:80%;
margin:auto;
}
ul#corpLogos {
overflow:hidden;
list-style:none;
padding:15px;
}
ul#corpLogos li a {
float:left;
margin-right:20px;
display:block;
text-align:center;
transition: all 0.3s ease 0s;
-webkit-transition: all ease 0.3s;
-moz-transition: all ease 0.3s;
-o-transition: all ease 0.3s;
-ms-transition: all ease 0.3s;
}
ul#corpLogos li a:hover {
transform: scale(1.1);
-webkit-transform: scale(1.1);
-moz-transform: scale(1.1);
-o-transform: scale(1.1);
-ms-transform: scale(1.1);
-webkit-filter: drop-shadow(5px 5px 5px rgba(0,0,0,0.5));
filter: url(#drop-shadow);
-ms-filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=12, OffY=12, Color='#444')";
filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=12, OffY=12, Color='#444')";
}
#corpLogos img { border : 0;
max-width: 100%;
height: auto;
width: auto\9; /* ie8 */ }
<div id="logoWrap">
<div id="logowrapInner">
<ul id="corpLogos">
<li><a href="http://www.bellator.com/" target="_blank"><img src="http://s513195336.onlinehome.us/wp-content/uploads/2014/02/bellator.png"/></li>
<li><a href="http://www.ncaa.com/" target="_blank"><img src="http://s513195336.onlinehome.us/wp-content/uploads/2014/02/ncaa.png" /></li>
<li><a href="http://http://www.ufc.ca/" target="_blank"><img src="http://s513195336.onlinehome.us/wp-content/uploads/2014/02/ufc.png" /></li>
<li><a href="http://www.nhl.com/" target="_blank"><img src="http://s513195336.onlinehome.us/wp-content/uploads/2014/02/nhl.png" /></li>
</ul>
</div>
</div>
A:
margin: auto; isn't working for you because you need to specify a width for the parent container.
Change this:
#logoWrap {
background:#F0F0F0;
text-align:center;
}
To something like this:
#logoWrap {
background:#F0F0F0;
text-align:center;
width: 800px;
}
See here for a working fiddle: http://jsfiddle.net/mp5Vn/
A:
Solved : http://jsfiddle.net/8V3Tr/7/
Add width to the UL and use margin: auto 0
Only changes here:
#logowrapInner {
width:100%;
}
ul#corpLogos {
width:60%;
overflow:hidden;
list-style:none;
margin:0 auto;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to run Integration just when merging to master
I've Travis CI which is working as expected for Go application
language: go
go:
- "1.10.x"
script:
- go get -v -t -d ./...
- go test -v ./...
This CI takes about a 60-80 sec to run.
The CI is triggered in two scenarios
Submitting to new branch
Merging to the master
Now I've new file which is called integration_test.go which is running integration test which takes about 10 min (deployment etc)
and I want to run this test only when merging to the master (since its more heavy) , and not run when submitting to branches, how it can be done it Travis?
I've tried with
on:
branch: master
condition: `go test -v integration_test.go`
A:
What you're likely looking for here is a 'Conditional job'. Using the example here:
https://docs.travis-ci.com/user/build-stages/matrix-expansion/
try:
language: go
go:
- "1.10.x"
script:
- go get -v -t -d ./...
- go test -v ./...
jobs:
include:
- stage: integration
if: branch = master
script: go test -v integration_test.go
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular directive dependency injection - TypeScript
There seem to be a number of ways to create Angular directives in TypeScript. The neatest I've seen is to use a static factory function:
module app {
export class myDirective implements ng.IDirective {
restrict: string = "E";
replace: boolean = true;
templateUrl: string = "my-directive.html";
link: ng.IDirectiveLinkFn = (scope: ng.IScope, el: ng.IAugmentedJQuery, attrs: ng.IAttributes) => {
};
static factory(): ng.IDirectiveFactory {
var directive: ng.IDirectiveFactory = () => new myDirective();
return directive;
}
}
angular.module("app")
.directive("myDirective", myDirective.factory());
}
But I'm not sure what to do if I need to inject something. Say I'd like $timeout:
module app {
export class myDirective implements ng.IDirective {
restrict: string = "E";
replace: boolean = true;
templateUrl: string = "my-directive.html";
constructor(private $timeout: ng.ITimeoutService) {
}
link: ng.IDirectiveLinkFn = (scope: ng.IScope, el: ng.IAugmentedJQuery, attrs: ng.IAttributes) => {
// using $timeout
this.$timeout(function (): void {
}, 2000);
}
static factory(): ng.IDirectiveFactory {
var directive: ng.IDirectiveFactory = () => new myDirective(); // Uhoh! - What's goes here?
directive.$inject = ["$timeout"];
return directive;
}
}
angular.module("app")
.directive("myDirective", myDirective.factory());
}
As you can see above, I'm not sure how to call the myDirective contructor and pass in $timeout.
A:
Just specify $timeout as the factory constructor function argument and pass it through.
static factory(): ng.IDirectiveFactory {
var directive: ng.IDirectiveFactory =
($timeout:ng.ITimeoutService) => new myDirective($timeout);
directive.$inject = ["$timeout"];
return directive;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Set detect insertion failure
Is there a simple way to detect when a set insert does not occur because the item being inserted already exists in the set? For example, I'd like to display a message to the user that shows the insert failure so that they can find and remove the duplicates in their data more easily. Here's some pseudo code to demonstrate what I'd like to do:
try
{
items.insert(item)
}
catch insert_failed_item_already_in_set
{
// show user the failed item
}
A:
A signature for set::insert is:
pair<iterator,bool> insert ( const value_type& x );
So, your code would look like:
if( !items.insert(item).second )
{
show user the failed item
}
A:
There is this insert signature in std::set
pair<iterator,bool> insert ( const value_type& x );
Test the second of the returned pair, should be set to true if inserted successfully.
A:
As set insert return pair you can check the state of second element of pair using get<1> which is the Boolean , if your insert is done or not .
if (get<1>(set.insert(x)) == false){
//Your error log.
}
| {
"pile_set_name": "StackExchange"
} |
Q:
npm is failing to compile – uikit3
I've just started using UIKit3 (getuitkit.com) and I keep getting this error when npm run watch is running – I also can't use npm run compile either. Any ideas?
This is the error I get with watch...
[compile-less] /Users/Michael/Sites/uikit-3/build/icons.js:10
glob(custom, (err, folders) =>
^^
SyntaxError: Unexpected token =>
at exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:443:25)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
[compile-less] [nodemon] app crashed - waiting for file changes before starting...
And this for compile...
/Users/Michael/Sites/uikit-3/build/icons.js:10
glob(custom, (err, folders) =>
^^
SyntaxError: Unexpected token =>
at exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:443:25)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
npm ERR! Darwin 16.1.0
npm ERR! argv "node" "/usr/local/bin/npm" "run" "icons"
npm ERR! node v0.12.0
npm ERR! npm v2.5.1
npm ERR! code ELIFECYCLE
npm ERR! [email protected] icons: `node build/icons`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] icons script 'node build/icons'.
npm ERR! This is most likely a problem with the uikit package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node build/icons
npm ERR! You can get their info via:
npm ERR! npm owner ls uikit
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! /Users/Michael/Sites/uikit-3/npm-debug.log
npm ERR! Darwin 16.1.0
npm ERR! argv "node" "/usr/local/bin/npm" "run" "compile-less"
npm ERR! node v0.12.0
npm ERR! npm v2.5.1
npm ERR! code ELIFECYCLE
npm ERR! [email protected] compile-less: `npm run icons && node build/less`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] compile-less script 'npm run icons && node build/less'.
npm ERR! This is most likely a problem with the uikit package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! npm run icons && node build/less
npm ERR! You can get their info via:
npm ERR! npm owner ls uikit
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! /Users/Michael/Sites/uikit-3/npm-debug.log
npm ERR! Darwin 16.1.0
npm ERR! argv "node" "/usr/local/bin/npm" "run" "compile"
npm ERR! node v0.12.0
npm ERR! npm v2.5.1
npm ERR! code ELIFECYCLE
npm ERR! [email protected] compile: `npm run compile-less && npm run compile-js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] compile script 'npm run compile-less && npm run compile-js'.
npm ERR! This is most likely a problem with the uikit package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! npm run compile-less && npm run compile-js
npm ERR! You can get their info via:
npm ERR! npm owner ls uikit
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! /Users/Michael/Sites/uikit-3/npm-debug.log
A:
You seem to be running node v0.12.0. UIkit's build tools require a minimum version of 4.4+. Please update to a current Node version. https://nodejs.org/en/
| {
"pile_set_name": "StackExchange"
} |
Q:
AUTimePitch or AUPitch in IOS 5
I'm poking around the ios documentation at the moment in the core audio section.
I'm just trying to do pitch shifting without having to write my own processing callback and I'm really confused with the documentation telling me one thing and the headers saying another.
My first question is about kAudioUnitSubType_Pitch
First ,In the ios section of the docs here the pitch unit is listed but when I try to add it to code its not listed in the code hint and in the audio unit header it says that its for desktop only. Is it possible to use this in ios 5 at all or am I looking at the wrong docs.
Second , also in the ios section of the docs here I'm interested in kAudioUnitSubType_TimePitch. It is listed but states ios 2.0 through ios 2.0. Does this mean that you cant use it in ios5 ?
Could somebody give me some clarity on the issue?
A:
Apple's time pitch modification AU is currently not available in iOS 5, only in the desktop Mac OS. The early AU docs have been corrected. The current iOS 5.x only supports a pitch resampler unit.
But there appear to be one or more commercial iOS library solutions for audio time pitch modification, if you don't want to roll your own.
ADDED later: Only the 1st gen iPad is limited to iOS 5.x. iOS 7 includes the NewTimePitch Audio Unit. But this audio unit is (currently) lower in quality than the OS X TimePitch audio unit
| {
"pile_set_name": "StackExchange"
} |
Q:
Sum latest records from each user
I have a table as below
id user_id bal createdDate
1 001 100 2015-02-17 16:45:44
2 001 200 2015-02-18 18:45:44
3 002 300 2015-02-20 16:45:44
4 002 800 2015-02-18 18:45:44
5 001 300 2015-03-01 16:20:44
6 002 500 2015-03-17 16:45:44
7 002 200 2015-03-18 18:45:44
8 003 300 2015-03-10 16:45:44
9 003 80 2015-03-18 18:45:44
10 003 200 2015-03-21 16:20:44
I want the latest balance of each user_id and sum all of them. As a result, i will get sum of combine latest balance from user 001,002,003
This table contain around 5 million records
This table save the history of account balance for each user. So the latest date is the latest account balance for that user.
Below is my query, but I don't get any result as my MySQL workbench froze.
SELECT (SUM(bal))
FROM hist_bal h1
WHERE h1.createDate = (SELECT MAX(h2.createDate)
FROM hist_bal h2
WHERE h2.user_id = h1.user_id GROUP BY h2.user_id)
A:
This should do it simply, no need for GROUP BY clouse:
SELECT SUM(bal)
FROM hist_bal h1
WHERE h1.createDate = (SELECT MAX(h2.createDate)
FROM hist_bal h2
WHERE h2.user_id = h1.user_id)
A:
SELECT SUM(h1.bal) AS Bal
FROM hist_bal h1 JOIN (SELECT user_id, MAX(h2.createDate) AS createDate
FROM hist_bal h2 GROUP BY h2.user_id) h2 ON h1.user_id = h2.user_id
AND h1.createDate = h2.createDate
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change URL's for each page in joomla 3.4?
I'm trying to understand the way Joomla handles URLs.
I've activated what they call "Search Engine Friendly URLs". But it appears that a page (or an "Article" only gets such a URL once I link it from a menu item.
All other menu items are fine, but when I try to insert a new one then the url is change (http://www.grundtvig.as/forside-general/uncategorised/blisterpakning).
I want the above link like this one: http://www.grundtvig.as/blisterpakning.
Thank you
A:
The quick answer for having a article with a url like this is to link it (as you already said) with a menu item.
Alternatively, if you would want this happening automatically, without menu items, then you need to install a SEF extension like SH404SEF or JoomSEF.
Update after your comment about JoomSEF:
hmm.. ok - I was actually writing a more extended answer to explain basics of how Joomla deals with URLs. But since you have a SEF extension, assuming you have enable it, then it's not Joomla but the component you are using that handles the urls.
So, you need to tweak the settings of JoomSEF and order it to create links directly to the root for uncategorized articles, or articles that do not have a menu item - meaning that you should set it to not include categories in the SEF URLs.
Finally to deal with already created urls, you need to delete them from the JoomSEF URLs list, and have JoomSEF recreate them according to your new configuration, otherwise the old ones will continue to be used.
| {
"pile_set_name": "StackExchange"
} |
Q:
Binary search not returning correct value
I'm implementing the binary search algorithm in C++, but the algorithm isn't returning the correct value. The code can be found here.
template<class T>
int binary_search(T search_value, T search_array[]) {
int mid; /* The middle element of the remaining array to be searched. */
int min = 0; /* The first index of the array. */
/* This forumla gives us the size of the array. */
int max = sizeof(search_array)/sizeof(search_array[0]);
/* Continue searching until min >= max. */
while (min < max) {
/* Compute the value of mid using a formula that won't produce a number
* larger than the maximum allowed value of an integer. */
mid = (max-min)/2 + min;
/* Depending the whether search_value is larger or smaller than the
* value of whatever is at search_array[mid], set one of mid and max
* equal to mid. */
if (search_value > search_array[mid])
min = mid + 1;
else if (search_value < search_array[mid])
max = mid + 1;
else {
return mid;
}
}
return -1;
}
Given an array {0, 1, 3, 5, 7, 9} and searching for 3, the function should return 2, the index of 3 in the array. My function is returning -1 though, which means 3 was not found in the array. Where's the problem?
A:
int max = sizeof(search_array)/sizeof(search_array[0]);
This approach is not good to compute the size of the array, it works only in the function where you create your array.
Pass the size of your array as a parameter of your function, it's the easiest approach.
A:
This line is a at least one problem:
int max = sizeof(search_array)/sizeof(search_array[0]);
Arrays are not passed through the function, so your declaration:
int binary_search(T search_value, T search_array[])
... is the same as:
int binary_search(T search_value, T *search_array)
And thus max is size of the pointer divided by the size of element, so in the best case scenario it could be up to 6, but most likely is 0 or 1.
I think in C++ you can pass array by reference and know its size using form of declaration like this:
template <size_t array_length>
void foo (const char (&data) [array_length])
{
// ...
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Finding Inverse of Matrix using Cramer's Rule
I have created a function determinant which outputs a determinant of a 3x3 matrix. I also need to create a function to invert that matrix however the code doesn't seem to work and I can't figure out why.
M = np.array([
[4.,3.,9.],
[2.,1.,8.],
[10.,7.,5.]
])
def inverse(M):
'''
This function finds the inverse of a matrix using the Cramers rule.
Input: Matrix - M
Output: The inverse of the Matrix - M.
'''
d = determinant(M) # Simply returns the determinant of the matrix M.
counter = 1
array = []
for line in M: # This for loop simply creates a co-factor of Matrix M and puts it in a list.
y = []
for item in line:
if counter %2 == 0:
x = -item
else:
x = item
counter += 1
y.append(x)
array.append(y)
cf = np.matrix(array) # Translating the list into a matrix.
adj = np.matrix.transpose(cf) # Transposing the matrix.
inv = (1/d) * adj
return inv
OUTPUT:
via inverse(M):
[[ 0.0952381 -0.04761905 0.23809524],
[-0.07142857 0.02380952 -0.16666667],
[ 0.21428571 -0.19047619 0.11904762]]
via built-in numpy inverse function:
[[-1.21428571 1.14285714 0.35714286]
[ 1.66666667 -1.66666667 -0.33333333]
[ 0.0952381 0.04761905 -0.04761905]]
As you can see some of the numbers match and I'm just not sure why the answer isn't exact as I'm using the formula correctly.
A:
You co-factor matrix calculation isn't correct.
def inverse(M):
d = np.linalg.det(M)
cf_mat = []
for i in range(M.shape[0]):
for j in range(M.shape[1]):
# for each position we need to calculate det
# of submatrix without current row and column
# and multiply it on position coefficient
coef = (-1) ** (i + j)
new_mat = []
for i1 in range(M.shape[0]):
for j1 in range(M.shape[1]):
if i1 != i and j1 != j:
new_mat.append(M[i1, j1])
new_mat = np.array(new_mat).reshape(
(M.shape[0] - 1, M.shape[1] - 1))
new_mat_det = np.linalg.det(new_mat)
cf_mat.append(new_mat_det * coef)
cf_mat = np.array(cf_mat).reshape(M.shape)
adj = np.matrix.transpose(cf_mat)
inv = (1 / d) * adj
return inv
This code isn't very effective, but here you can see, how it should be calculated. More information and clear formula you can find at Wiki.
Output matrix:
[[-1.21428571 1.14285714 0.35714286]
[ 1.66666667 -1.66666667 -0.33333333]
[ 0.0952381 0.04761905 -0.04761905]]
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get the generated scheme file .graphqls using SPQR?
I really like the way SPQR makes easy to integrate graphql with an existing system, the only thing I'd like to see is the .graphqls file so I can learn more on GraphQL Syntax.
Is there a way to generate the scheme file from an existing code with SPQR annotations integrated?
To provide some code let's use the same code from the GitHub site
Entity:
public class User {
private String name;
private Integer id;
private Date registrationDate;
@GraphQLQuery(name = "name", description = "A person's name")
public String getName() {
return name;
}
@GraphQLQuery
public Integer getId() {
return id;
}
@GraphQLQuery(name = "regDate", description = "Date of registration")
public Date getRegistrationDate() {
return registrationDate;
}
}
Service class:
class UserService {
@GraphQLQuery(name = "user")
public User getById(@GraphQLArgument(name = "id") Integer id) {
...
}
}
Expected Output:
type User {
id: Int!
name: String!
registrationDate: String
}
Query{
user(Int):User
}
A:
This is not really SPQR specific. All the needed classes are provided by graphql-java itself:
new SchemaPrinter().print(schema);
To get a more detailed output (with scalars, introspection types etc), provide the options to the printer:
new SchemaPrinter(
// Tweak the options accordingly
SchemaPrinter.Options.defaultOptions()
.includeScalarTypes(true)
.includeExtendedScalarTypes(true)
.includeIntrospectionTypes(true)
.includeSchemaDefintion(true)
).print(schema);
| {
"pile_set_name": "StackExchange"
} |
Q:
GCC error when installing ncurses on OS X 10.8
I'm trying to install ncurses 5.9 on OS X 10.8 with GCC 4.9 installed. No errors or warnings show up when I run ./configure in the ncurses directory, but when I run make, I get gcc: error: unrecognized command line option ‘-no-cpp-precomp’. Upon googling the issue (and trying it out), I found that --no-cpp-precomp (with two dashes, i.e in long flag form) is a valid command.
I'm not sure what was prompting GCC to run the invalid command – whether it was make, or if it was a command specified in ncurses itself.
Is there any way to fix this? If so, how?
EDIT: I tried changing the reference in the ./configure file from -no-cpp-precomp to --no-cpp-precomp manually, using a text editor, and was met with this, despite GCC seemingly accepting the --no-cpp-precomp option. After that, I tried running autoreconf, and got this:
configure:6558: error: possibly undefined macro: AC_DIVERT_HELP
If this token and others are legitimate, please use m4_pattern_allow.
See the Autoconf documentation.
autoreconf: /opt/local/bin/autoconf failed with exit status: 1
After running it with the m4_pattern_allow option:
autoreconf: 'configure.ac' or 'configure.in' is required
After running ./configure && make anyway:
cd man && make DESTDIR="" all
sh ./MKterminfo.sh ./terminfo.head ./../include/Caps ./terminfo.tail >terminfo.5
cd include && make DESTDIR="" all
cat curses.head >curses.h
AWK=gawk sh ./MKkey_defs.sh ./Caps >>curses.h
sh -c 'if test "chtype" = "cchar_t" ; then cat ./curses.wide >>curses.h ; fi'
cat ./curses.tail >>curses.h
gawk -f MKterm.h.awk ./Caps > term.h
sh ./edit_cfg.sh ../include/ncurses_cfg.h term.h
** edit: HAVE_TCGETATTR 1
** edit: HAVE_TERMIOS_H 1
** edit: HAVE_TERMIO_H 0
** edit: BROKEN_LINKER 0
cd ncurses && make DESTDIR="" all
gcc -o make_hash -DHAVE_CONFIG_H -I../ncurses -I. -I./../include -I../include -DUSE_BUILD_CC -DHAVE_CONFIG_H -I../ncurses -I. -D_DARWIN_C_SOURCE -DNDEBUG -I. -I../include -I/usr/local/include/ncurses -O2 --param max-inline-insns-single=1200 --no-cpp-precomp ./tinfo/make_hash.c -Wl,-search_paths_first
gcc: error: unrecognized command line option ‘--no-cpp-precomp’
make[1]: *** [make_hash] Error 1
make: *** [all] Error 2
A:
It looks like this has been fixed in the latest patches to ncurses 5.9
The 5.9 source can be found here: ftp://invisible-island.net/ncurses/ncurses-5.9.tar.gz
The latest patches are here: ftp://invisible-island.net/ncurses/5.9/ but the latest rollup patch appears to have the fix: ftp://invisible-island.net/ncurses/5.9/patch-5.9-20130504.sh.gz
To apply the patch, get the 2 files above then:
$ tar xvf ncurses-5.9.tar.gz
$ cd ncurses-5.9
$ gzip -dc ../patch-5.9-20130504.sh.gz | sh
| {
"pile_set_name": "StackExchange"
} |
Q:
Group by por fecha usando left join mysql
Estoy tratando de hacer una consulta que implica 3 tablas, post, comentarios y likes. necesito saber la fecha del post y el titulo del post, el número de personas que han comentado el post y el numero de likes por cada persona, el detalle está en que necesito hacer group by con la fecha de los comentarios y los likes de cada persona para hacer unas estadisca con los valores que obtengo con los datos de los likes y comentarios por persona. si no existe un valor en la tabla "comentarios o likes" lo reemplazaría por 0.
Tablas y datos
CREATE TABLE IF NOT EXISTS `post` (
`id` int(11) NOT NULL,
`titulo` varchar(200) NOT NULL,
`user_id` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
INSERT INTO `post` (`id`, `titulo`, `user_id`, `created_at`) VALUES
(1, 'group by mysql', 19, '2018-02-18 19:10:30');
CREATE TABLE IF NOT EXISTS `comentarios` (
`id` int(11) NOT NULL,
`content` varchar(200) NOT NULL,
`post_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
INSERT INTO `comentarios` (`id`, `content`, `post_id`, `user_id`, `created_at`) VALUES
(1, 'comentario 1', 1, 19, '2018-02-19 13:12:09'),
(2, 'comentario 2', 1, 20, '2018-02-20 23:42:09'),
(3, 'comentario 3', 1, 19, '2018-02-21 19:12:30'),
(4, 'comentario 4', 1, 21, '2018-02-26 11:38:34'),
(5, 'comentario 5', 1, 22, '2018-02-28 19:13:15');
CREATE TABLE IF NOT EXISTS `likes` (
`id` int(11) NOT NULL,
`post_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
INSERT INTO `likes` (`id`, `post_id`, `user_id`, `created_at`) VALUES
(1, 1, 19, '2018-02-28 19:16:12'),
(2, 1, 21, '2018-02-28 19:16:12'),
(3, 1, 22, '2018-02-22 19:16:21');
EDIT
He avanzado en la consulta, aun me falta lograr que si hay likes en una fecha que no hay comentarios los comentarios y el contador de los comentarios salga en null o 0.
de igual forma si hay un comentario en el fecha que no hay likes que los likes salgan en null o 0.
consulta actual
SELECT
p.id as post_id,
titulo,
MAX(DATE(p.created_at)) as fecha_post,
MAX(DATE(c.created_at)) as fecha_comentario,
COUNT(c.user_id) as count_personas,
MAX(DATE(l.created_at)) as fecha_likes,
COUNT(l.user_id) as count_likes
FROM post as p
LEFT OUTER JOIN comentarios as c
ON p.id=c.post_id
LEFT OUTER JOIN likes as l
ON p.id=l.post_id and date(c.created_at)=date(l.created_at)
GROUP BY p.id, DATE(p.created_at), DATE(c.created_at), DATE(l.created_at);
update campos
UPDATE likes
SET created_at='2018-02-22 14:46:21'
WHERE id=3
salida que espero
alguien podria ayudarme a terminar la consulta y obtener el resultado deseado?
A:
Para poder hacerlo, te hace falta hacer una serie de cambios:
La tabla comentarios debe tener una PRIMARY KEY bien definida.
Relacionar la tabla likes con la de comentarios.
Te dejo la estructura de las dos tablas:
CREATE TABLE `comentarios` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`content` varchar(200) NOT NULL,
`post_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `likes` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`post_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`comment_id` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `comment_idx` (`comment_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
No te olvides de agregar los valores de la columna comment_id que relacionan la tabla likes con comentarios, ejemplo:
UPDATE likes SET comment_id = 5 WHERE comment_id = 0;
La consulta deseada:
SELECT
p.id as post_id,
DATE(p.created_at) as fecha_post,
c.user_id AS usuario_comentario,
DATE(c.created_at) as fecha_comentario,
COUNT(c.user_id) as count_personas,
DATE(l.created_at) as fecha_likes,
COUNT(l.user_id) as count_likes
FROM post as p
LEFT JOIN comentarios as c
ON p.id=c.post_id
LEFT JOIN likes as l
ON p.id=l.post_id AND l.comment_id = c.id
GROUP BY p.id, DATE(p.created_at), DATE(c.created_at), DATE(l.created_at);
Salida deseada:
+---------+------------+--------------------+------------------+----------------+-------------+-------------+
| post_id | fecha_post | usuario_comentario | fecha_comentario | count_personas | fecha_likes | count_likes |
+---------+------------+--------------------+------------------+----------------+-------------+-------------+
| 1 | 2018-02-18 | 19 | 2018-02-19 | 1 | NULL | 0 |
| 1 | 2018-02-18 | 20 | 2018-02-20 | 1 | NULL | 0 |
| 1 | 2018-02-18 | 19 | 2018-02-21 | 1 | NULL | 0 |
| 1 | 2018-02-18 | 21 | 2018-02-26 | 1 | NULL | 0 |
| 1 | 2018-02-18 | 22 | 2018-02-28 | 3 | 2018-03-01 | 3 |
+---------+------------+--------------------+------------------+----------------+-------------+-------------+
| {
"pile_set_name": "StackExchange"
} |
Q:
normalizer of a Sylow $p$-subgroup of a simple group $G$ of order 60
I'm trying to show that a simple group $G$ is isomorphic to $A_5$.
now I proved that if $G$ has an index 5 subgroup $H$ that is, $|H|=12$, then $G\cong A_5$ using the group action. so I need to know that if $G$ actually has an index 5 group or not.
to show that, I'm actually following this article and it says that if $Q$ is a Sylow 3-subgroup of $G$, then $|N_G(Q)|=15$ for $n_3=4$, the number of Sylow 3-subgroup. and I don't understand why.
since $N_G(Q)$ is a subgroup of $G$, its order should divide $60$ and since any subgroup of $G$ can't have index less than $5$, it means any subgroup of $G$ should have order less than or equal to $12$. and since $|Q|=3$, $3$ divides $|N_G(Q)|$. so we have $|N_G(Q)|=3, 6,12$. I don't know where the number $15$ came out, and why all these $3,6,12$ are removed.
and my second question is that if $A,B$ are two different Sylow $p$-subgroup of any group $D$, then is it true that their normalizer $N_D(A), N_D(B)$ doesn't intersect nontrivially? I felt the author of the article is assuming this.
A:
All Sylow $3$-subgroups are conjugate. Their number is $n_3$
where $n_3=|G:N_G(Q)|$ where $Q$ is a Sylow $3$-subgroup. So if $n_3=4$ then $|N_G(Q)|=|G|/n_3=4$.
In any case $G$ acts transitively by conjugation on the set of Sylow $3$-subgroups. If $n_3=4$ then $G$ acts on a set of four objects
transitively, and so there is a homomorphism $G\to S_4$ whose image
is nontrivial. Its kernel is a nontrivial subgroup of $G$, contradiction.
By Sylow's third theorem, $n_3\equiv1\pmod 3$. As $n_3\mid 20$ and
$n_3\ge5$ then $n_3=10$. This means that $G$ has $20$ elements of order $3$.
| {
"pile_set_name": "StackExchange"
} |
Q:
trouble with basic numpy multiplication
In my code, I multiply two matrices:
c = b*a
Where a outputs as
array([array([-0.08358731, 0.07145386, 0.1052811 , -0.05362566]),
array([-0.05335939, -0.03136824, -0.01260714, 0.11532605]),
array([-0.09164538, 0.02280118, -0.00290509, 0.09415849])], dtype=object)
and b outputs as
array([ 0.60660017, 0.54703557, 0.69928535, 0.70157223])
...That should work right (where values of b is multiplied by each value of each row in a)?
Instead, I get
ValueError: operands could not be broadcast together with shapes (3) (4)
But then when I try it in a separate python console, it works great.
(bare in mind I've set array = np.array)
>>> aa = array([array([-0.12799382, 0.07758469, -0.02968546, -0.01811048]),
array([-0.00465869, -0.00483031, -0.00591955, -0.00386022]),
array([-0.02036786, 0.0078658 , 0.09493727, -0.01790333])], dtype=object)
>>> bb = array([ 0.16650179, 0.74140229, 0.60859776, 0.37505098])
>>> aa * bb
array([[-0.021311200138937801, 0.057521466834940096, -0.0180665044605696,
-0.0067923532722703999],
[-0.00077568022405510005, -0.0035812028954099002,
-0.0036026248702079999, -0.0014477792940156],
[-0.0033912851484694004, 0.0058317221326819992, 0.0577786098625152,
-0.0067146614617633995]], dtype=object)
The fact it works here really confuses me...
A:
Your first array has only 1 dimension and 3 "object" elements while your second array has 1 dimension and 4 float elements. numpy uses element-wise arithmetic operations and there is just no way it can do that with one 3-item array and a 4-item array therefore the Exception.
>>> x = np.empty(3, dtype=object)
>>> x[0] = np.array([-0.08358731, 0.07145386, 0.1052811 , -0.05362566])
>>> x[1] = np.array([-0.05335939, -0.03136824, -0.01260714, 0.11532605])
>>> x[2] = np.array([-0.09164538, 0.02280118, -0.00290509, 0.09415849])
>>> x.shape
(3, )
The example above is an awful way of creating a numpy.array and should be avoided!
The difference to your second example is that it doesn't have numpy-arrays inside an array, it creates a multidimensional (3x4) array:
>>> x_new = np.array(list(x))
>>> x_new # no nested arrays!
array([[-0.12799382, 0.07758469, -0.02968546, -0.01811048],
[-0.00465869, -0.00483031, -0.00591955, -0.00386022],
[-0.02036786, 0.0078658, 0.09493727, -0.01790333]], dtype=object)
>>> x_new.shape
(3, 4)
That the multiplication operation works with the new array (x_new or your aa) is because numpy broadcasts the arrays. Here every row will be multiplied by one of your items in the second array.
| {
"pile_set_name": "StackExchange"
} |
Q:
Bound ContentControl not displaying
I have two ContentControls on a page that bind to the same StaticResource and one of them draws correctly an the other doesn't draw at all.
The resource is defined thus:
<Path x:Key="ArrowNorth"
Stroke="DarkGray"
StrokeThickness="1"
Data="M 20,4 L 36,20 L 32,24 L 23,15 L 23,33 L 17,33 L 17,15 L 8,24 L 4,20 Z">
<Path.Fill>
<RadialGradientBrush GradientOrigin="0.15,0.2" Center="0.3,0.4">
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="{Binding Source={StaticResource MainWindowResource}, Path=ArrowColor}" Offset="1"/>
</RadialGradientBrush>
</Path.Fill>
</Path>
The resource is basically an arrow that I am trying to display on top of a circle. The place that it is not drawing correctly is define like this:
<Grid Canvas.Top="30" Canvas.Left="6" ToolTip="Up"
Visibility="{Binding Source={StaticResource MainWindowResource}, Path=ShowVertical}">
<Ellipse x:Name="lightEllipseU" Height="40" Width="40">
<Ellipse.Fill>
<RadialGradientBrush GradientOrigin="0.3,0.3" Center="0.4,0.4">
<GradientStop Color="White" Offset="0"/>
<GradientStop
Color="{Binding Source={StaticResource MainWindowResource}, Path=LightColorU}"
Offset="1"/>
</RadialGradientBrush>
</Ellipse.Fill>
</Ellipse>
<!-- This doesn't display -->
<ContentControl Content="{Binding Source={StaticResource ArrowNorth}}"/>
</Grid>
The Ellipse displays fine and just to test the Z order, I commented out the Ellipse and the ContentControl would still not display. Further down the page I use the arrow in a differnt place and the arrow displays just fine. Here is the code:
<Grid Canvas.Top="10" Canvas.Left="110" ToolTip="Y Axis">
<Ellipse x:Name="lightEllipseN" Height="40" Width="40">
<Ellipse.Fill>
<RadialGradientBrush GradientOrigin="0.3,0.3" Center="0.4,0.4">
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="{Binding Source={StaticResource MainWindowResource}, Path=LightColorN}" Offset="1"/>
</RadialGradientBrush>
</Ellipse.Fill>
</Ellipse>
<!-- This displays just fine -->
<ContentControl Content="{Binding Source={StaticResource ArrowNorth}}"/>
</Grid>
The code is absolutely the same (cut and paste). I can't understand why it will work in one place an not another.
A:
You are right, as each Visual can have only one parent and since you have only one Path then last time it's used it will be put in that place of visual tree. What you can do is create Geometry resource:
<Window.Resources>
<!-- ..... -->
<Geometry x:Key="myPath">M 20,4 L 36,20 L 32,24 L 23,15 L 23,33 L 17,33 L 17,15 L 8,24 L 4,20 Z</Geometry>
</Window.Resources>
and then you can use is in more then one Path:
<Grid ...>
<Ellipse Height="40" Width="40">
<Ellipse.Fill>
<RadialGradientBrush GradientOrigin="0.3,0.3" Center="0.4,0.4">
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="Black" Offset="1"/>
</RadialGradientBrush>
</Ellipse.Fill>
</Ellipse>
<Path Stroke="DarkGray" StrokeThickness="1" Data="{StaticResource myPath}">
<Path.Fill>
<RadialGradientBrush GradientOrigin="0.15,0.2" Center="0.3,0.4">
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="Black" Offset="1"/>
</RadialGradientBrush>
</Path.Fill>
</Path>
</Grid>
However, since it's used in more then one place and it basically looks the same, only colours change, it would be useful to create custom UserControl with 2 DependancyProperty for colours binding and then you can reuse it as many places you like
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get webm files resolution
I'm trying to make a c# app that reads webm files. I already managed to play the files on a panel using directshow.net and adding the vp8 and vp9 filters, however I couldn't manage to find out how to get resolution from the webm file to resize my form accordingly.
A:
ffprobe is a C library that parses video and audio files. I have used it to parse webm files. Check out the -show_format option.
| {
"pile_set_name": "StackExchange"
} |
Q:
Custom route change for download URL
I am trying to change my download file route so it can stay protected by adding a non-existing folder "/protected/"
My realpath is
"/var/www/html/var/uploads/Statements/2019-06/export-1.csv"
and in the end I need it to be:
"http://app.local:8080/protected/uploads/Statements/2019-06/export-1.csv"
I tried various versions but my code doesn't return wanted path.
Can some help with editing my code:
$file = realpath($file);
$projectDir = $this->container->get('kernel')->getProjectDir();
$webDir = realpath($projectDir);
$finalPath = substr($file, strlen($webDir));
$request = $this->container->get('request_stack')->getCurrentRequest();
$downloadUrl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath() . '/' . $finalPath;
return $downloadUrl;
$downloadUrl works as it should but $finalPath is not well formated.
A:
Instead of keeping your uploads in the public/ folder, you should keep them somewhere outside the public document root of the web server, as this is a potential security risk, i.e. someone might get them without going through the mechanism. You could for example have a directory next to public/ called data/uploads. This will ensure files are not reachable by the web server.
In your Symfony project you could create a DownloadController that takes a path or filename as argument and then appends it to the folder:
class DownloadController extends AbstractController
{
// This should be the path you store your files in
private $uploadDir;
public function __construct(string $uploadDir)
{
$this->uploadDir = $uploadDir;
}
/**
* @Route("/protected/uploads/{file}", name="download", requirements={"file"=".+"})
*/
public function index(string $file)
{
return new BinaryFileResponse($this->uploadDir . $file);
}
}
See: https://symfony.com/doc/current/routing/slash_in_parameter.html and https://symfony.com/doc/current/components/http_foundation.html#serving-files
You might have to make some clean ups and sanity checks, e.g. when the file is missing or someone wants to trick you into downloading something outside the base directory, but roughly this should be it.
Now instead of creating pseudo links, in your application you can just call, e.g. in your template:
{{ path('download', { 'file': 'Statements/2019-06/export-1.csv' }) }}
This will create a proper download link inside your application. You could also create a mapping from a virtual file name, e.g. a hash to the actual file name inside that controller action. You only have to keep track of the references somehow. You can also add access checks, or download counters on that action.
To recap, assuming your project is in /var/www/myproject, the web server's public directory is /var/www/myproject/public/ and your files are kept in /var/www/myproject/data/uploads/. The uploaded file then is in /var/www/myproject/data/uploads/Statements/2019-06/export-1.csv and the URL will look like this: http://app.local:8080/protected/uploads/Statements/2019-06/export-1.csv. By changing the path of the route annotation you can simply adjust the URL without having to move a single file.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the difference between " as string" and "stringvalue" in swift?
I have a code :
var i : AnyObject!
i = 10
println(i as String)
println(i.stringValue)
it get crashed on as String line but runs in second i.stringValue.
What is the difference between as String and stringValue in the above lines?
A:
.stringValue is a way to extract Integer into string value but as String will not work for that And if you use as String then Xcode will force you to add ! with as which is not good and it will never succeed and it would crash your app. you can't cast Int to String. It will always fail. Thats why when you do as! String it crashes the app.
So casting is not a good idea here.
And here is some more ways to extract Integer into string value:
let i : Int = 5 // 5
let firstWay = i.description // "5"
let anotherWay = "\(i)" // "5"
let thirdWay = String(i) // "5"
Here you can not use let forthway = i.stringValue because Int Doesn't have member named stringValue
But you can do same thing with anyObject as shown below:
let i : AnyObject = 5 // 5
let firstWay = i.description // "5"
let anotherWay = "\(i)" // "5"
let thirdWay = String(i) // "5"
let forthway = i.stringValue // "5" // now this will work.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python store line by line in List from Text File
i have a text file like so and i would like to process it in python
info.txt
firstname1
surname1
[email protected]
student1
-------------------
firstname2
surname2
[email protected]
student2
-----------------
i want to write a python code which iterares and stores each line in each indexs example: [firstname,surname,[email protected],student] and ignore the "-----"
python code
with open('log.txt') as f:
lines = f.read().splitlines()
x = x + 1
for i in lines:
print i
but i believe this is wrong i amm very new to python can some one please point me in the correct direction
i want the output to me somthing like so
output
index 1 :first name: firstname1
Surname: surname1
Email: [email protected]
Student student1
index 2 :first name: firstname2
Surname: surname2
Email: [email protected]
student: student2
A:
I know it'd be better form to explain the general guidelines of how to do something like this, but for a simple task like this, the code speaks for itself, really...
I'd implement it like this.
from pprint import pprint # For nicer formatting of the output.
# For the sake of a self-contained example,
# the data is inlined here.
#
# `f` could be replaced with `open('log.txt').
f = """
firstname1
surname1
[email protected]
student1
-------------------
firstname2
surname2
[email protected]
student2
-----------------
""".splitlines()
data = []
current = None
for line in f:
line = line.strip() # Remove leading and trailing spaces
if not line: # Ignore empty lines
continue # Skip the rest of this iteration.
if line.startswith('-----'): # New record.
current = None # Clear the `current` variable
continue # Skip the rest of the iteration
if current is None: # No current entry?
# This can happen either after a ----- line, or
# when we're dealing with the very first line of the file.
current = [] # Create an empty list,
data.append(current) # and push it to the list of data.
current.append(line)
pprint(data)
The output is a list of lists:
[['firstname1', 'surname1', '[email protected]', 'student1'],
['firstname2', 'surname2', '[email protected]', 'student2']]
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I display an arrow positioned at a specific angle in MATLAB?
I am working in MATLAB and I'm stuck on a very simple problem: I've got an object defined by its position (x,y) and theta (an angle, in degrees). I would like to plot the point and add an arrow, starting from the point and pointing toward the direction defined by the angle. It actually doesn't even have to be an arrow, anything graphically showing the value of the angle will do!
Here's a picture showing the kind of thing I'm trying to draw:
removed dead ImageShack link
A:
The quiver() plotting function plots arrows like this. Take your theta value and convert it to (x,y) cartesian coordinates representing the vector you want to plot as an arrow and use those as the (u,v) parameters to quiver().
theta = pi/9;
r = 3; % magnitude (length) of arrow to plot
x = 4; y = 5;
u = r * cos(theta); % convert polar (theta,r) to cartesian
v = r * sin(theta);
h = quiver(x,y,u,v);
set(gca, 'XLim', [1 10], 'YLim', [1 10]);
Take a look through online the Matlab documentation to see other plot types; there's a lot, including several radial plots. They're in the MATLAB > Functions > Graphics > Specialized Plotting section. Do "doc quiver" at the command line and browse around.
A:
If you want to try and make something that looks like the image you linked to, here's some code to help you do it (NOTE: you would first have to download the submission arrow.m by Erik Johnson on the MathWorks File Exchange, which I always like to use for generating arrows of any shape and size):
x = 1; % X coordinate of arrow start
y = 2; % Y coordinate of arrow start
theta = pi/4; % Angle of arrow, from x-axis
L = 2; % Length of arrow
xEnd = x+L*cos(theta); % X coordinate of arrow end
yEnd = y+L*sin(theta); % Y coordinate of arrow end
points = linspace(0, theta); % 100 points from 0 to theta
xCurve = x+(L/2).*cos(points); % X coordinates of curve
yCurve = y+(L/2).*sin(points); % Y coordinates of curve
plot(x+[-L L], [y y], '--k'); % Plot dashed line
hold on; % Add subsequent plots to the current axes
axis([x+[-L L] y+[-L L]]); % Set axis limits
axis equal; % Make tick increments of each axis equal
arrow([x y], [xEnd yEnd]); % Plot arrow
plot(xCurve, yCurve, '-k'); % Plot curve
plot(x, y, 'o', 'MarkerEdgeColor', 'k', 'MarkerFaceColor', 'w'); % Plot point
And here's what it would look like:
You can then add text to the plot (for the angle and the coordinate values) using the text function.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to export the contents of the string or textbox to txt file that remains the same format (If string has 5 lines, txt file will has 5 lines)?
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
FileInfo Myfile = new FileInfo(saveFileDialog1.FileName);
StreamWriter wri = Myfile.CreateText();
wri.WriteLine(Richtextbox.Text);
wri.Close();
}
When I export to a text file, all the lines in richtextbox stick into one line. I donnot know how to keep file txt'content same as in richtextbox'content.
A:
You can use SaveFile method
Richtextbox.SaveFile(FileName, RichTextBoxStreamType.PlainText);
A:
foreach (var line in Richtextbox.Lines)
{
wri.WriteLine(line);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
stat_smooth not displayed on the plot
Given the data set shown below, I ran this command to draw a line graph with an overlaid smooth curve:
ggplot(tmp,
aes(CalendarMonth, Score)) +
geom_line(stat='identity', group = 1) + ylim(0, 3) +
theme_few() + ylab('Average score in the month') +
theme(axis.text.x = element_text(angle=90)) +
stat_smooth(aes(CalendarMonth, Score), method='loess')
But this draws only a line graph, i.e. whether I run the stat_smooth part or leave it out, the output does not change, and the smooth curve is not overlaid. What am I missing here?
Data:
tmp <- data.frame(
CalendarMonth = c('2012-07', '2012-08', '2012-06', '2012-05', '2012-04', '2012-09',
'2012-10', '2012-11', '2012-12', '2013-01', '2013-02', '2013-03', '2013-04', '2013-05',
'2013-06', '2013-07', '2013-08', '2013-09', '2013-10', '2013-11', '2013-12', '2014-01',
'2014-02', '2014-03', '2014-04', '2014-05', '2014-06', '2014-07', '2014-08', '2014-09',
'2014-10', '2014-11', '2014-12', '2015-01', '2015-02', '2015-03', '2015-04', '2015-05',
'2015-06', '2015-07', '2015-08', '2015-09', '2015-10', '2015-11', '2015-12', '2016-01',
'2016-02', '2016-03', '2016-04', '2016-05', '2016-06', '2016-07', '2016-08', '2016-09',
'2016-10', '2016-11', '2016-12', '2017-01', '2017-02', '2017-03', '2017-04', '2017-05',
'2017-06', '2017-07', '2017-08', '2017-09'),
Score = c(2.716667, 2.577465, 2.615385, 3.000000, 3.000000, 2.446429,
2.426667, 2.683544, 2.526316, 2.568966, 2.506849, 2.537500, 2.578125,
2.470588, 2.741935, 2.560261, 2.479195, 2.545605, 2.577778, 2.539216,
2.556492, 2.535593, 2.567829, 2.557214, 2.587662, 2.580189, 2.512069,
2.572402, 2.582792, 2.555938, 2.512586, 2.561224, 2.572308, 2.557940,
2.540000, 2.593333, 2.513274, 2.566952, 2.548649, 2.623223, 2.565079,
2.537344, 2.516667, 2.509485, 2.519084, 2.544262, 2.612795, 2.496429,
2.467128, 2.596226, 2.560714, 2.563253, 2.588462, 2.569395, 2.668919,
2.581197, 2.543253, 2.524648, 2.594796, 2.551613, 2.583333, 2.474074,
2.627306, 2.505017, 2.561086, 2.554545)
)
A:
Your data type is important, and as @joran mentioned in the comment, your data will need to change type before you can have a proper display.
We can quickly troubleshoot your issue with str:
> str(tmp)
'data.frame': 66 obs. of 2 variables:
$ CalendarMonth: Factor w/ 66 levels "2012-04","2012-05",..: 4 5 3 2 1 6 7 8 9 10 ...
$ Score : num 2.72 2.58 2.62 3 3 ...
In general, when you create a data frame you will want to set the parameter stringsAsFactors to false. If you do, you'll need to first run as.factor before as.integer. Have a look at what as.integer does to your factored data.
> as.integer(as.character(tmp$CalendarMonth))
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[26] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[51] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
> as.integer(as.factor(as.character(tmp$CalendarMonth)))
[1] 4 5 3 2 1 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
[26] 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
[51] 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
You'll notice that because the data format is in a YYYY-MM pseudo-date format when converting from a factor to an integer the values become an ordered list of date ranges. In general, be careful when you notice these types of conversions in R. The as.integer is following an interesting format, where the character values are compared to determine the order. What might work in one format may not work on another. For example:
> df <- data.frame(month = c('jan', 'feb', 'mar', 'dec', 'apr'))
> str(df)
'data.frame': 5 obs. of 1 variable:
$ month: Factor w/ 5 levels "apr","dec","feb",..: 4 3 5 2 1
> as.integer(df$month)
[1] 4 3 5 2 1
Be sure you understand how the solution works, so as to avoid a potential headache in the future. With that being said:
> tmp$cm <- as.integer(tmp$CalendarMonth)
> ggplot(tmp,
+ aes(CalendarMonth, Score)) +
+ geom_line(stat='identity', group = 1) + ylim(0, 3) +
+ theme_few() + ylab('Average score in the month') +
+ theme(axis.text.x = element_text(angle=90)) +
+ stat_smooth(aes(cm, Score), method='loess')
Gets you the right graph:
| {
"pile_set_name": "StackExchange"
} |
Q:
Having issues with UILabel not updating like it should
I'm creating a simple app using Swift that tells you if the number you are entering is a prime number or not. I know the logic is correct, but when I run the app and enter a number and press the button my label is not updating like it should. Can someone help me?
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var number: UITextField!
@IBOutlet weak var results: UILabel!
@IBAction func buttonPressed(sender: AnyObject) {
var numberInt = number.text.toInt()
if numberInt != nil {
var unwrappedNumber = numberInt!
var isPrime = true
if unwrappedNumber == 1 {
isPrime = false
}
if unwrappedNumber != 2 && unwrappedNumber != 1 {
for var i = 2; i < unwrappedNumber; i++ {
if unwrappedNumber % i == 0 {
isPrime = false
}
}
}
if isPrime == true{
results.text = "\(unwrappedNumber)Is Prime"
}else {
results.text = "\(unwrappedNumber)Is not Prime"
}
}else {
results.text = "Enter a number"
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
A:
The problem in your project is you are performing a wrong action at wrong place like in your StoryBoard you right Click on TextField you find that you connected Editing Did End is connected with @IBAction func buttonPressed(sender: AnyObject) this action. because of this your action is not working.
Now the solution for your problem is remove your action connection from that textField by Clicking that cross button and it will look like :
after that connect ** buttonPressed** action with Run Test Button like this:
HERE I updated your code.
I recommended you to watch some tutorial on UI so you can batter understands how this all things works.
| {
"pile_set_name": "StackExchange"
} |
Q:
iCal Time Zone issue
I'm trying to allow a user to download an iCal for their calendar in ASP.Net, but am having a timezone issue.
If I download the file on my computer, the time appears correct and within the correct timeframe. However, when I try to download it on a phone, the timezone switches and it becomes 5 hours behind (aka 7:00 AM becomes 3:00 AM).
Does anyone know how to fix this issue/set the timezone?
Here is the code:
iCalendar iCal = new iCalendar();
Event evt = iCal.Create<Event>();
DateTime dt = (DateTime)Convert.ToDateTime(lblTicketDue.Text);
Console.Write(dt);
evt.Start = new iCalDateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);
evt.End = new iCalDateTime((DateTime)Convert.ToDateTime(lblTicketDue.Text).AddMinutes(15.0));
Alarm alarm = new Alarm();
alarm.Action = AlarmAction.Display;
alarm.Summary = "Ticket due!";
Trigger t = new Trigger();
iCalDateTime icdt = new iCalDateTime(dt.Subtract(TimeSpan.FromMinutes(120.0)));
t.DateTime = icdt;
alarm.Trigger = t;
evt.Alarms.Add(alarm);
iCal.Events.Add(evt);
iCalendarSerializer serializer = new iCalendarSerializer();
string output = serializer.SerializeToString(iCal);
Response.ContentType = "text/calendar";
Response.Write(output);
Response.End();
A:
Hard to tell without looking at the actual iCalendar stream that gets generated but it is quite likely that you are generating your DTSTART/DTEND using floating time (e.g. "20160517T070000" ).
If the event is not recurring (no RRULE), what you want to do is convert your datetime to UTC and use the "date with UTC time" format described in https://tools.ietf.org/html/rfc5545#section-3.3.5
i.e. something like "20160517Txx0000Z"
If the event is recurring you would then need to use the last form (date with local time and timezone reference).
| {
"pile_set_name": "StackExchange"
} |
Q:
$\int_{1}^{x}\frac{M(t)}{t}dt=o(x)$ implies $M(x)=o(x)$
Show that $$\int_{1-}^{x}\frac{M(t)}{t}dt=o(x)$$ implies $$M(x)=o(x)$$
where $M(x)=\sum_{n\leq x}\mu(n)$. My idea is complicated and goes like this : Note that $$\frac{M(t)}{t}dt=dM*t^{-1}dt$$
Now multiplying an 'approximate inverse' for $t^{-1}dt$ in the above equation and then integrating and using the hypothesis , we get $$\frac{M(x)}{x}+\frac{\int_{1}^{x}M(t)dt}{x^2}=o(1) $$ Using this equation recurrently one can get the desired result. The 'approximate inverse' i used was $d\left(\frac{1}{t}\right)$. I think this is not the intended solution. This a exercise from Bateman and Diamond's text on Analytic number thoery.
A:
It is not true in general, you need to use that $|M(x+n)-M(x)| \le n$.
Assume that $|M(x_k)| > a x_k$ for infinitely many $k$, and find a contradiction from $$\int_{x_k-a x_k}^{x_k} \frac{M(t)}{t}dt = \int_1^{x_k} \frac{M(t)}{t}dt- \int_1^{x_k-a x_k} \frac{M(t)}{t}dt=o(x_k)$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular 2 Routing with parameter undefined
I'm trying to create a route in Angular 2 that takes me to data of a json file, depending on the id. For instance I have 10001.json, 10002.json, 10003.json, etc...
People should be able to get to their patientfile by typing in that particular id as an url, but so far that's not working. I'm actually getting :
GET http://localhost:4200/assets/backend/patienten/undefined.json 404 (Not Found)
This is my patientcomponent:
import { Component, OnInit } from '@angular/core';
import {PatientService} from "../patient.service";
import {Patient} from "../models";
import {ActivatedRoute, Params} from "@angular/router";
import 'rxjs/add/operator/switchMap';
@Component({
selector: 'app-patient',
templateUrl: './patient.component.html',
styleUrls: ['./patient.component.sass']
})
export class PatientComponent implements OnInit {
patient:Patient[];
id:any;
errorMessage:string;
constructor(private patientService:PatientService, private route: ActivatedRoute) { }
ngOnInit():void {
this.getData();
this.id = this.route.params['id'];
this.patientService.getPatient(this.id)
.subscribe(patient => this.patient = patient);
}
getData() {
this.patientService.getPatient(this.id)
.subscribe(
data => {
this.patient = data;
console.log(this.patient);
}, error => this.errorMessage = <any> error);
}
}
This is the routing, very basic:
import {Routes} from "@angular/router";
import {AfdelingComponent} from "./afdeling/afdeling.component";
import {PatientComponent} from "./patient/patient.component";
export const routes: Routes = [
{path: '', component: AfdelingComponent},
{path: 'patient/:id', component: PatientComponent}
];
And the service:
import { Injectable } from '@angular/core';
import {Http, RequestOptions, Response, Headers} from '@angular/http';
import {Observable} from "rxjs";
import {Patient} from "./models";
@Injectable()
export class PatientService {
private patientUrl = "/assets/backend/patienten/";
constructor(private http: Http) { }
getPatient(id:any): Observable<Patient[]>{
return this.http.get(this.patientUrl + id + '.json' )
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || { };
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
addPatient(afdelingsNaam: string, afdeling: any): Observable<Patient> {
let body = JSON.stringify({"afdelingsNaam": afdelingsNaam, afdeling: afdeling});
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
return this.http.post(this.patientUrl, body, options)
.map(res => <Patient> res.json())
.catch(this.handleError)
}
}
A:
The problem is that you call getData before this.id is populated.
Just change places
ngOnInit():void {
this.id = this.route.params['id'];
this.getData();
this.patientService.getPatient(this.id)
.subscribe(patient => this.patient = patient);
}
Edited:
route.params is an Observable, so you need to use it like:
this.sub = this.route.params.subscribe(params => {
this.id = +params['id']; // (+) converts string 'id' to a number
// In a real app: dispatch action to load the details here.
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Confusion regarding spring.http.multipart.max-file-size vs spring.servlet.multipart.max-file-size
I have spent days wasted getting Spring Boot Upload file to work but, as is always with Spring you have no clue how the magic works and even after years of working with this framework - you have to google tonnes of times to unravel what has gone wrong and solve things like as if you are going thru a maze,it's a maintainability nightmare.
Using Spring Boot 2.2.0.M3 for file uploads what is the difference between the 2 pair's of settings ? Which is right ?
spring.http.multipart.max-file-size=-1
spring.http.multipart.max-request-size=-1
Is the above "http" used with Spring REST controller methods namely like this ...
@GetMapping("/files/{filename:.+}")
@ResponseBody
public ModelAndView yourMethod(.....)
Or is this not needed at all and is a complete red-herring and it is the setting below that does all the work for files bigger than the default of 1MB for both REST http or Servlet requests.
spring.servlet.multipart.max-file-size=-1
spring.servlet.multipart.max-request-size=-1
Exception on uploading
Maximum upload size exceeded; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes.
A:
They had changed the property names in different versions.
Spring Boot 1.3.x and earlier
multipart.max-file-size
multipart.max-request-size
After Spring Boot 1.3.x:
spring.http.multipart.max-file-size=-1
spring.http.multipart.max-request-size=-1
After Spring Boot 2.0:
spring.servlet.multipart.max-file-size=-1
spring.servlet.multipart.max-request-size=-1
max-file-size Vs max-request-size
spring.servlet.multipart.max-file-size = 2MB
Max size per file the upload supports is 2MB;
also supports the MB or KB suffixes;
by default 1MB
spring.servlet.multipart.max-request-size=10MB
max size of the whole request is 10MB;
also supports the MB or KB suffixes
For unlimited upload file size, It seems setting -1 will make it for infinite file size.
UPDATE:
You don't need to specify any spring.** property at Controller Level (expect headers Content-Type in some case). You can set these properties in appilcation.properties file as below.
# MULTIPART (MultipartProperties)
spring.servlet.multipart.enabled=true # Whether to enable support of multipart uploads.
spring.servlet.multipart.file-size-threshold=0B # Threshold after which files are written to disk.
spring.servlet.multipart.location= # Intermediate location of uploaded files.
spring.servlet.multipart.max-file-size=1MB # Max file size.
spring.servlet.multipart.max-request-size=10MB # Max request size.
spring.servlet.multipart.resolve-lazily=false # Whether to resolve the multipart request lazily at the time of file or parameter access.
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery selectors in an object - reduce redundancy versus readability
Let's say I have a web form that collects a company name and its address information from a user. In a related javascript file, to reduce the jQuery selectors scattered throughout the functions and to collect related information in a single object structure, I might store all that in one object like in this simple example:
var companyForm = {
name: {
inputField: $("#CompanyName"),
isValid: function() {
return IsNameValid(this.inputField.val());
},
labelField: $("#CompanyNameLabel")
},
address: {
inputField: $("#Address"),
isValid: function() {
return IsAddressValid(this.inputField.val());
},
labelField: $("#AddressLabel")
},
city: {
inputField: $("#City"),
isValid: function() {
return IsCityValid(this.inputField.val());
},
labelField: $("#CityLabel")
}
};
I only need to list these selectors once, and then whenever I need to reference the company name that the user entered, I can use this:
companyForm.name.inputField.val()
Or, if I want to check the validity of the user's input:
companyForm.name.isValid()
Etc. (The labelField would be, say, a label element that I might want to add a class named "error" to, should the user enter badly formatted input and I want to emphasize to them that it needs their attention).
My dilemma is, by applying the DRY principle to my jQuery selectors, I'm now hurting readability, since:
$("#CompanyName").val()
is a lot easier to read and understand than:
companyForm.name.inputField.val()
Should I not be trying to reduce redundancy in this manner? Is there a better way I can manage or minimize the selector references?
A:
How about implementing getter and setter functions? that way you'd only call companyForm.getName() to get the value of companyForm.name.inputField.val()
Let's say:
var companyForm = {
name: {
inputField: $("#CompanyName"),
isValid: function() {
return IsNameValid(this.inputField.val());
},
labelField: $("#CompanyNameLabel")
},
...
getName: function() {
return this.name.inputField.val();
}
};
| {
"pile_set_name": "StackExchange"
} |
Q:
Retrieving contents of several files in directory PHP
I need to get the contents of several files within a directory but which is the best way of doing this?
I am using
$data = file_get_contents('./files/myfile.txt');
but I want every file without having to specify the file individually as above.
A:
You can use glob to get particular file extention and file_get_contents to get the content
$content = implode(array_map(function ($v) {
return file_get_contents($v);
}, glob(__DIR__ . "/files/*.txt")));
| {
"pile_set_name": "StackExchange"
} |
Q:
Cmake Error for ITK with GDCM configuration
Following error found while configuring ITK with GDCM2.2
CMake Error at Modules/ThirdParty/GDCM/itk-module-init.cmake:5 (find_package):
By not providing "FindGDCM.cmake" in CMAKE_MODULE_PATH this project has
asked CMake to find a package configuration file provided by "GDCM", but
CMake did not find one.
Could not find a package configuration file provided by "GDCM" with any of
the following names:
GDCMConfig.cmake
gdcm-config.cmake
Add the installation prefix of "GDCM" to CMAKE_PREFIX_PATH or set
"GDCM_DIR" to a directory containing one of the above files. If "GDCM"
provides a separate development package or SDK, be sure it has been
installed.
Call Stack (most recent call first):
CMakeLists.txt:558 (include)
I have installed GDCM2.2 [not repository] and manually set path of gdcm directory but still this error returned by Cmake.
Please help.
A:
To build ITK with gdcm download .zip file of gdcm2.2.1 or latest version cause installing gdcm by exe is not include any GDCMconfig.cmake file but zip have it. And in ITK configuration we have to give path of directory where GDCMconfig.cmake is present.
| {
"pile_set_name": "StackExchange"
} |
Q:
Simple PHP for loop error
Just started learning. Here's what I have:
<?php
$i = 0;
$num = $i * 12;
for ($i=0; $i<13; $i++) {
echo($i." times 12 = ".$num."<br>");
}
?>
The outcome should be:
1 times 12 = 12
2 times 12 = 24
3 times 12 = 36
etc...
The outcome I actually get is:
1 times 12 = 0
2 times 12 = 0
3 times 12 = 0
any ideas?
A:
It is because you have this declaration before for loop:
$i = 0; $num = $i * 12;
so always $num will be 0. Just place it into for:
for ($i=1; $i<13; $i++) {
$num = $i*12;
echo($i." times 12 = ".$num."<br>");
}
You don't need declare $i variable before for loop. This variable will be overwritten. There is simple test:
$i = 5;
for($i = 1; $i<10; $i++);
echo $i;
OUTPUT:
10
| {
"pile_set_name": "StackExchange"
} |
Q:
How to have searchable dropdown in Redux-form
I'm using field-arrays from redux-form and i need a searchable dropdown menu in my form. I know a normal dropdown could be done like this,
<Field name={`${object}.method`} component="select" validate={required} id={`${object}.key`}>
<option value="id">id</option>
<option value="css">css</option>
<option value="xpath">xpath</option>
<option value="binding">binding</option>
<option value="model">model</option>
</Field>
But this is not searchable dropwdownlist. Even if i were to use this, this is only giving a basic html select, how would i be able to apply css style to this to make it match other bootstrap elements?
To have a searchable dropdownlist, I'm using react-select package. What I tried to do was;
<Field
name={`${object}.method`}
type='text'
component={this.renderDropdown}
label="Method"
validate={required}
id={`${object}.key`}
valueField='value'
/>
renderDropdown = ({ input, id, valueField, meta: { touched, error }, ...props }) => {
return (
<React.Fragment>
<div className='align-inline object-field-length'>
<Select {...input} id={id} value={input.value.value} onChange={input.onChange}
options={[
{ value: 'id', label: 'id' },
{ value: 'css', label: 'css' },
{ value: 'xpath', label: 'xpath' },
{ value: 'binding', label: 'binding' },
{ value: 'model', label: 'model' },
]}
/>
</div>
</React.Fragment>
)
};
This is not working correctly, the value is getting stored in the redux-store only when the dropdown is active(when it is being clicked), on event blur this loses the value.
What am i doing wrong here?
Is it possible to have searchable dropdownlist in redux-form?
A:
Answering my own question, finally i figured i couldn't use react-select package with redux-form.
When the value is being selected it gets added to the react-store but loses the value on event blur. This happens because the redux-form onBlur event triggers an action, which passes null in its payload. To avoid this there are a couple of solutions mentioned in the github issue thread
By defining a custom method to handle onBlur did it for me;
renderDropdown = ({ input, onBlur, id, meta: { touched, error }, ...props }) => {
const handleBlur = e => e.preventDefault();
return (
<React.Fragment>
<Select {...input}
id="object__dropdown--width"
options={allRepos}
onChange={input.onChange}
onBlur={handleBlur}
/>
</React.Fragment>
)
}
<Field name="listAllRepo"
value="this.state.accountno"
component={this.renderDropdown}
placeholder="Select"
/>
Hope this would be helpful for someone else!
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL query using where in field in other table
Hello I have 3 tables:
(This is example of users & posts system)
users: id, username, password
posts: id, user_id, content
post_likes: id, user_id, post_id, date
I want to fetch all the post likes that user made to OTHER users only. User can like all posts (his own post and other user's post).
In other words: I don't want to get his likes to posts that himeself published.
Something like (this is not the syntax, just example to express myself better):
SELECT * FROM post_likes WHERE user_id = 3 AND posts.user_id != 3
A:
Try this one
SELECT * FROM post_likes pl
LEFT JOIN posts p ON pl.post_id=p.id
WHERE pl.user_id = 3 AND p.user_id != 3
| {
"pile_set_name": "StackExchange"
} |
Q:
Gradient with Blend tool becomes fragmented, when Opacity is applied
I've created two strokes with gradients and connected them with blend tool.
Once i make one of the strokes 0% opacity the gradient stops looking smooth and starts to look fragmented.
I'm following an Illustrator tutorial. So i know it shouldn't look like that at all and i can't figure what's causing it to look like that.
How to fix it?
edit: When the Illustrator piece is exported it looks fine
A:
No idea is it a bug in Illustrator or in the graphic system. If export is ok, then at least Illustrator knows, how it should be. You can try to reduce the GPU performance in the preferences.
I couldn't repeat your problem because my illustrator is a legacy version which doesn't even as much as yours.
Workarounds:
Check, if you can use the export in Illustrator (if you need it there).
If you need the result in Illustrator as native (=fully editable), you can get the same effect different way. See the cartoon:
Draw a curve and make a copy. Then duplicate the pair.
Make one pair a closed path by connecting and joining the ends.(=select the curves and press twice Ctrl + J) Make the another pair a blend from white to black with the smooth color option.
Fill the closed path with a gradient. Here also a black test background is added to see the next step properly
Drag the BW blend onto the color gradient, select both and in the right top corner of the Transparency panel open the function menu. Select Make Opacity Mask. Now you should have the same result as you wanted.
Another trick to try: When you make your blend, do not take option "Smooth Color", but take "Specified Steps" and type the number of steps so high that the strokes surely overlap.
| {
"pile_set_name": "StackExchange"
} |
Q:
android application error
my xml code is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<com.google.android.maps.MapView
android:id="@+id/mapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:enable="true"
android:clickable="true"
android:apiKey="0THdCiXY7jaJ9Br1ZQahFE4Lu1xTv1hAiVJBvxQ"
/>
</RelativeLayout>
and manifest is:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.haha"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application android:icon="@drawable/icon" android:label="@string/app_name">
<uses-library android:name="com.google.android.maps"/>
<activity android:name=".NewActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
And this is main code:
package com.google.haha;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import android.app.Activity;
import android.os.Bundle;
public class NewActivity extends MapActivity {
/** Called when the activity is first created. */
MapController mControl;
GeoPoint GeoP;
MapView mapV;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapV=(MapView)findViewById(R.id.mapView);
mapV.displayZoomControls(true);
mapV.setBuiltInZoomControls(true);
double lat=21.00;
double longi=79.00;
GeoP=new GeoPoint((int)(lat*1E6),(int)(longi*1E6));
mControl=mapV.getController();
mControl.animateTo(GeoP);
mControl.setZoom(12);
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Everything is fine but I am getting error an on line:
mapV=(MapView)findViewById(R.id.mapView);
id field is not recognised.
A:
try to clean and rebuild your project, because that problem comes up sometimes on Eclipse IDE , the id of your MapView is not recognised on your R.java file :
Project ==> Clean ==> Choose your Project and Clic OK
| {
"pile_set_name": "StackExchange"
} |
Q:
Find a base for which the matrix of a linear transformation is diagonal
Define $T : R^2→R^2 $
by $T(x)=Ax$
Find a basis $B$ for $R^2$ with the property that $[T]_B$ is diagonal.
$$A=\left(\begin{matrix}1 & -7\\-5&3\end{matrix}\right)$$
I have worked out the eigenvalues: $\lambda =-4, 8$
I am confused as to what they're asking, what should I work out and try to prove? So I must find a vector(basis) $B$ so that $T$ with relation to $B$ is diagonal? Must I find the eigenvalues?
A:
First, to find the eigenvalues, you compute $\det A-\lambda I=(1-\lambda)(3-\lambda)-35=(\lambda-8)(\lambda+4)$. Hence the eigenvalues are $8$ and $-4$.
To find an eigenvector associated with $\lambda=8$, you solve the system
$$\left(\begin{matrix}-7&-7\\-5&-5\end{matrix}\right)\left(\begin{matrix}x_1\\x_2\end{matrix}\right)=\left(\begin{matrix}0\\0\end{matrix}\right)$$
This is equivalent to the single equation $x_1+x_2=0$, so there is an arbitrary parameter, say $x_2$, and $x_1=-x_2$. With $x_2=-1$, that yields the eigenvector $(1,-1)^T$.
For the eigenvalue $-4$, the system is
$$\left(\begin{matrix}5&-7\\-5&7\end{matrix}\right)\left(\begin{matrix}x_1\\x_2\end{matrix}\right)=\left(\begin{matrix}0\\0\end{matrix}\right)$$
This is equivalent to the single equation $5x_1-7x_2=0$, so there is also an arbitrary parameter. With $x_2=5$, you get $x_1=7$, so the eigenvector $(7,5)^T$.
Now, the matrix of your new base is $P=\left(\begin{matrix}1&7\\-1&5\end{matrix}\right)$. In this base, the matrix of the transformation $T$ is diagonal: $P^{-1}AP=\left(\begin{matrix}8&0\\0&-4\end{matrix}\right)$.
| {
"pile_set_name": "StackExchange"
} |
Q:
ThreadPool.QueueUserWorkItem inside foreach use same dataset
In the function below always the same user object is passed to the DoRestCall method
(I do have logging in the DoRestCall method and it has the same first data in the user object)
Do I need to use Parallel.ForEach instead of Threadpool
private void CreateUser(DataServiceCollection<User> epUsers)
{
foreach (User user in epUsers)
{
try
{
ThreadPool.QueueUserWorkItem(new WaitCallback(f =>
{
DoRestCall(string.Format("MESSAGE-TYPE=UserEnrollmentCreate&PAYLOAD={0}",
GenarateRequestUserData(user)), true);
}));
}
catch (Exception ex)
{
_logger.Error("Error in CreateUser " + ex.Message);
}
}
}
A:
The problem is how loop variables are handled when used in a lambda expression or anonymous methods. The lambda expression sees the current value of the loop variable at the time the lambda is executed. I believe this behaviour was changed in C# 5.0, but haven't tried it yet.
You need to store the current user in a variable inside the foreach loop and use that instead of the loop variable (also, your try / catch doesn't catch any exceptions inside your WaitCallback, see fix below):
foreach (User user in epUsers)
{
User currentUser = user;
ThreadPool.QueueUserWorkItem(new WaitCallback(f =>
{
try
{
DoRestCall(string.Format("MESSAGE-TYPE=UserEnrollmentCreate&PAYLOAD={0}",
GenarateRequestUserData(currentUser)), true);
}
catch (Exception ex)
{
_logger.Error("Error in CreateUser " + ex.Message);
}
}));
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Postman main source code repository?
I'm looking for the Postman main source code repository. Is this publicly available?
All I seem to be finding on https://github.com/postmanlabs is helper apps.
A:
Looking at the list of pull request and the comments there, it seems like indeed Postman's core application is closed source:
https://github.com/postmanlabs/postman-app-support/pulls?q=is%3Aclosed
| {
"pile_set_name": "StackExchange"
} |
Q:
Calculate overlap durations for time overlaps in MySQL
i have a database table containing events:
CREATE TABLE events
(event VARCHAR(32)
,down_time TIMESTAMP
,up_time TIMESTAMP
,id INT UNSIGNED NOT NULL AUTO_INCREMENT KEY
,INDEX(event(16))
);
INSERT INTO events(event, down_time, up_time) VALUES
('e1', '2015-01-01 00:00:03', '2015-01-01 00:00:08'),
('e2', '2015-01-01 00:00:05', '2015-01-01 00:00:06'),
('e3', '2015-01-01 00:00:02', '2015-01-01 00:00:09'),
('e4', '2015-01-01 00:00:01', '2015-01-01 00:00:04'),
('e5', '2015-01-01 00:00:07', '2015-01-01 00:00:10');
select * from events;
| event | down_time | up_time | id |
+-------+---------------------+---------------------+----+
| e1 | 2015-01-01 00:00:03 | 2015-01-01 00:00:08 | 1 |
| e2 | 2015-01-01 00:00:05 | 2015-01-01 00:00:06 | 2 |
| e3 | 2015-01-01 00:00:02 | 2015-01-01 00:00:09 | 3 |
| e4 | 2015-01-01 00:00:01 | 2015-01-01 00:00:04 | 4 |
| e5 | 2015-01-01 00:00:07 | 2015-01-01 00:00:10 | 5 |
I find event overlaps using the following query (query1):
SELECT *
FROM events a
JOIN events b
ON a.down_time <= b.up_time
AND a.up_time >= b.down_time
WHERE a.id < b.id
AND a.event != b.event
AND a.event regexp 'e[1-5]'
AND b.event regexp 'e[1-5]';
which produces the following event overlaps (results1):
| event | down_time | up_time | id | event | down_time | up_time | id |
+-------+---------------------+---------------------+----+-------+---------------------+---------------------+----+
| e1 | 2015-01-01 00:00:03 | 2015-01-01 00:00:08 | 1 | e2 | 2015-01-01 00:00:05 | 2015-01-01 00:00:06 | 2 |
| e1 | 2015-01-01 00:00:03 | 2015-01-01 00:00:08 | 1 | e3 | 2015-01-01 00:00:02 | 2015-01-01 00:00:09 | 3 |
| e1 | 2015-01-01 00:00:03 | 2015-01-01 00:00:08 | 1 | e4 | 2015-01-01 00:00:01 | 2015-01-01 00:00:04 | 4 |
| e1 | 2015-01-01 00:00:03 | 2015-01-01 00:00:08 | 1 | e5 | 2015-01-01 00:00:07 | 2015-01-01 00:00:10 | 5 |
| e2 | 2015-01-01 00:00:05 | 2015-01-01 00:00:06 | 2 | e3 | 2015-01-01 00:00:02 | 2015-01-01 00:00:09 | 3 |
| e3 | 2015-01-01 00:00:02 | 2015-01-01 00:00:09 | 3 | e4 | 2015-01-01 00:00:01 | 2015-01-01 00:00:04 | 4 |
| e3 | 2015-01-01 00:00:02 | 2015-01-01 00:00:09 | 3 | e5 | 2015-01-01 00:00:07 | 2015-01-01 00:00:10 | 5 |
+-------+---------------------+---------------------+----+-------+---------------------+---------------------+----+
I want to show overlap durations for each row in event overlaps (results1) and currently use the following conditional tests within PHP:
if (a.down_time <= b.down_time && b.up_time <= a.up_time)
{
overlap_duration = b.up_time-b.down_time;
}
else if (a.down_time >= b.down_time && a.up_time <= b.up_time)
{
overlap_duration = a.up_time-a.down_time;
}
else if (a.down_time <= b.down_time)
{
overlap_duration = a.up_time-b.down_time;
}
else if (a.down_time >= b.down_time)
{
overlap_duration = b.up_time-a.down_time;
}
1 2 3 4 5 6 7 8 9 10
| | | | | | | | | |
| | |----------e1-------| | |
| | | | | e2| | | | | a.down_time <= b.down_time && b.up_time <= a.up_time
| |------------e3-------------| | a.down_time >= b.down_time && a.up_time <= b.up_time
|----e4-----| | | | | | | a.down_time >= b.down_time
| | | | | | |-----e5----| a.down_time <= b.down_time
and then produce the following output (results2):
| event | down_time | up_time | duration |
| e1 | 2015-01-01 00:00:03 2015-01-01 00:00:08 00:00:00:05 |
| e2 | 2015-01-01 00:00:05 2015-01-01 00:00:06 00:00:00:01 |
| Overlap1 | 2015-01-01 00:00:05 2015-01-01 00:00:06 00:00:00:01 |
| | |
| e1 | 2015-01-01 00:00:03 2015-01-01 00:00:08 00:00:00:05 |
| e3 | 2015-01-01 00:00:02 2015-01-01 00:00:09 00:00:00:07 |
| Overlap2 | 2015-01-01 00:00:03 2015-01-01 00:00:08 00:00:00:05 |
| | |
| e1 | 2015-01-01 00:00:03 2015-01-01 00:00:08 00:00:00:05 |
| e4 | 2015-01-01 00:00:01 2015-01-01 00:00:04 00:00:00:03 |
| Overlap3 | 2015-01-01 00:00:03 2015-01-01 00:00:04 00:00:00:01 |
| | |
| e1 | 2015-01-01 00:00:03 2015-01-01 00:00:08 00:00:00:05 |
| e5 | 2015-01-01 00:00:07 2015-01-01 00:00:10 00:00:00:03 |
| Overlap4 | 2015-01-01 00:00:07 2015-01-01 00:00:08 00:00:00:01 |
| | |
| e2 | 2015-01-01 00:00:05 2015-01-01 00:00:06 00:00:00:01 |
| e3 | 2015-01-01 00:00:02 2015-01-01 00:00:09 00:00:00:07 |
| Overlap5 | 2015-01-01 00:00:05 2015-01-01 00:00:06 00:00:00:01 |
| | |
| e3 | 2015-01-01 00:00:02 2015-01-01 00:00:09 00:00:00:07 |
| e4 | 2015-01-01 00:00:01 2015-01-01 00:00:04 00:00:00:03 |
| Overlap6 | 2015-01-01 00:00:02 2015-01-01 00:00:04 00:00:00:02 |
| | |
| e3 | 2015-01-01 00:00:02 2015-01-01 00:00:09 00:00:00:07 |
| e5 | 2015-01-01 00:00:07 2015-01-01 00:00:10 00:00:00:03 |
| Overlap7 | 2015-01-01 00:00:07 2015-01-01 00:00:09 00:00:00:02 |
+-----------+-----------------------------------------------------------+
I suspect it may be better to calculate overlap durations within MySQL by processing results1 to produce results2
but not sure how best to proceed .. if at all? Thanks in advance.
A:
This should work as expected
SELECT
a.*,
b.*,
(least(a.up_time, b.up_time) - greatest(a.down_time, b.down_time)) as overlap_seconds
FROM events a
JOIN events b
ON a.down_time <= b.up_time
AND a.up_time >= b.down_time
WHERE a.id < b.id
AND a.event != b.event
AND a.event regexp 'e[1-5]'
AND b.event regexp 'e[1-5]'
GROUP BY a.id, b.id;
to get the overlap, all you need to do is compare the "smallest" up_time with the "biggest" down_time for each row ...
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I do dependency injection with service in Angular 5?
How do I do dependency injection with service?
I got the typescript notification:
[Angular] Can't resolve all parameters for LandingComponent in
landing.component.ts:
([object Object], ?).
Update
I shouldn't do just use LangService in constructor like this:
private _langService: LangService;
Because LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.
Service and it's interface
export interface ILangService {
}
export class LangService implements ILangService {
}
Component
import { ILangService } from '../../services/Ilang.service';
@Component({
selector: 'app-landing',
templateUrl: './landing.component.html',
styleUrls: ['./landing.component.less']
})
export class LandingComponent {
private langService: ILangService
constructor(
private http: HttpClient,
_langService: ILangService;
) {
this._langService = langService;
}
}
app.module.ts
import { ILangService } from './services/Ilang.service';
import { LangService } from './services/Lang.service';
@NgModule({
declarations: [
AppComponent,
LandingComponent,
],
imports: [
BrowserModule,
HttpClientModule,
RouterModule.forRoot([
{ path: '', component: LandingComponent },
], { useHash: false }),
],
providers: [
LangService
],
bootstrap: [AppComponent]
})
export class AppModule { }
A:
Updated Answer
If you want to use different implementations for the same service you should create an InjectionToken<T> and provide the right implementation for your interface in your module declarations.
Interface - lang.service.ts
Create an injection token that will be recognized by the injector typed with ILangService interface
export const LangService = new InjectionToken<ILangService>('LangService');
export interface ILangService { }
1st module - english.module.ts
Provide EnglishLangService for the LangService injection token where EnglishLangService implements ILangService interface
import { LangService } from './services/lang.service';
import { EnglishLangService } from './services/english-lang.service';
@NgModule({
declarations: [ LandingComponent ],
providers: [
{ provide: LangService, useClass: EnglishLangService }
]
})
export class EnglishModule { }
2nd module - french.module.ts
Provide FrenchLangService for the LangService injection token where FrenchLangService implements ILangService interface
import { LangService } from './services/lang.service';
import { FrenchLangService } from './services/french-lang.service';
@NgModule({
declarations: [ LandingComponent ],
providers: [
{ provide: LangService, useClass: FrenchLangService }
]
})
export class FrenchModule { }
Component - landing.component.ts
This way you can inject LangService in your component and the injector will retrieve the implementation provided in your module
import { LangService } from '../../services/lang.service';
@Component({
selector: 'app-landing',
templateUrl: './landing.component.html',
styleUrls: ['./landing.component.less']
})
export class LandingComponent {
constructor(
private http: HttpClient,
private langService: LangService,
) { }
}
Testing - mock-lang.service.ts
When testing you will be able to provide your mock implementation the same way you provide the right implementation in your application modules
import { LangService } from './services/lang.service';
import { MockLangService } from './services/mock-lang.service';
TestBed.configureTestingModule({
providers: [
{ provide: LangService, useClass: MockLangService },
],
});
Original Answer
You should import your service with the class instead of the interface
import { LangService } from '../../services/lang.service';
@Component({
selector: 'app-landing',
templateUrl: './landing.component.html',
styleUrls: ['./landing.component.less']
})
export class LandingComponent {
constructor(
private http: HttpClient,
private langService: LangService;
) { }
}
Also don't forget to set the @Injectable() decorator on your service class declaration
import { Injectable } from '@angular/core';
@Injectable()
export class LangService implements ILangService { }
And of course, you have to provide the service to your module
import { LangService } from './services/Lang.service';
@NgModule({
declarations: [
AppComponent,
LandingComponent,
],
imports: [ ... ],
providers: [
LangService
],
bootstrap: [AppComponent]
})
export class AppModule { }
You can read about Angular Dependency Injection here: https://angular.io/guide/dependency-injection
Another interesting link for advance service declarations: https://offering.solutions/blog/articles/2018/08/17/using-useclass-usefactory-usevalue-useexisting-with-treeshakable-providers-in-angular/
| {
"pile_set_name": "StackExchange"
} |
Q:
Developing call/vocie recording app (iphone)?
I want to make an iphone application to record the incoming and outgoing calls. If I can't develop such app , What are the technology and hardware hindrance in doing so ? BTW i was thinking to run my app in background while call, Hence recording the input and output voice through my app .
A:
An iPhone application doesn't have access to the voice channel in an iPhone in any circumstances. Which is a good thing, as having a background application recording voice could have very bad side effects.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.