input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Java - Unzip and Progress Bar <p>My program uses Tasks from JavaFX to download and unzip files and to show the progress on the screen, by using the <code>updateProgress(workDone, max)</code> method and the <code>progressProperty().bind(observable)</code> method.
It works for Download : </p>
<pre><code>package com.franckyi.lan.installer;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Paths;
import javafx.concurrent.Task;
public class DownloadTask extends Task<Void> {
private String file;
private String url;
public DownloadTask(String dir, String fileurl) {
file = dir;
url = fileurl;
}
@Override
protected Void call() throws Exception {
URLConnection connection = new URL(url).openConnection();
long fileLength = connection.getContentLengthLong();
try (InputStream is = connection.getInputStream();
OutputStream os = Files.newOutputStream(Paths.get(file))) {
long nread = 0L;
byte[] buf = new byte[1024];
int n;
while ((n = is.read(buf)) > 0) {
os.write(buf, 0, n);
nread += n;
updateProgress(nread, fileLength);
}
}
return null;
}
@Override
protected void succeeded(){
System.out.println("Download succeeded");
}
}
</code></pre>
<p>But it doesn't work well for Unzip : The file is correctly unzipped but I get a wrong ProgressBar (empty at the end).</p>
<pre><code>package com.franckyi.lan.installer;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javafx.concurrent.Task;
public class UnZipTask extends Task<Void>{
private File zipfile;
private File folder;
public UnZipTask(File zipfile, File folder){
this.zipfile = zipfile;
this.folder = folder;
}
@Override
protected Void call() throws Exception {
ZipInputStream zis = new ZipInputStream(
new BufferedInputStream(new FileInputStream(zipfile.getCanonicalFile())));
ZipEntry ze = null;
try {
while ((ze = zis.getNextEntry()) != null) {
File f = new File(folder.getCanonicalPath(), ze.getName());
if (ze.isDirectory()) {
f.mkdirs();
continue;
}
f.getParentFile().mkdirs();
OutputStream fos = new BufferedOutputStream(new FileOutputStream(f));
try {
try {
final byte[] buf = new byte[1024];
int bytesRead;
long nread = 0L;
long length = zipfile.length();
while (-1 != (bytesRead = zis.read(buf))){
fos.write(buf, 0, bytesRead);
nread += bytesRead;
System.out.println(nread + "/" + length);
updateProgress(nread, length);
}
} finally {
fos.close();
}
} catch (final IOException ioe) {
f.delete();
throw ioe;
}
}
} finally {
zis.close();
}
return null;
}
@Override
protected void succeeded(){
System.out.println("Unzip succeeded");
}
}
</code></pre>
<p>This is what I get in the console :</p>
<pre><code>Download succeeded
1024/91804
2048/91804
2815/91804
362/91804
326/91804
290/91804
386/91804
257/91804
250/91804
588/91804
1101/91804
1613/91804
2128/91804
2646/91804
3159/91804
3672/91804
4185/91804
4701/91804
5214/91804
5731/91804
6243/91804
6755/91804
7272/91804
7793/91804
8326/91804
8862/91804
9379/91804
9897/91804
10411/91804
10927/91804
11442/91804
11956/91804
12437/91804
447/91804
437/91804
978/91804
1525/91804
2040/91804
454/91804
1056/91804
1568/91804
2089/91804
2672/91804
3198/91804
3728/91804
4282/91804
4826/91804
5377/91804
5891/91804
6413/91804
6941/91804
7480/91804
8027/91804
8565/91804
9088/91804
9609/91804
9794/91804
507/91804
1019/91804
1531/91804
2043/91804
2239/91804
134/91804
548/91804
1292/91804
2316/91804
2584/91804
507/91804
837/91804
135/91804
486/91804
1001/91804
1514/91804
2027/91804
2545/91804
3057/91804
3571/91804
4086/91804
4599/91804
5113/91804
5627/91804
6144/91804
6655/91804
7166/91804
7679/91804
8196/91804
8710/91804
9229/91804
9745/91804
10259/91804
10773/91804
11288/91804
11802/91804
12321/91804
12834/91804
13348/91804
13864/91804
14378/91804
14893/91804
15407/91804
15918/91804
16431/91804
16944/91804
17458/91804
17971/91804
18484/91804
18997/91804
19508/91804
20021/91804
20535/91804
21047/91804
21560/91804
22072/91804
22584/91804
23096/91804
23609/91804
24122/91804
24638/91804
25149/91804
25664/91804
26176/91804
26689/91804
27203/91804
27715/91804
28227/91804
28739/91804
29251/91804
29764/91804
30277/91804
30789/91804
31301/91804
31813/91804
32325/91804
32838/91804
33306/91804
33819/91804
34333/91804
34846/91804
35357/91804
35869/91804
36381/91804
36894/91804
37407/91804
37922/91804
38435/91804
38948/91804
39460/91804
39972/91804
40488/91804
41002/91804
41514/91804
42028/91804
42540/91804
43052/91804
43566/91804
44079/91804
44594/91804
45105/91804
45619/91804
46132/91804
46644/91804
47156/91804
47668/91804
48180/91804
48692/91804
49204/91804
49716/91804
50228/91804
50741/91804
51252/91804
51765/91804
52277/91804
52790/91804
53305/91804
53821/91804
54335/91804
54852/91804
55365/91804
55881/91804
56396/91804
56442/91804
545/91804
1287/91804
2311/91804
2584/91804
507/91804
845/91804
4/91804
Unzip succeeded
</code></pre>
<p>Can someone help me ?</p>
| <p>It is because you use length of compressed zipFile as the maximum, and the count of bytes raeded from each uncompressed zipEntry as the postion - the size of compressed file is in most cases different from the uncompressed one, also you can have multiple files in the zip package - so the progres will jump from 0 to some value (the size of actual zipEntry not the compressed zipFile length) for each one in this case. To have the actual position in a zip file, get the reference to <code>FileChannel</code> from the <code>FileInputStream</code>, using this method: <code>FileInputStream#getChannel();</code></p>
<p>then when it comes to update the progres do:</p>
<pre><code> updateProgress(channel.position(), length);
</code></pre>
<p>This will update the progress bar according to the actual position that was readed in the zipFile (not the size of uncompressed content).</p>
<p>It could be something like:</p>
<pre><code>package com.franckyi.lan.installer;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javafx.concurrent.Task;
public class UnZipTask extends Task<Void>{
private File zipfile;
private File folder;
public UnZipTask(File zipfile, File folder){
this.zipfile = zipfile;
this.folder = folder;
}
@Override
protected Void call() throws Exception {
FileInputStream is = new FileInputStream(zipfile.getCanonicalFile());
FileChannel channel = is.getChannel();
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
ZipEntry ze = null;
try {
while ((ze = zis.getNextEntry()) != null) {
File f = new File(folder.getCanonicalPath(), ze.getName());
if (ze.isDirectory()) {
f.mkdirs();
continue;
}
f.getParentFile().mkdirs();
OutputStream fos = new BufferedOutputStream(new FileOutputStream(f));
try {
try {
final byte[] buf = new byte[1024];
int bytesRead;
long nread = 0L;
long length = zipfile.length();
while (-1 != (bytesRead = zis.read(buf))){
fos.write(buf, 0, bytesRead);
nread += bytesRead;
System.out.println(nread + "/" + length);
updateProgress(channel.position(), length);
}
} finally {
fos.close();
}
} catch (final IOException ioe) {
f.delete();
throw ioe;
}
}
} finally {
zis.close();
}
return null;
}
@Override
protected void succeeded(){
System.out.println("Unzip succeeded");
}
}
</code></pre>
|
Prevent text wrapping within an element <p>How can you force text within an element to not wrap, and have the element's width still determined by its contents (instead of manually setting width)?</p>
<p><strong>Example:</strong></p>
<p>On this page you can see a green button with the text "Get Started". For smaller screen sizes, the text wraps. How can I prevent this?</p>
<p><a href="https://pleth-test.herokuapp.com/" rel="nofollow">https://pleth-test.herokuapp.com/</a></p>
<p>I tried using <code>overflow</code> and <code>text-wrap</code> CSS properties, but couldn't get anything to work.</p>
| <p>Add this to your css:</p>
<pre><code>white-space: nowrap;
</code></pre>
|
Application Not Working Correctly C# <p>My code isn't storing a response as user input. It jumps to the else statement every time I get here. Then it throws the sum as 50? When I store input like Value of first number = 2 and value of second = 3.
I'm doing a class at home and I have been working for a few hours trying to figure out why my code doesn't work right.
C#, below:</p>
<pre><code> Console.Write("Would you like to stop adding here (a) or add another number (b)? ");
bool stopOrContinueAdding = true;
do
{
string inputMoreNumbers = Console.ReadLine();
switch (inputMoreNumbers.ToLower())
{
case "a":
inputMoreNumbers = "a";
stopOrContinueAdding = false;
break;
case "b":
inputMoreNumbers = "b";
stopOrContinueAdding = true;
break;
default:
stopOrContinueAdding = false;
break;
}
if (stopOrContinueAdding == false)
{
int sum = aNum.Sum();
Console.WriteLine("Here is the sum of your numbers: " + sum );
System.Threading.Thread.Sleep(4000);
Console.WriteLine("Redirecting to main menu...");
System.Threading.Thread.Sleep(2000);
Console.Clear();
Console.Write("Addition(a), Subraction(s), Multiplication(x), or Division(d)? ");
isInputValid = false;
}
else
{
Console.Clear();
Console.Write("Value of next number: ");
number++;
aNum[number - 1] = Convert.ToInt32(Console.Read());
Console.Write("Would you like to stop adding here (a) or add another number (b)? ");
}
} while (stopOrContinueAdding != true) ;
</code></pre>
<p>I'm not entirely sure where I went wrong. I'd like to understand more :(</p>
<p>Thanks!</p>
| <p>In your addition calculator, changing the following line:</p>
<pre><code>aNum[number - 1] = Convert.ToInt32(Console.Read());
</code></pre>
<p>from Console.Read() to Console.ReadLine() seems to fix the issue. ReadLine() will block the execution until Enter is hit - Read() will not... So when you enter your second number and hit Enter, it executes your next ReadLine() statement (where you are expecting "a" or "b" depending on whether they want to continue) as a blank string.</p>
|
Error: Declaration of non-variable 'strlen' in 'for' loop initial declaration - C <p>The title is the exact error my compiler(geany on ubuntu) gives me when I try to compile. The part of code in question is the following:</p>
<pre><code>for(int q=strlen(stringA)-1;q>0;q--)
{
//do stuff
}
</code></pre>
<p>I've already set the C99 mode and the initialization of variables in the 'for' header is accepted. Is what I did simply illegal in C?</p>
| <p>I assume you are missing an include. Try:</p>
<p><code>#include <string.h></code></p>
|
counter not inceasing in python <p>I have looked at other while loops and am stuck on why this one is not working.</p>
<pre><code>points = int(input('How many points: '))
while True:
u_cnt, c_cnt = 0, 0
if u_cnt < points or c_cnt < points:
if u < c:
c_cnt += 1
elif u > c:
u_cnt += 1
</code></pre>
<p>Is my problems having the <code>c_cnt += 1</code> inside of two if statements?</p>
<p>I have put it outside of the <code>while</code> loop, yet that doesn't increase count either. I have also put the <code>u_cnt = 0</code> and <code>c_cnt = 0</code> on separate lines.</p>
<p>It's not doing an infinite loop, as it should not do. It's just not incrementing.</p>
<p>Thank you</p>
<p>edit:</p>
<pre><code>import random
u_name = input('What is your name? ')
points = int(input('How many points: '))
u_cnt, c_cnt = 0, 0
while True:
a = ['rock', 'paper', 'scissors']
comp = random.choice(a)
print('Pick from:', str(a).strip('[]'))
user = input()
u = a.index(user)
c = a.index(comp)
line_1 = '{} : {}\t{} : {}'.format(u_name, user, 'Computer', comp)
line_2 = '{} : {}\t{} : {}\n'.format(u_name, u_cnt, 'Computer', c_cnt)
if c_cnt < points or u_cnt < points:
if u > c or u == 0 and c == 2:
u_cnt += 1
print(line_1, '\t', u_name, 'wins')
print(line_2)
elif u < c or u == 2 and c == 0:
c_cnt += 1
print(line_1, '\t', 'Computer wins')
print(line_2)
elif u == c:
print(line_1, '\t', 'Tie')
print(line_2)
else:
break
</code></pre>
<p>so when you run this the first time, you get an answer back like</p>
<pre><code>What is your name? chad
How many points: 3
Pick from: 'rock', 'paper', 'scissors'
rock
chad : rock Computer : scissors chad wins
chad : 0 Computer : 0
Pick from: 'rock', 'paper', 'scissors'
</code></pre>
<p>how to get the count be 1, 0 on the first iteration through. that might be a better question.</p>
| <p>The code have to be right there:</p>
<pre><code>points = int(input('How many points: '))
u_cnt, c_cnt = 0, 0 # asign the values before the loop
while True:
if u_cnt < points or c_cnt < points:
if u < c:
c_cnt += 1
elif u > c:
u_cnt += 1
</code></pre>
|
Ruby docs rindex example <p>This example is from the ruby docs.</p>
<pre><code>"hello".rindex(/[aeiou]/, -2) #=> 1
</code></pre>
<p>Why does this output 1 instead of 4? </p>
| <p>Because the second parameter. From the doc</p>
<blockquote>
<p>If the second parameter is present, it specifies the position in the
string to end the searchâcharacters beyond this point will not be
considered.</p>
</blockquote>
<p>So</p>
<pre><code>"hello".rindex(/[aeiou]/)
=> 4
</code></pre>
|
hybris commerce 5.7 and 6.1 installation and administration guide <p>I have downloaded hybris commerce 5.7 and 6.1 as a sap partner .
Where can I find detailed installation and administration guide ? does sap provide it ?</p>
| <p>The main page: <a href="https://wiki.hybris.com/dashboard.action" rel="nofollow">wiki.hybris</a></p>
<p>hybris release 5 documentation: <a href="https://wiki.hybris.com/display/release5/Release+5+Documentation+Home" rel="nofollow">Release-5-Documentation</a></p>
<p>hybris release 6 page: <a href="https://help.hybris.com/6.1.0/hcd/8c39af1286691014b2daed4f092998ca.html" rel="nofollow">Release-6</a></p>
<p>Another useful website: <a href="https://experts.hybris.com/" rel="nofollow">experts.hybris.com</a> - aggregates questions/answers/tips&tricks connected with hybris.</p>
|
configuring pyramid_beaker to use with mysql <p>i am using pyramid_beaker as session factory .I want to save session in mysql database.so i want to know how to configure that?
i have gone through this
<a href="http://docs.pylonsproject.org/projects/pyramid_beaker/en/latest/" rel="nofollow">http://docs.pylonsproject.org/projects/pyramid_beaker/en/latest/</a>
but it does not solve my problem.
it does not give clue where to write mysql username ,password etc.</p>
| <p>pyramid_beaker is a thin wrapper around beaker which can pull the settings from your INI file into beaker. Beaker [1] itself which contains docs on how to use its various backends. For example, if you're using the <code>beaker.ext.database</code> backend, then you should set <code>session.url = mysql://user:password@host:port/dbname</code> just like any other SQLAlchemy connection string.</p>
<p>[1] <a href="https://beaker.readthedocs.io/en/latest/configuration.html#options-for-sessions-and-caching" rel="nofollow">https://beaker.readthedocs.io/en/latest/configuration.html#options-for-sessions-and-caching</a></p>
|
Find positions of transparent areas in images using PIL <p>I want to fill transparent blocks in images by others images.
For example:
In this images we have 4 transparent blocks, witch need to fill.</p>
<p>Need to find positions of the blocks and determine x,y,x2,y2 coords so i will know how to resize the thumbnail to.</p>
<p><a href="https://i.stack.imgur.com/2pt93.png" rel="nofollow"><img src="https://i.stack.imgur.com/2pt93.png" alt="Image with transparent"></a></p>
<p>Someone know how i can do that using PIL, or maybe, unix tools.
Thanks for any help</p>
| <p>You can do that at the command-line with <strong>ImageMagick</strong>, or in Python, Perl, PHP or C/C++.</p>
<p>First, extract the alpha channel:</p>
<pre><code>convert input.png -alpha extract alpha.png
</code></pre>
<p><a href="https://i.stack.imgur.com/eD04t.png" rel="nofollow"><img src="https://i.stack.imgur.com/eD04t.png" alt="enter image description here"></a></p>
<p>But I am going to do morphology and I want white on black, so invert it:</p>
<pre><code>convert input.png -alpha extract -negate alpha.png
</code></pre>
<p><a href="https://i.stack.imgur.com/R6ppT.png" rel="nofollow"><img src="https://i.stack.imgur.com/R6ppT.png" alt="enter image description here"></a></p>
<p>Now run a <em>"Connected Components"</em> analysis to find the blobs of white:</p>
<pre><code>convert input.png -alpha extract -negate -threshold 50% \
-define connected-components:verbose=true \
-define connected-components:area-threshold=100 \
-connected-components 8 -auto-level null:
</code></pre>
<p><strong>Output</strong></p>
<pre><code>Objects (id: bounding-box centroid area mean-color):
0: 600x376+0+0 249.7,205.3 129723 srgb(0,0,0)
2: 203x186+70+20 170.8,112.6 27425 srgb(255,255,255)
1: 218x105+337+13 445.5,65.0 22890 srgb(255,255,255)
4: 218x105+337+251 445.5,303.0 22890 srgb(255,255,255)
3: 218x104+337+132 445.5,183.5 22672 srgb(255,255,255)
</code></pre>
<p>And there they are. Ignore the first row because it is black and corresponds to the whole image. Now, look at the second row and you can see the block is 203x186 at offset +70+20. The centroid is there too. Let me box that blob in in red:</p>
<pre><code>convert input.png -stroke red -fill none -draw "rectangle 70,20 272,205" z.png
</code></pre>
<p><a href="https://i.stack.imgur.com/BJS2k.png" rel="nofollow"><img src="https://i.stack.imgur.com/BJS2k.png" alt="enter image description here"></a></p>
|
How to force Windows to create the running user's profile directory <p>I am having an issue with a process being run, where the profile directory of the process' user has not yet been created.</p>
<p>To explain, here are the details of how this is happening:</p>
<p>We run a large distributed server grid, and are using (parts of) DataSynapse to execute processes on this grid. For those familiar with DataSynapse, the Engine is configured to run the particular service with "RunAs", where we use a certain AD domain service account for the service processes. I believe the problem is that DataSynapse, when running the process under "runas", does not set the <code>LoadUserProfile</code> flag (nor should it). Whatever the precise reason, if the "runas" service account (and AD domain account) has never logged on to some of the grid machines, then those machines will not have the user profile directory for the account.</p>
<p>For those not familiar with DataSynapse, here is a more generic explanation. On each machine on the grid, there is a process running, I'll call it <code>dsService</code>, and it runs under the credentials of the local machine's system account (or some similar account with elevated credentials). The process <code>dsService</code> will spawn a child process, say <code>childProcess</code>, but it runs <code>childProcess</code> under the credentials of our AD domain account, which I'll call <code>serviceUser</code>. There are thousands of machines on the grid, and typically they are never logged on to manually. In particular, the profile directory <code>C:\users\serviceUser</code> may not initially exist. Once it is created once, there are not further issues. But if new nodes are added to the grid, typically they will not have the <code>C:\users\serviceUser</code> initially. The problem is that when the <code>dsService</code> spawns <code>childProcess</code>, <code>C:\users\serviceUser</code> does not get created, and we need it.</p>
<p>I <em>believe</em> that this is because <code>dsService</code> does not set the <code>LoadUserProfile</code> flag to true when spawning <code>childProcess</code>, though I am not certain.</p>
<p>In any event, <code>childProcess</code> is a (.net) process (running as <code>serviceUser</code>) under our control, and <strong>I would like to know if there is a way (in C#) that <code>childProcess</code> can force the OS to create the running user's profile directory</strong> <code>C:\users\serviceUser</code> when it determines that it does not yet exist?</p>
<p>Edit:
Experimentation has confirmed that if one starts a process under another user ID, and the user's profile directory is not there (more specifically, if the user's <em>local profile</em> has not been created yet - merely deleting a pre-existing profile directory creates a different situation, one we're not interested in anyway), then (1) the profile directory (and one presumes, the local profile) gets created if the process is started with the <code>LoadUserProfile</code> set to true; and (2) the profile directory (and one presumes, the local profile) does NOT get created if the process is started with the <code>LoadUserProfile</code> set to false. This makes sense, and is as one would expect.</p>
<p>Related post: stackoverflow.com/q/9008742/1082063</p>
| <p>If the running account has admin privileges, the following code will cause the creation of the running account's profile, including its UserProfile directory. Without admin, I don't know if it is possible:</p>
<pre><code>using System.Runtime.InteropServices;
...
[DllImport("userenv.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int CreateProfile(
[In] string pszUserSid,
[In] string pszUserName,
System.Text.StringBuilder pszProfilePath,
int cchProfilePath);
....
public static string getUserProfilePath()
{
string userProfilePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
if(string.IsNullOrWhiteSpace(userProfilePath) || !Directory.Exists(userProfilePath))
{ //This will only work if we have admin...
var pathBuf = new System.Text.StringBuilder(240);
var Up = System.DirectoryServices.AccountManagement.UserPrincipal.Current;
if( 0 == CreateProfile(Up.Sid.ToString(), Up.SamAccountName, pathBuf, pathBuf.Capacity) }
{
userProfilePath = pathBuf.ToString();
}
}
return userProfilePath;
}
</code></pre>
<p>If anyone can tell me how to do this when the account is not admin, they will get their answer accepted as the correct answer. Until then, this at least gives others some idea.</p>
|
xPages radiobutton group onchange event doesn't work <p>Here is my simple page whit a listbox control that should refresh its values according to the radiobutton group selection. The list box uses a scope variable array as a source. So when I click on the radiobutton I want to change list box values. It works after first/second click then it does not refresh list box then it works again. What am I doing wrong?</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">
<xp:this.beforePageLoad><![CDATA[#{javascript:viewScope.MYARRAY = new Array();
viewScope.MYARRAY.push(["NAME1", "ID1"]);
viewScope.MYARRAY.push(["NAME2", "ID3"]);
viewScope.MYARRAY.push(["NAME3", "ID4"]);
viewScope.MYARRAY.push(["NAME4", "ID5"]);}]]>
</xp:this.beforePageLoad>
<xp:radioGroup id="radioGroupSortBy" defaultValue="0">
<xp:selectItem itemLabel="by Name" itemValue="0"></xp:selectItem>
<xp:selectItem itemLabel="by Id" itemValue="1"></xp:selectItem>
<xp:eventHandler event="onchange" submit="true"
refreshMode="partial" refreshId="listBox1">
</xp:eventHandler>
<xp:eventHandler event="onclick" submit="true"
refreshMode="partial" refreshId="listBox1">
</xp:eventHandler>
</xp:radioGroup>
<xp:listBox id="listBox1" style="width:390.0px;height:166.0px">
<xp:selectItems>
<xp:this.value><![CDATA[#{javascript:var arr = new Array();
for(var i=0; i<viewScope.MYARRAY.length; i++){
if(getComponent("radioGroupSortBy").getValue()==0){
arr.push(viewScope.MYARRAY[i][0] + " - " + viewScope.MYARRAY[i][1]);
} else {
arr.push(viewScope.MYARRAY[i][1] + " - " + viewScope.MYARRAY[i][0]);
}
}
return arr.sort();}]]>
</xp:this.value>
</xp:selectItems>
</xp:listBox>
</xp:view>
</code></pre>
| <p>Radio button events can be strange with certain browsers (IE). Do you have this setting in your xsp properties file?</p>
<p><a href="http://www-01.ibm.com/support/docview.wss?uid=swg21631834" rel="nofollow">http://www-01.ibm.com/support/docview.wss?uid=swg21631834</a></p>
<p>Don't use both onclick and on change.</p>
<p>Howard </p>
|
Constant 'XXX' used before being initialized <p>I am new in swift .. anyone help me to understand why this error throwing </p>
<blockquote>
<p>Constant 'parsedResult' used before being initialized </p>
</blockquote>
<p>on the other hand if i set <code>return</code> in the <code>catch</code> then compile error gone .what is the relation each other. explain please .</p>
<p>Here is my code :</p>
<pre><code> if let data = data {
let parsedResult : AnyObject!
do {
parsedResult = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
}
catch{
print("something worng ")
// return
}
// error compiler error this line
print(parsedResult)
}
</code></pre>
| <p>This is easily fixed by declaring parseResult as AnyObject? which means it will be initialised to nil. The print will print an optional value which it can do just fine. </p>
<p>Be careful with the words you use. "// error throwing this line " is totally misleading. There is no error thrown at this line. Errors are thrown at runtime. You have the compiler reporting an error at this line. Be precise. </p>
|
Cannot import urllib in Python <p>I would like to import <code>urllib</code> to use the function '<code>request</code>'. However, I encountered an error when trying to download via Pycharm: </p>
<blockquote>
<p>"Could not find a version that satisfies the requirement urllib (from versions: ) No matching distribution found for urllib" </p>
</blockquote>
<p>I tried <code>pip install urllib</code> but still had the same error. I am using Python 2.7.11. Really appreciate any help</p>
| <p>A few things:</p>
<ol>
<li>As metioned in the comments, <code>urllib</code> is not installed through <code>pip</code>, it is part of the standard library, so you can just do <code>import urllib</code> without installation. </li>
<li>Python 3.x has a <a href="https://docs.python.org/3/library/urllib.request.html" rel="nofollow"><code>urllib.request</code></a> module, but Python 2.x does not, as far as I know.</li>
<li><p>The functionality that you are looking for from <code>urllib.request</code> is most likely contained in <a href="https://docs.python.org/2/library/urllib2.html#module-urllib2" rel="nofollow"><code>urllib2</code></a> (which is also part of the standard library), but you might be even better off using <a href="http://docs.python-requests.org/en/master/" rel="nofollow"><code>requests</code></a>, which probably does need to be installed through <code>pip</code> in your case:</p>
<pre><code>pip install requests
</code></pre>
<p>In fact, the <code>urllib2</code> documentation itself recommends that you use the <code>requests</code> library "for a higher-level HTTP client interface" - but I am not sure what you wish to do, so it is hard to say what would be best for your particular use case. </p></li>
</ol>
|
More efficient way to loop through PySpark DataFrame and create new columns <p>I am converting some code written with Pandas to PySpark. The code has a lot of <code>for</code> loops to create a variable number of columns depending on user-specified inputs.</p>
<p>I'm using Spark 1.6.x, with the following sample code:</p>
<pre><code>from pyspark.sql import SQLContext
from pyspark.sql import functions as F
import pandas as pd
import numpy as np
# create a Pandas DataFrame, then convert to Spark DataFrame
test = sqlContext.createDataFrame(pd.DataFrame({'val1': np.arange(1,11)}))
</code></pre>
<p>Which leaves me with </p>
<pre><code>+----+
|val1|
+----+
| 1|
| 2|
| 3|
| 4|
| 5|
| 6|
| 7|
| 8|
| 9|
| 10|
+----+
</code></pre>
<p>I loop a lot in the code, for example the below:</p>
<pre><code>for i in np.arange(2,6).tolist():
test = test.withColumn('val_' + str(i), F.lit(i ** 2) + test.val1)
</code></pre>
<p>Which results in: </p>
<pre><code>+----+-----+-----+-----+-----+
|val1|val_2|val_3|val_4|val_5|
+----+-----+-----+-----+-----+
| 1| 5| 10| 17| 26|
| 2| 6| 11| 18| 27|
| 3| 7| 12| 19| 28|
| 4| 8| 13| 20| 29|
| 5| 9| 14| 21| 30|
| 6| 10| 15| 22| 31|
| 7| 11| 16| 23| 32|
| 8| 12| 17| 24| 33|
| 9| 13| 18| 25| 34|
| 10| 14| 19| 26| 35|
+----+-----+-----+-----+-----+
</code></pre>
<p>**Question: ** How can I rewrite the above loop to be more efficient?</p>
<p>I've noticed that my code runs slower as Spark spends a lot of time on each group of loops (even on small datasets like 2GB of text input).</p>
<p>Thanks</p>
| <p>There is a small overhead of repeatedly calling JVM method but otherwise for loop alone shouldn't be a problem. You can improve it slightly by using a single select:</p>
<pre><code>df = spark.range(1, 11).toDF("val1")
def make_col(i):
return (F.pow(F.lit(i), 2) + F.col("val1")).alias("val_{0}".format(i))
spark.range(1, 11).toDF("val1").select("*", *(make_col(i) for i in range(2, 6)))
</code></pre>
<p>I would also avoid using NumPy types. Initializing NumPy objects is typically more expensive compared to plain Python objects and Spark SQL doesn't support NumPy types so there some additional conversions required.</p>
|
How to open the chrome browser to a chrome dev tool url <p>With the most recent version of node,</p>
<p>Typing <code>node --inspect ajavascriptfile.js</code></p>
<p>Outputs a url for you to visit in your chrome browser, great!</p>
<p>(Documentation for V8 inspector <a href="https://nodejs.org/api/debugger.html#debugger_v8_inspector_integration_for_node_js" rel="nofollow">here</a>)</p>
<p>But how can I open that url with my terminal?</p>
<p>I can open the browser for files or urls with:</p>
<p><code>open -a Google\ Chrome ./path/to/file.html</code></p>
<p>or</p>
<p><code>open -a Google\ Chrome http://google.com</code></p>
<p>But trying the same for the url:</p>
<p><code>open -a Google\ Chrome chrome-devtools://devtools/remote/se...</code></p>
<p>Gives me the error:</p>
<pre><code>The file /Users/samhouston/proj/chrome-devtools:/devtools/remote/se... does not exist.
</code></pre>
<p>How can I get chrome to open its browser to this url through my terminal?</p>
<p>Thanks in advance for the help</p>
| <p><code>open</code> doesn't support the <code>chrome-devtools</code> protocol, so it just tries to open a local file path instead. Since it doesn't exist, it gives you the error you are getting. </p>
<p>I looked around for another solution and I found that you can use an <code>osascript</code> to tell the application itself to open the URL.</p>
<pre><code>/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome & osascript -e 'tell application "Google Chrome" to open location "chrome-devtools://devtools/remote/serve_file/@60cd6e859b9f557d2312f5bf532f6aec5f284980/inspector.html?experiments=true&v8only=true&ws=localhost:9229/node"'
</code></pre>
|
How taxing would running an NSTimer every second be? <p>I've got a tableview of information that is locked/unlocked based on timestamps.</p>
<p>If I've got cell A B and C and they unlock in 30 seconds, 1 min, and 1min 30 respectively based on timestamps pulled from Firebase, I need a way to check those timestamps to unlock them, aka enable them being able to select the cell.</p>
<p>The only way I can think of doing this is to set up a NSTimer that runs every second to check against an array of a Post Class which would have a timestamp attribute and a locked attribute. When the view loads I'd check the timestamp and initially set the locked attribute based on the timestamp, and then the NSTimer will run every second and compare the posts timestamp to its "unlock" date. If a post is ready to unlock its "locked" variable will switch off to "false" and the user will be able to click into it. </p>
<p>Because I'm showing what's locked/unlocked with an image on the cell as well this would require a reload on the tableview every second to keep the locked image up to date. This sounds awful.</p>
<p>Is there a good way to do this or would doing it this way be okay?</p>
| <p>Several thoughts:</p>
<ol>
<li><p>The tableview would not need to reload every second based on the scenario you described. You would be <em>checking</em> every second the timer fires but it would only need to be reloaded when the posts in question actually need to be unlocked (seems like that is roughly at 30 second intervals, not that bad at all).</p></li>
<li><p>If you can figure out the index of the cells that need to be reloaded, you can just call the <code>reloadRows(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation)</code> <code>UITableView</code> method directly. This would avoid updating the entire tableview to reload a single row and can improve UX a little bit if you are experiencing jumpiness due to rows reloading too much. <a href="https://developer.apple.com/reference/uikit/uitableview/1614935-reloadrows" rel="nofollow">Documentation here</a></p></li>
<li><p>If you are concerned about the actual timer firing every second but know that you have a finite number of rows (particularly if it is just 3 as you listed), then you can just create a separate timer for each row that fires at the appropriate time (30 seconds, 1 minute, etc). However, a single timer firing every second is not that big of a deal and shouldn't cause any noticeable performance issues.</p></li>
</ol>
|
Timer does not run in Swift 3.0 playground <p>Working in playground with Swift 3.0 I have this code:</p>
<pre><code>struct Test {
func run() {
var timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { timer in
print("pop")
}
}
}
let test = Test()
test.run()
</code></pre>
<p>But nothing is printing to console. I've read <a href="http://stackoverflow.com/questions/24007518/how-can-i-use-nstimer-in-swift">How can I use NSTimer in Swift?</a> and most of the usage of timer that I've seen in answers and tutorials online involves a selector so I tried this:</p>
<pre><code>class Test {
func run() {
var timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.peep), userInfo: nil, repeats: false)
}
@objc func peep() {
print("peep")
}
}
let test = Test()
test.run()
</code></pre>
<p>Still nothing seems to print to console. If I add <code>timer.fire()</code>, then I get the console prints, but obviously that defeats the purpose. <strong>What do I need to change to get the timer to run?</strong> </p>
<p><strong>EDIT:</strong></p>
<p>So adding <code>CFRunLoopRun()</code> after I called the <code>run</code> method for my <code>Test</code> struct did the trick. Much Thanks to those who answered, especially @AkshayYaduvanshi (who's comment pointed me to <code>CFRunLoopRun()</code>) and @JoshCaswell (whose answer brought up the fact that I timer only works with a run loop).</p>
| <p>You need to start a run loop.</p>
<pre><code>RunLoop.main.run(until: Date(timeIntervalSinceNow: 3))
</code></pre>
<p>The timer doesn't do anything unless there is a working run loop accepting input. The program simply ends.</p>
<p><a href="https://developer.apple.com/reference/foundation/timer" rel="nofollow"><code>Timer</code> reference</a>:</p>
<blockquote>
<p>Timers work in conjunction with run loops. [...] it fires only when one of the run loop modes to which the timer has been added is running and able to check if the timerâs firing time has passed.</p>
</blockquote>
|
root.query_pointer()._data causes high CPU usage <p>I'm a total noob in Python, programming and Linux. I wrote a simple python script to track usage time of various apps. I've noticed that after some time python is going nuts utilizing 100% of the CPU. Turns out it's the code obtaining mouse position is causing issues.</p>
<p>I've tried running this code in an empty python script:</p>
<pre><code>import time
from Xlib import display
while True:
d = display.Display().screen().root.query_pointer()._data
print(d["root_x"], d["root_y"])
time.sleep(0.1)
</code></pre>
<p>It works but the CPU usage is increasing over time. With <code>time.sleep(1)</code> it takes some time but sooner or later it reaches crazy values.</p>
<p>I'm on Ubuntu 16.04.1 LTS using Python 3.5 with python3-xlib 0.15</p>
| <p>To keep the CPU usual steady I put <code>display.Display().screen()</code> before the loop so that it didn't have to do so much work all the time. The screen shouldn't change so nor should that value so it made sense to set it up before.</p>
<pre><code>import time
from Xlib import display
disp = display.Display().screen()
while True:
d = disp.root.query_pointer()._data
print(d["root_x"], d["root_y"])
time.sleep(0.1)
</code></pre>
<p>I've tested it and it stays at about 0.3% for me.</p>
<p>Hope it this helps :)</p>
|
Android Studio 2.2 not displaying view properties <p>After upgrading my android studio to version 2.2 i'm getting following error when i click on a view in layout designer to see it properties:</p>
<blockquote>
<p>Exception in plugin Android Support Moments Ago. </p>
<p>Missing attribute definition for focusable
java.lang.IllegalArgumentException:</p>
<p>Missing attribute definition for focusable
at com.android.tools.idea.uibuilder.property.NlPropertyItem.(NlPropertyItem.java:88)
at com.android.tools.idea.uibuilder.property.NlPropertyItem.create(NlPropertyItem.java:72)
at com.android.tools.idea.uibuilder.property.NlProperties.getPropertiesWithReadLock(NlProperties.java:111)
at com.android.tools.idea.uibuilder.property.NlProperties.lambda$getProperties$537(NlProperties.java:64)
at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:966)
at com.android.tools.idea.uibuilder.property.NlProperties.getProperties(NlProperties.java:63)
at com.android.tools.idea.uibuilder.property.NlPropertiesManager.lambda$setSelectedComponents$228(NlPropertiesManager.java:174)
at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:369)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)</p>
</blockquote>
<p>and Properties panel stuck on loading,</p>
<p>My OS is ubuntu 16.04 and almost i have upgraded everything in Android SDK to the latest version.</p>
| <p>It might be problem with OpenJDK. Please remove it and install Oracle JDK instead using this post: <a href="http://www.webupd8.org/2012/09/install-oracle-java-8-in-ubuntu-via-ppa.html" rel="nofollow">http://www.webupd8.org/2012/09/install-oracle-java-8-in-ubuntu-via-ppa.html</a></p>
<p>Then go to <code>File -> Project Structure</code> and change Java sdk path.</p>
<p>Hope it will help</p>
|
Forward iterator with a moving end() <p>So, I'm designing a class which connects (over network) to a service to receive some data. I don't know how man data points I will be receiving in advance. Nevertheless I was wondering, if there is a way to make this class iterable using a forward_iterator in order to enjoy the STL in its full glory. My idea was something like:</p>
<pre><code>self_type operator++() {
// if there are some locally cached data points left return next
// else connect to service again to receive the next batch of data
}
</code></pre>
<p>However, as I cannot provide a valid <code>end()</code>, I'm curious, if this is somehow still possible to do.</p>
<p>An alternative (and iterator-less) interface would probably look something like:</p>
<pre><code>bool hasMoreDataPoints() const;
DataPoint& getNext();
</code></pre>
<p>which obviously won't work with any STL-algorithm.</p>
| <p>Do as the standard library do with <code>istream_iterator</code>: when you run out of data, set your iterator state such that it compares equal to a default-constructed object of that type. And then there's your <code>end()</code> equivalent.</p>
|
R: absolute coordinates in grid package <p>In the grid package, per default the x- and y-positions in a new viewport range between 0 and 1 (relative to width / height of the viewport).
In order to plot values I have to transform the values to a range between 0 and 1:</p>
<pre><code>library(grid)
vect1 <- rnorm(20)
vect1_relative <- vect1-min(vect1)
vect1_relative <- vect1_relative/max(vect1_relative)
vect2 <- rnorm(20)
vect2_relative <- vect2-min(vect2)
vect2_relative <- vect2_relative/max(vect2_relative)
pushViewport(viewport())
grid.lines(x = c(0,1),y = c(0,1))
grid.points(x = vect1_relative,y = vect2_relative)
</code></pre>
<p>I'm sure there is a more straightforward solution and I assume it has to do with using <code>unit()</code> while opening the viewport, but I haven't figured out yet how.
Can someone show me an example how to use absolute values (and define xlim / ylim) in grid viewports?</p>
| <p>One option is to use <code>dataViewport</code> and <code>native</code> units.</p>
<pre><code>library(grid)
d <- data.frame(x=100*rnorm(10),y=1e4*rnorm(10))
grid.newpage()
pushViewport(viewport(width=0.8,height=0.8))
grid.rect(gp=gpar(fill="grey98"))
vp <- dataViewport(xData = d$x, yData = d$y)
grid.points(d$x, d$y, default.units = "native", vp=vp,
pch=19, size = unit(0.2,"char"))
</code></pre>
<p><a href="https://i.stack.imgur.com/PXQYn.png" rel="nofollow"><img src="https://i.stack.imgur.com/PXQYn.png" alt="enter image description here"></a></p>
|
What alternatives to If-Else statements do batch files have? <p>I'm trying to create a .bat file for my shell:startup for ease-of-access. .bat does not accept else as a term. What can I do to make my code work? And if there is no 'else' alternative,is there an operator for not-equivilant?</p>
<p>Code:</p>
<pre><code>@echo off
cls
echo Desktop Startup Initiated...
cd "C:\Users\User1\Desktop
goto start
:start
pause
set /p x=Please select an option. 1.Heavy start 2.Light start Enter Here:
if %x% == 1 (goto heavy)
if %x% == 2 (goto light)
else (echo Invalid.
pause
goto :start)
:light
start Slack.lnk
start Outlook.lnk
exit
:heavy
start chrome.exe
start Review.txt
start Notes.txt
start Slack.lnk
start Outlook.lnk
exit
</code></pre>
<p>if there is no else alternative, I can make not-equals arguments in its place to redirect to start.</p>
| <p>Why using else ?
Logically if its not equal to 1 or 2 it will go to the invalid statement</p>
<pre><code>if %x% == 1 goto heavy
if %x% == 2 goto light
echo Invalid.
pause
goto :start
</code></pre>
<p>If you really want to use the <code>else</code></p>
<pre><code>if %x% == 1 goto heavy
if %x% == 2 (goto light
) else (
echo Invalid.
pause
goto :start
)
</code></pre>
|
Nestable Sortable List with Knockout Bindings? <p>I've been looking at building a draggable, sortable list in javascript using knockout, and I've found several strictly javacript based implementations that can handle the task, but I haven't been able to get any knockout bindings working for them.</p>
<p>I've taken a look at <a href="https://github.com/rniemeyer/knockout-sortable" rel="nofollow">Knockout Sortable</a>, and even <a href="http://stackoverflow.com/questions/15564545/jqueryui-sortable-list-in-combination-with-knockout-nested-sortable-lists">this question</a> seemed to address a similar request, but it just doesn't seem to quite handle what I'm after. </p>
<p>I'm looking for something that behaves more similar to <a href="http://mjsarfatti.com/sandbox/nestedSortable/" rel="nofollow">this nested sortable</a> plugin that works with knockout.</p>
<p>Essentially my object structure looks similar to the following:</p>
<pre><code>public class MenuItem {
public int Id { get; set; }
public string Name { get; set }
public MenuItem Children { get; set; }
}
</code></pre>
<p>Each menu item can contain any number of other menu items as children, and those children can have children, and so on and so forth.</p>
<p>I'm trying to figure out a way to recursively create these lists and to read them back so that I'm able to make something work.</p>
<p>Has anyone tried something similar, or is there already some bindings out there?</p>
| <p>Using the following jsfiddle, I managed to make a working version using knockout-sortable: <a href="http://jsfiddle.net/rniemeyer/UHcs6/" rel="nofollow">http://jsfiddle.net/rniemeyer/UHcs6/</a>.</p>
<p>To accomplish this, I only slightly modified the source. The hardest portion was getting knockout to find everything correctly after it was dynamically loaded from ajax.</p>
<p>To get knockout to bind correctly to a list of items, I used their mapping plugin in conjunction with their <code>fromJS</code> method. </p>
<p>First you have to define the model for the objects.</p>
<pre><code>var menuItem = function (id, name, menuId, pageId, icon, order, description, menuItems) {
this.id = ko.observable(id || 0);
this.name = ko.observable(name || "");
this.menuItems = ko.observableArray(menuItems || []);
};
</code></pre>
<p>Next, you have to build out from object from the returned ajax data.</p>
<pre><code>$.ajax({
type: "GET",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: 'URL',
success: function (data) {
this.menuItems(ko.mapping.fromJS(data)());
this.menuItems.notifySubscribers();
}.bind(this),
error: function (returndata) {
alert("Error:\n" + returndata.responseText);
}
});
</code></pre>
<p>From there, everything should work properly if you've setup your recursive template properly, like so:</p>
<pre><code><span data-bind="text: name"></span>
<ul data-bind="sortable: { template: 'childTmpl', data: menuItems }"></ul>
<script id="childTmpl" type="text/html">
<li>
<span data-bind="text: name"></span>
<ul data-bind="sortable: { template: 'childTmpl', data: menuItems }"></ul>
</li>
</script>
</code></pre>
|
Incorrect day format returned from momentJS countdown <p>I used this simple script from: <a href="https://github.com/icambron/moment-countdown" rel="nofollow">https://github.com/icambron/moment-countdown</a> to make a simple countdown. The code below i'm using.</p>
<blockquote>
<p><strong>Used Code:</strong></p>
</blockquote>
<pre><code>$interval(function(){
$scope.nextDate = moment().countdown($scope.nextDateGet,
countdown.DAYS|countdown.HOURS|countdown.MINUTES|countdown.SECONDS
);
$scope.daysCountdown = moment($scope.nextDate).format('dd');
$scope.hoursCountdown = moment($scope.nextDate).format('hh');
$scope.minutesCountdown = moment($scope.nextDate).format('mm');
$scope.secondsCountdown = moment($scope.nextDate).format('ss');
},1000,0);
</code></pre>
<blockquote>
<p><strong>This gives correct output</strong></p>
</blockquote>
<pre><code>$scope.nextDate.toString();
</code></pre>
<p>But this contains one string with the remaining days,hours,minutes and seconds. So i decided i want to split this string into 4 strings by using this:</p>
<pre><code>$scope.daysCountdown = moment($scope.nextDate).format('dd');
$scope.hoursCountdown = moment($scope.nextDate).format('hh');
$scope.minutesCountdown = moment($scope.nextDate).format('mm');
$scope.secondsCountdown = moment($scope.nextDate).format('ss');
</code></pre>
<blockquote>
<p><strong>Example for input</strong></p>
</blockquote>
<pre><code>2016-10-15 10:00:00 // $scope.nextDateGet
</code></pre>
<blockquote>
<p><strong>Desired output is something like this:</strong></p>
</blockquote>
<pre><code>0 // (days)
12 // (hours)
24 // (minutes)
30 // (seconds)
</code></pre>
<blockquote>
<p><strong>But i can't seem to format the remainings days, i get this output:</strong></p>
</blockquote>
<pre><code>Fr // Shortcode for the day the item is scheduled => I need the remaining days in this case that would be 0. The other formatting is correct.
</code></pre>
| <blockquote>
<p><strong>The following output was correct if remaining days was not 0:</strong></p>
</blockquote>
<pre><code>$scope.daysCountdown = moment($scope.nextDate).format('D');
</code></pre>
<blockquote>
<p><strong>If remaining days was 0 it would set remaining days on 14 so this work around did the trick:</strong></p>
</blockquote>
<pre><code>if(moment($scope.nextDate).isSame(moment(), 'day')){
$scope.daysCountdown = 0;
} else {
$scope.daysCountdown = moment($scope.nextDate).format('D');
}
</code></pre>
<p>Any suggestions to improve this code are always welcome.</p>
|
Merge Query in SQL Server with conditional update <p>I have a table with duplicate records. The table format is like this </p>
<p>FIRST Day input Table Name-ABC</p>
<pre><code>ani cdate
7076419812 2016-10-12 00:00:00.000
9168919394 2016-10-12 00:00:00.000
6282358407 2016-10-12 00:00:00.000
9168834643 2016-10-12 00:00:00.000
</code></pre>
<p>I want to insert into another table which will contains unique mdn with TS.But for the date 2016-10-12 00:00:00.000 i can easily insert into another table which has the same format.</p>
<pre><code>OUTPUT Table Name-- PQR
MDN, TS
7076419812 2016-10-12 00:00:00.000
9168919394 2016-10-12 00:00:00.000
6282358407 2016-10-12 00:00:00.000
9168834643 2016-10-12 00:00:00.000
</code></pre>
<p>but for date 2016-10-13 00:00:00.000 I have the same record of mixed date with same MDN and I want to update existing MDN with the new date and remaining MDN should be inserted as new records.
For the second day Input table records are like </p>
<pre><code>ani cdate
7076419812 2016-10-13 00:00:00.000
9168919394 2016-10-13 00:00:00.000
6282358233 2016-10-12 00:00:00.000
9168834609 2016-10-12 00:00:00.000
</code></pre>
<p>the output should be like this after processing of second-day input table</p>
<pre><code> mdn ts
7076419812 2016-10-13 00:00:00.000
9168919394 2016-10-13 00:00:00.000
6282358407 2016-10-12 00:00:00.000
9168834643 2016-10-12 00:00:00.000
6282358233 2016-10-12 00:00:00.000
9168834609 2016-10-12 00:00:00.000
</code></pre>
<p>This is my query:--</p>
<pre><code>merge PQR as lc
using (select ani, calldate from ABC ) as st
on lc.mdn = st.ani
WHEN MATCHED and lc.ts < st.calldate THEN
update set lc.ts = st.calldate
WHEN NOT MATCHED THEN
insert (mdn,ts) values (st.ani, st.calldate);
</code></pre>
| <p>This was too long for a comment, but posting this for others.</p>
<p>Your query seems fine, you need to elaborate on what isn't returning correctly for you. Here is some test data using your same logic...</p>
<pre><code>if object_id ('tempdb..#PRQ') is not null drop table #PRQ
create table #PRQ (mdn bigint, ts datetime)
insert into #PRQ (mdn, ts)
values
(7076419812,'2016-10-12 00:00:00.000'),
(9168919394,'2016-10-12 00:00:00.000'),
(6282358407,'2016-10-12 00:00:00.000'),
(9168834643,'2016-10-12 00:00:00.000')
if object_id ('tempdb..#ABC') is not null drop table #ABC
create table #ABC (ani bigint, cdate datetime)
--this is simulating "day 2" where the date is changing for 7076419812 and 9168919394
insert into #ABC (ani, cdate)
values
(7076419812,'2016-10-13 00:00:00.000'), --date change
(9168919394,'2016-10-13 00:00:00.000'), --date change
(6282358407,'2016-10-12 00:00:00.000'),
(9168834643,'2016-10-12 00:00:00.000')
--run the merge with the same logic you used
MERGE #PRQ AS T
USING(SELECT ani, cdate FROM #ABC) AS S
ON T.mdn = s.ani
WHEN MATCHED AND t.ts < s.cdate THEN
UPDATE SET t.ts = s.cdate
WHEN NOT MATCHED THEN
INSERT (mdn,ts) VALUES (s.ani, s.cdate);
--you will see the dates changed for 7076419812 and 9168919394
SELECT * FROM #PRQ
--Now we will update it for "day 3"
update #ABC
set cdate = '2016-10-14 00:00:00.000'
where ani in (7076419812,9168919394)
--run the same merge and select the results from #PRQ
MERGE #PRQ AS T
USING(SELECT ani, cdate FROM #ABC) AS S
ON T.mdn = s.ani
WHEN MATCHED AND t.ts < s.cdate THEN
UPDATE SET t.ts = s.cdate
WHEN NOT MATCHED THEN
INSERT (mdn,ts) VALUES (s.ani, s.cdate);
--see the date changes for 7076419812 and 9168919394
SELECT * FROM #PRQ
--now add two new records with two new ani to your ABC table
insert into #ABC (ani, cdate)
VALUES
(5469358407,'2016-10-15 00:00:00.000'),
(1234834643,'2016-10-15 00:00:00.000')
--and now run the merge again, and see the added rows since they won't match
MERGE #PRQ AS T
USING(SELECT ani, cdate FROM #ABC) AS S
ON T.mdn = s.ani
WHEN MATCHED AND t.ts < s.cdate THEN
UPDATE SET t.ts = s.cdate
WHEN NOT MATCHED THEN
INSERT (mdn,ts) VALUES (s.ani, s.cdate);
SELECT * FROM #PRQ
</code></pre>
|
Ionic2/Angular2 CORS settings <p>Please help me to figure out with CORS on my Ionic2/Angular2 application.
I'm trying to get data with http 'GET' request.
When I'm running '$npm run build' at laptop, I get an expected response.
When I'm running '$ cordova run android', I always get 'Response with status: 0 for URL: null'.
Here is the code snippet:</p>
<pre><code>this.http.get('https://httpbin.org/ip')
.subscribe((data: any) => {
this.result = data._body; // {"origin": "31.43.103.88"} on laptop
}, error => {
this.result = error; // 'Response with status: 0 for URL: null' on android
});
</code></pre>
<p>Thanks.</p>
| <p>Hmm... It looks like I figured out by myself.
I did this:
1) ionic platform rm android
2) ionic platform add android
It's weird, but works like a charm.</p>
|
custom control validator with same modification <p>I did the same modification on 3 kind of BaseValidator. I search a way to remove the duplicate code.</p>
<p>I did the same code for RequiredFieldValidator , RegularExpressionValidator and CustomValidator</p>
<pre><code>Public Class CustomValidator
Inherits System.Web.UI.WebControls.CustomValidator
Protected Overrides Sub Render(writer As HtmlTextWriter)
Try
If Not String.IsNullOrWhiteSpace(ControlToValidate) Then
Dim ctv As Control = Me.FindControl(ControlToValidate)
writer.AddAttribute("for", ctv.ClientID)
End If
Catch
End Try
MyBase.Render(writer)
End Sub
Protected Overrides ReadOnly Property TagKey() As System.Web.UI.HtmlTextWriterTag
Get
Return HtmlTextWriterTag.Label
End Get
End Property
End Class
</code></pre>
| <p>I ran into the same issue you have with these exact classes; I wanted to add some additional features to the validation controls. The way I ended up sharing some common code was implementing my own classes that inherited from the validator classes and then implementing the shared logic in a utility class. I'm not familiar with VB, so please bear with the C# example.</p>
<pre><code>public static class ValidationUtilities
{
public static void AddFor(Control validationControl, string controlToValidate, HtmlTextWriter writer)
{
if (!string.IsNullOrWhiteSpace(controlToValidate))
{
var ctv = validationControl.FindControl(controlToValidate);
writer.AddAddtribute("for", ctv.ClientID);
}
}
}
class MyRegularExpressionValidator : RegularExpressionValidator
{
protected override void Render(HtmlTextWriter writer)
{
ValidationUtilities.AddFor(this, ControlToValidate, writer);
}
}
class MyRequiredFieldValidator : RequiredFieldValidator
{
protected override void Render(HtmlTextWriter writer)
{
ValidationUtilities.AddFor(this, ControlToValidate, writer);
}
}
</code></pre>
<p>You could make the argument that's more work than it's worth for not duplicating a small amount of code, but if you have a lot more, or your duplicated code is complex in some way, this is a way you can share it. Also, I made my utility class static, but there's no reason it couldn't be otherwise.</p>
|
MiniBatchKMeans OverflowError: cannot convert float infinity to integer? <p>I am trying to find the right number of clusters, <code>k</code>, according to silhouette scores using <code>sklearn.cluster.MiniBatchKMeans</code>.</p>
<pre><code>from sklearn.cluster import MiniBatchKMeans
from sklearn.feature_extraction.text import HashingVectorizer
docs = ['hello monkey goodbye thank you', 'goodbye thank you hello', 'i am going home goodbye thanks', 'thank you very much sir', 'good golly i am going home finally']
vectorizer = HashingVectorizer()
X = vectorizer.fit_transform(docs)
for k in range(5):
model = MiniBatchKMeans(n_clusters = k)
model.fit(X)
</code></pre>
<p>And I receive this error:</p>
<pre><code>Warning (from warnings module):
File "C:\Python34\lib\site-packages\sklearn\cluster\k_means_.py", line 1279
0, n_samples - 1, init_size)
DeprecationWarning: This function is deprecated. Please call randint(0, 4 + 1) instead
Traceback (most recent call last):
File "<pyshell#85>", line 3, in <module>
model.fit(X)
File "C:\Python34\lib\site-packages\sklearn\cluster\k_means_.py", line 1300, in fit
init_size=init_size)
File "C:\Python34\lib\site-packages\sklearn\cluster\k_means_.py", line 640, in _init_centroids
x_squared_norms=x_squared_norms)
File "C:\Python34\lib\site-packages\sklearn\cluster\k_means_.py", line 88, in _k_init
n_local_trials = 2 + int(np.log(n_clusters))
OverflowError: cannot convert float infinity to integer
</code></pre>
<p>I know the <code>type(k)</code> is <code>int</code>, so I don't know where this issue is coming from. I can run the following just fine, but I can't seem to iterate through integers in a list, even though the <code>type(2)</code> is equal to <code>k = 2; type(k)</code></p>
<pre><code>model = MiniBatchKMeans(n_clusters = 2)
model.fit(X)
</code></pre>
<p>Even running a different <code>model</code> works:</p>
<pre><code>>>> model = KMeans(n_clusters = 2)
>>> model.fit(X)
KMeans(copy_x=True, init='k-means++', max_iter=300, n_clusters=2, n_init=10,
n_jobs=1, precompute_distances='auto', random_state=None, tol=0.0001,
verbose=0)
</code></pre>
| <p>Let's analyze your code:</p>
<ul>
<li><code>for k in range(5)</code> returns the following sequence:
<ul>
<li><code>0, 1, 2, 3, 4</code></li>
</ul></li>
<li><code>model = MiniBatchKMeans(n_clusters = k)</code> inits model with <code>n_clusters=k</code></li>
<li>Let's look at the first iteration:
<ul>
<li><code>n_clusters=0</code> is used</li>
<li>Within the optimization-code (look at the output):</li>
<li><code>int(np.log(n_clusters))</code></li>
<li>= <code>int(np.log(0))</code></li>
<li>= <code>int(-inf)</code></li>
<li>ERROR: no infinity definition for integers!</li>
<li>-> casting floating-point value of -inf to int not possible!</li>
</ul></li>
</ul>
<p>Setting <code>n_clusters=0</code> does not make sense!</p>
|
Javascript getDate()and getMonth() return wrong result <p>I create a new Date object, using timestamp. If I print out that object, it returns correct date and time. But if I try to use getDate()and getTime(), they get me back wrong numbers.</p>
<p>My code:</p>
<pre><code>var textDate = new Date(timestamp);
console.log(timestamp);
console.log(textDate);
console.log(textDate.getDate(),textDate.getMonth(),textDate.getFullYear());
</code></pre>
<p>My console result:</p>
<pre><code>1476483081000
Date 2016-10-14T22:11:21.000Z
15 9 2016
</code></pre>
<p>How can I get correct date and month from textDate variable?</p>
| <p>The getMonth() method returns the month from 0 to 11.</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth</a></p>
<p>When you print the date, it relies on the timezone. If you are in a timezone 2 hours away from GMT, then the 22:11 might shift to a new day, this is probably why getDate() returns the dext day.</p>
|
XML still empty? <p>This may be a very stupid question, but I can't seem to get this thing working.
I'm trying to form an XML with the following structure, and be able to add additional data into it at any point in time, as well as read the data.
Right now all I get is:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<sessions />
</code></pre>
<p>What I want</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<sessions>
<session date="14.10.2016" time="17:15" amount="3">
<folder>C:\\Users</folder>
<folder>C:\\Test</folder>
<folder>C:\\Asgbsf\\Aleksei</folder>
</session>
<sessions />
</code></pre>
<p>My C# code</p>
<pre><code> static void Main(string[] args)
{
createXML();
Console.WriteLine("Test XML");
folderList.Add("C:\\Users");
folderList.Add("C:\\Test");
folderList.Add("C:\\Asgbsf\\Aleksei");
XML();
Console.ReadKey();
}
static List<String> folderList = new List<String>();
private static string generateRandom(int min, int max)
{
Random rnd = new Random();
return rnd.Next(min, max).ToString();
}
public static string pathToXml = "test_aleksei2.xml";
public static void createXML()
{
XmlTextWriter textWritter = new XmlTextWriter(pathToXml, Encoding.UTF8); //Creating file
textWritter.WriteStartDocument(); //XML header
textWritter.WriteStartElement("sessions"); //XML head
textWritter.WriteEndElement(); //end writing element
textWritter.Close(); //close XmlTextWriter
}
public static void XML()
{
Console.WriteLine("XML function being executed");
XmlDocument document = new XmlDocument(); //using XmlDocument to Read
document.Load(pathToXml); //loading XML
XmlNode element = document.CreateElement("session"); //parent element
XmlAttribute date = document.CreateAttribute("date"); //creating attribute
date.Value = "14.10.2016";
element.Attributes.Append(date); //append attribute to element
XmlAttribute time = document.CreateAttribute("time");
time.Value = generateRandom(0, 23) + ":" + generateRandom(1, 59);
element.Attributes.Append(time);
XmlAttribute amount = document.CreateAttribute("amount");
amount.Value = generateRandom(1, 10);
element.Attributes.Append(amount);
XmlNode folder = null;
for (int i = 0; i < folderList.Count; i++)
{
Console.WriteLine(folderList[i]+" - " + i + "/" + folderList.Count);
folder = document.CreateElement("Folder");
folder.InnerText = folderList[i];
element.AppendChild(folder);
}
document.Save(pathToXml);
}
</code></pre>
<p>Help please, I don't understand what I'm doing wrong. If I just c&p I might not even learn what's the issue here... Thank you in advance</p>
| <p>In your XML method, you never append the <code>session</code> element to the document after you create it. So, even though you create and add all those children to the element, none of it gets added to the document.</p>
<p>You need to add this line before you save the document:</p>
<pre><code>document.DocumentElement.AppendChild(element);
</code></pre>
|
i want to find the perfect number between 0 to 1000 and its not runing <pre><code>int num;
num = 0;
for (int i = 1; i < 1000; i++)
{
for (int j = 1; j <= i / 2; j++)
{
if (i % j == 0)
num = num + j;
}
if (num == i)
Console.WriteLine(num);
}
</code></pre>
<p>I try to find the perfect number between 1 and 1000, i wrote this code but it didn't work! what is wrong?</p>
| <p>As others have mentioned move <code>num = 0</code> inside the outer loop. </p>
<pre><code>int num;
for (int i = 1; i < 1000; i++)
{
num = 0;
for (int j = 1; j <= i / 2; j++)
{
if (i % j == 0)
{
num = num + j;
}
}
if (num == i)
{
Console.WriteLine(num);
}
}
</code></pre>
<p>This will give you the output
<code>6 28 496</code> which are the perfect numbers between 0 and 1,000</p>
|
What is wrong with my PSQL view table? <p>I have two tables player and match:</p>
<pre><code>CREATE TABLE player(
id serial PRIMARY KEY NOT NULL,
name varchar(255) NOT NULL
);
CREATE TABLE match(
id serial PRIMARY KEY,
winner serial REFERENCES player(id) NOT NULL,
loser serial REFERENCES player(id) NOT NULL CHECK (loser != winner)
);
CREATE SEQUENCE playerid_sequence
start 1
increment 1;
CREATE SEQUENCE matchid_sequence
start 1
increment 1;
</code></pre>
<p>I want to create a view table that joins the two tables:</p>
<pre><code>CREATE VIEW matchplayers AS
SELECT winner.name, loser.name, m.id
from player winner, player loser, match m
WHERE m.winner = winner.id AND m.loser = loser.id;
</code></pre>
<p>But it is returning an error that "name" has been mentioned more than once. Fairly inexperienced to SQL</p>
| <p>Try</p>
<pre><code>CREATE VIEW matchplayers AS
SELECT winner.name as winner_name, loser.name as loser_name, m.id
from player winner, player loser, match m
WHERE m.winner = winner.id AND m.loser = loser.id;
</code></pre>
<p>to get unambiguous column names of the view.</p>
|
Dictionary key and value flipping themselves unexpectedly <p>I am running python 3.5, and I've defined a function that creates XML SubElements and adds them under another element. The attributes are in a dictionary, but for some reason the dictionary keys and values will sometimes flip when I execute the script.</p>
<p>Here is a snippet of kind of what I have (the code is broken into many functions so I combined it here)</p>
<pre><code>import xml.etree.ElementTree as ElementTree
def AddSubElement(parent, tag, text='', attributes = None):
XMLelement = ElementTree.SubElement(parent, tag)
XMLelement.text = text
if attributes != None:
for key, value in attributes:
XMLelement.set(key, value)
print("attributes =",attributes)
return XMLelement
descriptionTags = ([('xmlns:g' , 'http://base.google.com/ns/1.0')])
XMLroot = ElementTree.Element('rss')
XMLroot.set('version', '2.0')
XMLchannel = ElementTree.SubElement(XMLroot,'channel')
AddSubElement(XMLchannel,'g:description', 'sporting goods', attributes=descriptionTags )
AddSubElement(XMLchannel,'link', 'http://'+ domain +'/')
XMLitem = AddSubElement(XMLchannel,'item')
AddSubElement(XMLitem, 'g:brand', Product['ProductManufacturer'], attributes=bindingParam)
AddSubElement(XMLitem, 'g:description', Product['ProductDescriptionShort'], attributes=bindingParam)
AddSubElement(XMLitem, 'g:price', Product['ProductPrice'] + ' USD', attributes=bindingParam)
</code></pre>
<p>The key and value does get switched! Because I'll see this in the console sometimes:</p>
<pre><code>attributes = [{'xmlns:g', 'http://base.google.com/ns/1.0'}]
attributes = [{'http://base.google.com/ns/1.0', 'xmlns:g'}]
attributes = [{'http://base.google.com/ns/1.0', 'xmlns:g'}]
...
</code></pre>
<p>And here is the xml string that sometimes comes out:</p>
<pre><code><rss version="2.0">
<channel>
<title>example.com</title>
<g:description xmlns:g="http://base.google.com/ns/1.0">sporting goods</g:description>
<link>http://www.example.com/</link>
<item>
<g:id http://base.google.com/ns/1.0="xmlns:g">8987983</g:id>
<title>Some cool product</title>
<g:brand http://base.google.com/ns/1.0="xmlns:g">Cool</g:brand>
<g:description http://base.google.com/ns/1.0="xmlns:g">Why is this so cool?</g:description>
<g:price http://base.google.com/ns/1.0="xmlns:g">69.00 USD</g:price>
...
</code></pre>
<p>What is causing this to flip?</p>
| <pre><code>attributes = [{'xmlns:g', 'http://base.google.com/ns/1.0'}]
</code></pre>
<p>This is a list containing a set, not a dictionary. Neither sets nor dictionaries are ordered.</p>
|
Setting a Checkbox in ImageJ Macro <p>this is a basic question but I can't find the answer anywhere. </p>
<p>When using the run command for macros in ImageJ how do I set the checkboxes (that I'd see when running it manually) using the macro.</p>
<p>eg. I have:
run("Subtract Background...","radius=1") </p>
<p>But I want to automatically check the box for a sliding paraboloid, something like this:</p>
<p>run("Subtract Background...","radius=1","Sliding paraboloid=True")</p>
<p>Or is this a separate set command for each process?</p>
| <p>You can get those GUI commands easily with the macro recorder of ImageJ, see:</p>
<p><a href="https://imagej.nih.gov/ij/docs/guide/146-31.html#sub:Record" rel="nofollow">https://imagej.nih.gov/ij/docs/guide/146-31.html#sub:Record</a>...</p>
<p>The option you are searching is 'sliding', e.g.:</p>
<pre><code>run("Subtract Background...", "rolling=50 light sliding");
</code></pre>
|
re-displaying the same drop-down in HTML below original drop-down option? <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="ISO-8859-1">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function() {
$("select").change(function() {
$("select").after("<br>here");
//window.alert("We're getting somewhere!")
//document.write("#1");
});
});
</script>
<title>Query Tool</title>
</head>
<h1>Organizer Tool</h1>
<HR>
<p>Please choose search criteria:</p>
<select id=1>
<option value="MMSI">MIMSI</option>
<option value="Ship Type">shipType</option>
<option value="Anomaly Type">Anomaly Type</option>
</select>
<button type="button">Search</button>
<body><br><br><br>
<p>Testing.</p>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>I'm working on an application which interacts with the users via webserver(using <strong>JQuery</strong>) and receives a string which is received from the browser-side in the form of a drop-down option. After having chosen the option, the user is meant to click search and the http request is sent with that string, and received on the server-side at which point it interacts with the database and queries that string. After having found that search, it would print it back out onto the client screen in a tabulated format.
Now, my problem is with regards to choosing multiple options to query; How can I display a new drop-down menu for each time a user chooses one from the previous one?
I have a novice understanding of event handlers, and realize I can trigger an event on 'change' and display a text; yet can anyone be so kind as to explain how I may display that option drop-down menu below the first one after a 'change' has been detected?
So far I have been able to display the string 'here' everytime a change occurs in the drop-down.</p>
<p>Thanks so much,
Al</p>
| <p>If I've understood you right, you've been searching something like this:</p>
<pre><code><!DOCTYPE html>
<html lang="en-US">
<head>
<title>Query Tool</title>
<meta charset="ISO-8859-1">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function() {
$("#first_select").change(function() {
//$.post('where',{data},function (d) { //this is to post data to the server and get the answer with function
// documentation is at http://api.jquery.com/jQuery.post/
// if the answer is in JSON, decode it
var answer = '[{"ID":"1","name":"Astronomy"},{"ID":"2","name":"Microscopy"},{"ID":"3","name":"Bilogy"}]';
var d = JSON.parse(answer);
var s = $("<select id=\"select_two\" name=\"select_two\" />");
for(var val in d) {
$("<option />", {value: d[val].ID, text: d[val].name}).appendTo(s);
}
$("#selector_area").empty();
s.appendTo("#selector_area");
//}); // closing brackets for the post method
});
});
</script>
</head>
<body><br><br><br>
<p>Testing.</p>
<h1>Organizer Tool</h1>
<HR>
<p>Please choose search criteria:</p>
<select id="first_select">
<option value="MMSI">MIMSI</option>
<option value="Ship Type">shipType</option>
<option value="Anomaly Type">Anomaly Type</option>
</select>
<div id="selector_area"></div>
<button type="button">Search</button>
</body>
</html>
</code></pre>
|
make: *** [main.o] Error 1 <p>I am executing a simple makefile that contait 3 parts but it does not work well these are details of my files .h and .c :
1) main.c</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include "hello.h"
int main (void)
{
hello();
return EXIT_SUCCESS;
}
</code></pre>
<p>2) hello.h</p>
<pre><code>#ifndef hello
#define hello
void hello (void);
#endif
</code></pre>
<p>3) hello.c</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
void hello (void)
{
printf("Hello World\n");
}
</code></pre>
<p>4) makefile</p>
<pre><code>all: hello
hello: hello.o main.o
gcc -o hello hello.o main.o
hello.o: hello.c
gcc -o hello.o -c hello.c -W -Wall -ansi -pedantic
main.o: main.c hello.h
gcc -o main.o -c main.c -W -Wall -ansi -pedantic
clean:
rm -rf *.o
mrproper: clean
rm -rf hello
</code></pre>
<p>I get this error
<a href="https://i.stack.imgur.com/axBue.png" rel="nofollow">Image</a></p>
<p>any help ?</p>
| <p>When you write <code>#define hello</code> you define <code>hello</code> to be an empty token. Thus the function declaration on the next string effectively becomes this:</p>
<pre><code>void (void);
</code></pre>
<p>which is not valid C code.</p>
<p>What you are trying to do is probably the <a href="https://en.wikipedia.org/wiki/Include_guard" rel="nofollow">Include guard</a>, its purpose is to avoid multiple inclusion of one header. The name of the guard have to differ from any other token you use. Usual naming is <code>FILENAME_H</code>:</p>
<pre><code>#ifndef HELLO_H
#define HELLO_H
void hello(void);
#endif
</code></pre>
|
How to run ShellCommandActivity on my own EC2 instance? <p>I am trying to run a simple command to test a ShellCommandActivity with Data Pipeline from AWS.</p>
<pre><code>>>> /usr/bin/python /home/ubuntu/script.py
</code></pre>
<p>That script should create a file on a S3, I know I could create a S3 file using the same Data Pipeline, but I want to test how to execute the script.</p>
<p>When I execute the pipeline I get this error:</p>
<blockquote>
<p>/usr/bin/python: can't open file '/home/ubuntu/script.py': [Errno 2] No such file or directory</p>
</blockquote>
<p>This is because AWS DP create a complete new EC2 instance when it runs, and my <code>script.py</code> is not there.</p>
<p>I created a Resource EC2
<a href="https://i.stack.imgur.com/DNs9G.png" rel="nofollow"><img src="https://i.stack.imgur.com/DNs9G.png" alt="enter image description here"></a></p>
<p>But there is not a field to define my own EC2 instance. How can I do this? Or maybe there some other way to approach this.</p>
<p>Thanks.</p>
| <p>One workaround is directly execute script.py
like </p>
<p>"command": "script.py"</p>
<p>Be sure your script.py with header </p>
<pre><code>#!/usr/bin/env python
</code></pre>
|
Ansible: How to use backslash in lineinfile module? <pre><code>---
- hosts: local
tasks:
- name: Update cataline.properties 1
lineinfile: dest=/home/folder1/catalina.properties insertafter="# been granted." line="package.access=sun.,org.apache.catalina.,org.apache.coyote.,org.apache.jasper.,\"
</code></pre>
<blockquote>
<p>ERROR! Unexpected Exception: zero length field name in format</p>
</blockquote>
| <p>You need to use <code>\\</code>, otherwise you are escaping the last <code>"</code> and the expression is not closed.</p>
<pre><code>- hosts: local
tasks:
- name: Update cataline.properties 1
lineinfile:
dest: /home/folder1/catalina.properties
insertafter: "# been granted."
line: "package.access=sun.,org.apache.catalina.,org.apache.coyote.,org.apache.jasper.,\\"
</code></pre>
|
Find object in NSOrderedSet in CoreData. index(ofAccessibilityElement :) <p>I have an ordered To Many relationship and Xcode 8 has generated an attribute of type NSOrderedSet with a bunch of helper functions to insert and remove elements.</p>
<p>Now I am trying to find an object and the Apple documentation indicates that the following function is available for NSOrderedSet: </p>
<pre><code>func index(of object: Any) -> Int
</code></pre>
<p>However when I want to use this function the compiler and the autocompletion want me to use the following function instead: </p>
<pre><code>func index(ofAccessibilityElement element: Any) -> Int
</code></pre>
<p>which doesn't seem to be finding anything. </p>
<p>Could someone please help me understand what is going on?</p>
| <p>Autocompletion can and often is wrong. It can be handy but it's not a reference for what's correct.</p>
<p>I don't know what you mean about the compiler wanting to use that method, because it's not what you need to look up objects in an ordered set. The correct method would be <code>index(of:)</code>, as in</p>
<pre><code>var myset = NSMutableOrderedSet(array: [1, 2, 3])
myset.index(of:2)
</code></pre>
|
MSDeploy get error during upload big file to IIS server <p>I get following error, when I try to deploy a web app to IIS server using MSDeploy. I believe the cause of the issue is the size of the file. The file, which cause the problem, is the biggest file in the package with size 8M. May I know how to deal with it? </p>
<p><a href="https://i.stack.imgur.com/r00ip.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/r00ip.jpg" alt="enter image description here"></a></p>
| <p>We had this same error a while back and it was a network issue. Pulled in our Network Operations team and they ran a diagnostic test and found the issue. Not sure what it was but I bet this is the same.</p>
|
Using a Lambda Expression inside a function <pre><code>public int[] MyFunction(List<T> dataList, DateTime dateType, int howFarBack, string columnName, Boolean distinct)
</code></pre>
<p>I have created code to query a list of objects that have come from a SQL database. I'd like to store the code inside of a function, allowing it to be used repeatedly with different parameters.</p>
<p>This is my original lambda expression:</p>
<pre><code>dataArray[i] = dataList.Where(p => p.LastRequestDate<= endTime && p.LastRequestDate > startTime).Select(p => p.UserName).Distinct().Count();
</code></pre>
<p>LastRequestDate is a column in a specific table in the database. I'd like to use my same lambda expression but I can't figure out how to do it. I thought I could pass in a string containing the specific column name but I don't think it works like that.</p>
<p>I thought you could do something like:</p>
<pre><code>.Where(p => p.columnName <= endTime)
</code></pre>
<p>That way whomever calls the function could just use whichever columns they knew they needed.</p>
<p>Is there a way I can do this? </p>
| <p>Without resorting to more advanced techniques, maybe a little bit of IoC will do:</p>
<p>(contrived, just to show the idea)</p>
<pre><code> public static int MyFunction<T>(IEnumerable<T> data, Func<T, DateTime> dateColumnSelector, DateTime startDate, DateTime endDate, bool distinct)
{
var lastDate = default(DateTime);
var inRange =
data.
SkipWhile(item => dateColumnSelector(item) < startDate).
TakeWhile(item => dateColumnSelector(item) <= endDate).
Where
(
item =>
distinct ?
(
lastDate != dateColumnSelector(item)
?
// beware; a bit hacky, granted:
(lastDate = dateColumnSelector(item)) == lastDate
:
lastDate == default(DateTime)
)
:
true
);
return inRange.Count();
}
public class Person
{
public DateTime Dob { get; set; }
}
public class Thing
{
public DateTime PurchasedOn { get; set; }
}
static void Main(string[] args)
{
var persons = new[] {
new Person { Dob = DateTime.Parse("1969-01-01") },
new Person { Dob = DateTime.Parse("1975-01-01") }, // in 1970-1980 range
new Person { Dob = DateTime.Parse("1975-01-01") }, // in 1970-1980 range
new Person { Dob = DateTime.Parse("1980-01-01") }, // in 1970-1980 range
new Person { Dob = DateTime.Parse("1981-01-01") }
};
var things = new List<Thing> {
new Thing { PurchasedOn = DateTime.Parse("1970-01-01") }, // in 1970-1980 range
new Thing { PurchasedOn = DateTime.Parse("1975-01-01") }, // in 1970-1980 range
new Thing { PurchasedOn = DateTime.Parse("1980-01-01") } // in 1970-1980 range
};
var thingCount =
MyFunction
(
things,
(thing => thing.PurchasedOn),
DateTime.Parse("1970-01-01"),
DateTime.Parse("1980-01-01"),
true
);
var personCount1 =
MyFunction
(
persons,
(person => person.Dob),
DateTime.Parse("1970-01-01"),
DateTime.Parse("1980-01-01"),
false
);
var personCount2 =
MyFunction
(
persons,
(person => person.Dob),
DateTime.Parse("1970-01-01"),
DateTime.Parse("1980-01-01"),
true // (distinct years only)
);
Console.WriteLine(thingCount); // 3
Console.WriteLine(personCount1); // 3
Console.WriteLine(personCount2); // 2
Console.ReadKey();
}
}
</code></pre>
<p>'Hope this helps.</p>
|
SoftLayer SSL VPN Portal java.lang.NullPointerException @macOS Sierra <p>After updating the macOS to Sierra Version 10.12 I'm getting an error on the connection to the SoftLayer SSL VPN:</p>
<pre><code>Exception Name: JavaNativeException
Description: java.lang.NullPointerException
at sun.awt.SunToolkit.getSystemEventQueueImplPP(SunToolkit.java:1090)
at sun.awt.SunToolkit.getSystemEventQueueImplPP(SunToolkit.java:1085)
at sun.awt.SunToolkit.getSystemEventQueueImpl(SunToolkit.java:1080)
at java.awt.Toolkit.getEventQueue(Toolkit.java:1734)
at java.awt.EventQueue.invokeLater(EventQueue.java:1266)
at sun.plugin2.main.client.MacOSXKeyHandler.notifyFlagsChangedFromNative(Unknown Source)
User Info: (null)
...
</code></pre>
<p>I suppose this is a JAVA version error
Any advice is very welcome.
Thanks in advance</p>
| <p>It could be the same issue:</p>
<p><a href="http://stackoverflow.com/questions/39833751/java-applets-in-macos-sierra-crashes">Java applets in macOs Sierra crashes</a></p>
<p>Try to download JDK 9, if the issue persist submit a ticket to SoftLayer, perhaps they can provide another workaround</p>
|
error() function from Stroustrup's book behavior in Visual Studio 2015 <p>So I've arrived at Chapter 5 exercises in Programming Principles and Practices Using C++</p>
<p>I'm using VS 2015 as my IDE and I encountered a problem with errors.</p>
<p>If I run the code in Visual Studio 2015 and enter -280 to check the temp I get this: <a href="https://i.stack.imgur.com/2ZX8B.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/2ZX8B.jpg" alt="Visual studio error"></a></p>
<p>However, if I run the same code in codeblocks I get this: <a href="https://i.stack.imgur.com/ublq2.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/ublq2.jpg" alt="Codeblocks error"></a></p>
<p>As you can see, error given from codeblocks actually writes out the error message while VS 2015 does not. I tried to find out why this is happening but without success so far.</p>
<p>Here is the code I'm using:</p>
<pre><code>#include "../../std_lib_facilities.h"
double ctok(double c) //converts c to k
{
if (c<-273.15) error("Temperature below absolute zero!"); // checks that temp isn't below absolute zero
double k = c + 273.15;
return k;
}
double ktoc(double k)
{
double c = k - 273.15;
return c;
}
int main() {
double c = 0; //declare input variable
cin >> c; //input temp
double k = ctok(c); //convert temp
cout << k << '\n'; //print out tmep
return 0;
}
</code></pre>
<p>I'd be thankful if anyone would be able to explain the difference between the two. Thank you for your time.</p>
| <p>When an exception is not caught in the program, it is terminated abnormally. Different run time environments treat that differently. The standard does not guarantee any uniform mechanism that we can rely on.</p>
<p>There is nothing you can do about that other than learn how to deal with them.</p>
|
"The multi-part identifier 'xxx' could not be bound" when attempting to join three tables <p>I'd like to start off with the fact that I'm a SQL beginner with only 5 or 6 hours of experience. I'm learning fast though. </p>
<p>Ultimately I am trying to select the addresses of clients by product line. The first table (arinvch) contains invoices and therefore the addresses of the clients; the second table (aritrsh) contains the individual line items of the invoices of table 1, and the third table (icitemh) contains the product lines of the line items. </p>
<p>I attempted to join tables two and three in a subquery first to extract the product lines, then join that with the first table to get the customer addresses by product line. </p>
<p>Simply put, this is what I tried to do:</p>
<pre><code>SELECT
table1.addressinfo
FROM
table1
INNER JOIN
(SELECT * FROM
table2 INNER JOIN table3
ON table2.itemnumber = table3.itemnumber
WHERE table3.type = 'CRM') joinedtable
ON
table1.customernumber = joinedtable.customernumber;
</code></pre>
<p>The exact code:</p>
<pre><code>SELECT
arinvch.ccustno AS [Customer #],
arinvch.dinvoice AS [Invoice Date],
arinvch.cbcompany AS [Bill to Company],
arinvch.cbaddr1 AS [Bill to Address 1],
arinvch.cbaddr2 AS [Bill to Address 2],
arinvch.cbcity AS [Bill to City],
arinvch.cbstate AS [Bill to State],
arinvch.cbzip AS [Bill to Zip Code],
arinvch.cbcountry AS [Bill to Country],
arinvch.cbphone AS [Bill to Phone],
arinvch.cscompany AS [Ship To Company],
arinvch.csaddr1 AS [Ship To Address 1],
arinvch.csaddr2 AS [Ship To Address 2],
arinvch.cscity AS [Ship To City],
arinvch.csstate AS [Ship To State],
arinvch.cszip AS [Ship To Zip Code],
arinvch.cscountry AS [Ship To Country],
arinvch.csphone AS [Ship To Phone],
arinvch.cscontact AS [Ship To Contact],
aritrsh.cinvno AS [Invoice #],
aritrsh.citemno AS [Item Number],
icitemh.citemno AS [Item #]
FROM
arinvch
INNER JOIN
(SELECT
aritrsh.clineitem
FROM
aritrsh
INNER JOIN
icitemh
ON
aritrsh.citemno = icitemh.citemno
WHERE icitemh.ctype = 'CRM')table2
ON
arinvch.ccustno = aritrsh.ccustno;
</code></pre>
<p>This returns the following error message (in FlySpeed SQL):</p>
<p>[FireDAC][Phys][ODBC][Microsoft][ODBC SQL Server Driver][SQL Server]The
multi-part identifier "aritrsh.ccustno" could not be bound.</p>
<p>Thanks in advance!
(Also, as a side goal, if you could also explain how I can get the addresses to not repeat when I pull them from the invoices that would be great. I've tried incorporating SELECT DISTINCT in numerous places but can't seem to work out a solution (as I only want the table1.customernumber to be distinct and WHERE DISTINCT isn't a thing).)</p>
| <pre><code> arinvch
JOIN (
SELECT aritrsh.clineitem
FROM aritrsh
JOIN icitemh ON
aritrsh.citemno = icitemh.citemno
WHERE icitemh.ctype = 'CRM'
) table2 ON
arinvch.ccustno = aritrsh.ccustno;
</code></pre>
<p>the second table is table2 in your example, not aritrsh.</p>
<p>For the second part:
arinvch (1:M) -> aritrsh and
aritrsh (1:1) -> icitemh</p>
<p>aritrsh will have 1 or more products ordered by customers. This will repeat the address fields for each product ordered. You could summarize the entire thing by putting the entire select statement in parentheses then use group by to remove the invoice records.</p>
<pre><code>select a, b, c, d
from ( big select statement above ) A
group by a, b, c, d
</code></pre>
<p>the group by will remove duplicates (just like distinct.) Replace a,b,c,d with the names of your fields in the inner select without prefixes like aritrsh., but only have the fields that have to do with the address and the products, not the invoice lines.</p>
|
Polling I/O (MIPS) <p>I am attempting to write a program in MIPS that uses polling to read a character from the keyboard and then displays it using the builtin Keyboard and Display MMIO Simulator. Unfortunately, I am having trouble grasping the concept behind the registers used and the control bits, but have been trying to figure it out from examples online.</p>
<p>Here is what I have written so far:</p>
<pre><code> .data
.text
.globl main
main:
.eqv RCR 0xffff0000 # Receiver Control Register (Ready Bit)
.eqv RDR 0xffff0004 # Receiver Data Register (Key Pressed - ASCII)
.eqv TCR 0xffff0008 # Transmitter Control Register (Ready Bit)
.eqv TDR 0xffff000c # Transmitter Data Register (Key Displayed- ASCII)
keyWait: lw $t0, RCR
andi $t0, $t0, 1
beq $t0, $zero, keyWait
lb $a0, RDR
</code></pre>
<p>What I believe is happening here is that <code>keyWait</code> continues to loop until the ready bit is set to 1 (*), and then the ASCII value of the key is stored in <code>$a0</code>. Is this correct?</p>
<p>If this is correct, how can I then print the character on the display using the same polling technique with the TCR and TDR?</p>
<p>*I don't understand why this is needed to be checked with the <code>andi</code> operation - if <code>$t0</code> is 1 (or 0), it is <code>and</code>ed with 1, which equals 1 (or 0), which is then stored in <code>$t0</code>? So the value of <code>$t0</code> stays as it was prior to this operation regardless?</p>
<p><strong>EDIT</strong></p>
<p>Here is my attempt at passing the key pressed data to the display.</p>
<pre><code> .data
.text
.globl main
main:
.eqv RCR 0xffff0000 # Receiver Control Register (Ready Bit)
.eqv RDR 0xffff0004 # Receiver Data Register (Key Pressed - ASCII)
.eqv TCR 0xffff0008 # Transmitter Control Register (Ready Bit)
.eqv TDR 0xffff000c # Transmitter Data Register (Key Displayed- ASCII)
keyWait: lw $t0, RCR
andi $t0, $t0, 1
beq $t0, $zero, keyWait
lbu $a0, RDR
displayWait: lw $t1, TCR
andi $t1, $t1, 1
beq $t1, $zero, displayWait
sb $a1, TDR
li $v0, 11
syscall
j keyWait
</code></pre>
<p>This is just a test program which should print the character on the MMIO Display Simulator, and also in the console within MIPS. It is doing the latter, but not on the display simulator. In the display simulator, <code>Cursor:</code> is incrementing each time a key is pressed, but nothing is being printed. What am I missing?</p>
| <p>You probably didn't click "Connect to MIPS".</p>
<p>See this answer: <a href="http://stackoverflow.com/questions/10325970/how-to-print-to-the-screen-from-mips-assembly">How to print to the screen from MIPS assembly</a></p>
<p>When I was testing I've found that if you stop simulation, reload your program, you probably have to click on "Disconnect from MIPS" and then "Connect to MIPS" again (i.e. toggle it a bit)</p>
<p>Also, a <em>bug</em>: The data from <code>RDR</code> is in <code>$a0</code>, but you are storing into <code>TDR</code> from <code>$a1</code></p>
<p>From the link, notice that the <em>style</em> is slightly different than yours. In the link, they use offsets from a base register rather than hardwiring the addresses. This is much more usual for devices [in device drivers in the real world], particularly if the base address of the device could be configured/changed.</p>
<p>Also, in <code>mars</code>, if you look at the actual low level instructions generated from the pseudo-ops in the hardwired vs. base register versions, the base register version is more compact (i.e. fewer injected <code>lui</code> insts)</p>
<p>So, I've restyled your code to use a base register:</p>
<pre><code> .data
.eqv MMIOBASE 0xffff0000
# Receiver Control Register (Ready Bit)
.eqv RCR_ 0x0000
.eqv RCR RCR_($s0)
# Receiver Data Register (Key Pressed - ASCII)
.eqv RDR_ 0x0004
.eqv RDR RDR_($s0)
# Transmitter Control Register (Ready Bit)
.eqv TCR_ 0x0008
.eqv TCR TCR_($s0)
# Transmitter Data Register (Key Displayed- ASCII)
.eqv TDR_ 0x000c
.eqv TDR TDR_($s0)
.text
.globl main
main:
li $s0,MMIOBASE # get base address of MMIO area
keyWait:
lw $t0,RCR # get control reg
andi $t0,$t0,1 # isolate ready bit
beq $t0,$zero,keyWait # is key available? if no, loop
lbu $a0,RDR # get key value
displayWait:
lw $t1,TCR # get control reg
andi $t1,$t1,1 # isolate ready bit
beq $t1,$zero,displayWait # is display ready? if no, loop
sb $a0,TDR # send key to display
li $v0,11
syscall
j keyWait
</code></pre>
<p>I did a little "fancy footwork" with the <code>.eqv</code> above. In the general case, even though it's a bit more verbose, it may be clearer to do:</p>
<pre><code> .eqv RCR 0x0000
lw $t0,RCR($s0) # get control reg
</code></pre>
|
Equivalent function of MatLab's "dateshift(...)" in Python? <p>MatLab can take a date and move it to the end of the month, quarter, etc. using the <code>dateshift(...)</code> <a href="https://www.mathworks.com/help/matlab/ref/dateshift.html" rel="nofollow">function</a>.</p>
<p>Is there an equivalent function in Python?</p>
| <p>I'm not sure if it counts as the same, but the <a href="https://docs.python.org/3/library/datetime.html" rel="nofollow"><code>datetime</code></a> module can make times available as a <a href="https://docs.python.org/3/library/datetime.html#datetime.date.timetuple" rel="nofollow"><code>timetuple</code></a>, with separate components for year, month, day etc. This is easy to manipulate directly to advance to the next month, etc.</p>
<p>If you don't mind using an extension, check out <a href="https://dateutil.readthedocs.io/en/stable/" rel="nofollow"><code>dateutil</code></a>. The list of features starts with:</p>
<blockquote>
<ul>
<li>Computing of relative deltas (next month, next year, next monday, last week of month, etc); </li>
</ul>
</blockquote>
<p>The documentation for <a href="https://dateutil.readthedocs.io/en/stable/examples.html#relativedelta-examples" rel="nofollow"><code>dateutil.relativedelta</code></a> shows how to advance to various points.</p>
|
angular 2 subscribe to boolean from service <p>I have a service that has a changing boolean value, I want to subscribe to that boolean change in a component. How can this be achieved?</p>
<p>here is my service...</p>
<pre><code>private subBoolShowHideSource = new Subject<boolean>();
subBoolShowHide$ = this.subBoolShowHideSource.asObservable();
showHide(eventValue: boolean) {
this.subBoolShowHideSource.next(eventValue);
console.log("show hide service " + eventValue);
}
</code></pre>
<p>and here is the component I am trying to get to read the bool value...</p>
<pre><code>boolShowGTMDetails: any;
subscription: Subscription;
constructor(private service: ShowHideService){
this.subscription = this.service.subBoolShowHide$.subscribe(
(data:boolean) => {
this.boolShowGTMDetails = data,
error => console.log(error),
console.log("winner winner chicken dinner");
}
);
}
</code></pre>
<p>Basically the change detection isn't working, any help would be much appreciated, thanks in advance!</p>
| <p>You have some formatting issues in your subscription. This should work:</p>
<pre><code> this.subscription = this.service.subBoolShowHide$.subscribe(
(data:boolean) => { this.boolShowGTMDetails = data },
error => console.log(error),
() => console.log("winner winner chicken dinner")
);
</code></pre>
|
RecyclerView height changes if keyboard is visible <p>I have a RecyclerView in my app. It is part of a fragment (one of several) in an activity. The problem is, when the keyboard is closed it will max out in height and use its internal scroller. When the keyboard opens, the internal scroller turns off and the RecyclerView shows all its children.</p>
<p>The RecyclerView has the option for elements to be added or removed by the end user. In my full implementation, it shows four elements before starting to scroll (with the keyboard closed). When it is the sole fragment, it will max out its height at the screen height.</p>
<p>I've tried setting setting the NestedScrollEnabled to false and while this does stop scrolling, the items it would normally scroll to are no longer accessible. The RecyclerView still changes height depending on keyboard status so the 'hidden' rows become visible when the keyboard is open.</p>
<p>So in short, my RecyclerView is changing its height depending on keyboard visibility. How do I always make it show all its children?</p>
<p>Simplified fragment code that still shows the issue.
Java: <a href="https://gist.github.com/anonymous/bd46e137a0fb52f79399c11ba5be61bf" rel="nofollow">https://gist.github.com/anonymous/bd46e137a0fb52f79399c11ba5be61bf</a>
XML: <a href="https://gist.github.com/anonymous/c9bfb3f7577f75befc7aa6d5569311ce" rel="nofollow">https://gist.github.com/anonymous/c9bfb3f7577f75befc7aa6d5569311ce</a></p>
<p>I'm using com.android.support:recyclerview-v7:24.2.1</p>
| <p>I've encounter an issue using last RecyclerView version.. and even AOSP project don't use the last RecyclerView version.</p>
<p>So ,maybe this will solve your problem, use 23.x.x version and let me know if that resolved the problem :)</p>
|
phoenix ecto relationships on delete <p>There are two models: resource and metadata:</p>
<pre><code>defmodule Myapp.Repo.Migrations.CreateResources do
use Ecto.Migration
def change do
create table(:resources) do
add :name, :string
add :parent_id, references(:resources, on_delete: :delete_all)
timestamps
end
create index(:resources, [:parent_id])
end
end
defmodule Myapp.Repo.Migrations.CreateMetadata do
use Ecto.Migration
def change do
create table(:metadata) do
add :size, :integer
add :resource_id, references(:resources)
timestamps
end
create index(:metadata, [:resource_id])
end
end
schema "resources" do
field :name, :string
belongs_to :parent, Myapp.Resource
has_one :metadata, Myapp.Metadata, on_delete: :delete_all
has_many :childs, Myapp.Resource, foreign_key: :parent_id, on_delete: :delete_all
timestamps()
end
schema "metadata" do
field :size, :integer
belongs_to :resource, Myapp.Resource
timestamps()
end
</code></pre>
<p>resource can have children, which parent_id = id.
also has a resource metadata. Table Metadata has resource_id column.
Now, I want to delete the resource with the remove all his children, and all associated metadata.
when I write</p>
<pre><code>Repo.delete resource
</code></pre>
<p>I get an error:</p>
<pre><code>[error] #PID<0.441.0> running Myapp.Endpoint terminated
Server: localhost:4000 (http)
Request: POST /resources/%2Fdocs%2Ftest
** (exit) an exception was raised:
** (Postgrex.Error) ERROR (foreign_key_violation): update or delete on table "resources" violates foreign key constraint "metadata_resource_id_fkey" on table "metadata"
table: metadata
constraint: metadata_resource_id_fkey
Key (id)=(3) is still referenced from table "metadata".
</code></pre>
<p>that appears only when triggered to remove metadata from a resource children. If I try to delete a resource that has no childrens, then everything is working correctly. </p>
<p>Apparently, does not cause the removal of the children required callbacks removing metadata, so Postgres an error. </p>
<p>Whether it is possible to solve this problem without suffering from resource_id metadata metadata_id resource and without starting a recursive manual removal of all the children of the resource?</p>
| <p><strong>:delete_all</strong> does not cascade to child records unless set via database migrations. To fix the problem make sure you change your metadata migration script line to</p>
<pre><code>add :resource_id, references(:resources, on_delete: :delete_all)
</code></pre>
|
Loop for ARMA model estimation <p>Suppose that I have the following "for" loop in R.</p>
<pre><code>USDlogreturns=diff(log(prices))
for(i in 0:5){
for(j in 0:5){
fit <- arima(USDlogreturns, order=c(i,0,j), include.mean=TRUE)
}
}
</code></pre>
<p>How do you tell R to substitute a NA matrix with the coefficients of all the estimated models?</p>
| <p>You will need a matrix <code>M</code> with dimensions 36 times 13.
Then use</p>
<pre><code>M=matrix(NA,36,13)
k=0 # current row being filled in
for(i in 0:5){
for(j in 0:5){
k=k+1
fit <- arima(USDlogreturns, order=c(i,0,j), include.mean=TRUE)
if(i>0) M[k,c(1: i) ]=fit$coef[c( 1 : i )] # AR coefficients in the 2nd-6th columns
if(j>0) M[k,c(8:(7+j))]=fit$coef[c((i+1):(i+j))] # MA coefficients in the 8th-12th columns
M[k, 13 ]=tail(fit$coef,1) # "intercept" (actually, mean) in the 13th column
}
}
</code></pre>
<p>The columns 2 to 6 will contain AR coefficients.<br>
The columns 8 to 12 will contain MA coefficients.<br>
The 13th column will contain the "intercepts" (actually, the means, as the terminology in the <code>arima</code> function is misleading).</p>
|
Retaining punctuations in a word <p>How can i remove punctuations from a line, but retain punctuation in the word using <strong><em>re</em></strong> ??</p>
<p>For Example :</p>
<pre><code>Input = "Hello!!!, i don't like to 'some String' .... isn't"
Output = (['hello','i', 'don't','like','to', 'some', 'string', 'isn't'])
</code></pre>
<p>I am trying to do this:</p>
<pre><code>re.sub('\W+', ' ', myLine.lower()).split()
</code></pre>
<p>But this is splitting the words like "<strong><em>don't</em></strong>" into <strong><em>don</em></strong> and <strong><em>t</em></strong>. </p>
| <p>You can use lookarounds in your regex:</p>
<pre><code>>>> input = "Hello!!!, i didn''''t don't like to 'some String' .... isn't"
>>> regex = r'\W+(?!\S*[a-z])|(?<!\S)\W+'
>>> print re.sub(regex, '', input, 0, re.IGNORECASE).split()
['Hello', 'i', "didn''''t", "don't", 'like', 'to', 'some', 'String', "isn't"]
</code></pre>
<p><a href="https://regex101.com/r/qiNd4L/5" rel="nofollow">RegEx Demo</a></p>
<p><code>\W+(?!\S*[a-z])|(?<!\S)\W+</code> matches a non-word, non-space character that doesn't have a letter at previous position or a letter at next position after 1 or more non-space characters.</p>
|
LayoutInflater not working for Android <p>I am trying to add a LinearLayout as a child to another LinearLayout component, but it will not show up on the screen at all. </p>
<p>XML:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ReceivedMessage"
android:background="@android:color/holo_blue_light"
android:visibility="visible"
tools:showIn="@layout/content_chat">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@mipmap/ic_launcher"
android:id="@+id/ProfilePicture"
android:layout_weight="1" />
<TextView
android:text=" Message"
android:layout_width="305dp"
android:layout_height="match_parent"
android:id="@+id/MessageText"
android:gravity="center_vertical" />
</LinearLayout>
</code></pre>
<p>Code:</p>
<pre><code>Button testMessageButton = (Button) findViewById(R.id.TestMessageButton);
testMessageButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
LinearLayout msgLayout = (LinearLayout) findViewById(R.id.MessageLayout);
LayoutInflater vi = (LayoutInflater)getBaseContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.message_received, msgLayout, false);
msgLayout.addView(v);
}
});
</code></pre>
<p>What is causing the component to not appear on the screen?</p>
| <p>Your question is not correct but I will answer it in two different ways</p>
<p>First, if the LinearLayout you want to add is in a different xml file then you can inflate the xml file and add it to parent LinearLayout in your Activity class like this</p>
<pre><code>Button testMessageButton = (Button) findViewById(R.id.TestMessageButton);
testMessageButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
LinearLayout msgLayout = (LinearLayout) findViewById(R.id.MessageLayout);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LayoutInflater vi = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.message_received, null);
v.setLayoutParams(params);
msgLayout.addView(v);
}
});
</code></pre>
<p><strong>I have updated my solution</strong>. Part of the problem is in your layout file</p>
<p>This is the Activity class </p>
<pre><code>import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private LinearLayout mainLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainLayout = (LinearLayout)findViewById(R.id.main_layout);
Button addChatButton = (Button)findViewById(R.id.add_chat);
addChatButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LayoutInflater vi = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout mView = (LinearLayout)vi.inflate(R.layout.test_layout, mainLayout, false);
mView.setLayoutParams(params);
mainLayout.addView(mView);
}
});
}
}
</code></pre>
<p>The xml layout file for Activity class</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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.inducesmile.mylinear.MainActivity">
<Button
android:id="@+id/add_chat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="80dp"
android:text="@string/add_chat"
android:layout_gravity="center|center_horizontal"/>
</LinearLayout>
</code></pre>
<p>Finally, the layout file that contains the Linearlayout to be inflated and add to the root LinearLayout.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/ReceivedMessage"
android:background="@android:color/holo_blue_light"
android:visibility="visible">
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher"
android:id="@+id/ProfilePicture"
android:layout_weight="2" />
<TextView
android:text="@string/message"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/MessageText"
android:layout_weight="7"
android:paddingTop="14dp"
android:paddingBottom="14dp"
android:gravity="center_vertical" />
</LinearLayout>
</code></pre>
<p><a href="https://i.stack.imgur.com/PnXPH.png" rel="nofollow"><img src="https://i.stack.imgur.com/PnXPH.png" alt="enter image description here"></a></p>
|
How to save extra fields in archive table using Ejabberd mod_mam (Message Archive Management, XEP-0313)? <p>I am using Ejabberd server for chatting application. It works to save messages in arhieve table, but I want to save additional field in the table when message is sent. This field will be per message.</p>
| <p>There are some ways to achieve this.
The first and the simplest way (but it only affects 'xml' field in the 'archive' table) is an implementation of 'store_mam_message' hook in your custom module. You can modify Packet inside that hook and return new packet which should be saved in the DB. This hook is available since v16.09</p>
<p>If you modified 'archive' table (a new column has been added to it), then the second way helps:</p>
<ol>
<li><p>Create your custom module and call it "<strong>mod_mam</strong>_sql2"</p></li>
<li><p>Copy the content of "src/mod_mam_sql.erl" into your custom module</p></li>
<li><p>Find the function store/7.</p>
<pre>
store(Pkt, LServer, {LUser, LHost}, Type, Peer, Nick, _Dir) ->
TSinteger = p1_time_compat:system_time(micro_seconds),
ID = jlib:integer_to_binary(TSinteger),
SUser = case Type of
chat -> LUser;
groupchat -> jid:to_string({LUser, LHost, >})
end,
BarePeer = jid:to_string(
jid:tolower(
jid:remove_resource(Peer))),
LPeer = jid:to_string(
jid:tolower(Peer)),
XML = fxml:element_to_binary(Pkt),
Body = fxml:get_subtag_cdata(Pkt, >),
SType = jlib:atom_to_binary(Type),
case ejabberd_sql:sql_query(
LServer,
?SQL("insert into archive (username, timestamp,"
" peer, bare_peer, xml, txt, kind, nick) values ("
"%(SUser)s, "
"%(TSinteger)d, "
"%(LPeer)s, "
"%(BarePeer)s, "
"%(XML)s, "
"%(Body)s, "
"%(SType)s, "
"%(Nick)s)")) of
{updated, _} ->
{ok, ID};
Err ->
Err
end.
</pre></li>
<li><p>Change the SQL-query as you need</p></li>
<li><p>Compile your custom module: ejabberdctl module_install mod_mam_sql2</p></li>
<li><p>Update ejabberd.yml config file</p>
<pre>
mod_mam:
db_type: sql2
</pre></li>
<li><p>Restart ejabberd server: ejabberdctl restart</p></li>
</ol>
<p>I hope it will help you to solve your issue.</p>
|
Rails, Heroku and contact form <p>I am trying to implement a simple contact form inside my app. Read through couple of SO posts but still no full solution.</p>
<p>My contact form is working in the development environment.
Here is my setup in the config file:</p>
<pre><code> config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_url_options = { :host => 'my_app_name.herokuapp.com' }
ActionMailer::Base.smtp_settings = {
:address => 'smtp.gmail.com',
:domain => 'mail.google.com',
:port => 587,
:user_name => 'my_email@gmail.com',
:password => 'my_password',
:authentication => :plain,
}
</code></pre>
<p>What I get after running <code>heroku logs</code> is:</p>
<pre><code>2016-10-14T21:08:48.912404+00:00 app[web.1]: I, [2016-10-14T21:08:48.912360 #3] INFO -- : [eb99e511-dde1-45bc-b56a-6a919f519800] Completed 500 Internal Server Error in 858ms (ActiveRecord: 3.8ms)
2016-10-14T21:08:48.912986+00:00 app[web.1]: F, [2016-10-14T21:08:48.912936 #3] FATAL -- : [eb99e511-dde1-45bc-b56a-6a919f519800]
2016-10-14T21:08:48.913019+00:00 app[web.1]: F, [2016-10-14T21:08:48.912985 #3] FATAL -- : [eb99e511-dde1-45bc-b56a-6a919f519800] Net::SMTPAuthenticationError (534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbuE
</code></pre>
<p>I have also read <a href="http://stackoverflow.com/questions/18124878/netsmtpauthenticationerror-when-sending-email-from-rails-app-on-staging-envir">this thread</a>, turned on the things that the answer and the comment advised to, but the error still appears.</p>
<p>Anything I missed?</p>
<p>Are there any gems/ plugins that I should consider using instead of built-in ActionMailer?</p>
| <p>I ended up using Sendgrid free plan. Good documentation so it was simple to implement.</p>
|
Add Field Wrapping JSON - PowerShell <p>I have an array that I convert to json. But I want each object in the array to be wrapped by another field.</p>
<pre><code>$Array =
Field1; Field2
-----------------
Value11; Value12
Value21; Value22
</code></pre>
<p>If I convert that array to JSON it looks like this:</p>
<pre><code>Array
[
{
"Field1": "Value11",
"Field2": "Value12"
},
{
"Field1": "Value21",
"Field2": "Value22"
}
]
</code></pre>
<p>I want it to look like this:</p>
<pre><code>Array
[
{"NewWrapper":
{
"Field1": "Value11",
"Field2": "Value12"
}
},
{"NewWrapper":
{
"Field1": "Value21",
"Field2": "Value22"
}
}
]
</code></pre>
<p>How do I either format the source or the json to achieve that?</p>
| <p>Try the following:</p>
<pre><code>$Array | ForEach-Object { @{ NewWrapper=$_ } } | ConvertTo-Json
</code></pre>
<p><code>@{ NewWrapper=$_ }</code> wraps each input object in a hashtable (<code>@{ ... }</code>) whose one and only entry, <code>NewWrapper</code>, is the input object (<code>$_</code>).</p>
<p>When <code>ConvertTo-Json</code> serializes this hashtable, it produces the desired output.</p>
<hr>
<p>Complete example:</p>
<pre><code># Create sample input objects...
$Array = [pscustomobject] @{ Field1 = 'Value11'; Field2 = 'Value12' },
[pscustomobject] @{ Field1 = 'Value21'; Field2 = 'Value12' }
# ... wrap them, and convert them to JSON.
$Array | ForEach-Object { @{ NewWrapper=$_ } } | ConvertTo-Json
</code></pre>
|
Using raw_input inside functions <p>I can't figure out why <code>raw_input</code> isn't being called when I run the function. Instead of being asked <code>"At bats?"</code> I get the below error:</p>
<pre><code>Traceback (most recent call last):
File "ex19a.py", line 9, in <module>
Slugging()
TypeError: Slugging() takes exactly 2 arguments (0 given)
</code></pre>
<p>I know that two arguments are required but I thought I set up the function to use the <code>raw_input</code>s as the arguments.</p>
<p>My code is:</p>
<pre><code>def Slugging(At_Bats, Total_Bases):
At_Bats = float(raw_input("At bats?"))
Total_Bases = int(raw_input("Total Bases?"))
Percentage = (At_Bats / Total_Bases)
print "Analysing data..."
print "Your slugging percentage is %.3f" % Percentage
Slugging()
</code></pre>
| <p>Try removing the parameters from your Slugging function! Your current error is because you are calling the Slugging function with 0 arguments and it expects 2 (At_Bats and Total_Bases).</p>
<pre><code>def Slugging():
At_Bats = float(raw_input("At bats?"))
Total_Bases = int(raw_input("Total Bases?"))
Percentage = (At_Bats / Total_Bases)
print "Analysing data..."
print "Your slugging percentage is %.3f" % Percentage
Slugging()
</code></pre>
|
Recursive method call on es2015 class method transpiled with babel <p>I'm having problems when i try to call a instance method recursively. </p>
<p>The code looks as follows:</p>
<pre><code>import fs from 'fs';
import fsWatcher from 'filewatcher';
import path from 'path';
export default class SearchService {
initializeFileWatcher(foldersToWatch) {
let result = fsWatcher();
for (var i = 0; i < foldersToWatch.length; i++) {
result.add(foldersToWatch[i]);
}
return result;
}
getFilesFromDirectoriesRecursively(directories, fileExtension) {
let result = [];
for (var i = 0; i < directories.length; i++) {
var dir = directories[i];
var list = fs.readdirSync(dir);
list.forEach(function (file) {
file = dir + '/' + file;
var stat = fs.statSync(file);
if (stat && stat.isDirectory())
result = result.concat(this.getFilesFromDirectoriesRecursively([file], fileExtension).bind(this));
else
if (path.extname(file) === fileExtension)
result.push(file);
});
}
return result;
}
getFilesFromDirectory(directory, fileExtension) {
var result = [];
var files = fs.readdirSync(directory);
for (var i = 0; i < files.length; i++) {
if (files[i].endsWith(fileExtension))
result.push(files[i]);
}
return result;
}
</code></pre>
<p>}</p>
<p>The code get transpiled with babel-es2015 and runs on a electron app environment. No when I try to call the method <em>getFilesFromDirectoriesRecursively</em> inside itself the transpiled code get in troubles because of the <em>this</em> which point to the instance in es2015 but not in the transpiled code.</p>
<p>How can I get around this problem?</p>
| <p>I could solve the problem. As @zerkms mentioned is was using the <em>this</em> keyword false. I tried to bind <em>this</em> with the <code>.bind</code> keyword what does not work with anonymous functions.</p>
<p>So I applied the the solution described here: <a href="http://stackoverflow.com/questions/22814097/how-to-pass-context-to-foreach-anonymous-function">How to pass context to forEach() anonymous function</a></p>
<pre><code>list.forEach( (file) => {
file = dir + '/' + file;
let stat = fs.statSync(file);
if (stat && stat.isDirectory())
result = result.concat(this.getFilesFromDirectoriesRecursively([file], fileExtension));
else
if (path.extname(file) === fileExtension)
result.push(file);
}, this);
</code></pre>
<p>Now its passing the <em>this</em> to the closure on the forEach function call</p>
<h1>Edit:</h1>
<p>It's not necessary to pass this because the arrow function is doing this.</p>
<pre><code>list.forEach( (file) => {
file = dir + '/' + file;
let stat = fs.statSync(file);
if (stat && stat.isDirectory())
result = result.concat(this.getFilesFromDirectoriesRecursively([file], fileExtension));
else
if (path.extname(file) === fileExtension)
result.push(file);
});
</code></pre>
|
How to get a temporary (or permanent) regular URL for a file in OneDrive using the Microsoft Graph API <p>Using <a href="http://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/item_createlink" rel="nofollow">createLink</a>, for example with the POST parameters: {"type": "view", "scope": "anonymous"}, you get a response including a <strong>webUrl</strong> which will open the item (in read-only or read-write mode, depending on the POST parameters) in Office Online. Because of the 'anonymous' scope, anyone (no login required) can open the office online page.</p>
<p>Unfortunately, I don't a link to Office Online, and it looks like this is the functionality provided by <a href="http://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/item_createlink" rel="nofollow">Create a sharing link for a DriveItem</a>.</p>
<p>I need a link to the actual file (to download it).
Something like many other 'files' APIs allow. This is, generate a time-limited (or permanent) URL to file.</p>
<p>Is this possible?</p>
<p>EDIT: Clarification: <a href="http://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/item_downloadcontent" rel="nofollow">Download the contents of a DriveItem</a> (i.e. a Stream) is not what I'm looking for.</p>
| <p>There are four ways of linking to a file in OneDrive via Microsoft Graph:</p>
<ul>
<li>The web preview for the file, which is accessed from the webUrl property of DriveItem. This requires the user to be signed in to access.</li>
<li>The WebDAV URL for the file, which is accessed from the webDavUrl property of DriveItem. This also requires the user to be signed in to access, but is a direct link to the file. Note: this is available via Microsoft Graph, but is only documented on <a href="https://dev.onedrive.com/resources/item.htm" rel="nofollow">dev.onedrive.com</a>.</li>
<li><a href="https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/item_createlink" rel="nofollow">Creating a sharing link</a>, which provides anonymous or organization restricted access to the web preview of the file.</li>
<li><a href="http://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/item_downloadcontent" rel="nofollow">Download link</a>, which is a short-duration URL available to download the contents of the file programmatically.</li>
</ul>
<p>It sounds like webDavUrl might be the link you are looking for.</p>
|
Loop for pandas columns <p>I want to apply kruskal test for several columns. I do as bellow</p>
<pre><code>import pandas as pd
import scipy
df = pd.DataFrame({'a':range(9), 'b':[1,2,3,1,2,3,1,2,3], 'group':['a', 'b', 'c']*3})
</code></pre>
<p>and then the Loop</p>
<pre><code>groups = {}
res = []
for grp in df['group'].unique():
for column in df[[0, 1]]:
groups[grp] = df[column][df['group']==grp].values
args = groups.values()
g = scipy.stats.kruskal(*args)
res.append(g)
print (res)
</code></pre>
<p>I get </p>
<pre><code>[KruskalResult(statistic=8.0000000000000036, pvalue=0.018315638888734137)]
</code></pre>
<p>But i want</p>
<pre><code>[KruskalResult(statistic=0.80000000000000071, pvalue=0.67032004603563911)]
[KruskalResult(statistic=8.0000000000000036, pvalue=0.018315638888734137)]
</code></pre>
<p>Where is my mistake?</p>
<p>for a single column i do as below</p>
<pre><code>import pandas as pd
import scipy
df = pd.DataFrame({'numbers':range(9), 'group':['a', 'b', 'c']*3})
groups = {}
for grp in df['group'].unique():
groups[grp] = df['numbers'][df['group']==grp].values
print(groups)
args = groups.values()
scipy.stats.kruskal(*args)
</code></pre>
| <p>Your for loops are upside down: the one-column algorithm is your loop invariant with regards to the column you chose. So the column for loop must be the outer loop. In plain English "for each column apply the kruskal algorithm which consists of this group.unique for loop:</p>
<pre><code>groups = {}
res = []
for column in df[[0, 1]]:
for grp in df['group'].unique():
groups[grp] = df[column][df['group']==grp].values
args = groups.values()
g = scipy.stats.kruskal(*args)
res.append(g)
print (res)
</code></pre>
|
Database for counting page accesses <p>So let's say I have a site with appx. 40000 articles.
What Im hoping to do is record the number of page visits per each article overtime.</p>
<p>Basically the end goal is to be able to visualize via graph the number of lookups for any article between any period of time.<br>
Here's an example: <a href="https://books.google.com/ngrams" rel="nofollow">https://books.google.com/ngrams</a> </p>
<p>I've began thinking about mysql data structure -> but my brain tells me it's probably not the right task for mysql. Almost seems like I'd need to use some specific nosql analytics solution. </p>
<p>Could anyone advice what DB is the right fit for this job?</p>
| <p>SQL is fine. It supports <code>UPDATE</code> statements that guarantee your count is correct rather than just eventual consistency.</p>
<p>Although most people will just use a log file, and process this on-demand. Unless you are Google scale, that will be fast enough.</p>
<p>There exist many tools for this, often including some very efficient specialized data structures such as RDDs that you won't find in any database. Why don't you just use them?</p>
|
generalizing scalar inputs to array inputs for user-defined fucntions <p>The <code>round</code> function can take a scalar and operate on it. However it can also take an array and operate on it in expected manner. </p>
<pre><code>>> round(2.3)
ans =
2
>> round([2.3,3.4])
ans =
2 3
</code></pre>
<p>I similarly have a function and want it to work in the ""expected"" manner for array inputs. It works well for scalar inputs. I could run a <code>for</code> loop and evaluate my function on each element of the array but what other smarter ways do i have available?</p>
<p><strong>For further concreteness</strong>, i have:</p>
<pre><code>function [a,b]=func(c,d,e,f)
</code></pre>
<p>And i have <code>d,e,f</code> but i want to evaluate the function to several values of <code>c</code>:-</p>
<pre><code>g=[];
for i=1:10
[a,b]=func(c(i),d,e,f);
g=[g;[a,b]];
end
</code></pre>
<p>I am not fully sure how to apply <code>arrayfun</code> though i believe it is what i should use.</p>
| <p>What you are looking for is the <em>arrayfun</em> function.
Here is the documentation: <a href="http://www.mathworks.com/help/matlab/ref/arrayfun.html" rel="nofollow">http://www.mathworks.com/help/matlab/ref/arrayfun.html</a></p>
<p>Say, I have this function:</p>
<pre><code>function res = myTest(a,b)
size(a) % for checking that we work on each element
res = a+1;
res = res +b;
</code></pre>
<p>I have a matrix <em>A</em></p>
<pre><code>A = magic(3);
</code></pre>
<p>I want to apply <em>myTest</em> with <em>a</em> equal to each element in <em>A</em></p>
<pre><code>A1 = arrayfun(@(x) myTest(x,2),A)
</code></pre>
<p>(<em>x</em> is replaced by the elements of the array declared after the comma)</p>
|
Laravel blade global variable <p>I have a problem in global variables in laravel. I know about view composer and my question is not related to that subject.
How can I do such a simple thing in laravel view (*.blade.php | <em>.php) template engine?
for example this is a sample code from one of my views (</em>.blade.php | *.php):</p>
<pre><code><?php
function myFunc() {
global $myvar;
if ( ! $myvar ) {
$myvar = 'my var is empty';
}
dd( $myvar );
}
$myvar = 'my var value';
myFunc();
</code></pre>
<p>At the end of the execution it shows up 'my var is empty' and not 'my var value'.
Anybody knows why this happens?</p>
| <p>The best solution is to use the <code>Config</code> facade. You can create a new config file and set, in your case, global variables statically. But the best feature of this facade, are the <code>get()</code> and <code>set()</code> methods, which allow you to define these variables dynamically. See: <a href="http://stackoverflow.com/questions/36923763/set-global-variables-in-laravel-5">Set Global variables in Laravel 5</a></p>
<p>In your case:</p>
<pre><code><?php
function myFunc() {
$myvar = Config::get('vars.myvar');
if ( ! $myvar ) {
$myvar = 'my var is empty';
}
dd( $myvar );
}
Config::set('vars.myvar');
myFunc();
</code></pre>
<p>Make sure you import the <code>Config</code> facade by using <code>use</code> on the top of your file.</p>
|
how to sum multiple columns into one result from database in php? is that posible? <p>i have big database table and i need result from multiple columns into one. its about how much people is checked from some conturies and every contry has own column. here is some of it:
<code>rs_turista</code>, <code>rs_nocenja</code>, <code>agencija_turista</code>, <code>agencija_nocenja</code>, <code>at_turista</code>, <code>at_nocenja</code>, <code>be_turista</code>, <code>be_nocenja</code>, <code>ba_turista</code>...
they is checking every day. i need to sum it all in php for report. is that posible?</p>
| <p>Don't do it in PHP, that's needlessly selecting too much data from a database. All you gotta do is use a <code>SUM()</code> and <code>+</code> like so:</p>
<pre><code>SELECT SUM(column1) + SUM(column2) + SUM(column3) + ... AS total
FROM table
WHERE <filters for a date or other requirements>
</code></pre>
|
Qicli not starting on Naoqi SDK 2.4.3.28 <p>I tried to use qicli provided in the Naoqi SDK 2.4.3.28 on MacOS (10.12) but it doesn't start:</p>
<pre><code>dyld: Library not loaded: libboost_date_time.dylib
Referenced from: ..../naoqi-sdk-2.4.3.28-mac64/bin/./qicli
Reason: image not found
Abort trap: 6
</code></pre>
<p>Anyone knows how to solve this issue?</p>
| <p>There are apparently some broken dependencies in the SDK's binaries.</p>
<p>Would you mind having a go at the script <a href="http://pastebin.com/WgPdUBXr" rel="nofollow" title="here">here on pastebin</a>? It should fix the dependencies issue for the 2.4.3 SDK. You need to be either on El Capitan or Sierra, with either Xcode7 or Xcode8 installed.</p>
<p>The steps:</p>
<ul>
<li>run the fix_naoqi.sh script, giving it the full path to naoqi-bin
(e.g. /bin/naoqi-bin) </li>
<li>install opencv using: brew install homebrew/science/opencv </li>
<li>try now </li>
<li>if any problem (you may have if you already installed another NAOqi SDK): export DYLD_LIBRARY_PATH=""</li>
</ul>
|
React Native _this2.refs.myinput.focus is not a function <p>Using React-Native, I have a custom component which extends from TextInput like so:</p>
<p><strong>TextBox.js</strong></p>
<pre><code>...
render() {
return (
<TextInput
{...this.props}
style={styles.textBox}/>
);
}
...
</code></pre>
<p><strong>MyScene.js</strong> (imports TextBox.js)</p>
<pre><code>...
render() {
render(
<View>
<TextBox
rel='MyFirstInput'
returnKeyType={'next'}
onSubmitEditing={(event) => { this.refs.MySecondInput.focus(); }}/>
<TextBox
ref='MySecondInput'/>
</View>
);
}
</code></pre>
<p>When I build the app and press next on the keyboard when focusing on <code>MyFirstInput</code>, I expect <code>MySecondInput</code> to be in focus, instead I get the error:</p>
<pre><code>_this2.refs.MySecondInput.focus is not a function
</code></pre>
<p>What could the error be? Is it something to do with the scope of <code>this</code>? Thanks.</p>
| <p>Maybe it's because the ref doesn't return an HTML element? I don't think it has to do anything with the this scope, it just says .focus is not a function, so it can't be executed probably because .focus does not exist on a non HTML element?</p>
<p><a href="https://developer.mozilla.org/en/docs/Web/API/HTMLElement/focus" rel="nofollow">MDN .focus</a> shows that it has to be an HTML element, maybe you should log the ref MySecondInput and see if you get an element?</p>
|
How to combine SUM, LEFT JOIN and WHERE, the where is with a date range <p>I have 5 tables (all have the same name fields, except id), and I need to do a SUM but the SUM depends of a range of date.</p>
<pre><code>$query2= "SELECT SUM(i.unidadesllantas)+SUM(c.unidadesllantas)+SUM(t.unidadesllantas)+SUM(s.unidadesllantas)+SUM(ca.unidadesllantas) AS tunidadesllantas,
SUM(i.alineaciones)+SUM(c.alineaciones)+SUM(t.alineaciones)+SUM(s.alineaciones)+SUM(ca.alineaciones) AS talineaciones,
SUM(i.balanceos)+SUM(c.balanceos)+SUM(t.balanceos)+SUM(s.balanceos)+SUM(ca.balanceos) AS tbalanceos,
SUM(i.montajes)+SUM(c.montajes)+SUM(t.montajes)+SUM(s.montajes)+SUM(ca.montajes) AS tmontajes
FROM insurgentes i
LEFT JOIN cuesta c ON (i.id_insurgentes=c.id_cuesta)
LEFT JOIN torres t ON (c.id_cuesta=t.id_torres)
LEFT JOIN satelite s ON (t.id_torres=s.id_satelite)
LEFT JOIN campestre ca ON (s.id_satelite=ca.id_campestre) WHERE fecha>='$_POST[fecha1]' AND fecha<='$_POST[fecha2]'";
</code></pre>
<p>If I quit the WHERE clause it works, but I need the SUM in the range of date...</p>
<p>Can you help me</p>
| <p>When dealing with multiple tables, prefix all column names with the table name (or the table alias) in the WHERE clause of your statement so that MYSQL will know where to look for them.</p>
<p>Assuming the field <code>fecha</code> is in the <code>insurgentes</code> table, this should give you the result you want:</p>
<pre><code>SELECT
SUM(`i`.`unidadesllantas`) + SUM(`c`.`unidadesllantas`) + SUM(`t`.`unidadesllantas`) + SUM(`s`.`unidadesllantas`) + SUM(`ca`.`unidadesllantas`) AS `tunidadesllantas`,
SUM(`i`.`alineaciones`) + SUM(`c`.`alineaciones`) + SUM(`t`.`alineaciones`) + SUM(`s`.`alineaciones`) + SUM(`ca`.`alineaciones`) AS `talineaciones`,
SUM(`i`.`balanceos`) + SUM(`c`.`balanceos`) + SUM(`t`.`balanceos`) + SUM(`s`.`balanceos`) + SUM(`ca`.`balanceos`) AS `tbalanceos`,
SUM(`i`.`montajes`) + SUM(`c`.`montajes`) + SUM(`t`.`montajes`) + SUM(`s`.`montajes`) + SUM(`ca`.`montajes`) AS `tmontajes`
FROM
`insurgentes` `i`
LEFT JOIN `cuesta` `c`
ON
`i`.`id_insurgentes` = `c`.`id_cuesta`
LEFT JOIN `torres` `t`
ON
`c`.`id_cuesta` = `t`.`id_torres`
LEFT JOIN `satelite` `s`
ON
`t`.`id_torres` = `s`.`id_satelite`
LEFT JOIN `campestre` `ca`
ON
`s`.`id_satelite` = `ca`.`id_campestre`
WHERE
`i`.`fecha` >= '$_POST[fecha1]'
AND `i`.`fecha` <= '$_POST[fecha2]'"
</code></pre>
<p><strong>NOTE</strong></p>
<p>Your question is missing information on table structures, so the best I can is guess which table the field <code>fecha</code> belongs to.</p>
|
Python Flask: RQ Worker raising KeyError because of environment variable <p>I'm trying to setup a redis queue and a worker to process the queue with my flask app. I'm implementing this to handle a task that sends emails. I'm a little confused because it appears that the stack trace is saying that my 'APP_SETTINGS' environment variable is not set when it is in fact set.</p>
<p>Prior to starting up the app, redis or the worker, I set APP_SETTINGS:</p>
<pre><code>export APP_SETTINGS="project.config.DevelopmentConfig"
</code></pre>
<p>However, when an item gets added to the queue, here's the stack trace:</p>
<pre><code>17:00:00 *** Listening on default...
17:00:59 default: project.email.sendMailInBG(<flask_mail.Message object at 0x7fc930e1c3d0>) (aacf9546-5558-4db8-9232-5f36c25d521b)
17:01:00 KeyError: 'APP_SETTINGS'
Traceback (most recent call last):
File "/home/tony/pyp-launch/venv/local/lib/python2.7/site-packages/rq/worker.py", line 588, in perform_job
rv = job.perform()
File "/home/tony/pyp-launch/venv/local/lib/python2.7/site-packages/rq/job.py", line 498, in perform
self._result = self.func(*self.args, **self.kwargs)
File "/home/tony/pyp-launch/venv/local/lib/python2.7/site-packages/rq/job.py", line 206, in func
return import_attribute(self.func_name)
File "/home/tony/pyp-launch/venv/local/lib/python2.7/site-packages/rq/utils.py", line 150, in import_attribute
module = importlib.import_module(module_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/tony/pyp-launch/project/__init__.py", line 24, in <module>
app.config.from_object(os.environ['APP_SETTINGS'])
File "/home/tony/pyp-launch/venv/lib/python2.7/UserDict.py", line 40, in __getitem__
raise KeyError(key)
KeyError: 'APP_SETTINGS'
Traceback (most recent call last):
File "/home/tony/pyp-launch/venv/local/lib/python2.7/site-packages/rq/worker.py", line 588, in perform_job
rv = job.perform()
File "/home/tony/pyp-launch/venv/local/lib/python2.7/site-packages/rq/job.py", line 498, in perform
self._result = self.func(*self.args, **self.kwargs)
File "/home/tony/pyp-launch/venv/local/lib/python2.7/site-packages/rq/job.py", line 206, in func
return import_attribute(self.func_name)
File "/home/tony/pyp-launch/venv/local/lib/python2.7/site-packages/rq/utils.py", line 150, in import_attribute
module = importlib.import_module(module_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/tony/pyp-launch/project/__init__.py", line 24, in <module>
app.config.from_object(os.environ['APP_SETTINGS'])
File "/home/tony/pyp-launch/venv/lib/python2.7/UserDict.py", line 40, in __getitem__
raise KeyError(key)
KeyError: 'APP_SETTINGS'
17:01:00 Moving job to u'failed' queue
17:01:00
17:01:00 *** Listening on default...
</code></pre>
<p><strong>email.py</strong></p>
<pre><code>from flask.ext.mail import Message
from project import app, mail
from redis import Redis
from rq import use_connection, Queue
q = Queue(connection=Redis())
def send_email(to, subject, template, emailable):
if emailable==True:
msg = Message(
subject,
recipients=[to],
html=template,
sender=app.config['MAIL_DEFAULT_SENDER']
)
q.enqueue(sendMailInBG, msg)
else:
print("no email sent, emailable set to: " + str(emailable))
def sendMailInBG(msgContent):
with app.test_request_context():
mail.send(msgContent)
</code></pre>
<p><strong>worker.py</strong></p>
<pre><code>import os
import redis
from rq import Worker, Queue, Connection
listen = ['default']
redis_url = os.getenv('REDISTOGO_URL', 'redis://localhost:6379')
conn = redis.from_url(redis_url)
if __name__ == '__main__':
with Connection(conn):
worker = Worker(list(map(Queue, listen)))
worker.work()
</code></pre>
<p>I'd really appreciate another set of eyes on this. I can't for the life of me figure out what's going on here.</p>
| <p>Thanks to the prompting of @danidee, I discovered that the environment variables need to be defined in each terminal. Hence, APP_SETTINGS was defined for the actual app, but not for the worker.</p>
<p>The solution was to set APP_SETTINGS in the worker terminal. </p>
|
Form validation HTML5 <p>I am using the 'required' attribute in my form child tags for validation. The problem that I have is that, when I first click submit, no validation takes place and an empty form also gets submitted. </p>
<p>From the second time on wards, each time I click submit the validation check kicks in and reports an empty field. </p>
<p>My code: </p>
<pre><code><form>
<label for="id">ID:</label>
<input type="text" class="form-control" id="id" required>
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" required />
<button type="submit" class="btn btn-info pull-right" id="sub">Submit</button>
</form>
</code></pre>
<p>POST request:</p>
<pre><code>$("#sub").click(function(){
var sendf = {
id: $("#id").val(),
name: $("#name").val()
};
$.ajax({
type: "POST",
url: "",
data: sendf,
dataType: "text",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
success: function(response, status, xhr) {
},
}); //ajax ends
event.preventDefault();
$(this).unbind();
});//sub click ends
</code></pre>
<p>Am I doing anything wrong? On button click, its just a simple POST request that takes place. Any help is appreciated. Thanks !</p>
| <p>The problem is you are intercepting the click action on the button - so the html form validation never takes place and the POST will process happily because you never check that the form is valid before sending it.</p>
<p>It works fine the second time because after the first click you have unbound your click handler and the form submits using a regular form submit event - resulting in the page reloading as it is no longer being handled by the AJAX request (in the now unbound click handler).</p>
<p>If you instead bind your function to the form's submit event, the browser <em>will</em> run the HTML form validation first, before calling your event handler. If you remove the <code>$(this).unbind();</code> you will continue to submit the form via AJAX and not with a page reload.</p>
<p>use this code (<a href="https://jsfiddle.net/nhjm0h7b/" rel="nofollow">jsFiddle demo</a>):</p>
<pre><code>$("form").on("submit", function(ev){
ev.preventDefault(); //prevent regular form submission via a page reload
var sendf = {
id: $("#id").val(),
name: $("#name").val()
};
$.ajax({
type: "POST",
url: "https://httpbin.org/post",
data: sendf,
dataType: "text",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
success: function(response, status, xhr) {
console.log(response);
},
}); //ajax ends
});//sub click ends
</code></pre>
<p>If you do want to disable submitting the form more than once, see <a href="http://stackoverflow.com/questions/926816/how-to-prevent-form-from-submitting-multiple-times-from-client-side">this question</a>.</p>
|
Flow HTMLElement.querySelector returning an iframe <p>Flow doesn't seem to recognize that <code>querySelector</code> may return subtypes of <code>HTMLElement</code>:</p>
<pre><code>var myIframe = document.querySelector('iframe');
function foo(iframe: HTMLIFrameElement): void {
// I want to do iframe stuff!
}
foo(myIframe);
</code></pre>
<p>Produces</p>
<pre><code>10: foo(myIframe);
^ HTMLElement. This type is incompatible with
6: function foo(iframe: HTMLIFrameElement): void {
^ HTMLIFrameElement
</code></pre>
<p>On <a href="https://flowtype.org/try" rel="nofollow">https://flowtype.org/try</a>.</p>
<p>Is there any way I can type <code>myIframe</code> that will let me use both its <code>HTMLElement</code> properties and its <code>HTMLIFrameElement</code> properties, apart from typing it as <code>Object</code>?</p>
| <p>Flow doesn't know how to parse a selector, which it would need to do to understand what kind of element would be returned. It is able to understand <code>getElementsByTagName</code>'s simpler API, though, so <a href="https://github.com/facebook/flow/blob/efd42c2cade13f42a9be7522580a108c0e2a20b2/lib/dom.js#L811" rel="nofollow">it knows</a> that <code>getElementsByTagName('iframe')</code> returns <code>HTMLCollection<HTMLIFrameElement></code>.</p>
<p>Using <code>querySelector</code>, you'd need to cast it. Something like this:</p>
<p><code>var myIframe = ((document.querySelector('iframe'): any): HTMLIFrameElement);</code></p>
|
Strange behaviour when computing svd on a covariance matrix: different results between Microsoft R and vanilla R <p>I was doing some principal component analysis on my macbook running Microsoft R 3.3.0 when I got some strange results. Double checking with a colleague, I've realised that the output of the SVD function was different from what I may get by using vanilla R. </p>
<p>This is the reproducible result, please load the file (~78 Mb) <a href="https://dl.dropboxusercontent.com/u/1249990/Cx.rda" rel="nofollow">here</a> </p>
<p>With Microsoft R 3.3.0 (x86_64-apple-darwin14.5.0) I get:</p>
<pre><code>>> sv <- svd(Cx)
>> print(sv$d[1:10])
[1] 122.73664 104.45759 90.52001 87.21890 81.28256 74.33418 73.29427 66.26472 63.51379
[10] 55.20763
</code></pre>
<p>Instead on a vanilla R (both with R 3.3 and R 3.3.1 on two different linux machines):</p>
<pre><code>>> sv <- svd(Cx)
>> print(sv$d[1:10])
[1] 122.73664 34.67177 18.50610 14.04483 8.35690 6.80784 6.14566
[8] 3.91788 3.76016 2.66381
</code></pre>
<p>This is not happening with all the data, if I create some random matrix and I apply svd on that, I get the same results. So, it looks like a sort of numerical instability, isn't it? </p>
<p>UPDATE: I've tried to compute the SVD on the same matrix (<code>Cx</code>) on the same machine (macbook) with the same version of R by using the <code>svd</code>Â package and finally I get the "right" numbers. Then it seems due to the svd implementation used by Microsoft R Open. </p>
<p>UPDATE: The behaviour happens also on MRO 3.3.1 </p>
| <p>The typical example forms an ill-conditioned matrix. There are some SV closest to zero making the SVD decomposition numerical sensitive to different implementations of the SVD, which is probably what you are seen </p>
|
bootstrap hidden-xs not working <p>I just found out about hidden-xs, hidden-sm etc, so am trying it out for the first time..</p>
<p>How come this doesn't hide the review div on any screen size?</p>
<pre><code><div class="row hidden-sm">
<div class="col-xs-12">
<result-reviews [result]='selectedResult?.result.result'></result-reviews>
</div>
</div>
</code></pre>
<p>Here is more of my code:</p>
<pre><code><div class="modal-body">
<div class="container-fluid">
<div class="row">
<div class="col-lg-7">
<div class="row">
<div id="image-div" class="col-sm-5 col-lg-5">
<result-image [result]='selectedResult?.result.result'></result-image>
</div>
<div class="col-sm-7 col-lg-7">
<result-attributes [result]='selectedResult?.result.result'></result-attributes>
</div>
</div>
<div class="row hidden-sm">
<div class="col-xs-12">
<result-reviews [result]='selectedResult?.result.result'></result-reviews>
</div>
</div>
</div>
<div class="col-lg-5">
<div id="shops-section">
<div id="map" #map></div>
<ul>
<li *ngFor="let shop of selectedResult?.result.result.nearbyShops">
<div class="shop-details">
{{ shop.name }}
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</code></pre>
| <blockquote>
<p>How come this doesn't hide the review div on any screen size?</p>
</blockquote>
<p>Read this part of the bootstrap documentation: <a href="http://getbootstrap.com/css/#responsive-utilities-classes" rel="nofollow">http://getbootstrap.com/css/#responsive-utilities-classes</a></p>
<p><code>hidden-sm</code> will only apply to sizes between 768 and 992px width.</p>
|
Communication error between Arduino and Qt using Xbee PRO S1 <p>I've been trying to do a Lights GUI with an Arduino Mega 2560 with its Xbee Shield and two Xbee Pro S1, one connected to the Arduino and the other one to the PC. My problem is: however I can send data from Qt to my arduino and read it, i can't do the same in the other way. When trying to send a String as "Confirmado\r\n", it arrives to my Qt label wrong, sometimes I get the full String, other ones I receive half of it.</p>
<p>My arduino code is </p>
<pre><code>char buffer[50];
String trama, dir, com, data;
int indexdir, indexcom, indexdata;
void setup(){
Serial.begin(9600);
}
void loop(){
trama= "Confirmado\r\n";
const char *bf = trama.c_str();
if(Serial.available() > 0)
{
Serial.readBytesUntil('/', buffer,500);
Serial.print(bf);
Serial.flush();
}
}
</code></pre>
<p>My Qt QSerialPort config is</p>
<pre><code>MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
serial = new QSerialPort(this);
serial->setPortName("COM3"); //COM-port your Arduino is connected to
serial->open(QIODevice::ReadWrite);
serial->setBaudRate(QSerialPort::Baud9600);
serial->setDataBits(QSerialPort::Data8);
serial->setParity(QSerialPort::NoParity);
serial->setStopBits(QSerialPort::OneStop);
serial->setFlowControl(QSerialPort::NoFlowControl);
connect(serial,SIGNAL(readyRead()),this,SLOT(serialReceived()));
}
</code></pre>
<p>And I send and read data like this</p>
<pre><code>void MainWindow::serialReceived()
{
QByteArray readData = serial->readAll();
//while (serial->waitForReadyRead(500))
// readData.append(serial->readAll());
ui->label->setText(readData);
}
void MainWindow::writeData(const QByteArray &data)
{
serial->write(data);
serial->flush();
serial->waitForBytesWritten(500);
}
</code></pre>
<p>The toogle lines means I've tried both options...</p>
<p>I've noticed, doing Debug, that if I place a breakpoint in <code>ui->label->setText(readData);</code>; if it doesnt arrive well (the full "Confirmado\r\n" string), this breakpoint gets twice in this line, the first one readData equals the second half of the string (i.e "mado\r\n") and the other one it values the rest of the string (i.e "Confir").</p>
<p>I've also tried to set a higher baudrate, 57600, but I cant send or receive any data, though I've set the baudrate in the XCTU app before.</p>
<p>Does anyone know a way to receive the full string from Arduino? Or at leats how to setup properly Arduino's and PC's Xbee to work with higher baudrates?</p>
<p>Thanks for the answers, and sorry for my writing skills...</p>
| <p>Try use <code>serial->readLine()</code> instead of <code>serial->readall()</code> you can for example wait in loop after the <code>serial->canReadLine()</code> returns the true then you be sure that the data are you received is a full string.</p>
|
Mod x Page not updating <p>I've created a snippet and included it on my template and when I make changes to the file it does not show. If I view the snippet it looks like it has changed</p>
<p>This is my snippet (really simple):</p>
<pre><code>echo date();
</code></pre>
<p>This is my update:</p>
<pre><code>echo rand(0, 1000);
</code></pre>
<p>Shown above is the change however in my template it will not change.</p>
<p>I know this might seems stupid (it is). However I hope you can help.</p>
| <p>If partial cache is enabled then you will find you have will to clear the Modx cache manually.</p>
<p>To do this, log into the admin area, and go to:</p>
<p><code>Site</code> -> <code>Clear Cache</code></p>
|
Merge Multiple records into a single record <p>I have the following query that produces multiple records for a single id. I'm trying to figure out how to merge these multiple records into one record:</p>
<pre><code>SELECT DISTINCT id, gender, dateofbirth, city, state, zip
FROM t
</code></pre>
<p>This may give me the following resultset:</p>
<pre><code>1, M, 2000-01-01, dallas, tx, 12345
1, M, 2000-01-01, NULL, NULL, NULL
</code></pre>
<p>What I want is a single record:</p>
<pre><code>1, M, 2000-01-01, dallas, tx, 12345
</code></pre>
<p>A similar scenario occurs when the second row has different data:</p>
<pre><code>1, M, 2000-01-01, dallas, tx, 12345
1, M, 2000-01-01, houston, tx, 67890
</code></pre>
<p>In this case I would just want to pick one of the records and ignore the other in order to only have a single record per id.</p>
<p>Is there a way to do this in PostgreSQL? I've tried coalesce to no avail and is wondering if there is some way to handle this.</p>
| <p>The query below appears to be working, at least for your sample data. Have a look at the Fiddle below for a demo. I used MySQL, because Fiddle tends to break for any other database type.</p>
<pre><code>SELECT t1.*
FROM yourTable t1
INNER JOIN
(
SELECT id, MAX(city || ', ' || state || ', ' || zip) AS location
FROM yourTable
GROUP BY id
) t2
ON t1.id = t2.id AND
t1.city || ', ' || t1.state || ', ' || t1.zip = t2.location
</code></pre>
<p><a href="http://sqlfiddle.com/#!9/0442db/3" rel="nofollow"><h1>SQLFiddle</h1></a></p>
<p>The trick I use is to concatenate the city, state, and zip into a single string and then choose the max value for group of <code>id</code> values. This would work assuming that it is not possible to somehow form the same string from two different addresses. I think this would hold true for your US address format.</p>
|
Append new items in database only <p>I have a table called <code>classes</code>
Which has fields:</p>
<p><code>course name</code><br>
<code>times_mentioned</code></p>
<p>So what I'm trying to do is. Set <code>course_name</code> and <code>times_Mentioned</code> to null at first.
But when a user for instance in my website chooses a class, I just want to append that class name and keep adding +1 to <code>times_mentioned</code> for a specific class. </p>
<p>This is what I have so far</p>
<pre><code>class popular_courses(db.Model):
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(80), unique=True, default=None)
times_mentioned =db.Column(db.String(80), default=None, unique=True)
def __repr__(self):
return '<Popular Courses %r>' % (self.name)
@app.route('/add/<coursename>')
def AddCourseName(coursename):
addPopularCourse = popular_courses(name=coursename, times_mentioned=##DONT KNOW THE SYNTAX)
</code></pre>
<p>So like I'd want class name and add +1 every time the user visits /add URL. How would I do it? I don't know the syntax for it either.</p>
<p>@app.route('/add/')</p>
<pre><code>def AddCourseName(coursename):
try:
addPopularCourse = popular_courses(name=coursename, times_mentioned=1)
db.session.add(addPopularCourse)
db.session.commit()
return "added! " + coursename + " to db"
except exc.SQLAlchemyError:
db.session.rollback()
user = popular_courses.query.filter_by(name=coursename).first()
user.name = coursename
user.times_mentioned += 1
db.session.commit()
</code></pre>
<p>Is this the efficient approach?</p>
| <p>1- change type of <code>times_mentioned</code> to <code>integer</code></p>
<p>2- use <code>count</code> func to check if instance exist if so increase counter else create a new one</p>
<pre><code>def AddCourseName(coursename):
if db.session.query(popular_courses.id).filter(popular_courses.namââe==coursename).countââ() > 0:
course = popular_courses.query.filter_by(name=coursename).first()
course.name = coursename
course.times_mentioned += 1
db.session.commit()
return "increased by 1! "
else:
addPopularCourse = popular_courses(name=coursename, times_mentioned=1)
db.session.add(addPopularCourse)
db.session.commit()
return "added! " + coursename + " to db"
</code></pre>
|
RegExp: Match numbers inside the brackets, but not the brackets <p>Brackets cannot be nested, and I only need to match a number that's inside the round brackets, but not include the brackets themselves!</p>
<p>Example: <code>asd asdfad(000) asdda</code> and <code>aaa_. (000000)11xx(</code>, match should be <code>000</code> and <code>000000</code>.</p>
| <p>If you're looking to extract the number, you can use capture groups.</p>
<pre><code>str.match(/\((\d+)\)/)[1]
</code></pre>
<p>The important parts to note are that the literal parentheses are escaped like so <code>\(</code> and <code>\)</code> while the unescaped parentheses define the capture group.</p>
<p><code>\d+</code> matches any number of digits.</p>
|
VBS script to rename files using the pathname <p>i am new to VBS scripting and I have done few stuff with Excel VBA before. Now I have a script which renames single files with the pathname of the files (truncated to 4 letter each))see below. It is some script which I modified a bit to fit my purpose. However, I would like to automatize the file rename process and rename all files in a folder and its subfolders in the same way the scipt works for single files. Can anybody help me with this question?</p>
<pre><code>Set Shell = WScript.CreateObject("WScript.Shell")
Set Parameter = WScript.Arguments
For i = 0 To Parameter.Count - 1
Set fso = CreateObject("Scripting.FileSystemObject")
findFolder = fso.GetParentFolderName(Parameter(i))
PathName = fso.GetAbsolutePathName(Parameter(i))
FileExt = fso.GetExtensionName(Parameter(i))
Search = ":"
findFolder2= Right(PathName, Len(PathName) - InStrRev(PathName, Search))
arr = Split(findFolder2, "\")
For j=0 To UBound(arr)-1
arr(j) = ucase(Left(arr(j), 4))
Next
joined = Join(arr, "%")
prefix = right(joined, len(joined)-1)
fso.MoveFile Parameter(i), findFolder + "\" + prefix
next
</code></pre>
<p>Hoping that I can get some useful ideas. </p>
<p>Herbie</p>
| <p>Walking a tree requires recursion, a function calling itself for each level.</p>
<pre><code>On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
Dirname = InputBox("Enter Dir name")
ProcessFolder DirName
Sub ProcessFolder(FolderPath)
On Error Resume Next
Set fldr = fso.GetFolder(FolderPath)
Set Fls = fldr.files
For Each thing in Fls
msgbox Thing.Name & " " & Thing.DateLastModified
Next
Set fldrs = fldr.subfolders
For Each thing in fldrs
ProcessFolder thing.path
Next
End Sub
</code></pre>
<p>From Help on how to run another file.</p>
<pre><code>Set Shell = WScript.CreateObject("WScript.Shell")
shell.Run(strCommand, [intWindowStyle], [bWaitOnReturn])
</code></pre>
<p>So outside the loop,</p>
<pre><code>Set Shell = WScript.CreateObject("WScript.Shell")
</code></pre>
<p>And in the loop</p>
<pre><code>shell.Run("wscript Yourscript.vbs thing.name, 1, True)
</code></pre>
<p>Also the VBS help file has recently been taken down at MS web site. It is available on my skydrive at <a href="https://1drv.ms/f/s!AvqkaKIXzvDieQFjUcKneSZhDjw" rel="nofollow">https://1drv.ms/f/s!AvqkaKIXzvDieQFjUcKneSZhDjw</a> It's called script56.chm.</p>
|
Editing Highcharts.js donut data programmatically va JS <p>I am trying to do the same for donut (editing the donut data programmatically), but the code just wouldn't work for me, although the syntax seems to be straghtforward here. </p>
<p>My goal is to find the data point in the donut which corresponds to the given x-axis value and set the value to 10. Any ideas on this ?</p>
<p>Here's the <a href="http://jsfiddle.net/caLv5d6x/" rel="nofollow">JSFIddle</a></p>
<pre><code>btnEdit.click(function() {
// chart.series[0].data[0].update(x += 10); - this code doesn't work
var x = prompt("Please enter your name");
// find the data point that corresponds to x
// Set it to 10
});
</code></pre>
| <p>Actually, you are looking for a point by its name, not its x value, because x value is a number, name is a string (for categorized data there is natural mapping between those two).</p>
<pre><code>btnEdit.click(function() {
// chart.series[0].data[0].update(x += 10); - this code doesn't work
var i = 0,
points = chart.series[0].data,
len = points.length,
x = prompt("Please enter your name"),
point;
for (; i < len; i++) {
point = points[i];
if (point.name === x) {
point.update({
y: 10
});
break;
}
}
// find the data point that corresponds to x
// Set it to 10
});
</code></pre>
<p>Example: <a href="http://jsfiddle.net/caLv5d6x/3/" rel="nofollow">http://jsfiddle.net/caLv5d6x/3/</a></p>
<p>The above solution assumes that you have points which their name are unique - but it doesn't have to be like that.
A small adjustment is enough:</p>
<pre><code> btnEdit.click(function() {
// chart.series[0].data[0].update(x += 10); - this code doesn't work
var x = prompt("Please enter your name");
chart.series[0].data.forEach(function (point) {
if (point.name === x) {
point.update({
y: 10
}, false, false);
}
});
chart.redraw();
// find the data point that corresponds to x
// Set it to 10
});
</code></pre>
<p>Example: <a href="http://jsfiddle.net/caLv5d6x/4/" rel="nofollow">http://jsfiddle.net/caLv5d6x/4/</a></p>
|
Convert string to array in php, output it and then output in ascending and descending order <p>I have so far I have managed to convert a string to an array in php and out put it with a foreach and an echo statement. But when I try to sort it I get an error like this:</p>
<blockquote>
<p>Warning: asort() expects parameter 1 to be array. </p>
</blockquote>
<p>In the text book I'm studying it shows an example like this: </p>
<pre><code>sort($array[,$compare]).
</code></pre>
<p>I don't quite understand that. I don't want to use the <code>print_r</code> function. I just want to echo out the result So I've come here to ask for help. I appreciate any advice. Here is my code:</p>
<pre><code> <form action="list.php" method="post">
<input type="text" name="names">
<br>
<input type="submit" value="Submit">
<?php
if(!isset($name)) {$name = '';}
if(!isset($names)) {$names = '';}
if(!isset($value)) {$value = '';}
if(!isset($myarray)) {$myarray = '';}
$name = filter_input(INPUT_POST, 'name');
$names = filter_input(INPUT_POST, 'names');
$myarray = filter_input(INPUT_POST, 'myarray');
if($myarray === NULL){
$myarray = array();
}
$myarray = $names;
$name = explode(' ', $myarray);
foreach($name as $value){
echo ($value)."<br>";
}
$myarray = $names;
$name = explode(' ', $myarray);
foreach($name as $value){
echo asort($value)."<br>";
}
$myarray = $names;
$name = explode(' ', $myarray);
foreach($name as $value){
echo arsort($value)."<br>";
}
?>
</code></pre>
| <p>You have to sort before the loop.
I.e.</p>
<pre><code>asort($name);
foreach($name as $value){
echo $value."<br>";
}
$myarray = $names;
$name = explode(' ', $myarray);
arsort($name);
foreach($name as $value){
echo $value."<br>";
}
</code></pre>
|
Return from page not triggering `INavigationAware.OnNavigatedTo` <p>I have a <code>NavigationPage</code> with <code>ContentPage</code>s. When I use the back arrow provided by the <code>NavigationPage</code> instead of <code>INavigationService.GoBackAsync</code>, my implementation of <code>INavigationAware.OnNavigatedTo</code> is never called. Based on browsing the source, it looks like Prism doesn't listen for the event when the <code>NavigationPage</code> does a pop. </p>
<p>Is there something I need to do to make it hit that or is there no way to tap into that? Is there a specific reason not to hook in to that?</p>
| <p>This is a known issue. You can follow the request here:</p>
<p><a href="https://github.com/PrismLibrary/Prism/issues/634" rel="nofollow">https://github.com/PrismLibrary/Prism/issues/634</a></p>
<p>The problem is that there is no unified API for Prism to use in order to call INavigationAware when a Page is popped. There are many more scenarios that just NavigationPages that must be considered. For now, you can simply hook into the event yourself in a custom NavigationPage and call the INavigationAware events. Xamarin will be implementing an API for Prism to use n a future release. Until then, you must handle this manually.</p>
|
Template argument deduction for class templates and multiple parameters packs <p>In C++17 template arguments for a class template will be deduced more or less as it happens nowadays for a function template.<br>
<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0091r2.html" rel="nofollow">Here</a> is the relevant paper.</p>
<p>As an example from the above mentioned paper:</p>
<pre><code>template<class ... Ts> struct X { X(Ts...) };
X x1{1}; // OK X<int>
X x11; // OK X<>
</code></pre>
<p>Function templates have another interesting feature when deduction happens.<br>
Consider the following code:</p>
<pre><code>template<typename... U, typename... T>
auto func(T&&...) {}
// ...
// U is int, char - T is int, double
func<int, char>(0, .0);
</code></pre>
<p>We can have two parameters packs as long as deduction helps to discriminate between them.<br>
No need to wrap them within a tuple or some other structure.</p>
<p><strong>Will it be possible to do the same with class templates?</strong></p>
<p>As an example:</p>
<pre><code>template<typename... U, typename... T>
struct S {
S(T&&...) {}
};
// ...
// U is int, char - T is int, double
S<int, char> s{0, .0};
</code></pre>
<p>The paper contains the example below:</p>
<pre><code>template<class ... Ts> struct X { X(Ts...) };
X<int> x3{1, 'a', "bc"}; // OK X<int,char,const char*>
</code></pre>
<p>Anyway, it isn't exactly the same thing and I'm not sure if it will be allowed or not.</p>
| <p>This:</p>
<pre><code>template<typename... U, typename... T>
struct S { ... };
</code></pre>
<p>is just ill-formed per [temp.param]:</p>
<blockquote>
<p>If a <em>template-parameter</em> of a primary class template, primary variable template, or alias template is a template parameter pack, it shall be the last <em>template-parameter</em>.</p>
</blockquote>
<p>This case:</p>
<pre><code>template<class ... Ts> struct X { X(Ts...) };
X<int> x3{1, 'a', "bc"}; // OK X<int,char,const char*>
</code></pre>
<p>is problematic since <code>X<int></code> is already a valid type. This part of the paper was dropped in Oulu, though it's possible some proposal in the future will make it possible to indicate that some of the class template parameters should be deduced but others should be specified:</p>
<pre><code>X<string, ???> x3{"a", 1, "b"}; // X<string, int, const char*>.
</code></pre>
<p>where <code>???</code> is some series of tokens that makes intent clear. </p>
|
postgres json_populate_recordset not working as expected <p>I have a table called <code>slices</code> with some simple json objects that looks like this:</p>
<pre><code>id | payload | metric_name
---|---------------------------------------|------------
1 | {"a_percent":99.97,"c_percent":99.97} | metric_c
2 | {"a_percent":98.37,"c_percent":97.93} | metric_c
</code></pre>
<p>many records of this. I am trying to get this:</p>
<pre><code>a_percent | c_percent
----------|----------
99.97 | 99.97
98.37 | 97.93
</code></pre>
<p>I am creating the type and using <code>json_populate_recordset</code> along with <code>json_agg</code> in the following fashion:</p>
<pre><code>CREATE TYPE c_history AS(
"a_percent" NUMERIC(5, 2),
"c_percent" NUMERIC(5, 2)
);
SELECT * FROM
json_populate_recordset(
NULL :: c_history,
(
SELECT json_agg(payload::json) FROM slices
WHERE metric_name = 'metric_c'
)
);
</code></pre>
<p>The clause <code>select json_agg(...)</code> by itself produces a nice array of json objects, as expected:</p>
<pre><code>[{"a_percent":99.97,"c_percent":99.97}, {"a_percent":98.37,"c_percent":97.93}]
</code></pre>
<p>But when I run it inside <code>json_populate_recordset</code>, I get <code>Error : ERROR: must call json_populate_recordset on an array of objects</code>.</p>
<p>What am I doing wrong?</p>
| <p>You don't need to use <code>json_agg</code>, since it appears you want to get the set of <code>a_percent</code> and <code>c_percent</code> values for each <code>id</code> in a separate record. Rather just call <code>json_populate_recordset</code> as follows:</p>
<pre><code>SELECT id, (json_populate_record(null::c_history, payload)).* FROM slices
</code></pre>
|
PHP - Can't insert into table with PDO <p>I am connected to my database using PDO. My problem is, I can't insert stuff into the table for some reason. I could do it when I connected using <code>mysqli_connect();</code> but that isn't secure enough for me.</p>
<p>Here is my code that connects to the database:</p>
<pre><code><?php
$user = "root";
$pass = "";
$loggedin;
$conn = new PDO('mysql:host=localhost;dbname=login', $user, $pass);
if (!$conn) {
die("Connection to the database failed");
}
</code></pre>
<p>Here is the code that is trying to insert stuff into the database:</p>
<pre><code><?php
include '../dbh.php';
$first = $_POST['first'];
$last = $_POST['last'];
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
if (empty($first)) {
header("Location: ../signup.php?error=empty");
exit();
} if (empty($last)) {
header("Location: ../signup.php?error=empty");
exit();
} if (empty($uid)) {
header("Location: ../signup.php?error=empty");
exit();
} if (empty($pwd)) {
header("Location: ../signup.php?error=empty");
exit();
} else {
$sql = "SELECT uid FROM users WHERE uid='$uid'";
$result = mysqli_query($conn, $sql);
$uidcheck = mysqli_num_rows($result);
if ($uidcheck > 0) {
header("Location: ../signup.php?error=username");
exit();
} else {
$sql = "INSERT INTO users (first, last, uid, pwd)
VALUES ('$first', '$last', '$uid', '$pwd')";
$result = mysqli_query($conn, $sql);
header("Location: ../index.php");
}
}
</code></pre>
| <pre><code>$sql = "INSERT INTO `users` (`first`, `last`, `uid`, `pwd`)
VALUES (:first, :last, :uid, :pwd)";
$sth = $conn->prepare($sql);
$sth->bindValue(':first', $first);
$sth->bindValue(':last', $last);
$sth->bindValue(':uid', $uid);
$sth->bindValue(':pwd', $pwd);
$sth->execute();
</code></pre>
|
WPF Custom control binding image source <p>I have a custom control based on a button, and I put an image inside. I can set the source of the image in the xaml, but if I try and bind it, it doesn't work.</p>
<p>Generic.xaml</p>
<pre><code><ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CustomControl">
<Style TargetType="{x:Type local:MyCustomControl}" BasedOn = "{StaticResource {x:Type Button}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MyCustomControl}">
<Grid x:Name="InnerGrid">
<Image Source="pathname"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
</code></pre>
<p>This works just fine, however if I replace the <code><Image Source="pathname"/></code> with <code><Image Source={Binding MyImage, RelativeSource={RelativeSource Self}}"/></code>, and reference a Delegate Property in the class, it breaks.</p>
<p>MyCustomControl.cs</p>
<pre><code>public class MyCustomControl : Button
{
static DependencyProperty m_myimage = null;
private DependencyProperty MyImageProperty
{
get
{
return m_myimage;
}
}
public BitmapImage MyImage
{
get
{
return (BitmapImage)GetValue(MyImageProperty);
}
set
{
SetValue(MyImageProperty, value);
}
}
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
MyImage = new BitmapImage(new Uri(pathname));
}
private static void RegisterDependencyProperties()
{
if (m_myimage == null)
{
m_myimage = DependencyProperty.Register("MyImage",
typeof(BitmapImage), typeof(MyCustomControl), null);
}
}
static MyCustomControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl),
new FrameworkPropertyMetadata(typeof(MyCustomControl)));
RegisterDependencyProperties();
}
}
</code></pre>
<p>How can I get it to work?</p>
| <p>Figured it out myself after about 2 hours. The xaml binding should look like,</p>
<pre><code><Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MyCustomControl}">
<Grid x:Name="InnerGrid">
<Image Source="{Binding MyImage, RelativeSource={RelativeSource TemplatedParent}}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</code></pre>
<p>Note that the binding relative resource went from <code>RelativeSource={RelativeSource Self}</code> to <code>RelativeSource={RelativeSource TemplatedParent}</code></p>
|
How to get out of the maze using recursion? <p>Let's consider a maze represented by a matrix of ints: 0 - not visited, 1 - obstacles (blocked positions), 2 - visited, -1 - output, (x,y) - start position. I want to find a path from start to some output by using recursion.</p>
<pre><code>int[] x_dir = new int[] { 0, 0, -1, 1 }; // x, x, x-1, x + 1
int[] y_dir = new int[] { -1, 1, 0, 0 }; // y-1, y+1, y, y
bool dfs(int[,] maze, int x, int y, int[] x_dir, int[] y_dir)
{
if (maze[x, y] == -1) { return true; } // output cell marked -1
int i = 0;
while (i < 4 && !dfs(maze, x + x_dir[i], y + y_dir[i], x_dir, y_dir))
{
++i;
}
return (i > 4) ? false : true;
}
</code></pre>
<p>I have two problem: I don't know how to handle edge cases(<code>IndexOutOfRangeException inside maze[x,y]</code>) and how to print a path.
Please, help me.</p>
| <p>To print a path, you need to keep track of it, which suggests adding a parameter for that purpose. Care must be taken to not include wrong turns in it, or at least to remove them once you know that is what they are.</p>
<p>Alternatively, if you print out the step you took for each call to <code>dfs</code> that returned <code>true</code>, you would have the path, but in reverse.</p>
<p>As for the edge (not corner) cases: you need to check that <code>x+x_dir[i]</code> and <code>y+y_dir[i]</code> are valid indices into the maze before trying to access those locations in the maze.</p>
|
How to save a JavaScript string on a server with PHP and request it again later? <p>So my problem is actually pretty simple:</p>
<p>I have this function (simplified) - it is triggered when a button is clicked:</p>
<pre class="lang-js prettyprint-override"><code>$search.onclick = function () {
// let's just say the user did put in a valid documentname
// something like "John"
documentname = $('#userinput').val();
url = "https://example.api.url.com/" + documentname + "&format=json"
// looks weird but "source = $.getJSON(url).done..." works like expected
source = $.getJSON(url).done(function () {
sourcestring1 = JSON.stringify(source);
// this findid(); below is just a function that takes the id i'm looking for
// out of the just stringified JSON (works also), it does "id = "123456"
// (just a number but in string format)
findid();
// id has a value now ("123456"), so lets console.log it
console.log(id);
});
};
</code></pre>
<p><hr></p>
<h2>What I want to do is:</h2>
<p>After <code>findid();</code> is executed and <code>id</code> has a value I want to save this value as a readable file on the server. It's filename should be the same as the name of the document it's coming from (in this case <code>John</code>). The content of the file should just be the value of <code>id</code> (in this case <code>123456</code>). Which file format? I don't know. And here is the next problem...
<hr></p>
<h2>Reuse the file:</h2>
<p>The next thing I wish I would be able to do is, to load this generated file when the exact documentname was inputted again by another user. Because if the file already exists, it would be unnecessary to load the whole JSON again. So the updated code would look like this (i know that this isn't actual code, but maybe it's easier to understand with this):</p>
<pre class="lang-js prettyprint-override"><code>$search.onclick = function () {
// another user inputs "John"
documentname = $('#userinput').val();
// so we want to prove if a file called "John" already exists on the server
if ([A FILENAME ON THE SERVER] == documentname) {
// if it exists, we just have to open that file and take the content (the id we saved before) out of it
[OPEN FILE/TAKE CONTENT]
// and just assign it to the variable
id = [CONTENT OF FILE]
// console.log it
console.log(id);
}
else {
// if it doesn't already exist, just run the normal code
url = "https://example.api.url.com/" + documentname + "&format=json"
source = $.getJSON(url).done(function () {
sourcestring1 = JSON.stringify(source);
findid();
// console.log it
console.log(id);
// and of course save this now on the server
[SOME PHP ACTION HERE]
});
}
};
</code></pre>
<p><hr>
I already tried a lot of things with Ajax and jQuery's <code>$.get</code>, I just have no idea how to handle sent things with PHP. I don't know which file format is best for this, or if this is even possible. I don't know how to transfer variables from JavaScript to PHP documents or how to use them there or vice versa.
<hr>
PS: My developer environment: I don't run a server by myself, I have some webspace and a domain from a web service. Yes it supports PHP. MySQL and other database types are available too, if that's a useful information. jQuery is also installed.
<hr>
Sorry again, for my bad english and for my lack of knowledge and interest in PHP and other serverside things. However, I hope you can help me somehow.</p>
| <p>You can use <code>localStorage</code> to store a file at users browser configuration folder : user filesystem. If file exists at <code>localStorage</code>, use the file from <code>localStorage</code> without making <code>$.getJSON()</code> request, else call <code>$.getJSON()</code>; at <code>success</code> of <code>$.getJSON()</code> set the file at <code>localStorage</code>.</p>
<pre><code>$search.onclick = function () {
// another user inputs "John"
documentname = $('#userinput').val();
// so we want to prove if a file called "John" already exists on the server
if (localStorage.getItem(documentname) != null) {
// if it exists, we just have to open that file and take the content (the id we saved before) out of it
// and just assign it to the variable
id = localStorage.getItem(documentname);
// console.log it
console.log(id);
}
else {
// if it doesn't already exist, just run the normal code
// and of course save this now on the server
// [SOME PHP ACTION HERE]
url = "https://example.api.url.com/" + documentname + "&format=json"
source = $.getJSON(url).done(function () {
sourcestring1 = JSON.stringify(source);
findid();
// console.log it
console.log(id);
// set `localStorage` item key to `documentname`
// set value to `id`
localStorage.setItem(documentname, id);
});
}
};
</code></pre>
<p>See also <a href="http://stackoverflow.com/questions/39784514/how-to-cache-a-downloaded-javascript-fle-which-is-downloaded-using-script-tag/39784622#39784622">How to cache a downloaded javascript fle which is downloaded using script tag</a></p>
|
Angular2 ng-bootstrap - no provider error <p>I am trying to integrate ng bootstrap UI into my Angular 2 project.
After following the simple instructions found here:
<a href="https://ng-bootstrap.github.io/#/getting-started" rel="nofollow">https://ng-bootstrap.github.io/#/getting-started</a> i get the following error when using any ngb bootstrap tag:</p>
<blockquote>
<p><strong>Error: No provider for NgbAlertConfig!</strong></p>
</blockquote>
<h2>app.module.ts</h2>
<pre><code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { StocksComponent } from './stocks/stocks.component';
import { HighlightDirective } from './highlight.directive';
import { StockService } from './stock.service';
import { DateFormatterPipe } from './date-formatter.pipe'
import { routing } from './app.routing';
import { DashboardComponent } from './dashboard/dashboard.component'
import { CurrencyService } from './currency.service';
import { BondsDirective } from './bonds.directive';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
@NgModule({
declarations: [
AppComponent,
StocksComponent,
HighlightDirective,
DateFormatterPipe,
DashboardComponent,
BondsDirective
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
routing,
NgbModule
],
providers: [StockService, CurrencyService],
bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre>
<h2>app.component.ts</h2>
<pre><code>import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
}
</code></pre>
<h2>app.component.html</h2>
<pre><code> <ngb-alert>
Random Message
</ngb-alert>
</code></pre>
<h2>angular-cli.json</h2>
<pre><code> {
"project": {
"version": "1.0.0-beta.17",
"name": "my-prog-cli"
},
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": "assets",
"index": "index.html",
"main": "main.ts",
"test": "test.ts",
"tsconfig": "tsconfig.json",
"prefix": "app",
"mobile": false,
"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.css",
"styles.css"
],
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/tether/dist/js/tether.js",
"../node_modules/bootstrap/dist/js/bootstrap.js"
],
"environments": {
"source": "environments/environment.ts",
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
}
],
"addons": [],
"packages": [],
"e2e": {
"protractor": {
"config": "./protractor.conf.js"
}
},
"test": {
"karma": {
"config": "./karma.conf.js"
}
},
"defaults": {
"styleExt": "css",
"prefixInterfaces": false
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/LpC50.png" rel="nofollow"><img src="https://i.stack.imgur.com/LpC50.png" alt="CONSOLE ERROR"></a></p>
| <p>import NgbModule in your app.module.ts like this-</p>
<pre><code>import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
</code></pre>
<p>and add it in imports section of ngmodule-</p>
<pre><code>@NgModule({
declarations: [AppComponent, ...],
imports: [NgbModule.forRoot(), ...],
bootstrap: [AppComponent]
})
</code></pre>
<p>See if this helps.</p>
|
Compare if two vectors are the same <p>How do I check if two vectors are identical? I've tried to do it with a <code>for</code> loop and <code>if</code> statement but that option is not suited for the amount of data that I've got to work with. Is there any smart way to do it? I would like to create an <code>if</code> statement that only adds a specific vector to a matrix if there is no such vector already in my matrix.</p>
<p>For example if I've got a vector <code>[1 2 3 1 2]</code> in my matrix i don't want to add another vector <code>[1 2 3 1 2]</code> to the matrix.</p>
| <p>For just checking whether 2 vectors are equal you can use the <code>==</code> operator on a vector and then use <code>all( )</code> to check that every element of the returned logical array is true. Andras Deak link in the comments has some great methods on finding a vector in a larger set.</p>
<pre><code>v1 = [1 2 3 1 2];
v2 = [1 2 3 1 2];
returnsTrue = all(v1 == v2);
</code></pre>
|
Move view up on TextView Edit Swift 3.0 <p>I know this question has asked several times, but I'm looking for an implementation that uses Swift 3.0. To be clear I have a Text VIEW, not a text FIELD. </p>
<p>I tried doing something like this...</p>
<p>In <code>viewDidLoad()</code>:</p>
<pre><code>NotificationCenter.default.addObserver(self, selector: Selector(("keyboardWillShow")), name:NSNotification.Name.UIKeyboardWillShow, object: nil);
NotificationCenter.default.addObserver(self, selector: Selector(("keyboardWillHide")), name:NSNotification.Name.UIKeyboardWillHide, object: nil);
</code></pre>
<p>Then I created these methods in the ViewController:</p>
<pre><code>func keyboardWillShow(sender: NSNotification) {
self.view.frame.origin.y = -150
}
func keyboardWillHide(sender: NSNotification) {
self.view.frame.origin.y = 0
}
</code></pre>
<p>I get a crash when I select the text view. </p>
| <p>You need to modify your add observer code as mentioned below.
As per Swift 3 migration guide this is the new way that should be followed to declare the add observer of notification.</p>
<p><strong>Code :</strong></p>
<pre><code> NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
</code></pre>
<p>I have checked this with demo code with text view and notification center.</p>
<p>Hope it helps ...</p>
<p>Happy coding ...</p>
|
How to mount shared volume across EC2 instances via Vagrant? <p>I'm using <a href="https://github.com/mitchellh/vagrant-aws" rel="nofollow">vagrant-aws</a> Vagrant plugin to run multiple disposable EC2 instances which are running tests, however my problem is that the provisioning script takes too long time (e.g. apt-get and downloading same files). I'm terminating my instances after run, as I don't want to pay for the existing instances when they're not in use (100x16G).</p>
<p>How can I configure my <em>Vagrantfile</em>, or in other words, what's the easiest way doing that, so I can re-use the same volume across multiple EC2 instances? Like mounting the specific volume, snapshot, creating <em>ami</em> or anything else? For example having 20 pre-configured volumes, each used by 200 disposable instances on startup time.</p>
| <p>If I get your question right, you want to save your instance the way it is before you terminate them.</p>
<p>First let me ask, isn't it easier if you just pause your instance? No hourly charges applied on a stopped instance, you only pay for the volumes reserved (full size of your volumes).</p>
<p>Another approach would be to create an image (AMI - Amazon Machine Image) of your instance the way it is when it's ready to work. To do that:</p>
<blockquote>
<p>EC2 > Instances > Select your instance > Actions > Image > Create
Image</p>
</blockquote>
<p>After your image is ready, it will show up in:</p>
<blockquote>
<p>EC2 > AMIs</p>
</blockquote>
<p>Where you can select an image and then:</p>
<blockquote>
<p>Actions > Launch</p>
</blockquote>
<p>You can repeat this launch process as many times as you want, each time a new copy of the same original instance will be created.</p>
<p><strong>Note</strong>: AWS will charge for the disk space used by your images, so keep an eye on that before creating lots of images - at least if your instances use big volumes.</p>
<p>Hope this helps,</p>
|
The compiler suggests I add a 'static lifetime because the parameter type may not live long enough, but I don't think that's what I want <p>Sorry for the vague title, but I'm fairly new to Rust, so I don't exactly know how to succinctly sum up my issue.</p>
<p>I'm trying to implement something that (showing minimal example) looks like this:</p>
<pre><code>trait Bar<T> {}
struct Foo<T> {
data: Vec<Box<Bar<T>>>
}
impl<T> Foo<T> {
fn add<U: Bar<T>>(&mut self, x: U) {
self.data.push(Box::new(x));
}
}
</code></pre>
<p>Since Rust defaults to (as far as I can tell) pass-by-ownership, my mental model thinks this should work. The add method takes ownership of object <code>x</code>, and then is able to move this object into a <code>Box</code> because it knows the full type <code>U</code> (and not just trait <code>Bar<T></code>). Once moved into a box, the lifetime of the item inside the box should be tied to the actual lifetime of the box (e.g., when <code>pop()</code>ed off the vector the object will be destroyed).</p>
<p>Clearly, however, the compiler disagrees (and I'm sure knows a bit more than I...), asking me to consider adding a <code>'static</code> lifetime qualifier (E0310). I am 99% sure that's not what I want, but I'm not exactly sure what I'm supposed to do.</p>
<p>To clarify what I'm thinking and help identify misconceptions, my model is essentially (I come from a C++ background):</p>
<ul>
<li><code>Box<T></code> is essentially <code>std::unique_ptr<T></code></li>
<li>Without any annotations, variables are passed by value if <code>Copy</code> and rvalue-reference otherwise</li>
<li>With a reference annotation, <code>&</code> is roughly <code>const&</code> and <code>&mut</code> is roughly <code>&</code></li>
<li>The default lifetime is lexical scope</li>
</ul>
| <p>Check out the entire error:</p>
<pre class="lang-none prettyprint-override"><code>error[E0310]: the parameter type `U` may not live long enough
--> src/main.rs:9:24
|
9 | self.data.push(Box::new(x));
| ^^^^^^^^^^^
|
= help: consider adding an explicit lifetime bound `U: 'static`...
note: ...so that the type `U` will meet its required lifetime bounds
--> src/main.rs:9:24
|
9 | self.data.push(Box::new(x));
| ^^^^^^^^^^^
</code></pre>
<p>Specifically, the compiler is letting you know that it's possible that some arbitrary type <code>U</code> <em>might contain a reference</em>, and that reference could then become invalid:</p>
<pre><code>impl<'a, T> Bar<T> for &'a str {}
fn main() {
let mut foo = Foo { data: vec![] };
{
let s = "oh no".to_string();
foo.add(s.as_ref());
}
}
</code></pre>
<p>That would be Bad News.</p>
<p>Whether you want a <code>'static</code> lifetime or a parameterized lifetime is up to your needs. The <code>'static</code> lifetime is easier to use, but has more restrictions. Because of this, it's the default when you declare a <em>trait object</em> in a struct:</p>
<pre><code>struct Foo<T> {
data: Vec<Box<Bar<T>>>,
// same as
// data: Vec<Box<Bar<T> + 'static>>,
}
</code></pre>
<p>However, when used as an argument, a trait object uses <em>lifetime elision</em> and gets a unique lifetime:</p>
<pre><code>fn foo(&self, x: Box<Bar<T>>)
// same as
// fn foo<'a, 'b>(&'a self, x: Box<Bar<T> + 'b>)
</code></pre>
<p>These two things need to match up.</p>
<pre><code>struct Foo<'a, T> {
data: Vec<Box<Bar<T> + 'a>>
}
impl<'a, T> Foo<'a, T> {
fn add<U>(&mut self, x: U)
where U: Bar<T> + 'a
{
self.data.push(Box::new(x));
}
}
</code></pre>
<p><strong>or</strong></p>
<pre><code>struct Foo<T> {
data: Vec<Box<Bar<T>>>
}
impl<T> Foo<T> {
fn add<U>(&mut self, x: U)
where U: Bar<T> + 'static
{
self.data.push(Box::new(x));
}
}
</code></pre>
|
How can I specify the user inside my docker container? <p>I don't want to be root inside a docker container.</p>
<p>I have tried the -u option but without success, if I call "id" inside the docker container I'm always root, what am I doing wrong?</p>
<pre><code>docker run coursera -u 1000:1000 /grader/executeGrader.sh HgVw
uid=0(root) gid=0(root) groups=0(root)
</code></pre>
| <p>Sorry, got the order wrong:</p>
<pre><code>docker run -u 1000:1000 coursera /grader/executeGrader.sh HgVwK
</code></pre>
|
Custom navbar with changed collpase breakpoint <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
<li><a href="#">Page-A</a></li>
<li><a href="#">Page-B</a></li>
<li><a href="#">Page-C</a></li>
<li><a href="#">Page-D</a></li>
<li><a href="#">Page-E</a></li>
<li><a href="#">Page-F</a></li>
<li><a href="#">Page-G</a></li>
<li><a href="#">Page-H</a></li>
<li><a href="#">Page-I</a></li>
<li><a href="#">Page-J</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav></code></pre>
</div>
</div>
</p>
<p>(1) Failed to develop custom navbar
(2) Failed to change collapse breakpoint</p>
<p>I am using Bootstrap interface and using style.css for customization I am in a middle of designing my navbar which should be transparent on top but after 300px scrollits get solid color i.e. fixed navbar. </p>
<p>Also as I have many pages to show in navbar list so want to change the collapse breakpoint as I have tried all the queries but could achieve the required result.</p>
<p>I have attempted alot of times but failed to develop I appreciate if any one of you help me in this regards.</p>
<p>Here is the Example: <a href="https://www.lyft.com/" rel="nofollow">https://www.lyft.com/</a></p>
<p>Thanks in Advance...</p>
| <p>Try this out. adding a class that has position:fixed when scroll is greater than a number.</p>
<p>CSS</p>
<pre><code>.content {
position: relative;
height: 800px;
}
.sticky {
position: fixed;
left: 0;
right: 0;
}
.no-border {
background-color: transparent;
border: none
}
</code></pre>
<p>JS</p>
<pre><code>$(function(){
var $nav = $('nav');
$(window).on('scroll', function(e){
if(this.scrollY >= 50 && !$nav.hasClass('sticky')){
$nav.removeClass('no-border');
$nav.addClass('sticky');
} else if(this.scrollY < 50 && $nav.hasClass('sticky')){
$nav.removeClass('sticky');
$nav.addClass('no-border')
}
});
});
</code></pre>
<p>html I have is kind of long, checkout the <a href="https://jsfiddle.net/gabs00/92wyekh5/1/" rel="nofollow">fiddle</a></p>
<p>edit: to add transparency</p>
|
How to plot two level x-axis labels for a histogram? <p>Is there a way to do the same of this two x-axis labels but for a histogram plot?
<a href="http://stackoverflow.com/questions/31803817/how-to-add-second-x-axis-at-the-bottom-of-the-first-one-in-matplotlib/40053591#40053591">How to add second x-axis at the bottom of the first one in matplotlib.?</a></p>
<p>I want to show the values in two levels, one for metric and the second for English units. I tried to adapt the script in the link above to a histogram script but I'm not sure how to connect the histogram function with the ax1. handle.</p>
<pre><code>"""
Demo of the histogram (hist) function with a few features.
In addition to the basic histogram, this demo shows a few optional features:
* Setting the number of data bins
* The ``normed`` flag, which normalizes bin heights so that the integral of
the histogram is 1. The resulting histogram is a probability density.
* Setting the face color of the bars
* Setting the opacity (alpha value).
"""
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()
# example data
mu = 100 # mean of distribution
sigma = 15 # standard deviation of distribution
x = mu + sigma * np.random.randn(10000)
num_bins = 50
# the histogram of the data
n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5)
ax1.set_xlabel(r"Original x-axis: $X$")
new_tick_locations = np.array([.2, .5, .9])
def tick_function(X):
V = 1/(1+X)
return ["%.3f" % z for z in V]
# Move twinned axis ticks and label from top to bottom
ax2.xaxis.set_ticks_position("bottom")
ax2.xaxis.set_label_position("bottom")
# Offset the twin axis below the host
ax2.spines["bottom"].set_position(("axes", -0.15))
# Turn on the frame for the twin axis, but then hide all
# but the bottom spine
ax2.set_frame_on(True)
ax2.patch.set_visible(False)
for sp in ax2.spines.itervalues():
sp.set_visible(False)
ax2.spines["bottom"].set_visible(True)
ax2.set_xticks(new_tick_locations)
ax2.set_xticklabels(tick_function(new_tick_locations))
ax2.set_xlabel(r"Modified x-axis: $1/(1+X)$")
y = mlab.normpdf(bins, mu, sigma)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')
# Tweak spacing to prevent clipping of ylabel
plt.subplots_adjust(left=0.15)
plt.show()
</code></pre>
| <p>just replace your <code>hist</code> call by:</p>
<pre><code>n, bins, patches = ax1.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5)
</code></pre>
<p>Check the <a href="http://matplotlib.org/api/axes_api.html" rel="nofollow">documentation for <code>Axes</code></a> to see what member functions are available</p>
|
Yii2 get access only using pretty URLs <p>I'm using URL manager like the following:</p>
<pre><code>'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'verses/view/<id:\d+>' => 'verses/view',
],
],
</code></pre>
<p>It works fine to make access using <code>mysite.com/verses/view/158</code>. The problem is, it is still possible to access the same content using non pretty URL i.e using plain get parameter such as <code>mysite.com/verses/view?id=158</code>. I need any way to restrict the access using the pretty URL.</p>
<p>I have tried the following couples of rules separately, but nothing I have gotten:</p>
<ol>
<li><code>'verses/view<?id=>' => 'Error404',</code></li>
<li><code>'verses/view?id=<\d+>' => 'Error404',</code></li>
</ol>
| <p>What is the point of such restriction?</p>
<p>Anyway, one way to do it is something like this:</p>
<pre><code>public function actionView($id)
{
if (strpos(\Yii::$app->request->getUrl(), '?') !== false) {
throw new \yii\web\BadRequestHttpException;
}
// ... the rest of action
}
</code></pre>
<p>No changes in UrlManager needed.</p>
|
Interleaving in OCaml <p>I am trying to create a function which interleaves a pair of triples such as ((6, 3, 2), ( 4, 5 ,1)) and create a 6-tuple out of this interleaving.
I made some research but could understand how interleaving is supposed to work so I tried something on my own end ended up with a code that is creating a 6-tuple but not in the right interleaved way. This is my code</p>
<pre><code>let interleave ((a, b, c), (a', b', c')) =
let sort2 (a, b) = if a > b then (a, b) else (b, a) in
let sort3 (a, b, c) =
let (a, b) = sort2 (a, b) in
let (b, c) = sort2 (b, c) in
let (a, b) = sort2 (a, b) in
(a, b, c) in
let touch ((x), (y)) =
let (x) = sort3 (x) in
let (y) = sort3 (y) in
((x),(y)) in
let ((a, b, c), (a', b', c')) = touch ((a, b, c), (a', b', c')) in
(a, b', a', b, c, c');;
</code></pre>
<p>Can someone please explain to me how with what functions I can achieve a proper form of interleaving. I haven't learned about recursions and lists in case you would ask why I am trying to do it this way.
Thank you already.</p>
| <p>The problem statement uses the word "max" without defining it. If you use the built-in <code>compare</code> function of OCaml as your definition, it uses <a href="https://en.wikipedia.org/wiki/Lexicographical_order" rel="nofollow">lexicographic order</a>. So you want the largest value (of the 6 values) in the first position in the 6-tuple, the second largest value next, and so on.</p>
<p>This should be pretty easy given your previously established skill with the sorting of tuples.</p>
<p>For what it's worth, there doesn't seem to be much value in preserving the identities of the two 3-tuples. Once inside the outermost function you can just work with the 6 values as a 6-tuple. Or so it would seem to me.</p>
<p><strong>Update</strong></p>
<p>From your example (should probably have given it at the beginning :-) it's pretty clear what you're being asked to do. You want to end up with a sequence in which the elements of the original tuples are in their original order, but they can be interleaved arbitrarily. This is often called a "shuffle" (or a merge). You have to find the shuffle that has the maximum value lexicographically.</p>
<p>If you reason this out, it amounts to taking whichever value is largest from the front of the two tuples and putting it next in the output.</p>
<p>This is <em>much</em> easier to do with lists.</p>
|
Can prolog be used to determine invalid inference? <p>If I have two premises as follows:</p>
<ol>
<li>a -> c (a implies c)</li>
<li>b -> c (b implies c)</li>
</ol>
<p>and a derived conclusion:</p>
<ol start="3">
<li>a -> b (a therefore implies b),</li>
</ol>
<p>then the conclusion can be shown to be invalid because:</p>
<p>a -> c is valid for statement #1 when a is true and c is true, and
b -> c is valid for statement #2 when b is false and c is true. This leads to a -> b when a is true and b is false, a direct contradiction of statement #3.</p>
<p>Or, per proof with a truth table that contains a line for where the premises are true but the conclusion is false:</p>
<p><a href="https://i.stack.imgur.com/WemIU.gif" rel="nofollow">Truth Table with true premises and false conclusion</a></p>
<p>My question is: "Is there a way to use prolog to show that the assertions of statements #1 and #2 contradict the conclusion of statement #3? If so, what is a clear and concise way to do so?" </p>
| <p>@coder has already given a very good answer, using <a href="/questions/tagged/clpb" class="post-tag" title="show questions tagged 'clpb'" rel="tag">clpb</a> constraints.</p>
<p>I would like to show a slightly different way to show that the conclusion does <em>not</em> follow from the premises, also using CLP(B).</p>
<p>The main difference is that I post <em>individual</em> <code>sat/1</code> constraints for each of the premises, and then use <code>taut/2</code> to see whether the conclusion follows from the premises.</p>
<p>The first premise is:</p>
<blockquote>
<p>a → c</p>
</blockquote>
<p>In CLP(B), you can express this as:</p>
<pre><code>sat(A =< C)
</code></pre>
<p>The second premise, i.e., b → c, becomes:</p>
<pre><code>sat(B =< C)
</code></pre>
<p>If the a → b followed from these premises, then <code>taut/2</code> would <strong>succeed</strong> with <code>T = 1</code> in:</p>
<pre>
?- sat(A =< C), sat(B =< C), taut(A =< B, T).
<b>false</b>.
</pre>
<p>Since it doesn't, we know that the conclusion does not follow from the premises.</p>
<p>We can ask CLP(B) to show a <strong>counterexample</strong>, i.e., an assignment of truth values to variables where a → c and b → c both hold, and a → b does not hold:</p>
<pre>
?- sat(A =< C), sat(B =< C), sat(<b>~</b>(A =< B)).
A = C, C = 1,
B = 0.
</pre>
<p>Simply posting the constraints <em>suffices</em> to show the unique counterexample that exists in this case. If the counterexample were not unique, we could use <code>labeling/1</code> to produce ground instances, for example: <code>labeling([A,B,C])</code>.</p>
<p>For comparison, consider for example:</p>
<pre>
?- sat(A =< B), sat(B =< C), taut(A =< C, T).
<b>T = 1</b>,
sat(A=:=A*B),
sat(B=:=B*C).
</pre>
<p>This shows that a → c follows from a → b ∧ b → c.</p>
|
PHP equivalent of Python's `urljoin` <p>What is the PHP equivalent for building a URL from a base URL and a potentially-relative path? Python provides <a href="https://docs.python.org/2/library/urlparse.html#urlparse.urljoin" rel="nofollow"><code>urlparse.urljoin</code></a> but there does not seem to be any standard implementation in PHP.</p>
<p>The closest I've found is people suggesting the use of <a href="http://php.net/manual/en/function.parse-url.php" rel="nofollow"><code>parse_url</code></a> and then rebuilding the URL from parts, but implementations doing that generally get things like protocol-relative links wrong (for example, <code>//example.com/foo</code> turning into <code>http://example.com/foo</code> or <code>https://example.com/foo</code>, inheriting the base URL's protocol), and it also doesn't make it easy to handle things like parent directory links. Here are examples of those things working correctly in <code>urlparse.urljoin</code>:</p>
<pre><code>>>> from urlparse import urljoin
>>> urljoin('http://example.com/some/directory/filepart', 'foo.jpg')
'http://example.com/some/directory/foo.jpg'
>>> urljoin('http://example.com/some/directory/', 'foo.jpg')
'http://example.com/some/directory/foo.jpg'
>>> urljoin('http://example.com/some/directory/', '../foo.jpg')
'http://example.com/some/foo.jpg'
>>> urljoin('http://example.com/some/directory/', '/foo.jpg')
'http://example.com/foo.jpg'
>>> urljoin('http://example.com/some/directory/', '//images.example.com/bar.jpg')
'http://images.example.com/bar.jpg'
>>> urljoin('https://example.com/some/directory/', '//images.example.com/bar.jpg')
'https://images.example.com/bar.jpg'
>>> urljoin('ftp://example.com/some/directory/', '//images.example.com/bar.jpg')
'ftp://images.example.com/bar.jpg'
>>> urljoin('http://example.com:8080/some/directory/', '//images.example.com/bar.jpg')
'http://images.example.com/bar.jpg'
</code></pre>
<p>Is there an idiomatic way of achieving the same in PHP, or a well-regarded simple library or implementation that actually gets all of these cases correct?</p>
| <p>Because there is clearly a need for this functionality and none of the random scripts out there cover all the bases, I've started a <a href="https://github.com/plaidfluff/php-urljoin" rel="nofollow">project on Github</a> to try to do it right.</p>
<p>The implementation of <code>urljoin()</code> is currently as follows:</p>
<pre><code>function urljoin($base, $rel) {
$pbase = parse_url($base);
$prel = parse_url($rel);
$merged = array_merge($pbase, $prel);
if ($prel['path'][0] != '/') {
// Relative path
$dir = preg_replace('@/[^/]*$@', '', $pbase['path']);
$merged['path'] = $dir . '/' . $prel['path'];
}
// Get the path components, and remove the initial empty one
$pathParts = explode('/', $merged['path']);
array_shift($pathParts);
$path = [];
$prevPart = '';
foreach ($pathParts as $part) {
if ($part == '..' && count($path) > 0) {
// Cancel out the parent directory (if there's a parent to cancel)
$parent = array_pop($path);
// But if it was also a parent directory, leave it in
if ($parent == '..') {
array_push($path, $parent);
array_push($path, $part);
}
} else if ($prevPart != '' || ($part != '.' && $part != '')) {
// Don't include empty or current-directory components
if ($part == '.') {
$part = '';
}
array_push($path, $part);
}
$prevPart = $part;
}
$merged['path'] = '/' . implode('/', $path);
$ret = '';
if (isset($merged['scheme'])) {
$ret .= $merged['scheme'] . ':';
}
if (isset($merged['scheme']) || isset($merged['host'])) {
$ret .= '//';
}
if (isset($prel['host'])) {
$hostSource = $prel;
} else {
$hostSource = $pbase;
}
// username, password, and port are associated with the hostname, not merged
if (isset($hostSource['host'])) {
if (isset($hostSource['user'])) {
$ret .= $hostSource['user'];
if (isset($hostSource['pass'])) {
$ret .= ':' . $hostSource['pass'];
}
$ret .= '@';
}
$ret .= $hostSource['host'];
if (isset($hostSource['port'])) {
$ret .= ':' . $hostSource['port'];
}
}
if (isset($merged['path'])) {
$ret .= $merged['path'];
}
if (isset($prel['query'])) {
$ret .= '?' . $prel['query'];
}
if (isset($prel['fragment'])) {
$ret .= '#' . $prel['fragment'];
}
return $ret;
}
</code></pre>
<p>This function will correctly handle users, passwords, port numbers, query strings, anchors, and even <code>file:///</code> URLs (which seems to be a common defect in existing functions of this type).</p>
|
advanced tab menu angular <p>I'm designing a website based on AngularJS, and I saw an already existed website with a wonderful upper tab menu: <a href="http://brilliantbritz.com/" rel="nofollow">http://brilliantbritz.com/</a> .
I've searched for hours and hours for bootstrap/any file that could contain the menu code (with the underline animation and everything), but I found nothing.</p>
<p>my question is how to extract this design (or in general terms-any design) from a website (or how can I get the exact code), and in the worst case it's not possible- how to create a look-alike menu.</p>
<p>Thanks!</p>
| <p>By using Google. Try researching your problem a little bit more before asking a question. When asking a question, please provide some code and various methods of how you tried solving your problem. Please read <a href="http://stackoverflow.com/help/how-to-ask">How to properly ask a question</a> and this <a href="http://codepen.io/Webspicer/pen/QwvRzM" rel="nofollow">Example of what you are looking for</a>. Just modify the code so it suits your needs.</p>
<pre><code><div class="navbar navbar-inverse navbar-fixed-top opaque-navbar">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navMain">
<span class="glyphicon glyphicon-chevron-right" style="color:white;"></span>
</button>
<a class="navbar-brand" href="#">Your Company</a>
</div>
<div class="collapse navbar-collapse" id="navMain">
<ul class="nav navbar-nav pull-right">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Services and Pricing</a></li>
<li><a href="#">Contact Us</a></li>
</ul>
</div>
</div>
</div>
<section class="banner">
<div class="container">
<div class="row">
<h1>Transparent Background Example</h1>
</div>
</div>
</section>
<div class="container">
<div class="row" style="height:800px;">
<div class="cold-md-12">
<h2>Page Content</h2>
<p>This is an example of a navbar that is initially opaque, then turns into a solid background when user scrolls down the page.</p>
</div>
</div>
</div>
</code></pre>
|
How do I increment and decrement a field and limit it once for users? <p>Hello people I am developing an app, where I have a book table that has two columns âfooâ and âbarâ both are integer.</p>
<p>Now I have set the default values to zero. I want a user to be able to click a button and increment them by one and next time the same user clicks on it, the fields would decrement by one. Which means a particular user can only increment it just once and decrement once. The cycle continues: such that a total of âfooâ and âbarâ could be calculated for all the users
Below is what I have tried:
In the Bookâs controller I have</p>
<pre><code>Def increase_and_decrease_foo
If @book.foo == 0
@book.foo +=1
@book.save
Else
@book.foo -=1
@book.save
End
Def increase_or_decrease_bar
If @book.bar == 0
@book.bar +=1
@book.save
Else
@book.bar -=1
@book.save
End
</code></pre>
<p>In the view
I have <%=button_to âadd1â, increase_or_decrease_path(@book)%>
This adds one and removes one whenever all other users click on itâ¦That is not what I want. Please could someone direct me here on what to do? I am really lost here.</p>
| <p>By your description, it sounds like you want to maintain the counts per user, not just by the book.</p>
<p>one possible solution is to create a join table:</p>
<pre><code>class Book
has_many :user_votes
class UserVotes
belongs_to :books
belongs_to :users
class User
has_many :user_votes
</code></pre>
<p>The foo and bar columns would then be defined in the UserVotes table instead.</p>
<p>That gives you access to <code>@user.user_votes -> all votes by that user</code>
and <code>@book.user_votes -> all votes on that book</code></p>
<p>you would probably want to query them on both axis:</p>
<pre><code>class UserVotes
...
scope :for_user, ->(user_id) { where(user_id: user_id) }
scope :for_book, ->(book_id) { where(book_id: book_id) }
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.