qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
sequence | response
stringlengths 0
115k
|
---|---|---|---|---|
7,377,628 | I have a table of 5700 records. The primary key is an integer. Now I noticed that some values are missing. Like this:
```
100 data
101 data
102 data
104 data
```
`103` is missing. How I can update all the rows so that the order becomes correct (`104` becomes `103` in my example) in one SQL command? | 2011/09/11 | [
"https://Stackoverflow.com/questions/7377628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/616129/"
] | Try this:
```
SET @var:=0;
UPDATE `table` SET `id`=(@var:=@var+1);
ALTER TABLE `table` AUTO_INCREMENT=1;
``` |
45,876,099 | I'm programming an App for the Aldebaran's Pepper robot. I'm using Choregraphe and I made an html for displaying in robots tablet. I have made the boxes for displaying the web and I need to pass a variable from Python to the web Javascript.
Is there any way to do it?
The Python code is the same as the default of a Raise Event box, it receives a string "IMAGE" on his `onStart` input:
```
class MyClass(GeneratedClass):
def __init__(self):
GeneratedClass.__init__(self)
pass
def onLoad(self):
self.memory = ALProxy("ALMemory")
def onUnload(self):
self.memory = None
def onInput_onStart(self, p):
self.memory.raiseEvent(self.getParameter("key"), p)
self.onStopped(p)
def onInput_onStop(self):
self.onUnload() #~ it is recommended to call onUnload of this box in a onStop method, as the code written in onUnload is used to stop the box as well
pass
```
And the Javascript code is this:
```
$('document').ready(function(){
var session = new QiSession();
session.service("ALMemory").done(function (ALMemory) {
ALMemory.subscriber("PepperQiMessaging/totablet").done(function(subscriber) {
$("#log").text("AAA");
subscriber.signal.connect(toTabletHandler);
});
});
function toTabletHandler(value) {
$("#log").text("-> ");
}
});
```
It enters the first `#log` but not the second of JS.
[](https://i.stack.imgur.com/qst5d.jpg) | 2017/08/25 | [
"https://Stackoverflow.com/questions/45876099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1888372/"
] | I solved the problem. I put a **delay** box of 2 seconds between the **show HTML** box and the **sendImage** box like in the image below:
[](https://i.stack.imgur.com/ZWXjr.jpg)
I think the problem was that the string that is send to tabled was sent before the web was prepared to receive it, and the delay of 2 seconds (with 1 it doesn't work) the page have time to prepare for receiving data. |
44,811,928 | I'm looking to make a method which detects if the following value in an array is a duplicate, and deletes it if so. It should work for both strings and integers.
For example, given the Array:
```
arr = ["A", "B", "B", "C", "c", "A", "D", "D"]
```
Return:
```
arr = ["A", "B", "C", "c", "A", "D"]
```
I tried creating an empty Array `a`, and shovelling the values in, providing the following value was not equal to the current one. I attempted this like so:
```
arr.each do |x|
following_value = arr.index(x) + 1
a << x unless x == arr[following_value]
end
```
Unfortunately, instead of shovelling one of the duplicate values into the array, it shovelled neither.
```
arr = ["A", "C", "c", "A"]
```
Can anybody help? Bonus points for telling me exactly what went wrong with my method.
Thanks! | 2017/06/28 | [
"https://Stackoverflow.com/questions/44811928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6831572/"
] | First at all, here is simpler solution:
```
> arr.delete_if.with_index { |e, ind| e == arr[ind+1] }
#=> ["A", "B", "C", "c", "A", "D"]
```
But, this solution will mutate `arr`.
Here are one-line solutions without mutates:
```
arr.each_with_index.with_object([]) { |(e, ind), res| res << e if e != arr[ind+1] }
arr.each_with_object([]) { |e, res| res << e if res.last != e }
```
Your problem in this line: `a << x unless x == arr[following_value]`
You say: put this `element` into `result` if `next element` isn't equal to it. So, instead, you can say something like: *put this element to result if the last element of the result isn't equal to it*:
```
arr.each do |x|
a << x unless a.last == x
end
``` |
44,000,699 | In Wordpress editor (TinyMCE), whenever I switch between 'Visual' and 'Text' mode, all my HTML formatting gets removed. That includes tabs (indents) and line breaks. Sometimes, even elements and elements attributes are removed.
I searched a lot about this issue, wich is actually a pretty common problem for many users, but after browsing 10 pages of Google, I got nothing but a plugin called **[Preserved HTML Editor Markup Plus](https://wordpress.org/plugins/preserved-html-editor-markup-plus/)**. The problem is this **[plugin conflicts with Yoast SEO plugin](https://wordpress.org/support/topic/conflict-when-using-with-yoast-seo/)**.
Is there any thing I can do to preserve the HTML formatting, allowing both modes (Visual and Text) and not knowingly compromising other plugins? | 2017/05/16 | [
"https://Stackoverflow.com/questions/44000699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1301123/"
] | You should try TinyMCE Advanced Plugin.
[TinyMCE Advanced](https://wordpress.org/plugins/tinymce-advanced/) have set to Stop removing the `<p> and <br /> tags` when saving and show them in the HTML editor.
Try it after removing another editor plugin which you have installed to prevent conflict with other.
The second option is [Raw HTML](https://wordpress.org/plugins/raw-html/) plugin. It has also a good feature to prevent HTML formatting. You can use `[raw]` shortcode like `[raw] YOUR HTML [/raw]` to prevent HTML formating.
You can try this both plugin once. Hope one of from these option work for you.
Thanks. |
26,225,066 | I have tried many options both in Mac and in Ubuntu.
I read the Rserve documentation
```
http://rforge.net/Rserve/doc.html
```
and that for the Rserve and RSclient packages:
<http://cran.r-project.org/web/packages/RSclient/RSclient.pdf>
<http://cran.r-project.org/web/packages/Rserve/Rserve.pdf>
I cannot figure out what is the correct workflow for opening/closing a connection within Rserve and for shutting down Rserve 'gracefully'.
For example, in Ubuntu, I installed R from source with the ./config --enable-R-shlib (following the Rserve documentation) and also added the 'control enable' line in /etc/Rserve.conf.
In an Ubuntu terminal:
```
library(Rserve)
library(RSclient)
Rserve()
c<-RS.connect()
c ## this is an Rserve QAP1 connection
## Trying to shutdown the server
RSshutdown(c)
Error in writeBin(as.integer....): invalid connection
RS.server.shutdown(c)
Error in RS.server.shutdown(c): command failed with satus code 0x4e: no control line present (control commands disabled or server shutdown)
```
I can, however, CLOSE the connection:
```
RS.close(c)
>NULL
c ## Closed Rserve connection
```
After closing the connection, I also tried the options (also tried with argument 'c', even though the connection is closed):
```
RS.server.shutdown()
RSshutdown()
```
So, my questions are:
1- How can I close Rserve gracefully?
2- Can Rserve be used without RSclient?
I also looked at
[How to Shutdown Rserve(), running in DEBUG](https://stackoverflow.com/questions/24004257/how-to-shutdown-rserve-running-in-debug)
but the question refers to the debug mode and is also unresolved. (I don't have enough reputation to comment/ask whether the shutdown works in the non-debug mode).
Also looked at:
[how to connect to Rserve with an R client](https://stackoverflow.com/questions/15314880/how-to-connect-to-rserve-with-an-r-client)
Thanks so much! | 2014/10/06 | [
"https://Stackoverflow.com/questions/26225066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3570398/"
] | Load Rserve and RSclient packages, then connect to the instances.
```
> library(Rserve)
> library(RSclient)
> Rserve(port = 6311, debug = FALSE)
> Rserve(port = 6312, debug = TRUE)
Starting Rserve...
"C:\..\Rserve.exe" --RS-port 6311
Starting Rserve...
"C:\..\Rserve_d.exe" --RS-port 6312
> rsc <- RSconnect(port = 6311)
> rscd <- RSconnect(port = 6312)
```
Looks like they're running...
```
> system('tasklist /FI "IMAGENAME eq Rserve.exe"')
> system('tasklist /FI "IMAGENAME eq Rserve_d.exe"')
Image Name PID Session Name Session# Mem Usage
========================= ======== ================ =========== ============
Rserve.exe 8600 Console 1 39,312 K
Rserve_d.exe 12652 Console 1 39,324 K
```
Let's shut 'em down.
```
> RSshutdown(rsc)
> RSshutdown(rscd)
```
And they're gone...
```
> system('tasklist /FI "IMAGENAME eq Rserve.exe"')
> system('tasklist /FI "IMAGENAME eq Rserve_d.exe"')
INFO: No tasks are running which match the specified criteria.
```
Rserve can be used w/o RSclient by starting it with args and/or a config script. Then you can connect to it from some other program (like Tableau) or with your own code. RSclient provides a way to pass commands/data to Rserve from an instance of R.
Hope this helps :) |
23,979,303 | I wonder if it's possible to call the python interpreter in such a way that the python statements are printed (echoed) to standard output instead of being just silently executed.
any ideas? | 2014/06/01 | [
"https://Stackoverflow.com/questions/23979303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/700023/"
] | First of all, with Python, you can use negative indexes:
```
mystr = "hello world"
mystr[0] # "h"
mystr[-1] # "d"
mystr[-2] # "r"
```
Do not hesitate to use them!
```
for i in range(0, len(word)):
if word[i] != s[-1 - i]:
return False
return True
```
Then, as I said in my previous comment, there are some *pythonic ways* of doing such things. For instance, you can reverse a string in a single instruction:
```
mystr = "hello world"
mystr[::-1] # "dlrow olleh"
```
So, in a single line:
```
is_palyndrom = (mystr == mystr[::-1])
``` |
14,016,192 | >
> **Possible Duplicate:**
>
> [Ideal way to cancel an executing AsyncTask](https://stackoverflow.com/questions/2735102/ideal-way-to-cancel-an-executing-asynctask)
>
>
>
When I developed an Android application, I used an `AsyncTask` to download something, I used a `progressDialog` to show the progress of this AsyncTask, now **When I press the back button, I want to cancel this AsycTask**, I invoked the `AsycTask.cancel()`, but it doesn't work. How can I cancel a running AsyncTask ? | 2012/12/24 | [
"https://Stackoverflow.com/questions/14016192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1685245/"
] | The most correct way to do it would be to check periodically inside `doInBackground` if the task was cancelled (i.e. by calling `isCancelled`). From <http://developer.android.com/reference/android/os/AsyncTask.html>:
**Cancelling a task :**
A task can be cancelled at any time by invoking
`cancel(boolean)`. Invoking this method will cause subsequent calls to
`isCancelled()` to return `true`. After invoking this method,
`onCancelled(Object)`, instead of `onPostExecute(Object)` will be invoked
after `doInBackground(Object[])` returns. To ensure that a task is
cancelled as quickly as possible, you should always check the return
value of isCancelled() periodically from `doInBackground(Object[])`, if
possible (inside a loop for instance.)
Check also this blog post if you need more information: <http://vikaskanani.wordpress.com/2011/08/03/android-proper-way-to-cancel-asynctask/> |
23,309,861 | I'm new to android and am not familiar with using asynctask, I am performing login into my webservice but it fails on trying to read the inputstream on the line
```
InputStream in = urlConnection.getInputStream();
```
here's my code:
```
package com.test.connector;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import android.content.Context;
import android.os.AsyncTask;
public class TestConnection extends AsyncTask<String, String, String> {
static InputStream firstCertificate = null;
static InputStream secondCertificate = null;
static InputStream thirdCertificate = null;
private static String htmlString;
public void passCertificates(Context c){
c.getAssets();
try {
firstCertificate = c.getAssets().open("certificate1.crt");
} catch (IOException e) {
e.printStackTrace();
}
try {
secondCertificate=c.getAssets().open("certificate2.crt");
} catch (IOException e) {
e.printStackTrace();
}
try {
thirdCertificate=c.getAssets().open("certificate3");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected String doInBackground(String... params) {
String webHtmlData=null;
String inpUrl=params[0];
final String username=params[1];
final String password=params[2];
CertificateFactory cf = null;
try {
cf = CertificateFactory.getInstance("X.509");
} catch (CertificateException e) {
e.printStackTrace();
}
Certificate ca1 = null;
Certificate ca2 = null;
Certificate ca3 = null;
try {
ca1 = cf.generateCertificate(firstCertificate);
ca2 = cf.generateCertificate(secondCertificate);
ca3 = cf.generateCertificate(thirdCertificate);
} catch (CertificateException e) {
e.printStackTrace();
}
finally {
try {
firstCertificate.close();
secondCertificate.close();
thirdCertificate.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = null;
try {
keyStore = KeyStore.getInstance(keyStoreType);
} catch (KeyStoreException e) {
e.printStackTrace();
}
try {
keyStore.load(null, null);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
keyStore.setCertificateEntry("ca1", ca1);
} catch (KeyStoreException e) {
e.printStackTrace();
}
try {
keyStore.load(null, null);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
keyStore.setCertificateEntry("ca2", ca2);
} catch (KeyStoreException e) {
e.printStackTrace();
}
try {
keyStore.load(null, null);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
keyStore.setCertificateEntry("ca3", ca3);
} catch (KeyStoreException e) {
e.printStackTrace();
}
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = null;
try {
tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
tmf.init(keyStore);
} catch (KeyStoreException e) {
e.printStackTrace();
}
// Create an SSLContext that uses our TrustManager
SSLContext context = null;
try {
context = SSLContext.getInstance("TLS");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
context.init(null, tmf.getTrustManagers(), null);
} catch (KeyManagementException e) {
e.printStackTrace();
}
//authentication credentials
Authenticator myAuth = new Authenticator()
{
@Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username, password.toCharArray());
}
};
Authenticator.setDefault(myAuth);
// Tell the URLConnection to use a SocketFactory from our SSLContext
URL url = null;
try {
url = new URL(inpUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpsURLConnection urlConnection = null;
try {
urlConnection = (HttpsURLConnection)url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
urlConnection.setSSLSocketFactory(context.getSocketFactory());
try {
InputStream in = urlConnection.getInputStream();// my code fails here
webHtmlData=readStream(in);
} catch (IOException e) {
e.printStackTrace();
}
return webHtmlData;
}
public String readStream(InputStream in) {
StringBuilder response = null;
try {
BufferedReader is =
new BufferedReader(new InputStreamReader(in));
String inputLine;
response = new StringBuilder();
while ((inputLine = is.readLine()) != null) {
response.append(inputLine);
}
is.close();
}
catch (Exception e) {
e.printStackTrace();
}
return response.toString();
}
```
I'm executing doInBackground by using the following command through the mainActivity class
```
TestConnection tc=new TestConnection;
tc.passCertificates(this);
String[] param[]={"example.com","username","password"}
tc.doInBackground(param);
```
but the same code works as a java application without the asyncTask.
here's my Logcat
```
04-26 07:30:03.535: D/dalvikvm(1446): GC_FOR_ALLOC freed 37K, 4% free 2949K/3064K, paused 47ms, total 50ms
04-26 07:30:03.535: I/dalvikvm-heap(1446): Grow heap (frag case) to 3.558MB for 635812-byte allocation
04-26 07:30:03.585: D/dalvikvm(1446): GC_FOR_ALLOC freed 2K, 4% free 3567K/3688K, paused 40ms, total 40ms
04-26 07:30:03.935: W/System.err(1446): android.os.NetworkOnMainThreadException
04-26 07:30:03.945: W/System.err(1446): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
04-26 07:30:03.945: W/System.err(1446): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
04-26 07:30:03.955: W/System.err(1446): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
04-26 07:30:03.955: W/System.err(1446): at java.net.InetAddress.getAllByName(InetAddress.java:214)
04-26 07:30:03.955: W/System.err(1446): at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
04-26 07:30:03.955: W/System.err(1446): at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:179)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:246)
04-26 07:30:03.965: W/System.err(1446): at com.ovid.connector.Connector.downloadWebData(Connector.java:209)
04-26 07:30:03.965: W/System.err(1446): at com.ovid.connector.Connector.doInBackground(Connector.java:245)
04-26 07:30:03.965: W/System.err(1446): at com.ovid.connector.Connector.connectAndGetHtmlData(Connector.java:48)
04-26 07:30:03.965: W/System.err(1446): at com.ovid.expandablelistview.MainActivity.onCreate(MainActivity.java:70)
04-26 07:30:03.965: W/System.err(1446): at android.app.Activity.performCreate(Activity.java:5231)
04-26 07:30:03.965: W/System.err(1446): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-26 07:30:03.965: W/System.err(1446): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-26 07:30:03.965: W/System.err(1446): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-26 07:30:03.965: W/System.err(1446): at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-26 07:30:03.965: W/System.err(1446): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-26 07:30:03.965: W/System.err(1446): at android.os.Handler.dispatchMessage(Handler.java:102)
04-26 07:30:03.965: W/System.err(1446): at android.os.Looper.loop(Looper.java:136)
04-26 07:30:03.965: W/System.err(1446): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-26 07:30:03.995: W/System.err(1446): at java.lang.reflect.Method.invokeNative(Native Method)
04-26 07:30:03.995: W/System.err(1446): at java.lang.reflect.Method.invoke(Method.java:515)
04-26 07:30:03.995: W/System.err(1446): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-26 07:30:03.995: W/System.err(1446): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-26 07:30:03.995: W/System.err(1446): at dalvik.system.NativeStart.main(Native Method)
04-26 07:30:04.035: D/AndroidRuntime(1446): Shutting down VM
04-26 07:30:04.035: W/dalvikvm(1446): threadid=1: thread exiting with uncaught exception (group=0xb2ae0ba8)
04-26 07:30:04.055: E/AndroidRuntime(1446): FATAL EXCEPTION: main
04-26 07:30:04.055: E/AndroidRuntime(1446): Process: com.example.expandablelistview, PID: 1446
04-26 07:30:04.055: E/AndroidRuntime(1446): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.expandablelistview/com.ovid.expandablelistview.MainActivity}: java.lang.IllegalArgumentException: String input must not be null
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.os.Handler.dispatchMessage(Handler.java:102)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.os.Looper.loop(Looper.java:136)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-26 07:30:04.055: E/AndroidRuntime(1446): at java.lang.reflect.Method.invokeNative(Native Method)
04-26 07:30:04.055: E/AndroidRuntime(1446): at java.lang.reflect.Method.invoke(Method.java:515)
04-26 07:30:04.055: E/AndroidRuntime(1446): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-26 07:30:04.055: E/AndroidRuntime(1446): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-26 07:30:04.055: E/AndroidRuntime(1446): at dalvik.system.NativeStart.main(Native Method)
04-26 07:30:04.055: E/AndroidRuntime(1446): Caused by: java.lang.IllegalArgumentException: String input must not be null
04-26 07:30:04.055: E/AndroidRuntime(1446): at org.jsoup.helper.Validate.notNull(Validate.java:26)
04-26 07:30:04.055: E/AndroidRuntime(1446): at org.jsoup.parser.TreeBuilder.initialiseParse(TreeBuilder.java:24)
04-26 07:30:04.055: E/AndroidRuntime(1446): at org.jsoup.parser.TreeBuilder.parse(TreeBuilder.java:40)
04-26 07:30:04.055: E/AndroidRuntime(1446): at org.jsoup.parser.HtmlTreeBuilder.parse(HtmlTreeBuilder.java:54)
04-26 07:30:04.055: E/AndroidRuntime(1446): at org.jsoup.parser.Parser.parse(Parser.java:90)
04-26 07:30:04.055: E/AndroidRuntime(1446): at org.jsoup.Jsoup.parse(Jsoup.java:58)
04-26 07:30:04.055: E/AndroidRuntime(1446): at com.ovid.utils.ListProvider.getJournalName(ListProvider.java:15)
04-26 07:30:04.055: E/AndroidRuntime(1446): at com.ovid.expandablelistview.MainActivity.onCreate(MainActivity.java:73)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.Activity.performCreate(Activity.java:5231)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-26 07:30:04.055: E/AndroidRuntime(1446): ... 11 more
``` | 2014/04/26 | [
"https://Stackoverflow.com/questions/23309861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3556095/"
] | Try this..
```
new TestConnection().execute();
``` |
42,540,991 | I'm trying to make a shell "bosh>" which takes in Unix commands and keep getting a bad address error. I know my code reads in the commands and parses them but for some reason, I cannot get them to execute, instead, I get a "bad address" error.
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>
#define MAX_LINE 128
#define MAX_ARGS 10
int main(){
pid_t pid;
char command[MAX_LINE]; /*command line buffer*/
char *commandArgs[MAX_ARGS]; /*command line arg*/
int i;
char *sPtr=strtok(command," ");
int n=0;
printf("bosh>");
fgets(command, MAX_LINE-1,stdin);
command[strlen(command)-1]='\0';
while(strcmp(command,"quit")!=0)
{
n=0;
sPtr=strtok(command," ");
while(sPtr&&n<MAX_ARGS)
{
sPtr=strtok(NULL," ");
n++;
}
commandArgs[0]=malloc(strlen(command)+1);
strcpy(commandArgs[0],command);
if(fork()==0)
{
execvp(commandArgs[0],commandArgs);
perror("execvp failed");
exit(2);
}
pid=wait(NULL);
printf("%s",">" );
fgets(command, MAX_LINE-1,stdin);
command[strlen(command)-1]='\0';
}
printf("Command (%d) done\n", pid);
return 0;
}
``` | 2017/03/01 | [
"https://Stackoverflow.com/questions/42540991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7643500/"
] | These two lines are the culprit:
```
commandArgs[0]=malloc(strlen(command)+1);
strcpy(commandArgs[0],command);
```
First of all, `malloc(strlen(...))` followed by `strcpy` is what the POSIX function [`strdup`](https://stackoverflow.com/questions/252782/strdup-what-does-it-do-in-c) already does. But then, you don't need to even copy the string - it is enough to just store the pointer to the original string into `commandArgs[0]`:
```
commandArgs[0] = command;
```
But then, how does [`execvp`](https://linux.die.net/man/3/execvp) how many arguments the command is going to take? If you read the manuals carefully, they'd say something like:
>
> The `execv()`, `execvp()`, and `execvpe()` functions provide an array of pointers to null-terminated strings that represent the argument list available to the new program. The first argument, by convention, should point to the filename associated with the file being executed. ***The array of pointers* MUST *be terminated by a NULL pointer.***
>
>
>
Your argument array is not NULL-terminated. To fix it, use
```
commandArgs[0] = command;
commandArgs[1] = NULL; // !!!!
```
---
(Then you'd notice that you'd actually want to assign the arguments *within* the `strtok` parsing loop, so that you can actually assign all of the arguments into the `commandArgs` array; and compile with all warnings enabled and address those, and so forth). |
19,461,360 | I am a complete Haskell n00b, but I would like to define a new data type that is simple a list of numbers. How would I go about doing this? I've read Haskell wikibook on type declarations, as well as other online resources, but I cannot seem to figure it out. Here is, in essence, what I've tried:
```
type NumList = [Num]
```
That didn't work, so how can I do this? Thanks for the help. | 2013/10/19 | [
"https://Stackoverflow.com/questions/19461360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/887128/"
] | `Num` is a class, not a type. Choose a type instead; e.g. `Integer` or `Rational` are probably good choices.
```
type NumList = [Integer]
```
However, this does *not* create a new type; it just creates a new name for an old type. If you actually want a new type, you can use `newtype`, as in
```
newtype NumList = MkNumList [Integer]
```
which defines a new type named `NumList` and a new data constructor named `MkNumList`. |
184,785 | I'm new to Drupal Commerce.
I have created new product type and added custom fields everything and it's working fine.
I want to theme the Add a Product (form page). Please suggest me how to do that.
Thanks,
Selva | 2015/12/23 | [
"https://drupal.stackexchange.com/questions/184785",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/55616/"
] | It depends what part of the page you want to theme, simple CSS, change the layout, or adjust the form.
To add CSS, you could attach your CSS file in `hook_page_build` for that path.
To change the page template, you could override the `page.tpl.php` file as `page--node--add--product.tpl.php`
You could also set a custom template in `hook_preprocess_page` by checking for the relevant path and setting `theme_hook_suggestions` to your template (e.g node/add/product and node/[nid]/edit)
Another option is using `hook_custom_theme` to specify a whole new theme for that specific path.
Lastly, you can theme the form itself using `hook_form_alter` and using either a template for the form, or adjusting the form elements there. |
65,477,452 | When I click text fields on the main page (main.dart) which is the default dart given by the flutter. I can see a glitch when soft keyboard appears and there is no delay when soft keyboard disappears.I have attached a gif below for this case.
```
void main() {
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: primaryColor, //blue
statusBarIconBrightness: Brightness.dark,
));
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.pink,
primaryColor: primaryColor,
primaryColorBrightness: Brightness.dark,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
// setState(() {
// // This call to setState tells the Flutter framework that something has
// // changed in this State, which causes it to rerun the build method below
// // so that the display can reflect the updated values. If we changed
// // _counter without calling setState(), then the build method would not be
// // called again, and so nothing would appear to happen.
// _counter++;
// });
setState(() {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => PhoneAuth()));
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
backgroundColor: Colors.red,
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text('hell0000000'),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Container(
color: Colors.white,
child: ListView(
children: [
Column(
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
SizedBox(
height: 200,
),
Align(
alignment: Alignment.bottomCenter,
child: new Container(
child: TextField(
decoration: new InputDecoration(
hintText: 'Chat message',
),
),
),
),
],
),
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
```
**main.dart** **glich**
[](https://i.stack.imgur.com/KfqU5.gif)
---
2.
Also, When I click text fields on the other page (UserChatView.dart). I can see a glitch when soft keyboard appearing and disappearing. In this dart file, That glitch happening for both actions(Keyboard opening and closing). I have attached a gif below for this case.
```
class UserChatView extends StatelessWidget{
@override
Widget build(BuildContext context) {
return UserChatViewPage();
}
}
class UserChatViewPage extends StatefulWidget {
UserChatViewPage({Key key}) : super(key: key);
@override
_UserChatViewPageState createState() => _UserChatViewPageState();
}
class _UserChatViewPageState extends State<UserChatViewPage> {
final TextEditingController _textController = new TextEditingController();
@override
Widget build(BuildContext context) {
final focus = FocusNode();
return new Scaffold(
backgroundColor: Colors.red, // Scaffold background Color
appBar: new AppBar(
title: Row(
children: <Widget>[
// new Container(
// child: CircleAvatar(
// backgroundImage: AssetImage("assets/male_icon.png"),
// )
// ),
new SizedBox(
width: 5.00,
),
new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget> [
new Container(
child: new Text("Alex Marko",
style: TextStyle(color: Colors.white,
fontFamily: 'Roboto_Bold',
letterSpacing: 1.00
),
),
),
new Container(
child: new Text("Online",
style: TextStyle(color: Colors.white,
fontFamily: 'Roboto_Medium',
letterSpacing: 1.00,
fontSize: 12.00,
),
),
),
],
),
],
),
centerTitle: false,
titleSpacing: 0.0,
backgroundColor: primaryColor,
elevation: 0.0,
bottomOpacity: 0.0,
actions: <Widget>[
IconButton(
icon: Icon(
Icons.expand_more_rounded,
color: Colors.white,
),
onPressed: () {
// do something
},
),
],
),
body: Center(
child: new Container(
color: Colors.grey,
child: new Column(
children: <Widget>[
new Expanded(
child: _PageListView(),
),
new Container(
color: Colors.yellow,
padding: new EdgeInsets.all(10.0),
child: _buildTextComposer(),
),
],
),
),
),
);
}
Widget _buildTextComposer() {
return new Container(
color: Colors.yellow,//modified
margin: const EdgeInsets.symmetric(horizontal: 8.0),
child: new Row(
children: <Widget>[
new Flexible(
child: new TextField(
controller: _textController,
onSubmitted: _handleSubmitted,
decoration: new InputDecoration.collapsed(
hintText: "Send a message"),
),
),
new Container(
margin: new EdgeInsets.symmetric(horizontal: 4.0),
child: new IconButton(
icon: new Icon(Icons.send),
onPressed: () => _handleSubmitted(_textController.text)),
),
],
),
);
}
Widget _PageListView(){
return new Container(
child: ListView.builder(
reverse: true,
itemCount: 20,
itemBuilder: (context, position) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(position.toString(), style: TextStyle(fontSize: 22.0),),
),
);
},
),
);
}
```
**UserChatView.dart Glich**
[](https://i.stack.imgur.com/QPlXN.gif) | 2020/12/28 | [
"https://Stackoverflow.com/questions/65477452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11779017/"
] | The reason of this so called `Glitch` is that the default behaviour of the flutter `scaffold` widget is to resize it's body when soft keyboard opens up or closes down.
While the flutter scaffold is notified of any of the above two events, it will start resizing the widgets under its `body` to match the new state. The speed of resizing may differ based on the comlplexity of build process of the widget on screen & processing speed of the device itself.
What you can do is add a flag called `resizeToAvoidBottomInset` in the scaffold widget in your app, like this:
```dart
Scaffold(
...
resizeToAvoidBottomInset: false,
)
```
What this does is, It notifies the scaffole to not resize the widget under its `body` on keyboard up or down states.
So, unless you want to explicitely resize the content of the screen on keyboard state, this is a solution to your glitch.
On the other hand, if you want to resize the content, you can choose to `modularize`/`breakdown` the widgets that you have on screen `to smallest possible combination` & `make the layout simpler` so that the `glitch` portion of the resizing is taken care of by the speed of rebuild process. |
28,193,935 | I see this examples:
<https://openui5.hana.ondemand.com/#docs/guide/25ab54b0113c4914999c43d07d3b71fe.html>
I have this my formatter function:
```
rowVisibility: function (oRow, sGrid) {
var oModel = new sap.ui.model.json.JSONModel();
oModel.loadData("model/file/mapping/map.json", "", false);
var oGridInfo = oModel.getProperty("/elements")[sGrid];
var bVisible = true;
_.forEach(oGridInfo.fields, function (fld) {
if (oRow[fld] == null)
bVisible = false;
});
return bVisible;
}
```
And in XML view I try to pass more than one param:
```
visible="{parts:[{path: 'model>'}, {'MY_GRID_NAME'} ], formatter:'ui5bp.Formatter.rowVisibility'}"
```
but it don't work...
How can I send sGrid param? I want create only one formatter function, not one for each sGrid!
Example: the rowVisibility formatter function is called from 3 different context ("context\_a", "context\_b" and "context\_c"). I want have one function called from 3 context (the behavior will different based on the context)
```
visible="{parts:[{path: 'model>'}, {"context_a"} ], formatter:'ui5bp.Formatter.rowVisibility'}"
visible="{parts:[{path: 'model>'}, {"context_b"} ], formatter:'ui5bp.Formatter.rowVisibility'}"
visible="{parts:[{path: 'model>'}, {"context_c"} ], formatter:'ui5bp.Formatter.rowVisibility'}"
```
this is the unique function
```
rowVisibility: function (oRow) {
...
}
```
Now instead I have 3 different functions:
```
rowVisibility_contextA: function (oRow) {
...
}
rowVisibility_contextB: function (oRow) {
...
}
rowVisibility_contextC: function (oRow) {
...
}
``` | 2015/01/28 | [
"https://Stackoverflow.com/questions/28193935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3224058/"
] | You're mixing iteration with recursion, which is usually not a good idea.
(Your compiler should have warned about possibly not returning a value from the function. )
You're also possibly dereferencing a null pointer here:
```
int current = p->age;
```
and comparing the wrong thing here:
```
if (p->age == NULL)
```
(The fact that the program doesn't crash makes me suspect that you have an object with zero age somewhere, causing you to return that zero instead of recursing.)
If you read the loop carefully, you'll notice that it always returns a value on the first iteration, so `temp` is never advanced, and the `while` could be replaced with `if`.
You should rewrite the function to be either iterative or recursive.
An iterative solution would look like this:
```
int findLargest (StudentCard *p)
{
int current = std::numeric_limits<int>::min();
while (p != NULL){
if (p->age > current) {
current = p->age;
}
p = p->next;
}
return current;
}
```
and a recursive solution would look like this:
```
int findLargest (StudentCard *p)
{
if (p == NULL) {
return std::numeric_limits<int>::min();
}
return std::max(p->age, findLargest(p->next));
}
``` |
21,140,683 | In iOS 7, when navigating back using the new swipe-from-edge-of-screen gesture, the title of the Back button ("Artists") fades from being pink (in the example below) and having regular font weight to being black and having bold font weight.

It seems to me that the animation uses two different labels in order to achieve this effect; one fading out as the other fades in. However, Apple has somehow adjusted the font so that the regular label perfectly overlays the bold one, thus creating the illusion of a single label morphing between two different weights and colors.
Have they simply adjusted the letter spacing on the regular font so that it matches onto the bold one? In that case, how would that be achieved in iOS 7? Does Text Kit have any awesome features for doing this or how should I go about it? | 2014/01/15 | [
"https://Stackoverflow.com/questions/21140683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381416/"
] | You can adjust letter spacing like this, using `NSAttributedString`.
In Objective-C:
```objectivec
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"The Clash"];
[attributedString addAttribute:NSKernAttributeName
value:@(1.4)
range:NSMakeRange(0, 9)];
self.label.attributedText = attributedString;
```
In Swift 3:
```swift
let attributedString = NSMutableAttributedString(string: "The Clash")
attributedString.addAttribute(NSKernAttributeName, value: CGFloat(1.4), range: NSRange(location: 0, length: 9))
label.attributedText = attributedString
```
In Swift 4 and later:
```
label.attributedText = NSAttributedString(string: "The Clash", attributes: [.kern: 1.4])
```
More info on kerning is available in [Typographical Concepts from the Text Programming Guide](https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/TypoFeatures/TextSystemFeatures.html#//apple_ref/doc/uid/TP40009542-CH6-BBCFAEGE).
I don't think there's a TextKit feature that will automatically match font spacing between bold and regular text. |
95,387 | I have changed the language from my MacOS system and now it won't save the screenshots anymore. Is there a way to fix it?
Thanks. | 2013/07/02 | [
"https://apple.stackexchange.com/questions/95387",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/48696/"
] | I found this, and it works:
Say you restore your iPhone with a full wipe and restore. Then you choose a previous backup to restore all of your settings and applications. When your iPhone is done restoring to your backup, all your icons are mixed up on the SpringBoard.... what the heck? You want to get them back don't you? Well, I know a trick and I don't think it's documented anywhere. Here it goes.
\*\*Important: Before starting these instructions, backup your iPhone. Then go into iTunes preferences and turn on "Disable automatic syncing for iPhones and iPods" This way your backup won't get overwritten after your iPhone gets restored.
1. Restore your iPhone and let it restart and activate.
2. Then iTunes will happily ask you if you want to restore from a previous backup (with all of your settings and Applications). Click the backup you want to restore to and let it restore and reboot.
(Here's where things get messed up. Your iPhone backup actually restored the correct icon positions except none of your apps were installed before the restore was complete, so iTunes has to copy all of your apps back to your iPhone. When it does this, it copys them in alphabetical order, thus messing up the location of all your 3rd party icons). Here's how to fix this without memorizing where all your icons went.
1. Right click (or Control-click) on the iPhone icon in iTunes and choose "Restore from Backup" and choose the backup you chose in step 2 again.
2. Let your iPhone restore for a second time and when it reboots, all of your icons will be in their original places. (This is because iTunes didn't have to install the Apps because they were already there, thus keeping them in their original locations according to the backup).
3. Return your iTunes preferences and uncheck "Disable automatic syncing for iPhone and iPod" |
31,494,101 | We have a optimized Apache 2.2 setting which works fine, but after upgrading to Apache 2.4 it seems not reflecting. Both Apache were enabled with worker module, have shared the details below.
>
> Apache 2.2 Settings
> -------------------
>
>
>
> ```
> <IfModule worker.c>
> ServerLimit 40
> StartServers 40
> MaxClients 2000
> MinSpareThreads 2000
> ThreadsPerChild 50
> </IfModule>
>
> ```
>
> Apache 2.2 Server-Status output
> -------------------------------
>
>
>
> ```
> 35 requests currently being processed, 1965 idle workers
>
> ```
>
> Apache 2.4 Settings
> -------------------
>
>
>
> ```
> <IfModule worker.c>
> ServerLimit 40
> StartServers 40
> MaxRequestWorkers 2000
> MinSpareThreads 2000
> ThreadsPerChild 50
> </IfModule>
>
> ```
>
> Apache 2.4 Server-Status output
> -------------------------------
>
>
>
> ```
> 1 requests currently being processed, 99 idle workers
>
> ```
>
>
Need someone's help to point out me the missing setting so that I can have my Apache 2.4 to create 2000 threads at the startup of Apache service.
Thanks. | 2015/07/18 | [
"https://Stackoverflow.com/questions/31494101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4943986/"
] | Thanks Daniel for your response.
I just found the issue few hours back. The conf '00-mpm.conf' (which has the modules to enable prefork / worker / event) was called below the worker.c module setting which seems to have caused the issue. Moving it above the worker setting made apache to pick up the worker setting mentioned. |
9,750,355 | I have an object with a Flag enum with several possible "uses". The flag enum uses the proper power of 2.
Checking if a variable has a certain flag on, I can do it using the .NET 4 `HasFlag()`
BUT:
If I store that flag combination as a int in database... how can I retrive the objects that have certain flag on using Entity Framework?
For example, if my object is a "`Contact`" type, I would like to query those of them that are actually "Customers and Friends", being Customers and Friends flags in the `ContactType` Enum. | 2012/03/17 | [
"https://Stackoverflow.com/questions/9750355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7720/"
] | I doubt any ORM is going to have a way to adapt the HasFlags down to the appropriate SQL code for your DBMS.
What you are likely going to need to do is either write a stored procedure, or hand-crank the SQL Statement to be executed for this.
You don't mention what DBMS you're using - but if I assume you're using SQL Server, you are in luck as it has the [& (Bitwise AND) operator](http://msdn.microsoft.com/en-us/library/ms174965.aspx).
Practical example as T-SQL:
```
-- Setup Test Data
DECLARE @Contacts TABLE (id int, contactType int, name nvarchar(MAX))
INSERT INTO @Contacts VALUES (1, 0, 'Fred'); -- Not Wanted
INSERT INTO @Contacts VALUES (2, 3, 'Jim'); -- Wanted
INSERT INTO @Contacts VALUES (3, 36, 'Mary'); -- Not wanted
INSERT INTO @Contacts VALUEs (4, 78, 'Jo'); -- Wanted
-- Execute Query
SELECT *
FROM @Contacts
WHERE ContactType & 2 = 2
``` |
76,999 | apache ask for passphrase redirects to plymouth even when I'm remoted in using SSH and away from console.
How can I disabled plymouth?
Update: I did learn that I can `sudo plymouth --quit` and that will shutdown plymouth. I would like to know the recommended way to disable plymouth on boot. | 2011/11/08 | [
"https://askubuntu.com/questions/76999",
"https://askubuntu.com",
"https://askubuntu.com/users/1668/"
] | plymouth should be stopping on its own when the boot is finished.. on a GUI that is when kdm/xdm/gdm/lxdm start. On servers, that is when runlevel 2 is finished (ls /etc/rc2.d). If it is not stopped, this is likely a bug in the bootup, and should be reported with
```
apport-bug plymouth
```
Additional Resources:
* [How do I report a bug?](https://askubuntu.com/questions/5121/how-do-i-report-a-bug) |
12,473,821 | What is difference between.
what is best?
Do you **drain** same **release** but different in drain don't save **retain**, while release save retain?
**autorelease** save object in memory some time. | 2012/09/18 | [
"https://Stackoverflow.com/questions/12473821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1667650/"
] | What is best? The answer, of course, is 'it depends'.
For most newcomers to Cocoa, my opinion is 'none of the above' - it is ARC. Although even with ARC, some understanding of reference-counted memory management is important, you need not worry about missing a `release` or `autorelease`, over over-releasing.
In the situation described by @Anshuk Garg above where you are creating numerous temporary objects before the thread's autorelease pool would be drained, you can wrap the code in question in an `@autorelease { ... }` block. Instruments can tell you whether your memory footprint is an issue in these settings. |
370,830 | I just realized that the directions in "UPload" and "DOWNload" seem arbitrary to me as a non-native English speaker. I took a look at a couple of dictionaries and they said that this word is a result of merging "down" and "load", which doesn't seem to explain anything. Where could those two directions come from? | 2017/01/29 | [
"https://english.stackexchange.com/questions/370830",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/53295/"
] | Initially, "download" and "upload" were used in aviation, especially by the US military. "Download" meant to remove items such as weapons from the aircraft, while "upload" meant to load items onto the aircraft.
For example, the [August 1963 *Aerospace Maintenance Safety*](https://books.google.com/books?id=SNvGD-_SKL0C&pg=RA4-PA18&dq=download%20missile&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwi2zLC2qeXlAhUhc98KHRAbAPIQ6AEwAHoECAAQAg#v=snippet&q=%22download%22&f=false) (a publication of the US Air Force) says at page 18:
>
> Failure to follow written procedures and **download** the missiles...
>
>
>
(meaning failure to remove the missiles from the aircraft)
There are earlier examples of "download", "downloading" and "uploading" in the January 1961 [Aerospace Accident and Maintenance Review](https://books.google.com/books?id=Myb32suKp-EC&pg=RA1-PA23&dq=%22downloading%22&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwjX1JaMu-XlAhXBxFkKHQVBBaUQ6AEwA3oECAcQAg#v=snippet&q=%22download%22&f=false), also a USAF publication.
And still earlier in the October 1959 [Aircraft Accident and Maintenance Review](https://books.google.com/books?id=jlyg_p7KuQUC&pg=RA9-PA27&dq=%22downloading%22%20%22usaf%22&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwj1sZqviOblAhVmuVkKHd52DL4Q6AEwAnoECAEQAg#v=onepage&q=%22downloading%22%20%22usaf%22&f=false), USAF, at page 27:
>
> During **downloading** of armament for a routine check, it was discovered that all the missiles aboard the F-102 had their internal power source activated.
>
>
>
(There was also an even earlier meaning relating to the direction of load on an aircraft component, such as on the tail of the aircraft. See "download on tail" in the April 1957 NACA [Technical Note 3961](https://books.google.com/books?id=oNAjAQAAMAAJ&pg=RA5-PA8&dq=%22download%22%20%22tail%22&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwiWut3bruXlAhXIV98KHaNdDZoQ6AEwAHoECAUQAg#v=onepage&q=%22download%22%20%22tail%22&f=false) and ""download applied to the horizontal tail surface" in the [1952 US Code of Federal Regulations](https://books.google.com/books?id=hviyAAAAIAAJ&pg=PA83&dq=%22download%22%20%22tail%22&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwj55sL9sOXlAhWjVN8KHWVZAUkQ6AEwAXoECAUQAg#v=onepage&q=%22download%22%20%22tail%22&f=false) ).
Then, within the US Air Force, the concept was extended to computers.
The July 1968 [IMPLEMENTATION OF THE USAF STANDARD BASE SUPPLY SYSTEM: A QUANTITATIVE STUDY](https://pdfs.semanticscholar.org/1927/53b84b808edefd05faac90b7f215214599a2.pdf) says:
>
> ADC provided a three-man team, which visited the bases
> some 30 days prior to conversion and conducted a full-scale **download**
> of the 305 and **upload** of the 1050, requiring 10 to 15 days.
>
>
> ...
>
>
> 2. **Download** records from the previous computer
> 3. **Upload** records on the 1050 computer
>
>
> |
43,578,466 | So I got this
```
itemIds1 = ('2394328')
itemIds2 = ('6546345')
count2 = 1
itemIdsCount = ('itemIds' + count2)
while (count2 < 2):
#Do stuff
count2 = count2 + 1
```
I'm not sure if I explained this correct. But in line 4 I want to make the string to equal itemIds1 then once it looks make it equal itemsIds2.
If you don't know I'm clearly new to python so if you can explain what to do clearly that would be awesome. | 2017/04/24 | [
"https://Stackoverflow.com/questions/43578466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7147212/"
] | Here are possible options:
1. Use `%s`
>
> itemIdsCount = 'itemIds%s' + count
>
>
>
2. Cast integer to string first
>
> itemIdsCount = 'itemIds' + str(count)
>
>
>
3. Use `.format()` method
>
> itemIdsCount = 'itemIds{}'.format(count)
>
>
>
4. If you have python 3.6, you can use F-string (Literal String Interpolation)
>
> count = 1
>
>
> itemIdsCount = f'itemIds{count}'
>
>
> |
18,879 | I want to be able to grab multiple media clips from my project window all at once, then drag and drop them to a timeline stacked on top of each other as opposed to side by side. Each track would take its own track in the timeline.
Sort of like keyframe assisting in after effects.
Is there a way for this to be done, maybe by holding down a particular keyboard command? | 2016/07/11 | [
"https://avp.stackexchange.com/questions/18879",
"https://avp.stackexchange.com",
"https://avp.stackexchange.com/users/16118/"
] | I dont believe there is any native built in way to do this. The easiest way would likely to build a simple keyboard mouse macro which can be run to repeat the action of selecting the next clip down, and adding to a new track at the start of the sequence. |
59,955,394 | I got somme issue with Symfony to convert a DateTime into string. I use a DataTransformer to format my Datetime but in the form, there is an error that say : "This value should be of type string".
Here is my code:
My Entity : Shift.php (only the necessary)
```php
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="datetime")
* @Assert\DateTime(message="La date de début doit être au format DateTime")
*/
private $start_at;
```
My ShiftType :
```php
$builder
->add('start_at', TextType::class, ['attr' => [ 'class' => 'dateTimePicker']])
->add('end_at', TextType::class, ['attr' => [ 'class' => 'dateTimePicker']])
->add('has_eat')
->add('break_duration')
->add('comment')
;
$builder->get('start_at')->addModelTransformer($this->transformer);
$builder->get('end_at')->addModelTransformer($this->transformer);
```
And my DataTransformer :
```php
/**
* @param DateTime|null $datetime
* @return string
*/
public function transform($datetime)
{
if ($datetime === null)
{
return '';
}
return $datetime->format('Y-m-d H:i');
}
/**
* @param string $dateString
* @return Datetime|null
*/
public function reverseTransform($dateString)
{
if (!$dateString)
{
throw new TransformationFailedException('Pas de date(string) passé');
return;
}
$date = \Datetime::createFromFormat('Y-m-d H:i', $dateString);
if($date === false){
throw new TransformationFailedException("Le format n'est pas le bon (fonction reverseTransform)" . "$dateString");
}
return $date;
}
```
As i said, when i want submit the form, there are errors with the form.
It said "This value should be of type string." and it's caused by :
```
Symfony\Component\Validator\ConstraintViolation {#1107 ▼
root: Symfony\Component\Form\Form {#678 …}
path: "data.start_at"
value: DateTime @1578465000 {#745 ▶}
}
```
Something weard, when i want to edit a shift, Symfony get the date from the db and transform it into string with no error message. But as i want to save the edit, i got the same issue
Could you help me please ?
Thanks | 2020/01/28 | [
"https://Stackoverflow.com/questions/59955394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11013169/"
] | You can group by product and use conditional aggregation:
```
SELECT
[Product_ID/No], [Product_Name],
SUM(IIF(DATESERIAL(YEAR(DATE()), MONTH(DATE()), 1) = DATESERIAL(YEAR([Date]), MONTH([Date]), 1), Revenue, NULL)) AS Current_Month,
SUM(IIF(DATESERIAL(YEAR(DATEADD("m", -1, DATE())), MONTH(DATEADD("m", -1, DATE())), 1) = DATESERIAL(YEAR([Date]), MONTH([Date]), 1), Revenue, NULL)) AS Previous_Month,
Nz(Current_Month)- Nz(Previous_Month) AS Variance
FROM Sales
GROUP BY [Product_ID/No], [Product_Name]
```
Results:
```
Product_ID/No Product_Name Current_Month Previous_Month Variance
A APPLE 110 50 60
B BANANA 100 150 -50
C CHERRY 50 -50
``` |
132,170 | So, every time I switch to orthographic mode in Blender 2.8 (Didn't use to happen in 2.79) my model starts clipping (as shown in the video). I've tried changing the "clip start" value, but that just ruins it when I switch back over to the dynamic view.
Any ideas?
Video: <https://youtu.be/EuOuOvNPw78> | 2019/02/18 | [
"https://blender.stackexchange.com/questions/132170",
"https://blender.stackexchange.com",
"https://blender.stackexchange.com/users/69387/"
] | I've been having the same problem and fortunately we are not alone and somebody has already reported this bug. You can find the current state of it at the link below. It looks like it's been resolved and we're just waiting on an update now.
Bug report
<https://developer.blender.org/T61632>
Specific commit with the fix
<https://developer.blender.org/rB4bbd1b9610f6d85079ea5bc31fc1949f8409a1a4> |
66,190,751 | Problem Description:
--------------------
I am looking for a way to access the `li`-elements between two specific heading-tags only (e.g.from 2nd `h3` to 3rd `h3` or from 3rd `h3` to next `h4`) in order to create a table of historical events listed on <https://de.wikipedia.org/wiki/1._Januar> structured along the criteria mentioned in the headings.
A major problem (for me ...) is that - other than the `h1`-heading - the subtitles of the lower levels have no `className` or `id`.
Sample of HTML:
---------------
```html
<div class="mw-parser-output">
[...]
</h3>
<ul>
<li><a href="/wiki/153_v._Chr." title="153 v. Chr.">153 v. Chr.</a>: Die <a href="/wiki/Consulat" title="Consulat">Konsuln</a> der <a href="/wiki/R%C3%B6mische_Republik" title="Römische Republik">römischen Republik</a> beginnen ihre Amtszeit erstmals
am 1. Januar statt am 1. März; daher ist der 1. Januar heute der Jahresanfang.</li>
<li><span style="visibility:hidden;">0</span><a href="/wiki/45_v._Chr." title="45 v. Chr.">45 v. Chr.</a>: <a href="/wiki/Kalenderreform_des_Gaius_Iulius_Caesar" title="Kalenderreform des Gaius Iulius Caesar">Caesars Reform</a> des <a href="/wiki/R%C3%B6mischer_Kalender"
title="Römischer Kalender">römischen Kalenders</a> endet. Dieser wird ab 2. Januar 709 <a href="/wiki/Ab_urbe_condita_(Chronologie)" title="Ab urbe condita (Chronologie)">a. u. c.</a> durch den <a href="/wiki/Julianischer_Kalender" title="Julianischer Kalender">julianischen Kalender</a> ersetzt.</li>
<li><span style="visibility:hidden;">0</span><a href="/wiki/32_v._Chr." title="32 v. Chr.">32 v. Chr.</a>: <a href="/wiki/Augustus" title="Augustus">Oktavian</a> lässt sich vom <a href="/wiki/R%C3%B6mischer_Senat" title="Römischer Senat">Senat</a> zum
„Führer Italiens“ (<i><a href="/wiki/Dux_(Titel)" title="Dux (Titel)">dux Italiae</a></i>) ausrufen. Er erklärt <a href="/wiki/Kleopatra_VII." title="Kleopatra VII.">Kleopatra</a> und damit <i><a href="/wiki/De_jure/de_facto" title="De jure/de facto">de facto</a></i> auch <a href="/wiki/Marcus_Antonius" title="Marcus Antonius">Marcus Antonius</a> den Krieg.</li>
</ul>
[...]
</ul>
<h4><span id="Inkrafttreten_von_Gesetzen_und_Staatsvertr.C3.A4gen"></span><span class="mw-headline" id="Inkrafttreten_von_Gesetzen_und_Staatsverträgen">Inkrafttreten von Gesetzen und Staatsverträgen</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>
<a href="/w/index.php?title=1._Januar&veaction=edit&section=3" class="mw-editsection-visualeditor" title="Abschnitt bearbeiten: Inkrafttreten von Gesetzen und Staatsverträgen">Bearbeiten</a><span class="mw-editsection-divider"> | </span>
<a href="/w/index.php?title=1._Januar&action=edit&section=3" title="Abschnitt bearbeiten: Inkrafttreten von Gesetzen und Staatsverträgen">Quelltext bearbeiten</a><span class="mw-editsection-bracket">]</span></span>
</h4>
<p><i>Der 1. Januar wird oft für das Inkrafttreten von Gesetzen und Staatsverträgen verwendet. Das gilt unter anderem für:</i>
</p>
<ul>
<li><a href="/wiki/1812" title="1812">1812</a>: das <i><a href="/wiki/Allgemeines_b%C3%BCrgerliches_Gesetzbuch" title="Allgemeines bürgerliches Gesetzbuch">Allgemeine bürgerliche Gesetzbuch</a></i> <i>(ABGB)</i> in den <a href="/wiki/Habsburgermonarchie#Erblande"
title="Habsburgermonarchie">habsburgischen Erblanden</a>.</li>
</ul>
[...]
</h4>
<p><i>Folgende Staaten erhalten am 1. Januar ihre Unabhängigkeit:</i>
</p>
<ul>
[...]
</ul>
<h3><span class="mw-headline" id="Wirtschaft">Wirtschaft</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=1._Januar&veaction=edit&section=6" class="mw-editsection-visualeditor" title="Abschnitt bearbeiten: Wirtschaft">Bearbeiten</a>
<span class="mw-editsection-divider"> | </span><a href="/w/index.php?title=1._Januar&action=edit&section=6" title="Abschnitt bearbeiten: Wirtschaft">Quelltext bearbeiten</a><span class="mw-editsection-bracket">]</span></span>
</h3>
<h4><span class="mw-headline" id="Wichtige_Ereignisse_in_der_Weltwirtschaft">Wichtige Ereignisse in der Weltwirtschaft</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=1._Januar&veaction=edit&section=7"
class="mw-editsection-visualeditor" title="Abschnitt bearbeiten: Wichtige Ereignisse in der Weltwirtschaft">Bearbeiten</a><span class="mw-editsection-divider"> | </span><a href="/w/index.php?title=1._Januar&action=edit&section=7" title="Abschnitt bearbeiten: Wichtige Ereignisse in der Weltwirtschaft">Quelltext bearbeiten</a>
<span class="mw-editsection-bracket">]</span>
</span>
</h4>
<ul>
<li><a href="/wiki/1780" title="1780">1780</a>: In <a href="/wiki/Geschichte_Bratislavas" title="Geschichte Bratislavas">Preßburg</a> erscheint die erste ungarische Zeitung <i>Magyar hírmondó</i> („Ungarischer Kurier“).</li>
```
So far, I only managed to access **all** the `li`-elements (more than 1000!) that are not part of the table of contents with the following code:
Experimental Code Example:
--------------------------
```
Sub HistoricalEvents_Test()
Dim http As Object, html As New MSHTML.HTMLDocument
Dim oLiList As MSHTML.IHTMLDOMChildrenCollection
Dim data As String
Dim r As Integer
Dim oWord As Object, oWordDoc As Object
Dim wordApp As New Word.Application
Dim iFirstRow As Integer, iLastRow As Integer
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", "https://de.wikipedia.org/wiki/1._Januar", False
http.send
html.body.innerHTML = http.responseText
Dim lLiResultList As Long
Dim lLiResultLoop As Long
Set oLiList = html.querySelectorAll("#toc ~ ul li")
For lLiResultLoop = 0 To oLiList.Length - 1
Dim oLiChild As Object
Set oLiChild = oIlList.Item(lLilResultLoop)
data = oLiChild.innerText 'data = data & vbCrLf & oLiChild.innerText
Range("B" & lLiResultLoop +1).Value = data
data = vbNullString
Next lLiResultLoop
Dim j As Long
Dim Ws As Worksheet
Dim rngDB As Range
Set Ws = ActiveSheet
Set oWord = CreateObject("Word.Application")
Set oWordDoc = oWord.Documents.Open("D:\Jahrestage Geschichte.docx")
iFirstRow = 1 ' "Ws.Cells(1, 2).End(xlDown).Row" used to work fine but suddenly gives same as iLastRow!
'Debug.Print iFirstRow
iLastRow = Ws.Cells(ActiveSheet.Rows.Count, "B").End(xlUp).Row
'Debug.Print iLastRow
oWord.Visible = True
With wordApp
With Ws
Set rngDB = Ws.Range(.Cells(iFirstRow, 2), .Cells(iLastRow, 2))
End With
rngDB.Cut
oWord.Selection.PasteSpecial DataType:=wdPasteText
oWord.Selection.TypeParagraph
oWord.Selection = ""
End With
oWordDoc.Close savechanges:=True
wordApp.Quit 'it doesn't :(
End Sub
```
Description of General Idea/Final Project
-----------------------------------------
The final project is supposed to have a worksheet for every month, each containing a table with a row for every day of the respective month and columns for the different categories according to the (sub-)titles. The Word-output in the code is just an early-stage by-product and something I will round off only if/when the main problem can be solved.
Further Remarks
---------------
This is my first contribution on SO. I'm an absolute beginner when it comes to vba and web-scraping (or any kind of coding, scripting or programming for that matter), but I kind of got sucked into it and spent the better part of my winter holiday just to figure out the above code. I wouldn't have been able to accomplish even that poor piece of scripting without the invaluable knowledge shared with noobs like me by the cracks of SO. I've tried out various approaches but I always got stuck at some point, VBA triggering runtime errors and often Excel crashing. In particular, I wasn't able to implement the `nextSibling`/`previousSibling` methods or the `nodeName` selector successfully which I figure might be a promising approach to the problem. So any help or hint would be greatly appreciated!
Working Solution:
-----------------
Thanks to the feedback on my question I finally managed to figure out a solution that does the job, although maybe not in the most elegant way. The only remaining problem is that strangely the `li-elements` of the last column are duplicated. So if anyone has a clue how to deal with that ...
```
Sub SliceHtmlByHeaderTypes4()
Dim http As Object, html As MSHTML.HTMLDocument
Dim sh As Worksheet
Set sh = ThisWorkbook.ActiveSheet
Set http = CreateObject("MSXML2.XMLHTTP"): Set html = New MSHTML.HTMLDocument
http.Open "GET", "https://de.wikipedia.org/wiki/1._Januar", False
http.send
html.body.innerHTML = http.responseText
Dim hNodeList As Object
Dim startPos As Long, endPos As Long
Dim s As Integer, e As Integer
Set hNodeList = html.querySelectorAll("#toc ~ h2, #toc ~ h3, #toc ~ h4")
Debug.Print hNodeList.Length
Do While s < hNodeList.Length - 1
http.Open "GET", "https://de.wikipedia.org/wiki/1._Januar", False
http.send
html.body.innerHTML = http.responseText
Set hNodeList = html.querySelectorAll("#toc ~ h2, #toc ~ h3, #toc ~ h4")
startPos = InStr(html.body.outerHTML, hNodeList.Item(s).outerHTML)
endPos = InStr(html.body.outerHTML, hNodeList.Item(s + 1).outerHTML)
If startPos > 0 And endPos > 0 And endPos > startPos Then
Dim strS As String
strS = Mid$(html.body.outerHTML, startPos, endPos - startPos + 1)
Else
MsgBox "Problem slicing string"
Stop
Exit Sub
End If
Dim liList As Object
html.body.innerHTML = strS
Set liList = html.getElementsByTagName("li")
If liList.Length > 0 Then
Dim i As Integer
Dim liText As String
Dim lc As Integer
Dim liRange As Range
lc = (Cells(2, Columns.Count).End(xlToLeft).Column) + 1
Set liRange = sh.Range(Cells(2, lc), Cells(2, lc))
For i = 0 To liList.Length - 1
On Error Resume Next
liText = liList.Item(i).innerText
liRange.Value = liRange.Value & liText & vbNewLine
liText = vbNullString
Next i
strS = vbNullString
startPos = 0
endPos = 0
hNodeList = ""
i = 0
End If
s = s + 1
Loop
End Sub
``` | 2021/02/13 | [
"https://Stackoverflow.com/questions/66190751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11779702/"
] | Please verify your cproj file and check if they're being excluded. You can add this to your csproj file to have the content of `wwwroot` copied over:
```
<ItemGroup>
<None Include="wwwroot\**">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
``` |
41,655,412 | What I'm trying to do is to center the text (and image that will be side by side or on top of the text) but the command justify-content:center doesn't work for me. It centers horizontally but not vertically. Could you tell me what went wrong? I'm actually a beginner and that's my first website.
Here's the code:
```css
body {
font-family: Gotham A,Gotham B,Helvetica,Arial,sans-serif;
}
h1 {
font-size: 3em;
text-transform:uppercase;
}
h4 {
font-size: 1.5em;
color:#9e9e9e;
}
section {
width: 100%;
display: inline-block;
margin: 0;
max-width: 960;
height:100vh;
vertical-align: middle;
}
#welcome-screen {
width: 100%;
display: table;
margin: 0;
max-width: none;
height:100vh;
background-color:#ebebeb;
padding:0 7%;
}
.heading {
display:table-cell;
vertical-align: middle;
}
.heading-span {
display: block;
color: #8e8e8e;
font-size: 18px;
margin-top: 0px;
text-transform:none;
}
.scrolldown-button {
position: absolute;
display: table;
text-align: center;
bottom: 30px;
left: 0;
right: 0;
margin: 0 auto 0 auto;
width: 48px;
height: 48px;
font-size:20px;
}
a {
color:#000000;
transition: ease-in-out 0.15s
}
a:hover{
color:#fbd505;
}
#content {
width: 100%;
height:100vh;
}
.wrapper {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
p {
display:column;
vertical-align: middle;
max-width: 960px;
}
.content-heading-span {
display: block;
font-size: 32px;
margin-top: 0px;
text-transform:uppercase;
margin-left:-20px;
}
```
```html
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css'>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="https://cloud.typography.com/6493094/7214972/css/fonts.css">
</head>
<body>
<section id="welcome-screen">
<div class="heading">
<h1><span class="heading-span">Hi! My name is</span>
<strong>John Doe</strong>
</h1>
</div>
<div class="scrolldown-button">
<a href="#content"><span class="glyphicon glyphicon-chevron-down" aria-hidden="true"></span></a>
</div>
</section>
<section>
<div id="content">
<div class="wrapper">
<p><span class="content-heading-span"><strong>O Mnie</strong></span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eget bibendum odio, eget varius tortor. Etiam imperdiet, sem in faucibus convallis, justo purus rutrum magna, ut lacinia ex tellus sit amet lectus. Curabitur tempor imperdiet laoreet. Quisque magna magna, tempus a nibh vitae, maximus malesuada mi. Nulla a justo dolor. Nullam risus nisl, vulputate vel arcu id, viverra finibus mauris. Donec porttitor lectus ut augue vehicula, vitae vehicula turpis eleifend. Proin eu quam at odio consectetur tincidunt. Proin eget elit id purus lacinia tincidunt. Nam at urna est. Quisque viverra nisi eu molestie accumsan. Ut at porttitor sem, quis viverra massa. Nulla odio libero, dictum a diam euismod, rhoncus efficitur lectus. Suspendisse eu mi vel diam euismod fermentum at et.</p>
<p><span class="content-heading-span"><strong>O Mnie</strong></span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eget bibendum odio, eget varius tortor. Etiam imperdiet, sem in faucibus convallis, justo purus rutrum magna, ut lacinia ex tellus sit amet lectus. Curabitur tempor imperdiet laoreet. Quisque magna magna, tempus a nibh vitae, maximus malesuada mi. Nulla a justo dolor. Nullam risus nisl, vulputate vel arcu id, viverra finibus mauris. Donec porttitor lectus ut augue vehicula, vitae vehicula turpis eleifend. Proin eu quam at odio consectetur tincidunt. Proin eget elit id purus lacinia tincidunt. Nam at urna est. Quisque viverra nisi eu molestie accumsan. Ut at porttitor sem, quis viverra massa. Nulla odio libero, dictum a diam euismod, rhoncus efficitur lectus. Suspendisse eu mi vel diam euismod fermentum at et.</p>
</div>
</div>
</body>
</html>
``` | 2017/01/14 | [
"https://Stackoverflow.com/questions/41655412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7419823/"
] | This JS Bin is a working example of converting a File to base64: <http://jsbin.com/piqiqecuxo/1/edit?js,console,output> . The main addition seems to be reading the file using a `FileReader`, where `FileReader.readAsDataURL()` returns a base64 encoded string
```
document.getElementById('button').addEventListener('click', function() {
var files = document.getElementById('file').files;
if (files.length > 0) {
getBase64(files[0]);
}
});
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
``` |
29,934,126 | sorry, I need some help finding the right regular expression for this.
Basically I want to recognize via regex if the following format is in a string:
artist - title (something)
examples:
```
"ellie goulding - good gracious (the chainsmokers remix)"
"the xx - you got the love (florence and the machine cover)"
"neneh cherry - everything (loco dice remix)"
"my chemical romance - famous last words (video)"
```
I have been trying but haven't been able to find the right regular expression.
```
regex = "[A-Za-z0-9\s]+[\-]{1}[A-Za-z0-9\s]+[\(]{1}[\s]*[A-Za-z0-9\s]*[\)]{1}"
```
help please! | 2015/04/29 | [
"https://Stackoverflow.com/questions/29934126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4844612/"
] | Well for storing images you can try this
* If you want to save images which are not coming from server and are stored in drawable/mipmap folder just store their id like
initialValues.put(COLUMN\_IMAGE, R.mipmap.demp);
* And if they are coming from server or api call just save their url and load them using any library such as picaso or something.
I tried the same in one of my app it worked. |
597,089 | I dual booted windows 8.0 x86 with ubuntu 14.04. Then tried accessing the volume containing windows but I got this error message:
```
Error mounting /dev/sda2 at /media/van/BE96C17E96C13823: Command-line `mount -t "ntfs" -o "uhelper=udisks2,nodev,nosuid,uid=1000,gid=1000,dmask=0077,fmask=0177" "/dev/sda2" "/media/van/BE96C17E96C13823"' exited with non-zero exit status 14: Windows is hibernated, refused to mount.
Failed to mount '/dev/sda2': Operation not permitted
The NTFS partition is in an unsafe state. Please resume and shutdown
Windows fully (no hibernation or fast restarting), or mount the volume
read-only with the 'ro' mount option.
```
I would really appreciate the solution I can take to solve this problem. | 2015/03/15 | [
"https://askubuntu.com/questions/597089",
"https://askubuntu.com",
"https://askubuntu.com/users/388274/"
] | two things can cause this problem:
1. dont start Ubuntu after you hibernate windows. Always do proper shutdown before you start Ubuntu.
2. Disable *Hybird Shutdown* in windows. [Here](http://www.maketecheasier.com/disable-hybrid-boot-and-shutdown-in-windows-8/) is how you can do that.
now all you can do is shutdown Ubuntu and start windows then follow the second method and restart and switch to Ubuntu
Hint: Please read the last sentence from the error you got:
*Please resume and shutdown Windows fully (no hibernation or fast restarting), or mount the volume read-only with the 'ro' mount option.* |
21,004,823 | I would like to know how can I send a swipe gesture programmatically without actually swiping the phone. For instance, I have button that in the `onClick` event I would call `swipeGestureRecognizer`? Is this possible? | 2014/01/08 | [
"https://Stackoverflow.com/questions/21004823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2823451/"
] | You can call the method you are calling on Swipe, when user taps on button. For examaple, you have a method for swipe gesture, call it `onSwipe` . Now call onSwipe methos when user taps on the button. Thats it
**EDIT**
Here is the code for you:
```
-(void)myMethod{
//Write the logic you want to implement for swipe gesture here.
}
-(IBAction)onClick(UIButton *)sender{
[self myMethod];
}
-(IBAction)onSwipe:(UISwipeGestureRecognizer *)recognizer{
[self myMethod];
}
```
There might be bugs on the code as I am just typing the code using windows. Correct it for yourself in MAC & edit the answer too. it would definitely work for you |
49,689,536 | I have an overlay `(UIImageView)` which should have a transparent background and alpha. How can I set the `imageview` such that it covers the entire screen? Currently, it covers the screen but not the `UIStatusBar`. I am adding the view in `AppDelegate's` main `window` as a `subview`.
The code:
```
let overlay1 = UIImageView(image: UIImage(named: "overlay-image"))
overlay1.contentMode = .scaleAspectFit
overlay1.backgroundColor = UIColor.black
overlay1.alpha = 0.87
overlay1.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
overlay1.isUserInteractionEnabled = true
overlay1.layer.zPosition = 1
(UIApplication.shared.delegate as? AppDelegate).window.addSubview(overlay1)
``` | 2018/04/06 | [
"https://Stackoverflow.com/questions/49689536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8403513/"
] | After discussion in comments found that changing the `backgroundColor` of `statusBar` is the reason why your code is not working properly.
By printing the `superView` of `statusBar` I found that `statusBar` is not added on `UIWindow` instead it is on `UIStatusBarWindow` which is probably above the `mainWindow`.
Also please don't use force unwrapping it can be cause of crash. At last I put a `guard` to fetch the `statusBar`, to check if it responds to `backgroundColor` property, to fetch its `superView` and adding the overlay on this `superView` got it working.
Your check for `respondToSelector` is also wrong. See below code it works as per your requirement.
```
guard let statusBar = UIApplication.shared.value(forKey: "statusBar") as? UIView, statusBar.responds(to: NSSelectorFromString("backgroundColor")), let superView = statusBar.superview else {return}
statusBar.backgroundColor = UIColor.red
let overlay1 = UIImageView(image: UIImage(named: "overlay-image"))
overlay1.contentMode = .scaleAspectFit
overlay1.backgroundColor = UIColor.black
overlay1.alpha = 0.87
overlay1.frame = superView.bounds
overlay1.isUserInteractionEnabled = true
overlay1.layer.zPosition = 1
superView.addSubview(overlay1)
```
**Note: Changing the `statusBar` color is not recommended. You can set its style to `default` or `light`.** |
65,971,168 | I have some lines of text, and then their relevance weight.
```
Weight, Text
10, "I like apples"
20, "Someone needs apples"
```
Is it possible to get the combinations, keeping the values in the weights column? Something like:
```
weight, combinations
10, [I like]
10, [I apples]
10, [like apples]
20, [someone needs]
20, [someone apples]
20, [needs apples]
```
"Generate n-grams from Pandas column while persisting another column" (unsolved) is a similar question, but it is unsolved.
Thanks!!! | 2021/01/30 | [
"https://Stackoverflow.com/questions/65971168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14395605/"
] | To fill the first row in 2D array, use `Arrays.fill`, to fill the rest of the rows, use [`Arrays.copyOf`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#copyOf(T%5B%5D,int)).
Next, it's better to implement separate methods to perform different tasks:
1. Create and fill the grid
2. Print the grid
```java
static String[][] fillGrid(int rows, int cols, String cell) {
String[][] grid = new String[rows][cols];
String[] row = new String[cols];
Arrays.fill(row, cell);
grid[0] = row;
for (int i = 1; i < rows; i++) {
grid[i] = Arrays.copyOf(row, cols);
}
return grid;
}
static void printGrid(String[][] grid) {
for (int i = 0; i < grid.length; i++) {
if (i == 0) {
System.out.print(" ");
for (int j = 0; j < grid[0].length; j++) {
System.out.printf("%2d ", j + 1);
}
System.out.println();
}
for (int j = 0; j < grid[i].length; j++) {
if (j == 0) {
System.out.printf("%2d:", i + 1);
}
System.out.printf("%2s ", grid[i][j]);
}
System.out.println();
}
}
```
Then they may be tested like this:
```java
public static void main(String ... args) {
String[][] grid = fillGrid(8, 8, "x");
printGrid(grid);
}
```
The output will be as follows:
```
1 2 3 4 5 6 7 8
1: x x x x x x x x
2: x x x x x x x x
3: x x x x x x x x
4: x x x x x x x x
5: x x x x x x x x
6: x x x x x x x x
7: x x x x x x x x
8: x x x x x x x x
``` |
2,042 | Is there any way to manually focus the camera on my Android phone?
I know that you can tap on where to focus, but that's just assisted auto focus. What I want is to be able to manually adjust the focus. | 2010/10/09 | [
"https://android.stackexchange.com/questions/2042",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/113/"
] | I couldn't find a way to do it or an app that would do it. There were a couple out there that claimed to have manual focus but basically just did what you described as "assisted auto focus."
I found this thread at XDA where some people have been looking through the code to find a way to add the manual focus. From what they found it appears that it is possible but someone has to code it. Its worth keeping an eye on it: <http://forum.xda-developers.com/showthread.php?t=630989> |
30,937,236 | i have a problem.. i have an app that connects with a database with jSON, now the problem is that he cannot find the element in the response of the database.
This is the code :
```
func uploadtoDB(){
var SelectVehicle = save.stringForKey("SelectVehicleChoosed")
if SelectVehicle == nil {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Submit Failed!"
alertView.message = "Please Select the Vehicle"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}else {
var post:NSString = "vechicleNumber=\(SelectVehicle)"
NSLog("PostData: %@",post);
var url:NSURL = NSURL(string: "http://saimobileapp.com/services/sai_service_history.php?")!
var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
var postLength:NSString = String( postData.length )
var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
if ( urlData != nil ) {
let res = response as! NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300)
{
var responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %@", responseData);
println(responseData)
var error: NSError?
let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as! NSDictionary
var serviceDate = ((jsonData as NSDictionary)["serviceHistory"] as! NSDictionary) ["serviceDate"] as! String
var serviceType = ((jsonData as NSDictionary)["serviceHistory"] as! NSDictionary) ["serviceType"] as! String
var kms = ((jsonData as NSDictionary)["serviceHistory"] as! NSDictionary) ["mileage"] as! String
var serviceLocation = ((jsonData as NSDictionary)["serviceHistory"] as! NSDictionary) ["serviceLocation"] as! String
var serviced:Void = save.setObject(serviceDate, forKey: "ServiceDateChoosed")
var servicet:Void = save.setObject(serviceType, forKey: "ServiceTypeChoosed")
var kmsc:Void = save.setObject(kms, forKey: "KmsChoosed")
var servicel:Void = save.setObject(serviceLocation, forKey: "ServiceLocationChoosed")
save.synchronize()
TableView.reloadData()
}
}
}
}
```
and this is the response
```
{"serviceHistory":[{"id":"2","vehicleNumber":"mh03aw0001","mobileNumber":"9503322593","customerName":"samsun","serviceDate":"2012-06-02","serviceType":"Paid Service","mileage":"65","serviceState":"Maharashtra","serviceLocation":"Lower Parel","PUC":""}]}
```
the app crash in the line `var serviceDate = ((jsonData as NSDictionary)["serviceHistory"] as! NSDictionary) ["serviceDate"] as! String` with nil because i think he can't find the element.
Thanks in advance for the help. | 2015/06/19 | [
"https://Stackoverflow.com/questions/30937236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5028072/"
] | ```
// serviceHistory is an Array
var serviceHistoryArray = jsonData["serviceHistory"] as! NSArray
// fetch the first item...
var serviceHistoryItem = serviceHistoryArray[0] as! NSDictionary
var serviceDate = serviceHistoryItem["serviceDate"]
var serviceType = serviceHistoryItem["serviceType"]
var kms = serviceHistoryItem["mileage"]
var serviceLocation = serviceHistoryItem["serviceLocation"]
``` |
44,682,639 | I'm currently developing my own calculator and I'm getting an `NumberFormatException` when I press the plus button inside it:-
```
if(e.getSource() == p) {
String a[] = new String[2];
double d[] = new double[2];
for(int i =0; i<2; i++) {
a[i] = tf.getText();
d[i] = Double.parseDouble(a[i]);
System.out.println("First array is "+d[i]);
sum = sum + d[i];
tf.setText(null);
}
}
```
I'm not getting what the number format exception is i searched it's telling me that my string is empty but what i need to do now.
[please click here for errors](https://i.stack.imgur.com/MtA7S.png) | 2017/06/21 | [
"https://Stackoverflow.com/questions/44682639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7911099/"
] | You can't parse `+` inside `Double.parseDouble(String string)`
If the string does not contain a parsable double it throw `NumberFormatException`. |
946,739 | I have a WCF web service that I am hosting in IIS (actually running within the Visual Studio web host i.e. Cassini).
I have a file that I have to access in the root of the web directory from the service, and am having trouble figuring out the user identity that the service accesses the directory as. I've given permission to ASPNET, NETWORK SERVICE, and IUSR, but none of these seem to work.
Anyone know what the user is that a WCF service runs as when it's hosted within IIS?
MORE INFO:
Indeed, the WCF service is running as me (my windows account), but for whatever reason, it still cannot open a file in its root directory. The file failed with "Access is Denied". I've given "Everyone" Full Control of the folder, and it doesn't seem to matter. | 2009/06/03 | [
"https://Stackoverflow.com/questions/946739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146/"
] | Here's one way to do it, using `IO#read_nonblock`:
```
def quit?
begin
# See if a 'Q' has been typed yet
while c = STDIN.read_nonblock(1)
puts "I found a #{c}"
return true if c == 'Q'
end
# No 'Q' found
false
rescue Errno::EINTR
puts "Well, your device seems a little slow..."
false
rescue Errno::EAGAIN
# nothing was ready to be read
puts "Nothing to be read..."
false
rescue EOFError
# quit on the end of the input stream
# (user hit CTRL-D)
puts "Who hit CTRL-D, really?"
true
end
end
loop do
puts "I'm a loop!"
puts "Checking to see if I should quit..."
break if quit?
puts "Nope, let's take a nap"
sleep 5
puts "Onto the next iteration!"
end
puts "Oh, I quit."
```
Bear in mind that even though this uses non-blocking IO, it's still *buffered* IO.
That means that your users will have to hit `Q` then `<Enter>`. If you want to do
unbuffered IO, I'd suggest checking out ruby's curses library. |
352,121 | I'm trying to understand how to solve this differential equation:
$ [z^2(1-z)\dfrac{d^2}{dz} - z^2 \dfrac{d}{dz} - \lambda] f(z) = 0 $
I know the solution is related to the hypergeometric function $\_2F^1$, but as I recall from many sources: this functions satisfies another differential equation:
$ [z(1-z)\dfrac{d^2}{dz} + (c - (ab + 1)z) \dfrac{d}{dz} - ab] f(z) = 0 $
with $a,b,c \in \mathcal{R} $
I've tried to transform it in this form:
$ \dfrac{d}{dz} [(z-1)f'(z)] + \dfrac{\lambda}{z^2} f(z) = 0 $
or use quadratic transformation or other properties of $\_2F^1$, but I failed.
Any suggestions?
Thanks in advance for the attention. | 2020/02/07 | [
"https://mathoverflow.net/questions/352121",
"https://mathoverflow.net",
"https://mathoverflow.net/users/152035/"
] | Let $\alpha$ be a root of $\alpha^2-\alpha-\lambda=0$. The change of the dependent
variable $f(z)=z^\alpha w(z)$ reduces to the hypergeometric equation in $w$:
$$z(1-z)w''+(2\alpha(1-z)-z)w'-\alpha^2 w=0.$$ |
46,682,841 | I get this error when I try to execute my first Selenium/python code.
>
> selenium.common.exceptions.WebDriverException: Message: 'Geckodriver' executable may have wrong permissions.
>
>
>
My code :
```
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
if __name__ == '__main__':
binary = FirefoxBinary('C:\Program Files (x86)\Mozilla Firefox\firefox.exe')
driver = webdriver.Firefox(firefox_binary=binary,
executable_path="C:\\Users\\mohammed.asif\\Geckodriver")
driver=webdriver.Firefox()
driver.get("www.google.com");
``` | 2017/10/11 | [
"https://Stackoverflow.com/questions/46682841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8757346/"
] | Path for driver is not set correctly, you need to set path till the .exe as shown below
```
driver = webdriver.Firefox(firefox_binary=binary,
executable_path="C:\\Users\\mohammed.asif\\Geckodriver\\geckodriver.exe")
``` |
48,494 | I'm a very new player to the Pokemon TCG, and have picked up two themed decks to play with ([Ultra Prism](https://www.pokemon.com/us/pokemon-tcg/sun-moon-ultra-prism/theme-decks/)).
So far in my experience however it seems that if one player gets their active Pokemon to its final evolution (for example [Empoleon](https://www.pokemon.com/us/pokemon-tcg/pokemon-cards/sm-series/sm5/34/)) before the other player, then that player has a massive advantage, and is able to one shot all of the opponent's Pokemon before they can do enough damage to knock out the evolved Pokemon.
Is there a strategy for countering this? It can turn a game very one sided very quickly. | 2019/09/02 | [
"https://boardgames.stackexchange.com/questions/48494",
"https://boardgames.stackexchange.com",
"https://boardgames.stackexchange.com/users/28305/"
] | Which is one of the main concepts to win a game, prepare your pokemon so that they can do massive damage and dominate the scenario (either by evolving it or get it ready with necessary energy cards).
Since we are talking about theme decks here, cards and scenarios are limited which is really beginner-friendly. Each expansion (in your case, Ultra Prism) comes with 2 theme decks normally (which they balance out the odds of winning between them so they both will sell), each has it's strenghts and ways to take over the game.
There are a few ways to "comeback" in the game playing any mode, unfortunately (and fortunately at the same time) in Theme mode ways to win is limited to setting up your Over Powered evolutions and swiping your oponents actives. One way to comeback in themes which I have noticed is sacraficing some prizes and Pokemon until you prepare a Pokemon that could take out your oponents active.
Basically, while your opponent got their active evolved and ready with energies and is swiping your actives and taking prizes (he is 1-hit KOing your active Pokemon), he/she is probably "over comitting" on his active Pokemon, which they have spent a few turns only attaching enery cards to that pokemon and probably do not have other Pokemon prepared on their bench.
You can take the opportunity to stall by giving him the turns to KO your some of your Pokemon while preparing 1 Pokemon to fight against his "OP" Empoleon. E.g. have your garchomp set with a Cynthia in hand so you can KO his Empoloeon with 200 dmg.
Try to get the cards you need to set up powerful attackers while your oponent is putting all his eggs in one basket, by optimizing usage of trainers and supportes you have in hand.
You need to calculate your sacrafices and chances, and give your best shot. There have been many times where games were turned from 6-1 prizes to 0-1.
I'm no pro player but hope that helps : ) |
64,176,841 | I need to add days to a date in Javascript inside of a loop.
Currently, I have this -
```
var occurences = 2;
var start_date = "10/2/2020";
for(i=0; i < occurences; i++){
var repeat_every = 2; //repeat every number of days/weeks/months
var last = new Date(start_date);
var day =last.getDate() + repeat_every;
var month=last.getMonth()+1;
var year=last.getFullYear();
var fulldate = month + '/' + day + '/' + year;
console.log(fulldate);
}
```
However, this outputs 10/4/2020 twice. I know the issue is because in the 2nd iteration of the loop it again simply adds 2 to the date 10/2/2020, is there a way on the subsequent iterations I can add 2 to the previous result?
Thank you! | 2020/10/02 | [
"https://Stackoverflow.com/questions/64176841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4256916/"
] | You can use a multiple of your interval and then use `last.setDate( last.getDate() + repeat_every )` to add days and get the correct month and year:
```js
var occurences = 20;
var start_date = "10/2/2020";
for(i=1; i <= occurences; i++){
var repeat_every = 2*i; //repeat every number of days/weeks/months
var last = new Date(start_date);
last.setDate( last.getDate() + repeat_every );
console.log( `${last.getDate()}/${last.getMonth()+1}/${last.getFullYear()}` );
}
``` |
10,929,506 | I save a bool value in NSUserDefaults like this:
```
[[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"password"];
```
And then I synchronize defaults like this:
```
[[NSUserDefaults standardUserDefaults]synchronize];
```
But when my app enters background and then enters foreground my bool changes value to `YES`
Why does that happen ? I set my bool to `YES` only in one place in program, which is not managing when my app leaves/enters foreground.
Thanks! | 2012/06/07 | [
"https://Stackoverflow.com/questions/10929506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1088286/"
] | Just perform a simple test where you are saving your bool as
```
[[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"password"];
[[NSUserDefaults standardUserDefaults]synchronize];
NSLog(@"%d",[[NSUserDefaults standardUserDefaults] boolForKey:@"password"]);
```
see what's the value.. |
6,096,654 | I have a table with columns `user_id`, `time_stamp` and `activity` which I use for recoding user actions for an audit trail.
Now, I would just like to get the most recent timestamp for each unique `user_id`. How do I do that? | 2011/05/23 | [
"https://Stackoverflow.com/questions/6096654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192910/"
] | `SELECT MAX(time_stamp), user_id FROM table GROUP BY user_id;` |
70,672,530 | I have to create a route that uploads 1 audio file and 1 image (resized) to Cloudinary using Multer Storage Cloudinary, and save the url and name in my mongo database.
I get the error "Invalid image file" when I try to upload the audio file (even if I delete `transformation` and add "mp3" in `allowedFormats`.
Cloudinary code:
```
const cloudinary = require('cloudinary').v2;
const { CloudinaryStorage } = require('multer-storage-cloudinary');
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_KEY,
api_secret: process.env.CLOUDINARY_SECRET
});
const storage = new CloudinaryStorage({
cloudinary,
params: {
folder: 'nono',
// transformation: [
// {width: 500, height: 500, crop: "fill"}
// // ],
// allowedFormats: ['jpeg', 'png', 'jpg', 'mp3']
}
});
module.exports = { cloudinary, storage }
```
Route code:
```
router.route("/")
.get(catchAsync(sounds.index));
.post(isLoggedIn, upload.fields([{ name: 'sound[audio]', maxCount: 1 }, { name: 'sound[image]', maxCount: 1 }]), joiValidationSounds, catchAsync(sounds.newSound));
```
---
```
module.exports.newSound = async (req, res) => {
const sound = new Sound(req.body.sound);
console.log(req.files)
sound.image.url = req.files["sound[image]"][0].path;
sound.image.filename = req.files["sound[image]"][0].filename;
sound.audio.url = req.files["sound[audio]"][0].path;
sound.audio.filename = req.files["sound[audio]"][0].filename;
sound.author = req.user._id;
await sound.save();
req.flash("success", "Se ha añadido un nuevo sonido.");
res.redirect(`/sounds/categories/:category/${sound._id}`);
}
```
Form code:
```
<form action="/sounds" method="POST" novalidate class="validated-form" enctype="multipart/form-data">
<div class="row mb-3">
<label for="audio" class="col-sm-2 col-form-label">Audio:</label>
<div class="col-sm-10">
<input type="file" name="sound[audio]" id="audio">
</div>
</div>
<div class="row mb-3">
<label for="image" class="col-sm-2 col-form-label">Imagen:</label>
<div class="col-sm-10">
<input type="file" name="sound[image]" id="image">
</div>
</div>
<button type="submit" class="btn btn-success">Crear</button>
<button type="reset" class="btn btn-success">Limpiar</button>
</form>
```
I can upload 2 images instead without problems. I also checked that Cloudinary supports mp3 files.
EDIT: I managed to upload the audio with `resource_type: 'video', allowedFormats: ['mp3'],` and 2 different storages.
But now I get the error "Unexpected field" when I try to upload both.
New code:
```
const storageAudio = new CloudinaryStorage({
cloudinary: cloudinary,
params: {
folder: 'nono',
format: 'mp3',
resource_type: 'video',
allowedFormats: ['mp3'],
}
});
const storageImage = new CloudinaryStorage({
cloudinary: cloudinary,
params: {
folder: 'nono',
transformation: [
{width: 500, height: 500, crop: "fill"}
],
format: 'jpg',
resource_type: 'image',
allowedFormats: ['jpeg', 'png', 'jpg']
}
});
module.exports = { cloudinary, storageImage, storageAudio };
```
*
```
const multer = require("multer");
const { storageImage, storageAudio } = require("../cloudinary");
const uploadAudio = multer({ storage: storageAudio });
const uploadImage = multer({ storage: storageImage });
router.route("/")
.get(catchAsync(sounds.index))
.post(isLoggedIn,
// uploadAudio.fields([{ name: 'sound[audio]', maxCount: 1 }]), uploadImage.fields([{ name: 'sound[image]', maxCount: 1 }]),
uploadAudio.single("sound[audio]"),
uploadImage.single("sound[image]"),
// upload.fields([{ name: 'sound[audio]', maxCount: 1 }, { name: 'sound[image]', maxCount: 1 }]),
joiValidationSounds, catchAsync(sounds.newSound)
);
``` | 2022/01/11 | [
"https://Stackoverflow.com/questions/70672530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14882708/"
] | What they mean is that `BankDataWriterImpl` should inherit from `BankDataWriterBase` like so :
```py
class BankDataWriterBase():
...
class BankDataWriterImpl(BankDataWriterBase):
# this class inherit from parent class BankDataWriterBase
# when a `BankDataWriterBase` object is created, parent.__init__ method is executed.
def extract_jon(self, filename: str):
pass
```
then in driver code, you can create a `BankDataWriterImpl()` object instead of the `BankDataWriterBase()` as you did.
It will inherit its `__init__` method from parent and have a new `extract_json` method.
Another problem you didn't mention come from `BankDataWriterBase` attributes. Your code assume the existance of 3 global variables.
They should be passed to the class when you create the object, like so :
But watchout when creating a `BankSomething` object, since those arguments are now expected :
```py
class BankDataWriterBase:
def __init__(self, input_path, output_path, bank_identifier):
self.input_path = input_path
self.output_path = output_path
self.bank_identifier = bank_identifier
...
obj1 = BankDataWriterImpl(input_path, output_path, bank_identifier)
```
---
Edit after comment : but my lead said write class only for `BankDataWriterBase()`
```py
class BankDataWriterBase:
def __init__(self, input_path, output_path, bank_identifier):
self.input_path = input_path
self.output_path = output_path
self.bank_identifier = bank_identifier
...
def write_file(file_name: str):
pass
obj = BankDataWriterBase(input_path, output_path, bank_identifier)
# setattr add a new attribute to `obj`, first argument is the object,
# second argument its name (obj.name)
# third argument the attribute itself
# here we attach a new method `obj.write_file` to the object
setattr(obj, 'write_file', write_file)
# now you can use it like that :
# this line would have raised an exception before the `setattr` line
obj.write_file("correct_file_path")
``` |
14,372,385 | I have a UITextView that is being edited and I want to add a custom keyboard... is there any way to dismiss the keyboard but leave the textView in edit mode so the blue cursor keeps flashing? Or better yet is there any way to put a view ontop of the keyboard? | 2013/01/17 | [
"https://Stackoverflow.com/questions/14372385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2057171/"
] | You should register for notification `UIKeyboardWillShowNotification`. It will hit the registered function before displaying keyboard.
Here you can iterate through all Windows and can identify keyboard by below way:
```
for (UIWindow *keyboardWindow in [[UIApplication sharedApplication] windows])
{
for (UIView *keyboard in [keyboardWindow subviews])
{
if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES
||[[keyboard description] hasPrefix:@"<UIPeripheralHost"]== YES)
{
//Set proper frame to hide key board here..
}
```
} |
6,457,699 | I am having some issues with the following query, the issue is that I need it so it displays the courses for the current day until the end of the day not just till the start of the day like it does currently. Basically users cannot access the course if they are trying to access the course on its enddate so i need to some how make it so that they can still access it for 23 hrs 59 mnutes and 59 seconds after the end date I think I have to add some sort of time to the NOW() to accomplish this but im not sure how to go about this.The query is as follows:
```
if ($courses = $db->qarray("
SELECT `CourseCode` AS 'code' FROM `WorkshopUserSessions`
LEFT JOIN `WorkshopSession` ON (`WorkshopUserSessions`.`sessionid` = `WorkshopSession`.`id`)
LEFT JOIN `WorkshopCourses` ON (`WorkshopSession`.`cid` = `WorkshopCourses`.`cid`)
WHERE `WorkshopUserSessions`.`userid` = {$info['uid']} AND `WorkshopUserSessions`.`begindate` <= NOW() AND `WorkshopUserSessions`.`enddate` >= NOW()
ORDER BY `WorkshopUserSessions`.`begindate` ASC
")) {
```
Any help would greatly be aprreciated!
Thanks,
Cam | 2011/06/23 | [
"https://Stackoverflow.com/questions/6457699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/487003/"
] | I think you need to modify it like this
```
enddate + INTERVAL 1 DAY >= NOW()
```
Ofcourse this adds 24 hours, for 23:59:59 just change >= to > |
133,380 | As the sole product designer in my past two startups I have been an essential piece towards bringing the product to reality (user research, ux, visual design, qa). However, in both situations I found myself not sitting at the leadership table when discussing the future of the product.
Marketing, sales, support, development all had multiple employees and each department head would get a seat at the table, while I found myself on the outside looking in.
I brought this up several times (along with trying to lobby for more resources in my "departments") in 1-1 meetings with the owners but to no avail. I possibly have delusions of grandeur, but in my view if anyone should be at the table with ownership it would be the individual that is creating the experience that customers are going to pay for.
Any suggestions for how to improve/approach this situation or book recommendations that might help? | 2020/06/05 | [
"https://ux.stackexchange.com/questions/133380",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/103302/"
] | You Can Sit at My Table When You Improve the Things I Care About
----------------------------------------------------------------
Your owners (like the users you research) have goals, needs, tasks to accomplish, and metrics to improve so they and their business can succeed. If you want a seat at the table you will need to not only understand those goals, needs, and tasks; but help your owners with them.
The best tactic is to tie the owners' business metrics directly to your work:
* Show how your UX work improved Customer Acquisition by X%
* Show how your interaction design changes reduced support costs by $X
* Show how a redesign attracted a specific angel investor
Once you show your owners that you can directly impact their goals for the better, they will be more than happy to "pull up a chair" for you and include you in the product and company's roadmap.
After showing your positive impact on the bottom line and getting acknowledgement from you owners, then you can request investment in more UX resources (people and tools). |
45,835,422 | I have the following code:
```
def getContentComponents: Action[AnyContent] = Action.async {
contentComponentDTO.list().map(contentComponentsFuture =>
contentComponentsFuture.foreach(contentComponentFuture =>
contentComponentFuture.typeOf match {
case 5 =>
contentComponentDTO.getContentComponentText(contentComponentFuture.id.get).map(
text => contentComponentFuture.text = text.text
)
}
)
Ok(Json.toJson(contentComponentsFuture))
)
```
and get this error message while assigning a value:
[](https://i.stack.imgur.com/FzB9O.png)
Is there a way to solve this issue?
I thought about creating a copy but that would mean that I have do lots of other stuff later. It would be much easier for me if I could reassign the value.
thanks | 2017/08/23 | [
"https://Stackoverflow.com/questions/45835422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4367019/"
] | You could try using the SIM Card in a normal 3G USB Dongle and an application called "[Gammu](https://wammu.eu/docs/manual/gammu/)" which can answer a call and sendDTMF codes i.e. number presses. I have only used Gammu on linux systems but I believe it works on Windows as well. |
69,981,157 | I have a text in flexbox item `.learn--text` which needs to be vertically centered, but `word-break: break-word` rule doesn't work.
This is the current state
[](https://i.stack.imgur.com/tgQ3I.png)
and desired state
[](https://i.stack.imgur.com/sMm4I.png)
```css
.learn {
display: flex;
flex: 0 0 50px;
margin-top: auto;
align-items: stretch;
height: 50px;
border: 1px solid black;
width: 250px;
}
.learn--icon {
display: flex;
align-items: center;
justify-content: center;
padding: 0 6px;
}
.learn--text {
display: flex;
flex-wrap: wrap;
align-items: center;
flex: 1;
padding: 0 6px;
white-space: break-spaces;
word-break: break-word;
}
```
```html
<div class="learn"><div class="learn--icon">icon</div><span class="learn--text"><a href="#">Learn more</a> about content management →
</span></div>
``` | 2021/11/15 | [
"https://Stackoverflow.com/questions/69981157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/968379/"
] | Erase all the flex settings from `learn--text` - they "divide" its content into two parts, the link and the following text, treating them as flex items and therefore units. If you erase that, the result is as follows:
```css
.learn {
display: flex;
flex: 0 0 50px;
margin-top: auto;
align-items: center;
height: 50px;
border: 1px solid black;
width: 250px;
}
.learn--icon {
display: flex;
align-items: center;
justify-content: center;
padding: 0 6px;
}
.learn--text {
padding: 0 6px;
white-space: break-spaces;
word-break: break-word;
}
```
```html
<div class="learn"><div class="learn--icon">icon</div><span class="learn--text"><a href="#">Learn more</a> about content management →
</span></div>
``` |
43,241,784 | I'm struggling with achieving following goal: I have the API requests typed in a manner that they return either a desired value, or an error when the status code wasn't indicating success, or when the auth token has been invalid etc: `Either String r`.
Now, I don't want to care about it when I'm `eval`ing my components queries. I am only interested in happy path (expected errors like invalid logon attempt is considered happy path, just want to keep unexpected stuff out of it), and the errors should be handled uniformily and globally (sending some notification to the bus).
For this, I've created transformer stack:
```
type App = ReaderT Env (ExceptT String (Aff AppEffects))
```
Now, to use it with `runUI`, I needed to provide natural transformation to be used with `hoist` (unless I'm missing other possibilities):
```
runApp :: Env -> App ~> Aff AppEffects
runApp env app = do
res <- runExceptT $ runReaderT app env
case res of
Right r -> pure unit
Left err -> do Bus.write err env.bus
-- what to return here?
```
Because we're using `~>` here, we're forced to retain the return type, but for the `Left` case I don't have it at hand!
How would one tackle such requirement? To reiterate - I only want to be able to 'cancel' the evaluation of my component query when the executed action encounters an error, but I want to do it silently and handle it from the top. | 2017/04/05 | [
"https://Stackoverflow.com/questions/43241784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/590347/"
] | You have an exceptional case where the current thread can't continue, so the only thing to do would be to throw an exception in `Aff` using `throwError :: forall eff a. Error -> Aff eff a`. |
35,362,301 | I want to order list1 based on the strings in list2. Any elements in list1 that don't correspond to list2 should be placed at the end of the correctly ordered list1.
For example:
```
list1 = ['Title1-Apples', 'Title1-Oranges', 'Title1-Pear', 'Title1-Bananas']
list2 = ['Bananas', 'Oranges', 'Pear']
list1_reordered_correctly= ['Title1-Bananas','Title1-Oranges','Title1-Pear','Title1-Apples']
``` | 2016/02/12 | [
"https://Stackoverflow.com/questions/35362301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5851615/"
] | Here's an idea:
```
>>> def keyfun(word, wordorder):
... try:
... return wordorder.index(word)
... except ValueError:
... return len(wordorder)
...
>>> sorted(list1, key=lambda x: keyfun(x.split('-')[1], list2))
['Title1-Bananas', 'Title1-Oranges', 'Title1-Pear', 'Title1-Apples']
```
To make it neater and more efficient (`index` has to traverse the list to find the right item), consider defining your word-order as a dictionary, i.e.:
```
>>> wordorder = dict(zip(list2, range(len(list2))))
>>> wordorder
{'Pear': 2, 'Bananas': 0, 'Oranges': 1}
>>> sorted(list1, key=lambda x: wordorder.get(x.split('-')[1], len(wordorder)))
['Title1-Bananas', 'Title1-Oranges', 'Title1-Pear', 'Title1-Apples']
``` |
61,421,408 | I want to implement a profile popup like Books app on iOS. Do you know any package or something to make this? Thank a lot.
GIF below shows the behavior that I want to implement:
<https://gph.is/g/EvAxvVw> | 2020/04/25 | [
"https://Stackoverflow.com/questions/61421408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10398593/"
] | **You can't check both the conditions using `(a == ("A" or "U"))`** because when you execute `"A" or "U"` in python interpreter you will get `"A"` (the first truthy value) similarly when you execute `"A" and "U"` you will get `"U"` (the last truthy value).
If you want simplified expression, you can use,
```
if a in ("A", "U"):
# TODO: perform a task
``` |
41,887,434 | I have a data file ( users.dat) with entries like:
```
user1
user2
user4
user1
user2
user1
user4
...
user3
user2
```
which command I should ( grep? wc?) use to count how many times each word repeats and output it to user\_total.dat like this:
```
user1 80
user2 35
user3 18
user4 120
```
the issue is that I cannot specify "user1" or "user19287" because there are too many users with random, but repeating numbers.
But there are repeating users in that DAT file.
Thanks for your help!!! | 2017/01/27 | [
"https://Stackoverflow.com/questions/41887434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3741790/"
] | Use the `uniq` command to count the repetitions of a line. It requires the input to be sorted, so use `sort` first.
```
sort users.dat | uniq -c > user_total.dat
``` |
25,259,336 | I am using this url to download the magento. I registered and login but nothing happening. Every time on download it shows me login popup.
```
http://www.magentocommerce.com/download
```
Please help to let me know if i am doing something wrong. | 2014/08/12 | [
"https://Stackoverflow.com/questions/25259336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1918324/"
] | The problem is apparently a local browser issue as I was able to log in, go to the downloads page, choose and be presented with the download popup.
If the downloads page is not working for you, you can always try the direct assets link with either a web browser or wget. For example, to get Magento 1.9.0.1:
<http://www.magentocommerce.com/downloads/assets/1.9.0.1/magento-1.9.0.1.tar.gz>
And if you know the version and file name, you should be able to work out the file URL for other versions. |
1,052,600 | The solution of the following [Lorenz system](https://en.wikipedia.org/wiki/Lorenz_system)
```
s=10; r=28; b=8/3;
f = @(t,y) [-s*y(1)+s*y(2); -y(1)*y(3)+r*y(1)-y(2); y(1)*y(2)-b*y(3)];
```
in the interval $[0,8]$ with initial values $y\_1(0)=1$,$y\_2(0)=0$,$y\_3(0)=0$ using MATLAB `ode45()` function are
```
>> [t y] = ode45(f,[0 8],[1 0 0]);
>> [t(end) y(end,:)]
ans =
8.0000 -7.3560 -5.6838 27.8372
```
But the results are very poor with RK4 even with one million sub-interval (i.e. `h=(8-0)/1e6`)
```
ans =
8.0000 -7.4199 -5.6639 28.0052
```
My questions are:
1. Why the results are different?
2. Is `ode45()` the best function for Lorenz system?
3. How can I improve the RK4 accuracy?
4. Is Lorenz system an [stiff equation](https://en.wikipedia.org/wiki/Stiff_equation)? | 2014/12/05 | [
"https://math.stackexchange.com/questions/1052600",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/96402/"
] | Basically, if we can write one vector in our set as a linear combination of the others, then that initial vector is linearly dependent with the rest of the vectors.
Note that $v\_{4} = 0v\_{3} + v\_{2} + v\_{1}$ is a linear combination of $v\_{1}, v\_{2}, v\_{3}$. So if a vector in the set doesn't play a role in the linear combination, set its coefficient to $0$. |
55,485,823 | I have an array of objects like so:
```js
[
{
id: 'a',
name: 'Alan',
age: 10
},
{
id: 'ab'
name: 'alanis',
age: 15
},
{
id: 'b',
name: 'Alex',
age: 13
}
]
```
I need to pass an object like this `{ id: 'a', name: 'al' }` so that it does a wildcard filter and returns an array with the first two objects.
So, the steps are:
1. For each object in the array, filter the relevant keys from the given filter object
2. For each key, check if the value starts with matching filter object key's value
At the moment I'm using lodash's filter function so that it does an exact match, but not a start with/wildcard type of match. This is what I'm doing:
`filter(arrayOfObjects, filterObject)` | 2019/04/03 | [
"https://Stackoverflow.com/questions/55485823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183384/"
] | I *think* you're looking for something like this? Would basically be doing a string.includes match on the value of each key in your filter object--if one of the key values matches then it will be included in the result. If you wanted the entire filter object to match you could do `.every` instead of `.some`...
```
const data = [
{
id: 'a',
name: 'Alan',
age: 10
},
{
id: 'ab',
name: 'alanis',
age: 15
},
{
id: 'b',
name: 'Alex',
age: 13
}
]
const filter = { id: 'a', name: 'al' }
function filterByObject(filterObject, data) {
const matched = data.filter(object => {
return Object.entries(filterObject).some(([filterKey, filterValue]) => {
return object[filterKey].includes(filterValue)
})
})
return matched
}
console.log(filterByObject(filter, data))
``` |
3,997,905 | I have a webpage having four Checkboxes as follows:
```
<p>Buy Samsung 2230<label>
<input type="checkbox" name="checkbox1" id="checkbox1" />
</label></p>
<div id="checkbox1_compare" style="display: none;"><a href="#">Compair</a></div>
<p>Buy Nokia N 95<label>
<input type="checkbox" name="checkbox2" id="checkbox2" /></label></p>
<div id="checkbox2_compare" style="display: none;"><a href="#">Compair</a></div>
p>Buy Motorola M 100<label>
<input type="checkbox" name="checkbox3" id="checkbox3" /></label></p>
<div id="checkbox3_compare" style="display: none;"><a href="#">Compair</a></div>
<div id="checkbox2_compare" style="display: none;"><a href="#">Compair</a></div>
p>Buy LG 2000<label>
<input type="checkbox" name="checkbox4" id="checkbox4" /></label></p>
<div id="checkbox4_compare" style="display: none;"><a href="#">Compair</a></div>
```
If I check two or more Checkbox then after every last checked check box I need a div which initially should be in hidden state to be displayed as a link that is **Compare**.
Below is my code:
However, It should be displayed under the last checked checkbox, if only two or more checkboxarees checked and that is the ***compare*** link.
You can also get a clear understanding if you check my code:
```
$(document).ready(function() {
$('input[type=checkbox]').change(function() {
if ($('input:checked').size() > 1) {
$('#checkbox1_compare').show();
}
else {
$('#checkbox1_compare').hide();
}
})
});
``` | 2010/10/22 | [
"https://Stackoverflow.com/questions/3997905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/484156/"
] | This might be what you want:
```
$(function() {
$('input:checkbox').change(function() {
var $ck = $('input:checkbox:checked');
$('input:checkbox').each(function() {
$('#' + this.id + '_compare').hide();
});
if ($ck.length > 1) {
$ck.each(function() {
$('#' + this.id + '_compare').show();
});
}
});
});
```
That always starts by hiding all the "compare" `<div>` elements, then shows the ones corresponding to the checked checkboxes when 2 or more are checked. |
38,193,503 | I think I'm being dense here because I keep getting a `stack too deep` error...
I have a `Child` and a `Parent` relational objects. I want 2 things to happen:
* if you try to update the `Child`, you cannot update its `status_id` to `1` unless it has a `Parent` association
* if you create a `Parent` and then attach it to the `Child`, then the `Child`'s status should be auto-set to `1`.
Here's how the `Parent` association gets added:
```
parent = Parent.new
if parent.save
child.update_attributes(parent_id:1)
end
```
I have these callbacks on the `Child` model:
```
validate :mark_complete
after_update :set_complete
# this callback is here because there is a way to update the Child model attributes
def mark_complete
if self.status_id == 1 && self.parent.blank?
errors[:base] << ""
end
end
def set_complete
if self.logistic.present?
self.update_attribute(:status_id, 1)
end
end
```
The code above is actually not that efficient because it's 2 db hits when ideally it would be 1, done all at once. But I find it too brain draining to figure out why... I'm not sure why it's not even working, and therefore can't even begin to think about making this a singular db transaction.
**EXAMPLE**
Hopefully this helps clarify. Imagine a `Charge` model and an `Item` model. Each `Item` has a `Charge`. The `Item` also has an attribute `paid`. Two things:
* If you update the `Item`, you cannot update the `paid` to `true` until the `Item` has been associated with a `Charge` object
* If you link a `Charge` object to a `Item` by updating the `charge_id` attribute on the `Item`, then code should save you time and auto set the `paid` as `true` | 2016/07/04 | [
"https://Stackoverflow.com/questions/38193503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2731253/"
] | There's a lot that I find confusing here, but it seems to me that you call `:set_complete` after\_update and within `set_complete` you are updating attributes, thus you seem to have a perpetual loop there. There might be other loops that I can't see but that one stands out to me. |
207,586 | I would like to have the words 'to mean' and the following mathematical statement to be on the same straight line. Thank you very much!
```
\documentclass[11pt,a4paper]{article}
\usepackage{blindtext}
\usepackage{mathtools}
\DeclareMathOperator{\sgn}{sgn}
\begin{document}
\begin{flalign*}
3=+1+1+1
\end{flalign*}
to mean
\begin{flalign*}
(+1+1+1)=+1+1+1,
\end{flalign*}
\end{document}
``` | 2014/10/17 | [
"https://tex.stackexchange.com/questions/207586",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/61127/"
] | Try this.
```
\documentclass[11pt,a4paper]{article}
\usepackage{mathtools}
\begin{document}
\begin{flalign*}
&3=+1+1+1 & \\
\intertext{to mean}
&(+1+1+1)=+1+1+1,&
\end{flalign*}
\end{document}
```
 |
12,419,812 | Is there any way to find the version of Jquery using normal plain javascript.
I know to do this using JQuery itself by using the following code.
```
jQuery.fn.jquery;
```
or
```
$().jquery;
```
But this wont works for me beacuse I am not allowed to use Jquery code. Please suggest any alternative methods using only plain javascript.
Thanks in advance. | 2012/09/14 | [
"https://Stackoverflow.com/questions/12419812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1648144/"
] | ```
jQuery.fn.jquery
```
is a plain JavaScript property. This has nothing to do with 'using jQuery', so that's a proper 'JavaScript' way of getting jQuery's version.
*Edit:* If you just need to check, if a version of jQuery already exists, you can simply test for `window.jQuery`:
```
if ("jQuery" in window) {
// get its version:
var jquery_version = window.jQuery.fn.jquery;
}
```
(If you haven't seen that before: `window.jQuery` is basically the same as a global variable with the name `jQuery` in most cases.) |
599,960 | I guess `~/.config` (`XDG_CONFIG_HOME`) is not correct because that way users have to be constantly aware which files are safe to commit to their dotfiles repository. | 2020/07/23 | [
"https://unix.stackexchange.com/questions/599960",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/4393/"
] | You'd rather want:
```
grep -rilZ 'first_string' . | xargs -r0 grep -Hi 'second_string'
```
assuming GNU utilities (which you seem to be having as you're already using the `-r` GNU extension).
That is:
* use `-Z` and `xargs -0` to reliably pass the list of paths (which on Unix-like systems can contain any byte value except 0, while `xargs` without `-0` expects a very specific format).
* use `-r` for `xargs` to avoid running the second `grep` if the first one doesn't find any file (ommiting it here is no big deal, it would just cause the second `grep` to grep its empty stdin).
* options should be placed before non-option arguments.
* we use the `-H` option for the second `grep` to make sure the file name is always printed (even if only one file path ends up being passed to it) so we know where the matches are. For `grep` implementations that don't support `-H`, an alternative is to add `/dev/null` to the list of files for `grep` to look in. Then, `grep` being passed more than one filename will always print the filename. |
6,707,720 | I would like to know how I can change the date in my "selectedDate" with jquery datepick. Here's my HTML where I want the magic to show
```
<h3>Historique des tâches (<span class="selectedDate"><?= date("Y-m-d");?></span>) <span class="chooseDate">Choisir date</span> <span class="taskDate"></span></h3>
```
And the javascript
```
$(".chooseDate").toggle(function() {
$(this).text("Choisir date");
$(".taskDate").datepick({
onSelect: function(date) {
alert($.datepick.formatDate(date))
}
});
},
function() {
$(this).text("Choisir date");
$(".taskDate").datepick('destroy');
});
```
When I select a date it should popup an alert message with the selected date in yyyy-mm-dd format but nothing happens.
Could someone help me?
Thanks
Update (Found it):
```
$(".taskDate").datepick({
onSelect: function(test){
var newDate = new Date(test);
alert(newDate.getFullYear()+'-'+(newDate.getMonth()+1)+'-'+newDate.getDate());
}
});
```
I've just reformat the date it gave me to the one I wanted. Event by telling it the show it in yyyy-mm-dd format it was still showing me the full date with day , time zone, etc...
Thanks guys | 2011/07/15 | [
"https://Stackoverflow.com/questions/6707720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845217/"
] | Usually the downgrade in performance is only when creating the connection to the database. That operation is intensive for all provider types.
Someone please correct me if I'm wrong, but as of .NET4 Microsoft has created an Oracle driver which I believe allows LINQ to SQL. I know it was in the works at one point and I know the Oracle driver is for .NET4, so I'm assuming that's the same one.
However, LINQ to Entities is db agnostic so as long as you stick with that you should be ok. |
30,694,305 | This code gives me... array? with columns and data, as i understand
console.log
```
{ columns: [ 'n.name' ],
data: [ [ '(' ], [ 'node_name' ], [ ';' ], [ 'CREATE' ], [ ')' ] ] }
```
Code
```
function show() {
var cypher = [
'MATCH (n)-[r:CREATE_NODE_COMMAND]->(s)RETURN n.name'
].join('\n');
db.queryRaw(cypher, {}, function(err, result) {
if (err) throw err;
for (var key in result) {
}
console.log(result);
})}
```
How to get clean data: keys like this (n.name;CREATE) ? | 2015/06/07 | [
"https://Stackoverflow.com/questions/30694305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4967368/"
] | If you want to return a map of `key : value` in the cypher result set you can change the return statement to something like this...
```
return { name : n.name }
``` |
34,490 | I'm new to the Raspberry Pi community and to working with electricity, so I'm looking for some advice.
I've brought the WS2801 LED strip from eBay (but I think it's the same as this: <https://www.sparkfun.com/products/retired/11272>). Using a computer PSU I've connected the LED strip power to my 5V molex rail and data to my Raspberry Pi. Everything seems to work as it should.
Similar to this, but power drawn from my PSU rather then a DC Jack:
[](https://i.stack.imgur.com/T5bRL.png)
After reading a bit more about this setup online, I found out that it might not be wise to connect the power directly to the GPIO. Apart from that I also don't want to use a bulky PSU to power this, but rather a smaller power brick if possible.
What I intend to do is to use a male molex connector and connect it to micro USB header and to the power pins of the same connector used by the power strip. This way I intend to power both the LED strip and my PI using the 5V provided. When it comes to the data connection I'm going to do the same as in the picture and use the GPIO as previously. Is it possible/a good idea to split the power between the LED strip and my RPi this way or is there something I should be aware of?
I think about using a Molex connector in the beginning, just to verify that everything works. Then trying to measure the current needed and replace my Molex and PSU with a DC Jack connector and suited power brick. I have one that says 5V/8A max (5V 8A 8000mA AC-DC Switching Adapter Desktop Power Supply YT-0508 PSU 2.5/2.1), but I'm not sure if that's ridiculous high amount of amps and if it's ok to be trusted...
Any suggestions on this or things I should be careful about would be awesome!
**Edit:**
This is the micro usb connector I intend to use. I plan to just remove the red and black and replace it with my own from the molex power connector. I've that the usb connector has a connector on the side as well (Ground?). Do I have to connect this one to ground (the other black cable that already goes to the connector) as well or just leave it? | 2015/08/16 | [
"https://raspberrypi.stackexchange.com/questions/34490",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/33814/"
] | What you are suggesting sounds fine to me (but I'm not an electronics type so treat anything I say with caution).
As the Pi and LED strip will have a common ground you don't need to connect a Pi ground to the LED strip ground. If you ever use a separate power supply for the Pi and the LED strip you will have to join the grounds. |
14,286,230 | Is it possible to test two `EXISTS` conditions in a single `IF` SQL statement? I've tried the following.
```
IF EXIST (SELECT * FROM tblOne WHERE field1 = @parm1 AND field2 = @parm2)
OR
EXIST (SELECT * FROM tblTwo WHERE field1 = @parm5 AND field2 = @parm3)
```
I've tried playing with adding additional `IF` and parenthesis in there, but to no avail.
Can you help me out with the proper syntax? | 2013/01/11 | [
"https://Stackoverflow.com/questions/14286230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1142433/"
] | If SQL Server
```
IF EXISTS (SELECT *
FROM tblOne
WHERE field1 = @parm1
AND field2 = @parm2)
OR EXISTS (SELECT *
FROM tblTwo
WHERE field1 = @parm5
AND field2 = @parm3)
PRINT 'YES'
```
Is fine, note the only thing changed is `EXISTS` not `EXIST`. The plan for this will probably be a `UNION ALL` that short circuits if the first one tested is true. |
69,792,953 | I have Json Data through which I'm doing this .
```
fun getFact(context: Context) = viewModelScope.launch{
try {
val format = Json {
ignoreUnknownKeys = true
prettyPrint = true
isLenient = true
}
val factJson = context.assets.open("Facts.json").bufferedReader().use {
it.readText()
}
val factList = format.decodeFromString<List<FootballFact>>(factJson)
_uiState.value = ViewState.Success(factList)
} catch (e: Exception) {
_uiState.value = ViewState.Error(exception = e)
}
}
```
This is the way i m getting my job from viewModle in Ui sceeen
```
viewModel.getFact(context)
when (val result =
viewModel.uiState.collectAsState().value) {
is ViewState.Error -> {
Toast.makeText(
context,
"Error ${result.exception}",
Toast.LENGTH_SHORT
).show()
}
is ViewState.Success -> {
val factsLists = mutableStateOf(result.fact)
val randomFact = factsLists.value[0]
FactCard(quote = randomFact.toString()) {
factsLists.value.shuffled()
}
}
}
```
I have fact card where i want to show that fact .also i have there a lambda for click where i want my factList to refresh every time whenever is clicked.
```
@Composable
fun FactCard(quote: String , onClick : ()-> Unit) {
val fact = remember { mutableStateOf(quote)}
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.
.clickable { onClick() }
) {
Text(.. )
}
}
```
I don't know how to approach this, i think there is silly thing I'm doing. | 2021/11/01 | [
"https://Stackoverflow.com/questions/69792953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11630186/"
] | Composables can only recompose when you update state data. You aren't doing that. Your click event should return the new quote that you want to display. You then set `fact.value` to the new quote. Calling `fact.value` with a new value is what triggers a recompose:
```
when (val result = viewModel.uiState.collectAsState().value) {
is ViewState.Error -> {
Toast.makeText(
context,
"Error ${result.exception}",
Toast.LENGTH_SHORT
).show()
}
is ViewState.Success -> {
val factsLists = mutableStateOf(result.fact)
val randomFact = factsLists.value[0]
FactCard(quote = randomFact.toString()) {
return factsLists.value.shuffled()[0]
}
}
}
@Composable
fun FactCard(quote: String , onClick : ()-> String) {
var fact = remember { mutableStateOf(quote)}
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.
.clickable {
fact.value = onClick()
}
) {
Text(.. )
}
}
``` |
37,310,398 | I want to make the length of one of my divs longer on a button click, however the jquery doesn't seem to be working. Here's the script.
```
<script type="text/javascript">
$(document).ready(function(){
function extendContainer() {
$('#thisisabutton').click(function() {
$('#one').animate({
height: "200px"
},
300);
});
}
})
</script>
```
Here's the html, with the code for the button
```
<div id="div1" id="buttons" >
<ul class="actions">
<li><input id="thisisabutton" type="button" onclick="extendContainer()" onclick="loadXMLDocTraditional()" value="Traditional" class="special"/></li>
</ul>
</div>
```
And here's the css just in case.
```
#one .container {
width: 50em;
height: 22em; /* Height of the #one section*/
}
``` | 2016/05/18 | [
"https://Stackoverflow.com/questions/37310398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6304516/"
] | The solution you came up with yourself for now is the best what you could do.
We discussed whether we should expose any other API for singular backlinks, but as there is no way to enforce their multiplicity on the data storage layer, it didn't made sense so far. In addition, you would still need a wrapper object, so that we can propagate updates. For that reason a unified way to retrieve the value via `LinkedObjects` seemed to be the way so far. |
18,561 | In the Pokemon School, you can create a group and other players can join. I created and some friends of mine joined. The NPC says something about syncing events.
What does being in a group do? What kind of things does it sync? | 2011/03/18 | [
"https://gaming.stackexchange.com/questions/18561",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/7902/"
] | >
> Joining a group is a feature introduced in Generation IV. Players in the same group encounter the same swarming Pokémon, weather conditions, changing Pokémon in the Great Marsh, Feebas location, and other things each day. Group members can compare records on the third floor of Jubilife TV.
>
>
>
Source: [Bulbapedia](http://bulbapedia.bulbagarden.net/wiki/Groups) |
50,898,924 | I have coo\_matrix `X` and indexes `trn_idx` by which I would like to get access of that maxtrix
```
print (type(X ), X.shape)
print (type(trn_idx), trn_idx.shape)
<class 'scipy.sparse.coo.coo_matrix'> (1503424, 2795253)
<class 'numpy.ndarray'> (1202739,)
```
Calling this way:
```
X[trn_idx]
TypeError: only integer scalar arrays can be converted to a scalar index
```
Either this way:
```
X[trn_idx.astype(int)] #same error
```
How to access by index? | 2018/06/17 | [
"https://Stackoverflow.com/questions/50898924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1739325/"
] | The `coo_matrix` class does not support indexing. You'll have to convert it to a different sparse format.
Here's an example with a small `coo_matrix`:
```
In [19]: import numpy as np
In [20]: from scipy.sparse import coo_matrix
In [21]: m = coo_matrix([[0, 0, 0, 1], [2, 0, 0 ,0], [0, 0, 0, 0], [0, 3, 4, 0]])
```
Attempting to index `m` fails:
```
In [22]: m[0,0]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-22-1f78c188393f> in <module>()
----> 1 m[0,0]
TypeError: 'coo_matrix' object is not subscriptable
In [23]: idx = np.array([2, 3])
In [24]: m[idx]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-24-a52866a6fec6> in <module>()
----> 1 m[idx]
TypeError: only integer scalar arrays can be converted to a scalar index
```
If you convert `m` to a CSR matrix, you can index it with `idx`:
```
In [25]: m.tocsr()[idx]
Out[25]:
<2x4 sparse matrix of type '<class 'numpy.int64'>'
with 2 stored elements in Compressed Sparse Row format>
```
If you are going to do more indexing, it would be better to save the new array in a variable, and use it as needed:
```
In [26]: a = m.tocsr()
In [27]: a[idx]
Out[27]:
<2x4 sparse matrix of type '<class 'numpy.int64'>'
with 2 stored elements in Compressed Sparse Row format>
In [28]: a[0,0]
Out[28]: 0
``` |
50,645,382 | I am creating several mobile applications in react-native that share common components. I have difficulties handling the dependencies. Here is what I do, which is tedious, is there a better way?
* A repository "common-modules" has shared components
* Several repositories include the common one as a dependency like this:
### Package.json
```
"dependencies": {
"common-components": "file:../common-components"
},
```
I use it like that in the different apps:
```
import XXX from 'common-components/src/...'
```
Now this is great because all other dependencies are in "common-components", but as soon as one of them has native code, I am forced to link the library again in each app.
For instance, if I use "react-native-image-picker", I have to install it again in each application and link it in XCode, edit build.gradle etc. etc.
* It takes forever
* Are my linked dependencies bundled twice?
* I fear the day when I must change/upgrade one of them...
Is there a better way? | 2018/06/01 | [
"https://Stackoverflow.com/questions/50645382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2197181/"
] | I've heard of projects that share code being managed in a monorepo. That may help managing shared code but won't solve the problem of linking native modules N times for N apps.
However, there is `react-native link` that should automate the process, and ease linking the native modules a lot. Note there is no need to re-link if you just upgrade a native dependency.
Alternatively, I think it should be possible to wrap multiple native modules into one. If you take a look at [MainReactPackage.java](https://github.com/facebook/react-native/blob/master/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java) in RN repo, it wraps several native modules. I imagine similar mechanism can be employed on iOS, with static libraries. Obviously, this means that it won't be easy to selectively include some modules and others not. |
28,249,388 | How to store the temporary data in Apache storm?
In storm topology, bolt needs to access the previously processed data.
```
Eg: if the bolt processes varaiable1 with result as 20 at 10:00 AM.
```
and again `varaiable1` is received as `50` at `10:15 AM` then the result should be `30 (50-20)`
later if varaiable1 receives `70` then the result should be `20 (70-50)` at `10:30`.
How to achieve this functionality. | 2015/01/31 | [
"https://Stackoverflow.com/questions/28249388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2431957/"
] | In short, you wanted to do micro-batching calculations with in storm’s running tuples.
First you need to define/find key in tuple set.
Do field grouping(don't use shuffle grouping) between bolts using that key. This will guarantee related tuples will always send to same task of downstream bolt for same key.
Define class level collection List/Map to maintain old values and add new value in same for calculation, don’t worry they are thread safe between different executors instance of same bolt. |
67,723,390 | **I'm trying to predict probability of X\_test and getting 2 values in an array. I need to compare those 2 values and make it 1.**
when I write code
```
y_pred = classifier.predict_proba(X_test)
y_pred
```
It gives output like
```
array([[0.5, 0.5],
[0.6, 0.4],
[0.7, 0.3],
...,
[0.5, 0.5],
[0.4, 0.6],
[0.3, 0.7]])
```
**We know that if values if >= 0.5 then it's and 1 and if it's less than 0.5 it's 0**
I converted the above array into pandas using below code
```
proba = pd.DataFrame(proba)
proba.columns = [['pred_0', 'pred_1']]
proba.head()
```
And output is
```
pred_0 pred_1
0 0.5 0.5
1 0.6 0.4
2 0.7 0.3
3 0.4 0.6
4 0.3 0.7
```
How to iterate the above rows and write a condition that if row value of column 1 is greater than equal to 0.5 with row value of 2, then it's 1 and if row value of column 1 is less than 0.5 when compared to row value of column 2.
For example, by seeing the above data frame the output must be
```
output
0 0
1 1
2 1
3 1
4 1
``` | 2021/05/27 | [
"https://Stackoverflow.com/questions/67723390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15224778/"
] | Try
```
"string0;string1;string2".split(';')
```
Further reading:
<https://python-reference.readthedocs.io/en/latest/docs/str/split.html> |
32,602,441 | I have 3 unread messages. For this reason, I have to show `3` at the top of a message like this picture:
[](https://i.stack.imgur.com/iSjcI.png)
How can I do this? PLease help me. | 2015/09/16 | [
"https://Stackoverflow.com/questions/32602441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1282443/"
] | I think this repo will help you.
<https://github.com/jgilfelt/android-viewbadger>
[](https://i.stack.imgur.com/ZEyse.png) |
2,090,753 | I know that a symmetric tensor of symmetric rank $1$ can be viewed as a point on the so-called *Veronese variety*. A symmetric tensor of rank $r$ is then in the linear space spanned by $r$ points of the Veronese variety. My question is the following: can any given symmetric tensor of **rank $1$** ever reside in the linear space spanned by $r$ *other* points of the Veronese *variety*, *i.e.* be written as a linear combination of $r$ *other* symmetric rank-$1$ symmetric tensors?
I am an engineer, currently working on tensor decompositions for signal processing applications. I'm not very familiar with algebraic geometry, but it seems that I need the answer to the question above, to ensure uniqueness of one such decomposition. I looked for (a hint toward) an answer in the literature on Veronese varieties, but it is rather hard to dig into. | 2017/01/09 | [
"https://math.stackexchange.com/questions/2090753",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/405499/"
] | Your question is: Can a given symmetric tensor of rank $1$ be written as a linear combination of other symmetric tensors of rank $1$? The answer is yes. Yes, a symmetric tensor of rank $1$ can be written as a linear combination of other symmetric tensors of rank $1$. This is true over the complex numbers, the real numbers, and other fields. For simplicity I'll write this answer over a field of characteristic zero; everything I say will be valid over real numbers and over complex numbers. (It can also be valid over other fields with mild conditions but I will ignore that for now.)
Before proceeding with generalities, perhaps a concrete example might be helpful? Let $V$ be a two-dimensional vector space with basis $x,y$. (You are welcome to think of this as $V = \mathbb{R}^2$ and $x = (1,0)$, $y=(0,1)$.) One of the symmetric tensors of rank $1$, and order $3$, in $V \otimes V \otimes V$, is $x \otimes x \otimes x$, which for short we might denote $x^3$. Can we write this $x^3$ as a linear combination of other rank $1$ symmetric tensors? Yes, in various ways; here is one.
$$
\begin{split}
(x+y) \otimes (x+y) \otimes (x+y) &= x \otimes x \otimes x + x \otimes x \otimes y \\
&\quad + x \otimes y \otimes x + y \otimes x \otimes x \\
&\quad + x \otimes y \otimes y + y \otimes x \otimes y \\
&\quad + y \otimes y \otimes x + y \otimes y \otimes y \\
&= x^3 + 3x^2y + 3xy^2 + y^3,
\end{split}
$$
where $x^3 = x \otimes x \otimes x$, $x^2y = \frac{1}{3}(x \otimes x \otimes y + x \otimes y \otimes x + y \otimes x \otimes x)$, and in general $xyz = \frac{1}{6}(x \otimes y \otimes z + \text{all permutations})$.
Well,
$$
(x+y)^3 + (x-y)^3 = x^3 + 6xy^2,
$$
and
$$
(x+2y)^3 + (x-2y)^3 = x^3 + 24xy^2 .
$$
So therefore
$$
4(x+y)^3 + 4(x-y)^3 - (x+2y)^3 - (x-2y)^3 = 3x^3.
$$
So the rank $1$ symmetric tensor $x^3$ is in the span of the $4$ rank $1$ symmetric tensors $(x \pm y)^3$ and $(x \pm 2y)^3$.
Now, this example begins to point the way to a more general answer. Because when we consider the space of symmetric tensors in $V \otimes V \otimes V$—it is a subspace that can be denoted $S^3 V$ ($S$ for Symmetric), or $S\_3 V$, depending on the author—we see that it has dimension $4$. A basis is given by $x^3, x^2y, xy^2, y^3$. And another different basis is given by $(x\pm y)^3$, $(x \pm 2y)^3$. At that point it becomes clear that *every* symmetric tensor is a linear combination of those $4$ symmetric rank $1$ tensors, *including* all the symmetric rank $1$ tensors such as $x^3$.
So we have the first answer to your question: Let $V$ be any finite dimensional vector space. Let $d \geq 1$. Let $N$ be the dimension of $S^d V$. Now $S^d V$ is spanned by the symmetric rank $1$ tensors, so we can take some $N$ of them to form a basis. And now all the symmetric rank $1$ tensors can be written as linear combinations of those.
Now there is a reasonable follow-up question, which might perhaps be a natural question from a standpoint of an engineer who is interested in identifiability issues: Okay, if some symmetric rank $1$ tensor is equal to a linear combination of some $r$ other symmetric rank $1$ tensors, then what is $r$?
We can certainly have such linear combinations when $r=N$ (the dimension of $S^d V$) but unfortunately it can happen sooner than that. It happens as soon as $r=d+1$. Because if $V$ has a basis $x\_1,\dotsc,x\_n$, then $x\_1^d$ can be written as a linear combination of $(x\_1 + t\_i x\_2)^d$ for any (!) $d+1$ nonzero values of $t\_i$. (Nutshell: with Vandermonde matrices you can show these are linearly independent, and there are enough of them to span all the degree $d$ polynomials in $x\_1,x\_2$, including $x\_1^d$.)
I believe the converse may be true: if $L^d$ is a linear combination of some $r$ other symmetric rank $1$ tensors, then $r \geq d+1$. But at the moment I'm not sure where to find a result along those lines. (I looked in some papers of Reznick and the book of Iarrobino-Kanev; it might be in there somewhere but so far I have not been able to find it.) If you are interested, please let me know and I will be happy to resume the search. |
308,615 | I am fairly new to JavaEE, so I have some concepts still missing.
I am learning Docker to use it in our DEV / CI Build environments. I could make it work on my machine. But for it to work in the CI server, my current approach would be to store the docker-compose.yml and dockerfiles in git and, in the CI server download it, build the images and start it.
To setup the docker image for the web container (Wildfly) I had to add:
* DB Drivers (.jar files)
* Standalone.xml (.xml file)
* Modules we use (mix of .xml and .jar files)
But these files are not present in the CI server.
I could download the DB drivers when building the image, but the modules and standalone.xml are not available online.
Is this approach the reasonable? If so, where would one store these files so they get updated when needed and the CI Server is able to download them to build the image? | 2016/01/28 | [
"https://softwareengineering.stackexchange.com/questions/308615",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/7764/"
] | For point 1. and 3. You could create private Ivy repository and fetch DB Drivers and Modules from it via your Build tool ( Mvn, Ant, Gradle support getting dependencies from Ivy repos ) when building your app.
And for `.xml` files - you can have git repository for your Test Environment config files. Or have them encrypted in your app repository, and configure CI script to encrypt those files with key that will be embedded in that CI script. ( encrypt, so people with git access to your app won't get password to your test DB ) |
35,214,887 | I have this call:
```
get_users('meta_key=main_feature&value=yes');
```
but the query is also returning users with the meta key 'featured' set to yes as well. I have a plugin that allows me to check all the user meta and have confirmed that the meta key for users that shouldn't be showing up is empty.
Is there something I'm doing wrong here? | 2016/02/05 | [
"https://Stackoverflow.com/questions/35214887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ```
jQuery(document).ready(function($) {
var e = "mailto:[email protected]";
$("footer .copyright").append('<div> Website by <a href="' + e + '" target="_top">John Bob</a></div>');
});
```
Pretty close. |
65,044,704 | I am trying to write a test with the new cypress 6 interceptor method ([Cypress API Intercept](https://docs.cypress.io/api/commands/intercept.html)). For the test I am writing I need to change the reponse of one endpoint after some action was performed.
**Expectation:**
I am calling cy.intercept again with another fixture and expect it to change all upcomming calls to reponse with this new fixture.
**Actual Behaviour:**
Cypress still response with the first fixture set for the call.
**Test Data:**
In a test project I have recreated the problem:
test.spec.js
```js
describe('testing cypress', () => {
it("multiple responses", () => {
cy.intercept('http://localhost:4200/testcall', { fixture: 'example.json' });
// when visiting the page it makes one request to http://localhost:4200/testcall
cy.visit('http://localhost:4200');
cy.get('.output').should('contain.text', '111');
// now before the button is clicked and the call is made again
// cypress should change the response to the other fixture
cy.intercept('http://localhost:4200/testcall', { fixture: 'example2.json' });
cy.get('.button').click();
cy.get('.output').should('contain.text', '222');
});
});
```
example.json
```json
{
"text": "111"
}
```
example2.json
```json
{
"text": "222"
}
```
app.component.ts
```ts
import { HttpClient } from '@angular/common/http';
import { AfterViewInit, Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
public text: string;
public constructor(private httpClient: HttpClient) { }
public ngAfterViewInit(): void {
this.loadData();
}
public loadData(): void {
const loadDataSubscription = this.httpClient.get<any>('http://localhost:4200/testcall').subscribe(response => {
this.text = response.body;
loadDataSubscription.unsubscribe();
});
}
}
```
app.component.html
```html
<button class="button" (click)="loadData()">click</button>
<p class="output" [innerHTML]="text"></p>
``` | 2020/11/27 | [
"https://Stackoverflow.com/questions/65044704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2844348/"
] | Slightly clumsy, but you can use one `cy.intercept()` with a [Function routeHandler](https://docs.cypress.io/api/commands/intercept.html#Intercepting-a-response), and count the calls.
Something like,
```
let interceptCount = 0;
cy.intercept('http://localhost:4200/testcall', (req) => {
req.reply(res => {
if (interceptCount === 0 ) {
interceptCount += 1;
res.send({ fixture: 'example.json' })
} else {
res.send({ fixture: 'example2.json' })
}
});
});
```
Otherwise, everything looks good in your code so I guess over-riding an intercept is not a feature at this time. |
44,879,049 | I do not want to manually type in thousands of posts from my old website on the front end of my new website. I simply want to merge the database from the old into the new website in phpmyadmin. I'll tweak the tables to suit the new software afterwards.
1. I think there are only four tables that need to be merged for my purposes: wp\_postmeta, wp\_posts, wp\_usermeta and wp\_users.
2. The old website is still live, and the most recent post is post\_id 28,556. So to be safe and neat, I want all my new website post ids to begin at 30,000.
I found this code which is sort of what I'm looking for, but not really: <https://gist.github.com/jazzsequence/99dbee218c1b9a84df0d>. This code simply adds +1 to every row, ignoring all associations with usermeta, users, post\_ids inside postmeta etc. It cannot be used.
If you are unable to answer the question in it's entirety (it will help thousands of wordpress users if you do it properly), please tell me how to add 30,000 to every value in a given column. eg. If the column is called ID and the existing values are 1,2,4,9,13,24,25,26,28, then they would become 30001,30002,30004,30009,30013,30024,30025,30026,30028. | 2017/07/03 | [
"https://Stackoverflow.com/questions/44879049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1069432/"
] | **Setup**
Consider the dataframes `inventory` and `replace_with`
```
inventory = pd.DataFrame(dict(Partnumbers=['123AAA', '123BBB', '123CCC']))
replace_with = pd.DataFrame(dict(
oldPartnumbers=['123AAA', '123BBB', '123CCC'],
newPartnumbers=['123ABC', '123DEF', '123GHI']
))
```
**Option 1**
*`map`*
```
d = replace_with.set_index('oldPartnumbers').newPartnumbers
inventory['Partnumbers'] = inventory['Partnumbers'].map(d)
inventory
Partnumbers
0 123ABC
1 123DEF
2 123GHI
```
---
**Option 2**
*`replace`*
```
d = replace_with.set_index('oldPartnumbers').newPartnumbers
inventory['Partnumbers'].replace(d, inplace=True)
inventory
Partnumbers
0 123ABC
1 123DEF
2 123GHI
``` |
1,246,300 | So this is probably really simple but for some reason I can't figure it out. When I run the below code I can't get it to go into the `if` statement even though when I go into the debugger console in xcode and I execute `po [resultObject valueForKey:@"type"]` it returns `0`. What am I doing wrong? Thanks for your help!
```
NSManagedObject *resultObject = [qResult objectAtIndex:i];
if (([resultObject valueForKey:@"type"])== 0) {
//do something
}
``` | 2009/08/07 | [
"https://Stackoverflow.com/questions/1246300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/149839/"
] | The result of `valueForKey:` is always an object — and the only object equal to 0 is nil. In the case of a numerical value, it will be an NSNumber. At any rate, I think you want to ask for `[[resultObject valueForKey:@"type"] intValue]`. |
71,860,572 | ```
#include <string>
void foo(int x, short y, int z) { std::cout << "normal int" << std::endl; } //F1
void foo(double x, int y, double z) { std::cout << "normal double" << std::endl; } //F2
int main()
{
short x = 2;
foo(5.0, x, 8.0);
}
```
Based on function overloading rules,
F1( Exact = 1, Promote = 0, Convert = 2 ) and
F2( Exact = 2, Promote = 1, Convert = 0 ). Shouldn't F2 be called? Why is the call ambiguous? | 2022/04/13 | [
"https://Stackoverflow.com/questions/71860572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14250223/"
] | Overload resolution can get complicated. But here it's fairly straightforward. I'll rewrite the function prototypes to remove the third argument, since it doesn't affect the analysis.
```
void foo(int, short);
void foo(double, int);
double d = 1.0;
short s = 2;
f(d, s); // ambiguous
```
The rule is that you look at each argument, one at a time, and determine which function has the "best" conversion **for that argument**. If one function has the best conversion for every argument, that's the one that's called. If there's no function that's best for every argument, the call is ambiguous.
For the first argument, the type of the argument is `double`. Calling the first version of `foo` requires a conversion from `double` to `int`; calling the second version of `foo` requires no conversion; it's an exact match. So for the first argument, the second version of `foo` has the best conversion.
For the second argument, the type of the argument is `short`. Calling the first version of `foo` requires no conversion; it's an exact match. Calling the second version of `foo` requires a promotion from `short` to `int`. So for the second argument, the first version of `foo` has the best conversion.
Since the first version of `foo` has the best match for the second argument and the second version of `foo` has the best match for the first argument, there is no function with the best match on all arguments, and the call is ambiguous. |
19,724,319 | In JavaScript, I have complex objects comprising functions, variables and closures.
These objects are very large, very complex and created and destroyed over and over again. I will be working on a very low-powered, very low-memory device, so it's important to me that when the objects are deleted that they are really gone.
Here's a code example:
```
window["obj"] = {};
obj.fun1 = function(){
console.log(1);
};
(function(){
var n = 2;
function fun(){
console.log(n);
}
obj.fun2 = fun;
})();
(function(){
var w = "Three";
function fun(){
console.log(w);
}
obj.fun3 = fun;
})();
(function(){
var w = "f.o.u.r.";
function fun(){
setInterval(function(){
console.log(w);
}, 1e3); // e.g. a timeout
}
obj.fun4 = fun;
})();
obj.fun1();
obj.fun2();
obj.fun3();
obj.fun4();
var fun2 = obj.fun2;
// window.obj = null;
// window.obj = undefined;
delete window.obj;
console.log(typeof obj); // undefined
```
A secondary issue is the question of "lingering references", such as the following:
```
fun2(); // 2
// Interval: "f.o.u.r.", "f.o.u.r.", "f.o.u.r.", "f.o.u.r." ...
```
Is there anything that can be done about those (except a manual clean up before deleting the object)?
A JSFiddle of the code above is here: <http://jsfiddle.net/8nE2f/> | 2013/11/01 | [
"https://Stackoverflow.com/questions/19724319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/681800/"
] | You will have the best effect by doing this
```
window.obj = null;
delete window.obj;
```
Setting objects to null removes any references to it. Also remember that the delete command has no effect on regular variables, only properties.
To better ensure object destruction you may consider not using the global context at all, that is usually considered as an antipattern. |
10,196,344 | Does any body know what I have to check if my app freezes? I mean, I can see the app in the iPad screen but no buttons respond. I have tried debugging the code when I click on the button, but I haven't seen anything yet. I was reading about the Instruments tools; specifically how do I use them?
Can anybody help me? I just need an explanation about how use the tools. | 2012/04/17 | [
"https://Stackoverflow.com/questions/10196344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013554/"
] | It sounds like you've blocked the main thread somehow. To debug, run the app in the debugger and when the app freezes, hit the pause button above the log area at the bottom of Xcode. Then on the left side, you'll be able to see exactly what each thread is doing, and you can see where it's getting stuck.
[](https://i.stack.imgur.com/utV2J.png)
Probably either a long loop on the main thread or a sync deadlock. |
71,198,618 | ```
const howLong = 5
```
```
let special = [
"!",
"@",
"#",
"$",
"%",
"+",
"&",];
let finalPassword = []
for (let i = 0; i < howLong; i++) {
finalPassword += special[Math.floor(Math.random() * howLong)].push
}
```
console prints undefined 5x, my goal is to make it copy 5 random characters from the "special" array into a new var "finalPassword" | 2022/02/20 | [
"https://Stackoverflow.com/questions/71198618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17978619/"
] | you should remove the .push call
```
const howLong = 5;
let special = [
"!",
"@",
"#",
"$",
"%",
"+",
"&",];
let finalPassword = "";
for (let i = 0; i < howLong; i++) {
finalPassword += special[Math.floor(Math.random() * howLong)]
}
``` |
519,113 | Why I can write formula derivative $$ f'(x) = \lim\_{h\rightarrow 0}\frac{f(x+h)-f(x)}{h}$$ in this form: $$ f'(x)=\frac{f(x+h)-f(h)}{h}+O(h)$$
I know, that it's easy but unfortunately I forgot. | 2013/10/08 | [
"https://math.stackexchange.com/questions/519113",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/99324/"
] | The formula $f'(x) = \lim\_{h \to 0} \frac{f(x+h)-f(x)}{h}$ is equivalent to
$\lim\_{h \to 0} \frac{f(x+h)-f(x)-f'(x)h}{h} = 0$.
This in turn is equivalent to the function $g(h) = f(x+h)-f(x)-f'(x)h$ satisfying $\lim\_{h \to 0} \frac{g(h)}{h} = 0$.
Such a function is referred to as 'little o' or $o(h)$, and we say $g$ is 'little o' of $h$, or simply just write $o(h)$.
That is, we abuse notation and write $f(x+h)-f(x)-f'(x)h = o(h)$, which gives rise to $f(x+h) = f(x)+f'(x)h + o(h)$.
**Note**: This is $o(h)$, not $O(h)$. The function $f(x) = |x|$ is not differentiable at $x=0$, but we can write $f(h)=f(0)+0.h + O(h)$, but you cannot replace the $O(h)$ by $o(h)$, if you see what I mean. |
18,863 | I have this code
```
$collection = Mage::getModel("news/views");
->addFieldToSelect('post_id', array('eq' => $this->getRequest()->getParam("id")));
```
And when i'm trying to save my post i get en error:
>
> Invalid method Iv\_News\_Model\_Views::addFieldToSelect(Array ( [0] =>
> post\_id [1] => Array ( [eq] => 13 ) ) )
>
>
> | 2014/04/25 | [
"https://magento.stackexchange.com/questions/18863",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/6086/"
] | The `addFieldToSelect` is available for collection objects. It is defined in `Mage_Core_Model_Resource_Db_Collection_Abstract` so it is available in all its child classes.
You are calling it on a model object that most probably is a child of `Mage_Core_Model_Abstract`.
I think you meant to do this:
```
$collection = Mage::getModel("news/views")->getCollection()
->addFieldToSelect('post_id', array('eq' => $this->getRequest()->getParam("id")));
``` |
46,303,233 | I cannot find a solution to this particular demand.
I have a mysql dump on my computer and I want to import it in a web server using SSH.
How do I do that ?
Can I add the ssh connection to the mysql command ?
Edit :
I did it with SCP
```
scp -r -p /Users/me/files/dump.sql user@server:/var/www/private
mysql -hxxx -uxxx -pxxx dbname < dump.sql
``` | 2017/09/19 | [
"https://Stackoverflow.com/questions/46303233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1787994/"
] | As the comment above says, the simplest solution is to scp the whole dump file up to your server, and then restore it normally. But that means you have to have enough free disk space to store the dump file on your webserver. You might not.
An alternative is to set up a temporary ssh tunnel to your web server. Read <https://www.howtogeek.com/168145/how-to-use-ssh-tunneling/> for full instructions, but it would look something like this:
```
nohup ssh -L 8001:localhost:3306 -N user@webserver >/dev/null 2>&1 &
```
This means when I connect to port 8001 on my local host (you can pick any unused port number here), it's really being given a detour through the ssh tunnel to the webserver, where it connects to port 3306, the MySQL default port.
In the example above, your `user@webserver` is just a placeholder, so you must replace it with your username and your webserver hostname.
Then restore your dump file as if you're restoring to a hypothetical MySQL instance running on port 8001 on the local host. This way you don't have to scp the dump file up to your webserver. It will be streamed up to the webserver via the ssh tunnel, and then applied to your database directly.
```
pv -pert mydumpfile.sql | mysql -h 127.0.0.1 -P 8001
```
You have to specify 127.0.0.1, because the MySQL client uses "localhost" as a special name for a non-network connection.
I like to use `pv` to read the dumpfile, because it outputs a progress bar. |
17,058 | We have ants in our house, and nothing I've tried so far has been sufficiently successful. Now I'm considering using ant traps, but only under the kitchen cabinets behind the plinth, a place where neither my cats nor my kids (a baby and a toddler) would ever be able to reach them (no chance of them getting in there). Would that be safe? Are there other aspects we'd need to consider? | 2017/05/09 | [
"https://pets.stackexchange.com/questions/17058",
"https://pets.stackexchange.com",
"https://pets.stackexchange.com/users/2554/"
] | I don't think it is overstocked at the moment.
But these are all schooling fish and they might be happier if the schools are a bit bigger.
A better mix would be to remove 2 species (eg the tetra's and the barbs) and replace them with the other species (more corys and rainbows for example).
6-7 fish for a 'school' is usually really them minimum. |
5,058 | When running MSM add-on, how can I manage the file upload folders etc, via a config.php file?
Ideally I would want to use a hook to do it, but it doesn't seem to work.
Normally I would do this:
>
>
> ```
> $config['upload_preferences'] = array(
> 1 => array(
> 'name' => 'Images',
> 'server_path' => $uploads_path . "/images/",
> 'url' => $uploads_url . "/images/"
> ),
> 2 => array(
> 'name' => 'Files',
> 'server_path' => $uploads_path . "/files/",
> 'url' => $uploads_url . "/files/"
> ),
> 3 => array(
> 'name' => 'Icons',
> 'server_path' => $uploads_path . "/icons/",
> 'url' => $uploads_url . "/icons/"
> )
> );
>
> ```
>
> | 2013/01/18 | [
"https://expressionengine.stackexchange.com/questions/5058",
"https://expressionengine.stackexchange.com",
"https://expressionengine.stackexchange.com/users/362/"
] | Actually, every upload location you create is going to have a different ID, be it one site or in multiple sites using MSM. You can thus safely keep everything in config.php becuse every upload location you define (even if you share physical folders) is going to have a different ID anyway.
Basically:
* Step 1: create all your upload location in the CP for all sites
* Step 2: take the upload location id and configure all upload location
in your central config.php file for all sites. Since they all have
specific ids, no conflict problem whatsoever |
71,595,153 | I made a simple 1 button LED dimmer and I would like to have the LED go back to full brightness after the button has not been touched for a set amount of time. But the code I came up with does not seem to be working as I cannot dim the LED
```
int buttonPin = 12;
int LEDPin = 3;
int buttonVal;
int LEDbright = 0;
int dt = 500;
int fdt = 60000;
void setup() {
// put your setup code here, to run once:
pinMode(buttonPin, INPUT);
pinMode(LEDPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
static unsigned long whenButtonWasTouchedMs = 0;
buttonVal = digitalRead(buttonPin);
Serial.print("Button = ");
Serial.print(buttonVal);
Serial.print(", ");
delay(dt);
if (buttonVal == 1) {
LEDbright = LEDbright + 20;
whenButtonWasTouchedMs = millis();
}
Serial.println(LEDbright);
//
if (LEDbright > 255) {
LEDbright = 255;
delay(dt);
}
unsigned long afterButtonWasTouchedMs = millis() - whenButtonWasTouchedMs;
if (afterButtonWasTouchedMs >= 60000) {
LEDbright = 0;
analogWrite(LEDPin, LEDbright);
}
}
``` | 2022/03/23 | [
"https://Stackoverflow.com/questions/71595153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14318258/"
] | Your question doesn't seem to line up with how the code was written. It looks like you want to do the opposite (have the light get brighter when the button is held down, and then switch off 60 seconds after the button was released).
Here's the code I came up with to help with your stated problem:
```
int buttonPin = 12;
int LEDPin = 3;
int buttonVal;
int whenButtonWasTouched;
unsigned int LEDbright = 255;
int dt = 500;
int fdt = 60000;
unsigned long whenButtonWasTouchedMs = 0;
void setup() {
// put your setup code here, to run once:
pinMode(buttonPin, INPUT);
pinMode(LEDPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
//static unsigned long whenButtonWasTouchedMs = 0;
buttonVal = digitalRead(buttonPin);
Serial.print("Button = ");
Serial.print(buttonVal);
Serial.print(", ");
delay(dt);
if (buttonVal == 1) {
LEDbright = LEDbright - 20;
whenButtonWasTouchedMs = millis();
}
//
if (LEDbright < 20 || LEDbright > 255) { // The LEDbright > 255 part is because sometimes there can be an integer overflow if we don't keep this.
LEDbright = 0;
}
Serial.println(LEDbright);
unsigned long afterButtonWasTouchedMs = millis() - whenButtonWasTouched;
if (afterButtonWasTouchedMs >= 60000) {
LEDbright = 255;
}
analogWrite(LEDPin, LEDbright);
}
```
As you can see I changed it so that analogWrite is not in the if statement, it checks for integer overflows, and prints out the adjusted value for the led brightness. To make it grow brighter as the button is held and then switch off after 60 seconds just change the minus sign to a plus sign in the LEDbright adjustment line, and change some of the other values around. |
6,542,566 | How do you get last 3 words from the string?
I managed to get working doing like this:
```
$statusMessage = explode(" ", str_replace(' '," ",$retStatus->plaintext));
$SliceDate = array_slice($statusMessage, -3, 3);
$date = implode(" ", $SliceDate);
echo $date;
```
Is there a shorter way? Maybe there is a PHP function that I did not know.. | 2011/07/01 | [
"https://Stackoverflow.com/questions/6542566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/622378/"
] | explode() is good, but once you've done that you can use
```
$size = sizeof($statusMessage);
```
and last 3 are
```
$statusmessage[$size-1];
$statusmessage[$size-2];
$statusmessage[$size-3];
``` |
64,037,433 | I have some code but I just found out it works on like 90% of the computers. Here is the distinguishedName:
*CN=2016-10-05T12:19:16-05:00{393DA5A5-4EEF-4394-90F7-CBD0D2F20CC9},CN=**Computer01-T2**,OU=Product,OU=Workstations,OU=KDUYA,DC=time,DC=local*
What I am trying to do is parse out just the ComputerName. 3 of the 27 OU we have use 3 letter Names instead of the 5 which all the other sites use. Ive been banging my head against the wall and reaching out for some help and or guidance. Watching some videos on regex understand the basics but still working on more complicated things like this.
Here is what I have. Any advice or help would be greatly appreciated.
```
let str = "CN=2016-10-05T12:19:16-05:00{393DA5A5-4EEF-4394-90F7-CBD0D2F20CC9},CN=Computer01-T2,OU=Product,OU=Workstations,OU=KDUYA,DC=time,DC=local";
str = str.substring(70, str.length -53);
console.log(str);+
``` | 2020/09/23 | [
"https://Stackoverflow.com/questions/64037433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12201298/"
] | I don't think they have support for geometry buffers at this stage. ST\_AREA isn't going to help you. Last I heard they are working on improving their geospatial support.
That said, can you buffer your data somewhere else in your workflow? Such as using shapely buffer in python, or turf circle/buffer in javascript? |
26,830,227 | The following is my code for positioning text over image. The requirements are:
1. Image should be adapt to screen automatically. Even on smart phone, the image should be displayed completely. Only showing part of the image is not allowed.
2. Text should be accurately positioned anywhere I wish.
```css
.txtimg{
position: relative;
overflow: auto;
color: #fff;
border-radius: 5px;
}
.txtimg img{
max-width: 100%;
height: auto;
}
.bl, .tl, .br,
.tr{
margin: 0.5em;
position: absolute;
}
.bl{
bottom: 0px;
left: 0px;
}
.tl{
top: 0px;
left: 0px;
}
.br{
bottom: 0px;
right: 0px;
}
.tr{
top: 0px;
right: 0px;
}
```
```html
<div class="txtimg">
<img src="http://vpnhotlist.com/wp-content/uploads/2014/03/image.jpg">
<p class="bl">(text to appear at the bottom left of the image)</p>
<p class="tr"> (text to appear at the top right of the image)</p>
</div>
```
However, the bottom left text is hide from fully displayed on my **firefox** browser.

It is wired that the code snippet runs pretty well in **stackoverflow** by clicking the `Run Code Snippet` below.
I don't know why. Anywhere I found a solution: change `overflow:auto` to `overflow:visible`. The problem will disappear.
Anyone advice? | 2014/11/09 | [
"https://Stackoverflow.com/questions/26830227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2336707/"
] | I can't reproduce the problem on this specific code, but i know the problem. Simply add a vertical-align on the image.
```
.txtimg img {
max-width: 100%;
height: auto;
vertical-align: bottom;
}
```
This also work like this :
```
.txtimg img {
max-width: 100%;
height: auto;
display: inline-block;
}
``` |
3,402,360 | Given any bounded set $E$ in $\mathbb{R}^{N}$, is there a general way to choose a sequence $(G\_{n})$ of open sets such that $\chi\_{G\_{n}}\downarrow\chi\_{E}$ pointwise?
Here $\chi$ denotes the characteristic/indicator function on $E$.
One may think of $G\_{n}:=E+B(0,1/n)$, but we have instead that $\chi\_{G\_{n}}\downarrow\chi\_{\overline{E}}$ pointwise.
So if $E$ is closed, then it follows.
**As @TheoBendit has noted in the comment box that it is what $G\_{\delta}$ set is meant to be.**
So the answer is no.
Let me loose a little bit. What if I require only that $\chi\_{G\_{n}}\downarrow\chi\_{E}$ pointwise almost everywhere?
One may think of remove the boundary $\partial E$ of the set $E$, but note that the boundary need no to be of measure zero, for example, $\partial(\mathbb{Q}\cap[0,1])=[0,1]$.
I also hope to have something like $\chi\_{G\_{n}}\downarrow\chi\_{E}$ pointwise quasi-everywhere with respect to $\text{Cap}\_{\alpha,s}$.
Here I introduce briefly the definition of $\text{Cap}\_{\alpha,s}$.
For compact sets $K$, we let $\text{Cap}\_{\alpha,s}(K)=\inf\{\|\varphi\|\_{W^{\alpha,s}}^{s}:\varphi\geq 1~\text{on}~K\}$.
For open sets $G$, we let $\text{Cap}\_{\alpha,s}(G)=\sup\{\text{Cap}\_{\alpha,s}(K): K~\text{is compact in}~G\}$.
For arbitrary sets $E$, we let $\text{Cap}\_{\alpha,s}(E)=\inf\{\text{Cap}\_{\alpha,s}(G): G~\text{is open that contains}~E\}$. | 2019/10/21 | [
"https://math.stackexchange.com/questions/3402360",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/284331/"
] | Let $\mu$ denote Lebesgue measure on $\Bbb R^N. $
If $E$ is $\mu$-measurable then there exists a sequence $(G\_n)\_n$ of open sets such that $E\subset \cap\_nG\_n$ and $\mu(\,(\cap\_nG\_n)\setminus E\,)=0.$
Let $H\_n=\cap \{G\_j:j\le n\}.$
If $p\in E$ then $\chi\_{H\_n}(p)=1=\chi\_E(p)$ for all $n.$
If $p\not \in \cap\_n H\_n$ then $\{n:p\in H\_n\}$ is finite. So for all but finitely many $n$ we have $\chi\_{H\_n} (p)=0=\chi\_E(p).$
So if $\chi\_{H\_n}(p)$ does not converge to $\chi\_E(p)$ then $p\in (\cap\_nH\_n)\setminus E, $which is a set of measure $0.$ |
42,653,910 | isInSet requires two arguments, but binds passes only theSet as first argument. I am not able to figure out how bind method works in this case
```
function isInSet(set , person) {
return set.indexOf(person.name) > -1;//checks for existence of person.name in theSet
}
console.log(ancestry .filter(function(person) {
return isInSet( theSet , person) ;
}) ) ;
// ! [{ name : " Maria van B r u s s e l " , ...} ,
// { name : " Carel H a v e r b e k e " , ...}]
console.log(ancestry.filter(isInSet.bind(null, theSet))) ;//**how does this work?**
// !... same result
``` | 2017/03/07 | [
"https://Stackoverflow.com/questions/42653910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7659474/"
] | Read the text from the book a few times and compare the unbound and the bound version.
Calling `.bind()` on a function, return a new function, with some of the arguments already filled in. The isInSet function, expects two parameters: the set to filter, and a person having a name.
The `.filter()` method of an array, expects one parameter, namely the function to which each element of the array has to be sent to.
So when you look to the unbound version, you see that the filter function used, just returns `isInSet(theSet, person)`.
So to make the two compatible, we `.bind()` to create a new function with only one parameter left (namely 'person'), that is bound to theSet. So every time this new function returned by bind gets called, it will use theSet as it's first parameter and will expect only one parameter, 'person'.
Here, person, the second parameter of the original isInSet function we didn't bind, is used as the first and only parameter of the bound function.
So we have exactly what we need after using the bind. A function that will take a 'person' as a parameters and will always look inside the same array (theSet).
If you read the docs for `.bind()`, you see that it accepts a variable list of arguments. The first argument is the 'this' argument. So if you have a function that uses 'this' inside it and you want to bind it to eg. an object, you can use the 1st parameter. Eg. `myFunc.bind( objectToCallUpon, firstArg, secondArg );`
Since we don't actually use the 'this' argument in the isInSet() function, we just pass 'null' as the 'this' value.
All the other parameters used are the arguments of isInSet you want to make 'fixed'. Since we want the first parameter to always be theSet, we bind that value.
If the isInSet function would accept two parameters, you would use:
`isInSet.bind( null, theSet, secondParameter );` |
10,663 | I received a new iPhone yesterday and connected it to my home Wifi network.
On content heavy sites it runs perfectly fine, but if I use either the Youtube site or the Youtube app I can't watch anything. It takes forever to watch 5 seconds of video.
My first question is, how can I be sure that my phone is using local Wifi for the internet connection and Youtube app (it says connected in the settings, but is there an icon in the display etc. to confirm Wifi connection)?
Any suggestions as to why Youtube runs slow when other heavy sites load without problem? | 2011/03/22 | [
"https://apple.stackexchange.com/questions/10663",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/1434/"
] | Yes, you can have both versions. In fact you can install the new Firefox in your home directory's Application folder (and it will be only accessible with your account). If you don't have ~/Applications folder, you can create it (and Finder will mark it with the same icon as the /Applications one). Note that you cannot use both versions simultaneously. You can also rename the Firefox.app to Firefox 4.app, and install it in /Applications - it'll work flawlesly.
ps. I prefer the first method - Install applications that I'm testing in my home Applications folder, and when I'm sure they're ok, move them/replace application in /Applications. |
4,382 | I have seen one form of using *avoir*, recently, like this: **à avoir eu**.
I forgot the phrase itself, but, for example in this phrase I just found in Google:
>
> Les jeunes de l’OM sont 2 sur 14 à avoir eu le bac cette année.
>
>
>
What kind of form is it? When/Where it supposed to be used?.. | 2012/11/06 | [
"https://french.stackexchange.com/questions/4382",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/1606/"
] | This *à* is a preposition and is not part of the verb form. This sentence is based on the construction “***être*** [un certain nombre] **à**” like in:
>
> Ils **sont** 3 sur 4 **à** regarder la télé plus de trois heures par jour.
>
> Ils **sont** plus de la moitié **à** regretter son départ.
>
>
>
This preposition is then followed by a verb in infinitive form. In French an infinitive can be given an “accomplished aspect” (*aspect révolu*), which is formed using the appropriate auxiliary verb (it depends on the main verb) and the past participle. In your case “*avoir*” becomes “*avoir eu*”. Other examples:
>
> Elle se rappelle *avoir marché* sur les Champs Élysées.
>
> Il pensait *avoir résolu* le problème.
>
> Ils croient *être allés* sur Mars.
>
>
>
And in passive form:
>
> Il croyait *avoir été compris*.
>
>
> |
10,234,208 | When I link a library such as libm in with ld, I need to drop the lib prefix. What if the file does not follow this naming convention? Is there a way to link it other than renaming the file? | 2012/04/19 | [
"https://Stackoverflow.com/questions/10234208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
] | You can link against any library, e.g. `foo.a`, by specifying full path to it on the link line:
```
gcc main.o /path/to/foo.a
```
What you lose with non-standard library name is the ability for the linker to search for it, e.g. this will not work:
```
gcc main.o -L/path/to foo.a
```
You can avoid that lack of search by using `-l:foo.a` syntax:
```
gcc main.o -L/path/one -L/path/two -l:foo.a
```
>
> When I link a library such as libm in with ld
>
>
>
Note that in general you should *not* link anything with `ld`. Use the compiler driver instead -- it adds objects and libraries to the link line that are required for correct result. |
17,630,368 | Will the contents and rendering output be indexed by Google and other search engines?
Code:
```
<script>
var html = '<!DOCTYPE html>';
html += '<html>';
html += '<head>';
html += '<meta charset="utf8" />';
html += '<title>This Is The Stacked Overflown Network</title>';
html += '<meta name="description" value="i, are, description, ized" />';
html += '<meta name="keywords" value="key, words, and, all, that" />';
html += '</head>';
html += '<body>';
html += '<h1>The Stacked Overflown Network</h1>';
html += '<hr />';
html += '<p>Will I get the opportunity to be indexed at the Googol Seek Engine?</p>';
html += '<p><strong> - No! You Will Not! And bye bye!</strong></p>';
html += '</html>';
html += '</html>';
html += "\n";
document.write( html );
</script>
``` | 2013/07/13 | [
"https://Stackoverflow.com/questions/17630368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | That's *definitely* **not** a good style of writing Webpages.
Many crawlers *don't run* JavaScript at all.
Though it may be possible that JavaScript *source code* gets indexed to some extent, this content is very unlikely to get high rating.
The *result* of the script *may* be indexed by Google, but some crawlers just won't get your content. |
19,001,457 | I have created one group of radio buttons in a table like
```
<table cellpadding="0" cellspacing="0" border="0">
<tbody>
<tr>
<td>
<input type="radio" name="radios" id="8-9" />
<label for="8-9">08-09 am</label>
</td>
</tr>
<tr>
<td>
<input type="radio" name="radios" id="9-10" />
<label for="9-10">09-10 am</label>
</td>
</tr>
</tbody>
</table>
```
and when any of the radio button clicked then the background of parent is need to be changed and JQuery for it is like-
```
$(document).on('click', '#8-9', function (event) {
$checked = $("#8-9").is(':checked');
if ($checked) {
$(this).parent().css("background-color", "#000");
$(this).parent().css("color", "#fff");
} else {
$(this).parent().css("background-color", "#ff0000");
$(this).parent().css("color", "#fff");
}
});
$(document).on('click', '#9-10', function (event) {
$checked = $("#9-10").is(':checked');
if ($checked) {
$(this).parent().css("background-color", "#000");
$(this).parent().css("color", "#fff");
} else {
$(this).parent().css("background-color", "#252525");
$(this).parent().css("color", "#fff");
}
});
```
this code is working , when radio is clicked the background of parent is changed, but when radio is unchecked the background of parent is not been reset to default. Is there any mistake in my script or any other way is there of this? | 2013/09/25 | [
"https://Stackoverflow.com/questions/19001457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2814574/"
] | Check this : <http://jsfiddle.net/ChaitanyaMunipalle/R4htK/>
First you have to reset css of parent of radio buttons and then set which ever is checked.
```
$('input[name=radios]').on('change', function() {
$('input[name=radios]').parent().css("background-color", "#ff0000");
$('input[name=radios]').parent().css("color", "#fff");
$(this).parent().css("background-color", "#000");
$(this).parent().css("color", "#fff");
});
``` |
44,541,048 | I have already done some searches, and this question is a duplicate of another post. I am posting this just for future reference.
Is it possible to define SUMPRODUCT without explicitly using variable names x, y?
Original Function:
```
let SUMPRODUCT x y = List.map2 (*) x y |> List.sum
SUMPRODUCT [1;4] [3;25] // Result: 103
```
I was hoping to do this:
```
// CONTAINS ERROR!
let SUMPRODUCT = (List.map2 (*)) >> List.sum
// CONTAINS ERROR!
```
But F# comes back with an error.
I have already found the solution on another post, but if you have any suggestions please let me know. Thank you. | 2017/06/14 | [
"https://Stackoverflow.com/questions/44541048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7676509/"
] | Function composition only works when the input function takes a single argument. However, in your example, the result of `List.map2 (*)` is a function that takes two separate arguments and so it cannot be easily composed with `List.sum` using `>>`.
There are various ways to work around this if you really want, but I would not do that. I think `>>` is nice in a few rare cases where it fits nicely, but trying to over-use it leads to unreadable mess.
In some functional languages, the core library defines helpers for turning function with two arguments into a function that takes a tuple and vice versa.
```
let uncurry f (x, y) = f x y
let curry f x y = f (x, y)
```
You could use those two to define your `sumProduct` like this:
```
let sumProduct = curry ((uncurry (List.map2 (*))) >> List.sum)
```
Now it is point-free and understanding it is a fun mental challenge, but for all practical purposes, nobody will be able to understand the code and it is also longer than your original explicit version:
```
let sumProduct x y = List.map2 (*) x y |> List.sum
``` |
323,978 | how to prove $\forall n$ : $p\_1p\_2...p\_n +1$ isn't the perfect square. $p\_i$ is $i$th prime number. | 2013/03/07 | [
"https://math.stackexchange.com/questions/323978",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/48921/"
] | Let $n \ge 1$. Since $2$ is the first prime, our product is even. Thus $p\_1\cdots p\_n+1$ is odd. Suppose it is equal to the odd perfect square $m^2$.
Note that $m^2-1$ is divisible by $4$, indeed by $8$. But $p\_1\cdots p\_n$ is not divisible by $4$. Thus $p\_1\cdots p\_n+1$ cannot be a perfect square.
**Remark:** The prime $2$ played a crucial role in this argument. Note for example that $3\cdot 5+1=4^2$, and $11\cdot 13 +1=12^2$. |
133,767 | Inspired by [this](https://codegolf.stackexchange.com/questions/125470/multiply-two-strings) challenge (thanks @cairdcoinheringaahing for the title!), your task is to take two printable ASCII strings and multiply them element-wise with the following rules.
### How does it work?
Given two strings (for example `split` and `isbn`) you will first, truncate the longer one such that they have equal length and then determine their [ASCII codes](https://en.wikipedia.org/wiki/ASCII#Printable_characters):
```
split -> spli -> [115, 112, 108, 105]
isbn -> isbn -> [105, 115, 98, 110]
```
The next step will be to map them to the range `[0..94]` by subtracting `32` of each code:
```
[115, 112, 108, 105] -> [83, 80, 76, 73]
[105, 115, 98, 110] -> [73, 83, 66, 78]
```
Now you will multiply them element-wise modulo `95` (to stay in the printable range):
```
[83, 80, 76, 73] ⊗ [73, 83, 66, 78] -> [74, 85, 76, 89]
```
Add `32` to get back to the range `[32..126]`:
```
[74, 85, 76, 89] -> [106, 117, 108, 121]
```
And the final step is to map them back to ASCII characters:
```
[106, 117, 108, 121] -> "july"
```
### Rules
* You will write a program/function that implements the described steps on two strings and either prints or returns the resulting string
* The input format is flexible: you can take two strings, a tuple of strings, list of strings etc.
* The input may consist of one or two empty strings
* The input will be characters in the printable range (`[32..126]`)
* The output is either printed to the console or you return a string
* The output is allowed to have trailing whitespaces
### Test cases
```
"isbn", "split" -> "july"
"", "" -> ""
"", "I don't matter" -> ""
" ", "Me neither :(" -> " "
"but I do!", "!!!!!!!!!" -> "but I do!"
'quotes', '""""""' -> 'ck_iKg'
"wood", "hungry" -> "yarn"
"tray", "gzip" -> "jazz"
"industry", "bond" -> "drop"
"public", "toll" -> "fall"
"roll", "dublin" -> "ball"
"GX!", "GX!" -> "!!!"
"4 lll 4", "4 lll 4" -> "4 lll 4"
"M>>M", "M>>M" -> ">MM>"
```
**Note**: The quotes are just for readability, in the 6th test case I used `'` instead of `"`. | 2017/07/21 | [
"https://codegolf.stackexchange.com/questions/133767",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/48198/"
] | [MATL](https://github.com/lmendo/MATL), 12 bytes
================================================
```
c32-p95\32+c
```
[**Try it online!**](https://tio.run/##y00syfn/P9nYSLfA0jTG2Eg7@f//avXigpzMEnUdBfXM4qQ89VoA "MATL – Try It Online")
### Explanation
```
c % Implicitly input cell array of 2 strings. Convert to 2-row char matrix.
% This pads the shorter string with spaces
32- % Subtract 32, element-wise. Each char is interpreted as its ASCII code.
% Note that padding spaces will give 0.
p % Product of each column. Since (padding) spaces have been mapped to 0, the
% product effectively eliminates those colums. So the effect is the same as
% if string length had been limited by the shorter one
95\ % Modulo 95, element-wise
32+ % Add 32, element-wise
c % Convert to char. Implicitly display
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.