INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
how to get output of ls command to an array in c++
Is there a way to run the linux command ls, from c++, and get all the outputs stored in one array, in c++?
Thanks | If you insist on actually running `ls`, you can use `popen` to launch the process and read the output:
FILE *proc = popen("/bin/ls -al","r");
char buf[1024];
while ( !feof(proc) && fgets(buf,sizeof(buf),proc) )
{
printf("Line read: %s",buf);
}
But you could probably better be reading the directory contents and file info yourself, using `opendir` and `readdir`. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 3,
"tags": "c++, linux, arrays, ls, output"
} |
Can the iPad support multiple Regional Settings simultaneously?
I need spell-checking in different languages such as English, German and Norwegian. I currently have only German spell-checking and it is quite irritating that it messes up with other languages' words. Is there some easy way of having spell-checking in multiple languages on the iPad?
What about keyboards? Is it possible to have many regional settings on one iPad, easily? | You can have multiple keyboards enabled: `Settings -> General -> Keyboard -> International Keyboards`. Add whichever keyboards you wish. Then, when you are typing text, hit the globe key on the keyboard to switch between the different keyboards.
As far as I know, you can't have multiple languages enabled at the same time for spell checking. However, you can switch between them using `Settings -> International -> Language`. | stackexchange-apple | {
"answer_score": 1,
"question_score": 1,
"tags": "keyboard, language, spelling"
} |
How do you use EclipseLink 2.3 as persistence provider in NB 7?
I downloaded the latest EclipseLink 2.3 and want to give it a try. But I cannot find a way to choose EclipseLink 2.3 as a persistence provider in NB7.
Here's what I did. 1\. Go to my project's persistence.xml. In Design view-> Persistence Provider drop down menu -> New Persistence Library 2\. I added the EclipseLink 2.3 jar files and gave it a name. 3\. Hit OK.
Nothing happened. It still shows "EclipseLink (JPA 2.)(Default) as my Persistence Provider. And I cannot find the newly created library in the drop down menu. (But if I go Project Properties->Libaries->Add Library I can see it got created).
So how do i use EclipseLink 2.3 as a persistence provider in NB7? | As long as your Libraries list contains your EclipseLink 2.3 jar and that the persistence.xml file contains the following line: org.eclipse.persistence.jpa.PersistenceProvider
You will be using version 2.3 of EclipseLink. As for the display in netbeans, I'm not sure why it wouldn't update but I wouldn't worry about it.
FYI, I've been using EclipseLink 2.3.0 in Netbeans via the method I've described above and it works fine. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "netbeans, eclipselink"
} |
Evaluate $\lim_{x \to \infty}{\frac {a - x^2 \ln {\left|1-\frac {a}{x^2}\right|}}{b\ln {\left|1-\frac {a}{x^2}\right|}}}$
Evaluate:$$\lim_{x \to \infty}{\frac {a - x^2 \ln {\left|1-\frac {a}{x^2}\right|}}{b\ln {\left|1-\frac {a}{x^2}\right|}}}$$
I tried solving this using L'Hôpital's rule, and the limit appears to be unbounded. However, when graphed using a calculator (with random values of $a$ and $b$), it appears to converge to a definite value. I wanted to confirm if this limit exists. | The numerator tends to $2a$ (which is non-zero otherwise the expression has no sense), and the denominator tends to $0$, so the limit is not finite. | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "calculus, limits"
} |
resizing a vector of vectors causes a seg fault
class MyVect:private std::vector<std::vector<std::string> >
{
typedef std::vector<std::vector<std::string> > super;
public:
///When this is commented out -- No Seg Fault//////////////
std::vector<std::string>& operator[](int plt)
{
return static_cast<super>(*this)[(int)plt];
}
///////////////////////////////////////////////////////////
MyVect()
{
this->resize(4); // this works fine
for (int i = 0; i<4;i++)
{
(*this)[i].resize(3); // I think this doesn't
}
(*this)[0][0] = "hello";
}
};
The above code, causes a seg fault and I can't figure out what is wrong?
*** glibc detected *** invalid fastbin entry (free): 0x09267040 | `static_cast<super>(*this)` creates a temporary and slices `*this`.
You want `static_cast<super&>(*this)`. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 2,
"tags": "c++, c++11"
} |
How to send multiple commands to terminal(linux) from python?
I want to send commands to run a python script to the Linux terminal. I have a list of python files which I want to run and I want to run them one after the other as we read the list sequentially. Once the first file is finished, it should send the second one to run and so on. | You can use the `check_call` function of the subprocess module which is a blocking call. when you iterate through the list one will run after another.
import subprocess
files = ['script1.py', 'script2.py']
for _file in files:
call_output = subprocess.check_all(['python', _file]) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -3,
"tags": "python, linux, python 3.x"
} |
if recursively find ext, then, else on unix
This is what I normally use. But I need to recursively find an extension with, then, and else. The problem with this one is that it is not recursive.
if ls $HOME/Downloads/*.ext >/dev/null 2>&1
then
:
else
:
fi | Use `find` instead of ls. If you have GNU find, you can use `-quit` to exit after the first match. Then just check if it returned any result.
The script would look something like
if [ -n "$(find $HOME/Downloads -name '*.ext' -print -quit | head -n 1)" ]
then
:
else
:
fi
Use -iname instead of -name to do a case insensitive search. | stackexchange-superuser | {
"answer_score": 2,
"question_score": 0,
"tags": "unix"
} |
Is there any Ruby framework to return database data to XML?
Instead of writing the SQL query, is there any lazy way to get the data from database in XML format. | Well... Rails is a framework for Ruby that can accomplish what you are looking for, give this a try in a controller:
respond_to do |format|
if @obj.save!
format.xml {}
end
end
Activerecord can do lots of other magic as well.
After installing rails you must install the Gem for SQL Server:
sudo gem install activerecord-sqlserver-adapter --source=
Then add a few things to your `database.yml` to get it to work with SQL Server:
development:
...
adapter: sqlserver
mode: odbc
dsn: sqlserverapp
...
Rails has some cool methods for manipulating and reading XML built in, but I suggest the gem Nokogiri. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "sql, sql server, ruby"
} |
Youtube "end=" embed tag not working?
I am trying to embed a Youtube video on my site with specific start and end times. Sites such as snipsnip.it and splicd.com use the start= and end= tags in the iframe src like so:
<iframe src=' width='640' height='360'>
</iframe>
However, this does not work on my web page. The video starts at the right time but then just plays till the end of the video. The Youtube API states that there is no "end=" tag, yet these sites all use it successfully.
Any idea on how to get embedded Youtube videos to end at a specific point? | splicd.com doesn't actually depend on the YouTube to stop the video. They poll the player with the following JavaScript and the YouTube Player API:
function checkYouTubePlayHead()
{
current = player.getCurrentTime();
if((current >= end) && splice) {
player.seekTo(start, true);=
player.pauseVideo();
}
if(current > start)
played = true;
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "youtube, embed"
} |
SQL- JOIN two column from two tables
I need help to formulate a query. I want to select all DISTINCT colors from TABLE A and TABLE B.
This is the wanted result from the query:
BLACK
RED
YELLOW
BLUE
I have these tables:
TABLE A
ID NAME COLOR
5 SOCKS BLACK
4 SOCKS RED
TABLE B
ID NAME COLOR
0 CAR BLUE
1 BIKE BLUE
5 TRUCK YELLOW
10 PLANE NULL
I have tried:
SELECT DISTINCT A.color FROM A JOIN B ON b.color
But I don't get all the colors. :( | SELECT color FROM A
UNION
SELECT color FROM B
WHERE color IS NOT NULL -- only filters NULL from B
ORDER BY color -- sorts all rows
`UNION` (instead of `UNION ALL`) removes duplicates. No need for additional subqueries or `DISTINCT`. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 1,
"tags": "mysql, sql, database, union"
} |
Can transactions sent later have a lower block number?
I apologize in advance if my question is stupid.
> What I'm curious about is that transactions sent first must be recorded in the preceding **block number**?
As far as I know, just because you enter the pending `state` first does not mean you will be in the commit state first.
> If so, can transactions sent later have a lower block number? | You are correct, a transaction you send after another can be included before the earlier one if you set a higher gas fee to it and it’s picked up by a miner before the earlier one.
A transaction sent doesn’t mean it was added to a block and processed yet.
Edit: there is actually two cases here:
1. both transaction have the same nonce, and the first one included in a block will make the other one invalid since a nonce can only be used once
2. the transactions have following nonce, and the higher nonce transaction will only be processed once the lower nonce transaction is processed. | stackexchange-ethereum | {
"answer_score": 1,
"question_score": 0,
"tags": "contract development, transactions, ether"
} |
Nutch Error: JAVA_HOME is not set
I followed this tutorial < When I finally tried to run Nutch `sudo bin/nutch inject urls` I got this error
Error: JAVA_HOME is not set.
but when I echo JAVA_HOME it returns
/usr/lib/jvm/java-7-openjdk-amd64
and it is also in /etc/environment
JAVA_HOME="/usr/lib/jvm/java-7-openjdk-amd64"
and also I added line to end of file ~/.bashrc
export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64
but it still returns this error. How can I fix it? | You are running the command as root user, so the environment variables the application sees are the one's visible for root user not your user. Just check that the root has a JAVA_HOME environment variable set or run the program as your user, if possible.
You can try `sudo -E bin/nutch inject urls`
As the sudo manual says, -E, --preserve-env Indicates to the security policy that the user wishes to preserve their existing environment variables. The security policy may return an error if the user does not have permission to preserve the environment. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "java, ubuntu, nutch"
} |
What is the -v switch in go get -u -v
According to documentation
> Usage:
>
> `go get [-d] [-t] [-u] [-v] [build flags] [packages]`
The text explain every switch, but `-v` is missing from docs.
`go help get` also doesn't mention `-v`, although it is clearly present in usage:
$ go help get
usage: go get [-d] [-t] [-u] [-v] [-insecure] [build flags] [packages]
What is this switch for? | From this documentation :
> The -v flag enables verbose progress and debug output.
Get also accepts build flags to control the installation. See `go help build`.
For more about specifying packages, see `go help packages`.
For more about how 'go get' finds source code to download, see `go help importpath`. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -2,
"tags": "go, documentation, go get"
} |
index string has no method of isin()
I have a dataframe with index is string name like 'apple' etc.
Now I have a list
name_list=['apple','orange','tomato']
I'd like to filter dataframe rows by selecting rows with index is in the above list
df=df.loc[df.index.str.isin(name_list)]
then I got an error of
AttributeError: 'StringMethods' object has no attribute 'isin' | Use `df.index.isin`, not `df.index.str.isin`:
df = df.loc[df.index.isin(name_list)] | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "python, pandas"
} |
Site on localhost not displaying image
I am trying to get an image to appear using Django template.
In settings I have:
MEDIA_ROOT = 'C:/workspace/mysite/uploaded_media/'
MEDIA_URL = '
The html is
<img source = "
I have an image file blabla.jpg in the folder uploaded_media
What am I missing here?
Edit: first problem was writing "source" instead of "src" in the tag. doh. (attempting the answer below right now.) | try
MEDIA_URL = '/media/'
and in template
<img src="/media/blabla.jpg" />
Also put these lines of code inside your urls.py and set DEBUG to True
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT})) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "django, image"
} |
Parse encoded $_SERVER['request_uri']
Quick question, `$_SERVER['request_uri']` doesn't contain decoded url but the original one. If I access ` it contains `asd/%20/`. What's the function name to parse it to `asd/ /`? | You are looking for `urldecode()`
> Decodes any %## encoding in the given string. Plus symbols ('+') are decoded to a space character. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "php, url, request"
} |
Where can I find a standalone installer for Windows 7 Service Pack 1?
I've searched everywhere and can't find a standalone MSI or EXE for Windows 7 Service Pack 1.
Does it exist somewhere? | Yes.
<
For 64-bit Windows 7, download the file "windows6.1-KB976932-X64.exe"
For 32-bit Windows 7, download the file "windows6.1-KB976932-X86.exe" | stackexchange-superuser | {
"answer_score": 6,
"question_score": 6,
"tags": "windows 7, download, service pack"
} |
JS function for writing out a word, binary counter style
How can I create a loop to output any given word like this:
...if the word is 'abcd'
a---
-b--
ab--
--c-
a-c-
-bc-
abc-
---d
a--d
-b-d
ab-d
--cd
a-cd
-bcd
abcd
in other words, letters appear in binary counter order
1000
0100
1100
0010
1010
etc.
Thanks | var i = 1;
console.log("abcd".replace(/./g, function(c,n) {
return (i & (1 << n)) ? c : '-';
}));
Just loop `i` from `1` to `(2 ^ length) -1` | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 1,
"tags": "javascript, string, binary"
} |
Is Banshee damaging my music files?
I don't know whether that's true, but sometime from now (maybe since I've started using ubuntu 11.04), my music files have started showing errors on the execution. Basically, many .mp3 files I had are damaged and start the music twice, like: the music starts then 2 seconds later it restarts and continues playing. This errors appear when listening to the songs in any players, being from ubuntu, windows or iPod. Is it possible that Banshee is doing this? | Banshee should not be damaging your files as it should be merely reading them. Unless there is something (extremely) wrong with how the metadata is being written back into the mp3 files.
Go to Edit >> Preferences and see if the record metadata to files box is checked. If it is, try disabling it. If it is disabled, than it is unlikely Banshee is causing it.
You mention starting to use ubuntu 11.04 - did you do a clean install or a direct upgrade? An upgrade could represent an issue with audio drivers. I'm baffled because you mention trying it in ubuntu, windows and the iPod.
Have you done any sort of re-enconding/conversion of the files?
What you can do to test is first testing an album in windows and then trying in ubuntu (and vice-versa).
There are so many factors in to question that I ultimately think you are better off filing a bug report over Banshees launchpad. < | stackexchange-askubuntu | {
"answer_score": 2,
"question_score": 0,
"tags": "banshee"
} |
Magento 2: cURL webAPI request for Customer search
Trying to find a way how to integrate Magento 2 via cURL to search for a customer.
For Example the below command is able to bring the customer details of 8
curl -X GET "
-H "Authorization: Bearer myaccesstoken"
In the similar fashion how can I construct the search URL with Search Criteria
I spent a day with this website and no luck.
curl -X GET
-H "Authorization: Bearer xxxxxxx"
-d '{"searchCriteria":{"filterGroups":[{"filters":[{"field":"email","value":"[email protected]","condition_type":"eq"}]}]}}'
And I got the error
{"message":"%fieldName is a required field.","parameters":{"fieldName":"searchCriteria"}}
There is something wrong in my request... | Finally after 3 days of struggle got the answer how to put the search criteria in cURL
curl -X GET "
?searchCriteria[filterGroups][0][filters][0][field]=email
&searchCriteria[filterGroups][0][filters][0][value][email protected]
&searchCriteria[filterGroups][0][filters][0][condition_type]=eq"
-H "Authorization: Bearer xxxxxx"
-H "Content-type: application/json" -g
The above command will just connect to my store and search for the customer who is having the exact email address. | stackexchange-magento | {
"answer_score": 7,
"question_score": 3,
"tags": "magento2, api, rest api"
} |
Build fails with simple Haskell library with cabal new-build with GHC 8.6.3
Trying to build a Simple library with Haskell. It worked once and then just stopped working(weirdly)
only a few commands were run, a simple cabal init with only library
then the following library was added
Greet.hs
module Greet where
greeet s = "Hey, " ++ s
then cabal new-build was run and then cabal new-repl
the error is as follows
Build profile: -w ghc-8.6.3 -O1
In order, the following will be built (use -v for more details):
- HaskellTry-0.1.0.0 (lib) (ephemeral targets)
Preprocessing library for HaskellTry-0.1.0.0..
GHCi, version 8.6.3: :? for help
Ok, one module loaded.
Prelude Greet> greeet "h"
"
everything is just stuck after that. | GHC 8.6.3 on Windows suffers from a bug that makes it pretty much unusable. The issue should be solved in 8.6.4. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "haskell, cabal, haskell platform, cabal new"
} |
NSUserDefault Maximum Size
> **Possible Duplicate:**
> Is there any limit in storing values in NSUserDefaults
How much data i can save on NSUserDefaults . Is there is storage size is different for all devices. or same for all devices . | Why on earth will you want to store so much data in `NSUserDefaults`?
`NSUserDefaults' should not be used as a global dictionary.
Try using property lists & core data. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "iphone, objective c, ios, size, nsuserdefaults"
} |
Intuition behind conjugate symmetry axiom in inner product spaces
In inner product spaces what is the motivation behind conjugate symmetry axiom?
Well if it is a real inner product I could make sense of symmetry, but here I couldn't make sense of conjugate symmetry
Any insight toward it or any geometric ideas would be helpful | If we replace conjugate symmetry by symmetry, we will have $\alpha^2\langle u,u\rangle=\langle \alpha^2u,u\rangle=\langle \alpha u,\alpha u\rangle>0$ for every nonzero complex scalar $\alpha$ and nonzero vector $u$. But this is a contradiction as $\alpha^2$ is not necessarily real or positive. | stackexchange-math | {
"answer_score": -1,
"question_score": 0,
"tags": "linear algebra, complex numbers, inner products"
} |
Создать зависимое свойство
Прочёл главу книги Мак-Дональда про зависимые свойства, но не удаётся использовать приведённые фрагменты кода. Не могли бы Вы привести простейший полноценный пример создания зависимого свойства ? Вот код, который приводится в статьях, но не ясно как его использовать для создания зависимого свойства:
public class FrameworkElement: UIElement
{
public static readonly DependencyProperty MarginProperty;
...
}
...
static FrameworkElement()
{
MarginProperty = DependencyProperty.Register("Margin",
typeof(Thickness), typeof(FrameworkElement), null);
...
}
...
public Thickness Margin
{
get { return (Thickness)GetValue(MarginProperty); }
set { SetValue(MarginProperty, value); }
} | 1. Для начала, вам нужен класс (ваш собственный!), в котором будет определено DP. Этот класс должен быть потомком `DependencyObject`. Если вы определяете контрол, вам достаточно унаследоваться от любого UI-класса, например, `UserControl`. Пусть имя вашего класса `C`.
2. Затем, в классе `C` пишете такой код:
public static readonly DependencyProperty XProperty =
DependencyProperty.Register("X", typeof(int), typeof(C));
public int X
{
get { return (int)GetValue(XProperty); }
set { SetValue(XProperty, value); }
}
(можно писать не руками, а воспользоваться сниппетом `propdp`). Таким образом вы определяете DP типа `int` с именем `X`. Если нужен другой тип или другое имя, подправьте во **всех** нужных местах. (Если подправить не везде, работать не будет. Наверное легче стереть старое DP и создать новое.)
3. Если что-то не работает, то вы что-то сделали неправильно. Должно работать. | stackexchange-ru_stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c#, silverlight"
} |
Training both positive and negative data with naive bayesian classification?
This might not be the best forum for this question so please forgive me.
So I was demo'ed a custom naive bayesian classifier that accepted both positive & negative training data. An example:
"I am really excited about getting my python tonight"
This would be trained as positive on the class "pets", "happy" but negative against "python", "programming"
This dramatically increased how quickly a class could be trained accurately.
So my question: is this really naive bayesian classification? Is there anything else out there like this?
Additional information: The classifier didn't just return a single matching class against input but returned an array of classes and their "scores" | Not only is this a naive Bayesian classifier (so far as I understand your description), but it's a general rule that naive Bayes needs both positive and negative examples in its training data in order to perform well. A spam filter should have known examples of non-spam as well as known examples of spam. | stackexchange-stats | {
"answer_score": 0,
"question_score": 0,
"tags": "classification, naive bayes"
} |
How to create and use responsive themes in Flutter?
I'm getting `MediaQuery.of() called with a context that does not contain a MediaQuery.` when trying to access MediaQuery from `MaterialApp`:
return new MaterialApp(
title: 'Flutter Demo',
theme: getTheme(MediaQuery.of(context)),
home: new Container(),
); | Use `builder` of `MaterialApp` instead. So that you can use `MediaQuery` instantiated by `MatetialApp` inside your `Theme`.
new MaterialApp(
builder: (context, child) {
return new Theme(
data: getTheme(MediaQuery.of(context)),
child: child,
);
},
home: new ChatScreen(),
), | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 3,
"tags": "flutter, flutter layout"
} |
Entity name must Immediately follow the '&' in the entity reference
I created String array for the List of Bank names in **string.xml** file. When I'm using item name **State Bank of Bikaner & Jaipur** as array item:
<item>State Bank of Bikaner & Jaipur</item>
I'm getting the following error: **`"The Entity name must Immediately follow the '&' in the entitiy reference"`**
Ideas on how to fix this? Any help would be greatly appreciated. | The `&` symbol is an entity specifier in XML. If you want to put a literal ampersand in the XML, you will need to use `&`, which is the standard entity for an ampersand. | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 1,
"tags": "android, string"
} |
Angular 2 Interpolation with view container and templateRef
I am trying to mimic ngfor for a paging directive. Any interpolated value does not display. In my directive I have :
Input() set pageOf(a){
for(let x of a) {
this.viewContainer.createEmbeddedView(this.templateRef);
}
}
In my html I have :
<table>
<tr *page="let a of test" >
<td>abc</td>
<td>{{a}}</td>
</tr>
</table>
"abc" displays fine for each element in test but what {{a}} interpolates to does not display. My guess is somehow I need to tell the view container what a is. | Found my own answer...in case any one is looking.
@Input() set pageOf(a){
for(let x of a) {
const view = this.viewContainer.createEmbeddedView(this.templateRef);
view.context.$implicit = x;
}
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "angular"
} |
Convert Hex string of high length to decimal
I'm trying to write a function that can convert a seriesof uint_8 values (set in an array) into one single Decimal number and print it. The values get parsed in an array of known, but not constant length len:
void print_decimal(size_t len, uint8_t buf[len]);
Buf is ordered, so that the most significant digits of the resulting decimal number are at the front of the array, f.e.: -> buf[0] = 1111 1111; buf[1] = 0000 0000 -> Result: 0xFF00 -> Convert to decimal
The issue is, that the length / size of the resulting number exceeds the size of a single cariable like uint64_t (or even 128 Bit types), so simply converting it is not an option.
Are there any smart and easy ways to convert this? F.e. digitwise through an algorithm? | As an example of the repeated division by 0x0A using 'longhand'
1 2C
------
0A ) 0B BB
0A
---
1 BB
1 B8
-----
3 l.s. digit
Repeat
0 1E
------
0A ) 01 2C
00
---
1 2C
1 2C
-----
0 next l.s. digit
Repeat
0 03
------
0A ) 00 1E
00
---
0 1E
0 1E
-----
0 next l.s. digit
Repeat
0 00
------
0A ) 00 03
00
---
0 03
0 00
-----
3 m.s. digit
Result of the string of remainders is `3003` which is decimal of `0xBBB`.
Note that we were never "in base ten". The division was by ten, but the only decimals are the digits that fall out with each repetition. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -2,
"tags": "c, numbers, hex, decimal, number formatting"
} |
mysql views get decreased
I own a image hosting website and I capture image views using php and mysql.
I use the following code to count the views.
include 'mysql.php';
$result = mysql_query("SELECT * FROM DB WHERE ID='$id'");
$row = mysql_fetch_array($result);
$views=$row['views'];
$query = "UPDATE DB SET views=$views+1 WHERE ID='$id'";
$result2 = mysql_query($query);
mysql_close($con);
views is _mediumint(9)_ type field.
I noticed that the views get decreased day by day.can anyone say what is the problem and offer a solution.
Thanks. | You should use this to update instead:
$query = "UPDATE DB SET views=views+1 WHERE ID='$id'";
If a page takes a long time to execute, you can have one query overwrite another. Also using this, you might not need to even run the first query - unless you want other info from it.
The reason you are getting an error is that one script is reading the data and grabbing the value, then updating it - based on the value it is storing - but in the meantime other scripts could be updating the row. You could avoid it by using transactions, but that seems utter overkill for what you are doing. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 0,
"tags": "php, mysql, image, view"
} |
How do I change the placeholder text?
Adding the following prop does not seem to work
text={{placeholder: "Select product"}}
<DropdownTreeSelect
data={data}
texts={{placeholder: 'Some other text'}}
onChange={onChange}
className="bootstrap-demo"
/>
Placeholder text still shoews default "Choose ..." | The prop name is `placeholderText` try:
<DropdownTreeSelect
data={data}
placeholderText={'Some other text'}
onChange={onChange}
className="bootstrap-demo"
/> | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "react dropdown tree select"
} |
Backup/Copy pip modules from folder structure
My laptop recently died, and while there are easy ways to backup modules on a working system (for example), I wasn't intelligent enough to do so.
I do, however, have a very recent backup of the entire Python folder. I can't execute that python version anymore, seeing as I'm on a new, freshly installed windows system. So my question is:
Is there an elegant way to tell Python (2.7.5 AND 3.6.1) to install all the modules I already had inside the folder? | The documentation says modules are installed here: 
If these methods don't work for all your libs, they can at least serve you as a temporary fix until you find a better way to detect and install all old libs with new version. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "python"
} |
No JS module 'tweener' found in search path, Gnome shell extension error on Ubuntu 20.10
Today I upgraded Ubuntu 20.04 to Ubuntu 20.10 and there is problem in one of the extensions in Gnome shell extensions.
The Extension Panel OSD giving the error " **No JS module 'tweener' found in search path** ".
How to resolve this? | The `tweener` module has been moved to a new path, from `imports.ui.tweener` to `imports.tweener.tweener`. In the exention's repository, somebody already created a merge request to merge the necessary changes into the code, but the extension's developer hasn't merged it yet.
You can either wait until the developer does the change and puts out a new version of the extension, or - if you feel comfortable with it - change the import path in your local copy of the extension yourself. You can look up in the merge request what to change. | stackexchange-askubuntu | {
"answer_score": 7,
"question_score": 4,
"tags": "gnome, gnome shell extension, 20.10"
} |
How does one tell if logical expressions are equivalent?
How do I check if these expressions are equivalent?
* ∀a,b [P(a) ∧ ¬R(a) ∧ S(b)] → G(a,b)
* ∀a [(P(a) ∧ ¬R(a)) → (∀b [S(b) → G(a,b)])] | Expressions are equivalent if they can be related with an if and only if connection.
One way to check if they are equivalent is to use a tree proof generator. Putting these expressions into such a tool will also require one to write a well-formed formula eliminating any ambiguity.
Here is the result of the tool showing that the expressions are equivalent as I entered them:
 {
var input = document.createElement("INPUT");
input.name = key;
input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
form.appendChild(input);
}
As such, file data from a file input cannot be loaded via javascript to be posted via the `postJson` call as it currently exists so your best bet for that would be to just upload the files and post the JSON in two separate requests. It may also be possible to inject the file input into this form the `postJson` method creates (by overriding the method) but its kind of hacky and may not be forward compatible. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "asp.net mvc, knockout.js"
} |
Expansion of vector for swing operations
I have a JPanel and a vector of JButtons and want to add each button to the panel.
The issue I'm having is that I have a variable btns that represents the vector of buttons, but the macro function just sees it as a symbol, not a vector. Is there a way to expand it somehow?
Here's the code:
(defmacro add_all [panel btns]
;; help?
)
(let [x 10, y 10
btns get_buttons] ;; just a vector of JButton objects
(doto (JPanel.)
(.setLayout (GridLayout. x y))
(add-all btns)))
I would like this to expand to:
(doto (JPanel.)
(.setLayout (GridLayout. x y))
(.add (btns 0))
(.add (btns 1))
;; etc
(.add (btns 99))) | There's no need for a macro (and indeed the problem as stated cannot be solved with a macro). Just write a function which operates on a panel and a seq of buttons:
(defn add-all [panel buttons]
(doseq [button buttons]
(.add panel button))) | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 3,
"tags": "swing, macros, clojure, lisp"
} |
Using event of control under datalist
I have a datalist control which some controls(ex: button) are in it. I want to write some code into click event of button which is in the datalist control. But in the code behind page I can't see the name of controls into datalist. How can I solve this problem? | If you don't want to add a handler to all the child events, you could instead add your code to the OnItemCommand.
<asp:DataList id="DataList1" runat="server">
<ItemTemplate>
<asp:Button ID="btnDoSomething" Runat=server CommandName="DoSomething"
CommandArgument="<%# DataBinder.Eval(Container.DataItem, "SomeID")
%>"></asp:LinkButton>
</ItemTemplate>
</asp:DataList>
protected void DataList1_ItemCommand(
object source, DataListCommandEventArgs e)
{
if (e.CommandName == "DoSomething")
{
//Do stuff
}
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "asp.net, events, datalist"
} |
Grunt with Jasmine/Mocha: accessing tests on filesystem or through webserver?
I am setting up a testing environment for a client-side javascript project.
I am using Grunt for my build automation. As a test framework I am going to use Jasmine or Mocha.
I notice that both grunt-contrib-jasmine and grunt-mocha can be configured to run the test from the local filesystem or through a webserver (typically using grunt-contrib-connect). i.e by using options.urls (Mocha) or options.host (Jasmine).
The default Yeoman generator "webapp" uses the latter method.
I would imagine that running from the filesystem is more performant and less error prone. What is the advantage of going through a webserver? Or what scenarios require going through a webserver? | If your tests are accessed through a webserver you gain the ability to run them on browsers on other devices. Depending on how your test suite looks you could use time-grunt to determine how long runs take via direct access and through the web. Then either choose web if there isn't a performance hit, or consider having two paths, disk for speed, and web for testing with other devices. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "javascript, gruntjs, jasmine, mocha.js"
} |
Angular 5 remove class using wildcard
I have an input attribute with a class :
<input class="color b1 b2 b3" text="text">
I want to remove all the classes after color so i can add other classes. But how to do it with a wildcard using .renderer.removeClass ? So far i do this which is redundant and not clean
// remove class
this.renderer.removeClass(this.elRef.nativeElement.querySelector(".color"), 'b1');
this.renderer.removeClass(this.elRef.nativeElement.querySelector(".color"), 'b2');
this.renderer.removeClass(this.elRef.nativeElement.querySelector(".color"), 'b3');
// add class
this.renderer.addClass(this.elRef.nativeElement.querySelector(".color"), 'b4');
I tried something like this but with no success :
this.renderer.removeClass(this.elRef.nativeElement.querySelector(".color"), 'color*'); | You can remove all the `classes` of an element matching the `regex` as follows :
let el = this.elRef.nativeElement.querySelector(".color");
let regex = /^b\d$/;
let classes = el.getAttribute('class').split(' '); // get all classes
classes.forEach((cl) => {
if(cl.match(regex)) { // match classes b1, b2, b3....
this.renderer.removeClass(el, cl);
}
});
this.renderer.addClass(el, 'b4');
See this working code | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "angular, angular5, renderer"
} |
str_replace from a particular position in a string
I want to replace a string within a string, but only a specific part of it, e.g. from character position 7 onwards
e.g. 'test.string.1' and I want to replace the second '.' with e.g. '2'
I have this obviously:
$string = str_replace('.', '2', $string);
But that will replace both periods, I just want replace the second period, and some strings may have multiple periods, I just want to replace the period after an arbitrary character position. The first period after e.g. 5 characters | You must use substr and str_replace.
$string = 'test.string.1';
$string = substr($string, 0, 7).str_replace('.', '2', substr($string, 7));
echo $string;
Result: test.string21 | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "php, string"
} |
C reading input in while loop
In c what does this do after gets
int c;
while ((c = getchar()) != EOF && c != '\n');
I saw that many of you are telling me its while loop and all, why so much complication to it? Why cant we just use this code which I have given below?
gets(name);
if(name == '\n'|| name == EOF)
gets(name);` | Well, this piece of code
int c;
while ((c = getchar()) != EOF && c != '\n');
is used to clear the buffer, as mentioned in @napnac's answer. It is mainly used instead of `fflush (stdin);`, which is UB. But note that this is successful only if the input buffer happens to contain data ending in a newline.
Otherwise, you can use `fflush (stdin);`, which is not recommended. You can also use the `flushinp` function provided by the curses library. It throws away any typeahead that has been typed by the user and has not yet been read by the program | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -5,
"tags": "c, while loop, int, eof, getchar"
} |
How to use a variable twice in C?
I am quite new to C and i am trying to use a variable twice in one line:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int myAge = 10;
char PL = "C";
printf("I am Rydex (not my real name) and i am %d years old. This was made using %s", myAge, PL);
}
But, when i run it, I get:
> I am Rydex (not my real name) and i am 10 years old. This was made using (null)
Instead of the value in the variable "PL" i get "(null)". Can someone please help me? | PL is a string, not a char. You need to change the declaration to:
char* PL = "C";
The double-quoted delimiter is for a string constant, which has a span of characters terminated with a null character \0. A single quote delimiter is to define a single character constant. Here's a good write-up | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "c"
} |
SKSpriteKit blending destination alpha
Here is the source code in SKScene constructor:
self.backgroundColor = [SKColor greenColor];
SKSpriteNode* sprite1 = [[SKSpriteNode alloc] initWithColor: [SKColor colorWithRed: 0.5 green:0.5 blue:0.5 alpha:1.0] size: CGSizeMake(500.0, 500.0)];
sprite1.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
[self addChild: sprite1];
SKSpriteNode* sprite2 = [[SKSpriteNode alloc] initWithColor: [SKColor colorWithRed: 1.0 green:1.0 blue:1.0 alpha: 1.0] size: CGSizeMake(100.0, 100.0)];
sprite2.blendMode = SKBlendModeSubtract;
[sprite1 addChild: sprite2];
I expected to get a green color on area covered by sprite2, as I set the blend mode SKBlendModeSubtract which should cause destination alpha to be 0.0 after blending. I need help to get it or a reason why it doesn't work as expected? Thanks in advance | The Subtract blend mode subtracts color values, not alpha values. The intersection you see should be black because the color of the intersection is (1,0,0)-(1,0,0)=(0,0,0).
What you are looking for is layer mask. SKCropNode does this, but maybe not in the way you want. You may want to look at one of these questions to get some ideas: Animate masked image in SpriteKit (SKCropNode), Is it possible to use a circle (SKShapeNode) as a mask in Sprite Kit? | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ios, sprite kit"
} |
Accessing variable in class by value of string
I am making a text based adventure and want to have a `function` in my **player class** that increases a variable in the class by accepting a `string`(for the variable name ) and `int` (for the amount)
class player
{
private int stat1 = 1;
private int stat2 = 2;
public void statincrease(string name, int amount)
{
//variable called by string// += amount
}
private void main()
{
player.statincrease(stat2,5);
}
}
sorry if i have not explained my self very well, but any help on this would much appreciated | I can tell you're new at this so I'll be easy on you.
There are several ways to go about something like what you're asking.
My first suggestion is to make a method for each name you need, so instead of string name you have shieldStatIncrease(int amount); swordStatIncrease(int amount); etc.
If you don't want to do that then you can use if or switch statements
public void statincrease(string name, int amount)
{
switch(name)
{
case "stat1":
//Increase stat1
break;
case "stat2":
//Increase stat2
break; //etc...
}
}
If this isn't what you're talking about then I apologize... Let me know and I'll adjust my answer.
Now if you're trying to get real technical you can use reflection to find the property name and adjust the variable for you... But I don't recommend that; especially not for a game because reflection has a little more overhead. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c#"
} |
Using gem Curb (curl) to download file
I have understood that I could use the RubyGem Curb to fulfill my needs of curl'ing down a file to my computer. But I cannot figure out how to actually "touch" the file. This is what I have got so far
include 'rubygems'
include 'curb'
curl = Curl::Easy.new('
curl.perform
I think I understand that `perform` actually downloads the file. But how can I interact with the file afterwards? Where is it downloaded to?
Regards, Mattias | The file can be accessed with the body_str method.
puts curl.body_str | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "ruby, curb"
} |
Monaco Editor, best way to add code when new line added?
For a client I need to provide a Web Ide to edit yaml file. So, Monaco Editor seems to be the perfect choice.
One requested feature is:
> add list item ( - ) for a new line if the previous one is a list item
I used `onDidChangeModelContent()` to detect change and I figure out how to add this "-" after a new line added but my problem is cursor stay before "-".
I try `setPosition()` or use `executeEdits()` but after `onDidChangeModelContent()` execution, some code override cursor position ...
So, may be, it's not the good way to do it ? any ideas ? | I would use `editor.onDidType`, which I believe is not in the docs (that means it might be gone by the time v1.0 comes out).
editor.onDidType(text => {
const bulletText = '- ';
const insertBullet = (pos) => {
const range = new monaco.Range(pos.lineNumber, pos.column, pos.lineNumber, pos.column);
editor.executeEdits('new-bullets', [{identifier: 'new-bullet', range, text: bulletText}])
}
if (text === '\n') {
const model = editor.getModel();
const position = editor.getPosition();
const prevLine = model.getLineContent(position.lineNumber - 1);
prevLine.trim().indexOf(bulletText) === 0 && insertBullet(position);
}
})
I haven't actually tested this, but it should point you in the right direction. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "monaco editor"
} |
Why are we called 'Jews'?
The term established itself in one way or the other in many different languages as early as the dark age. The question: why is that?
I thought it to be somewhat of a misnomer. After all, Yaakov had 12 children that formed the 12 tribes of Israel. Why is it that we are (pretty much) globally known after the fourth son?
Disclaimer: I've read an explanation on chabad.org which dwelled on the linguistic aspect of it, what the root meant in Hebrew and the like. But it didn't really answer this question. | The earliest reference to the term _Jew_ (יהודי in Hebrew is found in Esther 2:5 where it has Mordechai
> האִ֣ישׁ יְהוּדִ֔י הָיָ֖ה בְּשׁוּשַׁ֣ן הַבִּירָ֑ה וּשְׁמ֣וֹ מָרְדֳּכַ֗י בֶּ֣ן יָאִ֧יר בֶּן־שִׁמְעִ֛י בֶּן־קִ֖ישׁ אִ֥ישׁ יְמִינִֽי:
>
> 5 There was a Judean man in Shushan the capital, whose name was Mordecai the son of Jair the son of Shimei the son of Kish, a Benjamite,
Rashi explains:
> **a Judean man:** because he was exiled with the exile of Judah; all those who were exiled with the kings of Judah were called יְהוּדִים [Judeans, Jews] among the nations, even if they were from another tribe.
Thus we see that all members of our religion, from that time on were called by the term that is currently translated as _Jews_ because of the exile from the Kingdom of Judah. | stackexchange-judaism | {
"answer_score": 9,
"question_score": 4,
"tags": "names, am yisrael jewish nation"
} |
curly braces when define array
Regards to the following code:
int[] to = new int[] { text };
I understand it tries to define an array of integer, but What does the **curly braces** do in array definition? | The curly braces contain values to populate the array. | stackexchange-stackoverflow | {
"answer_score": 14,
"question_score": 26,
"tags": "java, arrays, curly braces"
} |
How can I use a narrowing conversion?
bool digit{ (pdigit >= bdigitplace) ? 1 : 0 };
Both `pdigit` and `bdigitplace` are of type `int` and need to be. `digit` does not have to be boolean, but for the sake of aesthetics, I would like it to be.
The line returns error C2397 in Visual Studios: "conversion from 'int' to 'bool' requires a narrowing conversion"
How can I make this line work while still using a conditional operator and keeping `digit` type `bool`? | Use true and false instead of 1 and 0 | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": -1,
"tags": "c++"
} |
How to sort options in dropdown using AngularJS?
I have dropdown with array of objects for options:
<select class="auc-form-control" ng-options="dataValue.Id as dataValue.Name for (dataKey, dataValue) in Types" ng-model="name">
</select>
Options are sorted by Id like this:
<option value="0">0</option>
<option value="1">1</option>
<option value="10">10</option>
<option value="11">11</option>
...
**How can I sort options in a natural way?** [1, 2, 3, ...] | It seems like your `Id` properties are strings (not numbers).
In that case, you have to use a custom getter to get a value for sorting. For example:
$scope.getSortValue = function (item) {
return +item.Id; // convert string to number
};
Then use it with the `orderBy` filter like this:
<select class="auc-form-control" ng-options="dataValue.Id as dataValue.Name for (dataKey, dataValue) in Types | orderBy:getSortValue" ng-model="name"></select>
**Example Plunker:** < | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "angularjs"
} |
Can't edit "Gmail SMTP Server" on iOS 10.3.1
I'm having problems recently with sending email from my gmail account on my iPhone using the mail app (keep being told username or password is incorrect, when they definitely are not). In trying to troubleshoot, I wanted to edit my SMTP server settings, but there is only one "Primary Server" shown and when I tap it to edit (it has no username or password so I wanted to manually add them in), everything is greyed out, and nothing can be edited. Not only that, but I can't even turn it off because when I flip the switch to deactivate it, there is no way to "save" the change, and as soon as I back out of that page in any way, the change is lost and the server remains activated.
How can I edit this SMTP server's settings? | Well I'm really not sure why this changed anything, but I logged out of my Google account from my desktop browser, then logged back in. Immediately after so doing, I sent a new email on my phone from my GMail account, and it worked perfectly fine, without a hitch. Go figure! | stackexchange-apple | {
"answer_score": 0,
"question_score": 0,
"tags": "iphone, ios, gmail"
} |
Would android-ndk be any help for NFC programming?
I am working on an Android 4.0 application using NFC on my Samsung Nexus S and I would need to modify some advance settings: the time of the NFC field pulse especially.
I developed my first applications and they work fine with most of the NFC tags but I need to use some special tags which need much more time to make calculations and the NFC field pulse is too short: my tag will consistently be stopped (power cut down by the phone every ~0.1 or 0.05 sec).
I am very new in Android development but I have heard about the Native Development Kit (NDK) which provides "more advanced" tools to deal with low-level operations. I also heard it was often mystified by Android programmers as the magic solution for any problem.
Do you think NDK provides more flexibility regarding NFC programming? Could it help me with my task?
I thank you in advance, Regards | Your tag problem may be due to the fact that the NFC stack checks for an NFC Forum NDEF message (Type 4 Tag in this case, I am guessing) and the tag takes too long to answer (it is likely sending Waiting Time Extension requests). The connection to the tag is then simply broken off and the NFC stack continues polling for new tags. You cannot influence this behaviour without changing and recompiling parts of the Android OS, so use of the NDK will, in all likelihood, not help in solving your problem. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "android, android ndk, nfc"
} |
Question about passive voice and modal verbs
In South Park s19e02, there is the following dialog:
1) - The X has been fu**ed to death.
- Yes! Yes!
- What? Are you sure?
- What is it, Thomas?
2) - The X got fu**ed to death, darling.
The first sentence seems to be Present Perfect, Passive voice.
But what tense is used in the second sentence?
Is it Present Simple, or Passive voice with _got_ used as a Modal verb? | _Got_ in example 2 is the simple past tense of _get_.
_Got_ is never a modal.
_X get(s) Y'ed_ means "X undergoes an event where the end result is that we can say X is Y'ed."
> I got blessed with 20 dollars = I underwent an event where the end result is that I am blessed with 20 dollars
There is _have got_ , and the _got_ here in this expression emphasizes _have_ in any of its meanings but not where _have_ is being used in a perfect tense. _Had got_ doesn't work.
> I have 10 dollars.
>
> I have got 10 dollars.
>
> I have to talk to John.
>
> I have got to talk to John.
>
> I have talked to Jerry.
>
> I have got talked to Jerry (doesn't work). | stackexchange-ell | {
"answer_score": 2,
"question_score": 1,
"tags": "passive voice, past perfect, past simple"
} |
Why is NA | FALSE = NA?
I first wondered why `FALSE | NA` returns
`#> [1] NA`, while
`TRUE | NA` returns
`#> [1] TRUE`.
Then I read the explanation that "because the value of the missing element matters in `NA | FALSE`, these are missing".
So I tried `TRUE | FALSE` and `FALSE | TRUE`. And indeed, both return `#>[1] TRUE`.
It makes sense that because the result of `NA | FALSE` depends on the value of NA, it returns NA, while the value of NA does not really matter for `NA | TRUE` to be TRUE.
However, can someone explain why `TRUE | FALSE` returns TRUE?
Thank you! | Essentially, it asks whether at least one side is `TRUE`. As there is one `TRUE` value, the result is also `TRUE`.
It is the same as with:
1 > 0 | 0 > 2
[1] TRUE
Conversely, when it asks whether all sides are `TRUE`:
TRUE & FALSE
[1] FALSE
As with the numerical example:
1 > 0 & 0 > 2
[1] FALSE | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 4,
"tags": "r, boolean, logical operators"
} |
How to get the IP address of a known hostname in Linux?
I have a device in a public network (I'm not the owner/admin of the WiFi) and I want to know if there is a way to get the devices IP address by knowing its hostname from a second device in the same network? | The multicast DNS protocol is designed to do exactly that. You simply append `.local` after the hostname of the device and you have a name that you can use with all the usual commands. For example:
ssh hostname.local | stackexchange-serverfault | {
"answer_score": 1,
"question_score": -1,
"tags": "networking, ip, linux networking, hostname"
} |
In the interest of being mekarev somebody is it permitted to minimize the spiritual & focus on the practical?
Are you allowed to convince an agnostic Jew to start keeping parts of the Torah for purely practical purposes like: prayer & faith have a calming effect, learning Torah sharpens the mind, Shabbos is a weekly gift of peace & serenity, kosher food is healthier than non kosher, the many benefits that come from being part of a close knit community, etc?
Is there a problem with glossing over the spiritual & moral aspects in favor of highlighting the practical benefits that come with being a religious Jew? | Sure, we follow what the Gemmorah taught us (Psochim 50b):
> דְּאָמַר רַב יְהוּדָה אָמַר רַב, לְעוֹלָם יַעֲסוֹק אָדָם בְּתוֹרָה וּבְמִצְוֹת אַף עַל פִּי שֶׁלּא לִשְׁמָהּ שֶׁמִּתּוֹךְ שֶׁלּא לִשְׁמָהּ בָּא לִשְׁמָהּ
>
> A person should always engage in Torah study and performance of mitzvot, **even if he does so for his own sake** , as through the performance of mitzvot not for their own sake, one gains understanding and comes to perform them for their own sake.
The translation is based on the following Gemmorah (Nozir 23b):
> אָמַר רַב יְהוּדָה אָמַר רַב, לְעוֹלָם יַעֲסוֹק אָדָם בְּתוֹרָה וּבְמִצְווֹת אֲפִלּוּ שֶׁלּא לִשְׁמָן, שֶׁמִּתּוֹךְ שֶׁלּא לִשְׁמָן בָּא לִשְׁמָן.
So pasken rambam in Talmud Torah 3:5. | stackexchange-judaism | {
"answer_score": 2,
"question_score": 2,
"tags": "hashkafah philosophy, kiruv outreach"
} |
The relation between $T^{\alpha\beta}$ and its trace
I have a simple question. Is it true? $$T^{\alpha\beta}T_{\alpha\beta}=T^2$$ Where $T$ is the trace of $T^{\alpha\beta}.$ I think they are different. | Since $T_{\alpha\beta}T^{\beta\gamma} = T^2{_\alpha^{~~\gamma}}$, $T_{\alpha\beta}T^{\alpha\beta}$ is the trace of the squared tensor $T^2_{\alpha\beta}$, rather than the square of the trace of $T_{\alpha\beta}$. | stackexchange-physics | {
"answer_score": 1,
"question_score": 0,
"tags": "homework and exercises, tensor calculus, trace"
} |
Transfer to Capture Orbit Delta-V
Computing a delta-V budget from one heliocentric orbit to another can be done as a Hohmann transfer.
How does one calculate delta-V for transferring from a heliocentric orbit to be captured by another planet? Is it as simple as computing the Hohmann delta-V and subtracting the velocity of the orbit around the destination planet?
This question is inspired by comments in Is space mining and development as shown in the television show “The Expanse” realistic?.
Bonus: Is the reverse process symmetrical? (I.e. same delta-V) | Your capture delta-v is calculated by
$\sqrt{v_e^2+v_{inf}^2}-v$
Where $v_e$ is the escape velocity at your target periapsis, and $v_{inf}$ is the velocity at infinity. For any given target orbit, replace the $-v$ after the square root with the velocity of your orbit.
A minimal capture is when your periapsis is as low as possible, and the apoapsis just within the sphere of influence. If you do not know the SOI, using $v_e$ for $v$ gives a good aproximation.
This is a symmetrical process. You can also be captured by passing through the atmosphere of the planet, if it exist. In that case, it is not a reversible process. | stackexchange-space | {
"answer_score": 2,
"question_score": 1,
"tags": "orbital mechanics, hohmann transfer"
} |
Usage of the phrase "Eat your tea"
This is another bit of unusual English (to an American) that I picked up from Terry Pratchett's writings. Characters in the books have told others to "Eat their tea", in the literal sense.
Is this a common British usage of the term? Does "tea" in this context refer to both the drink and the food that one would eat at teatime? Would "Take your tea" be more a common phrase? | "Eat your tea" refers only to a meal served at about 5–6 p.m. If one were talking about the beverage, it would be "drink your tea". | stackexchange-english | {
"answer_score": 3,
"question_score": 3,
"tags": "phrases, british english"
} |
Monitoring CPU usage using MS tools
Can CPU usage be monitored in Event Viewer? I don't want to use a third-party software. Can I set a rule so that Event Viewer can show me if the CPU usage gets higher than a set value? | In _Event Viewer_? No, that only shows events. You can however use the _Performance_ MMC snap-in. Run `perfmon.msc` then you can view the CPU usage as well as a bevy of other performance counters.
You can also configure it to log an event to the Application system log by adding and configuring an alert.
**Figure 1:** Adding a performance alert in XP (a little less direct, but similar in 7)
!enter image description here | stackexchange-superuser | {
"answer_score": 8,
"question_score": 2,
"tags": "windows, performance, cpu, monitoring, event viewer"
} |
Why can't I use my server name (SQL Server)?
I'm about to study how to join tables from multiple, different databases. So the way I refer to a particular table is by following this format **db_server_name.db_name.schema_name.table_name**. So after searching around how to get the server name using this command :
SELECT @@SERVERNAME
I got the following server name:
LAPTOP-FV8FREL6\SQLEXPRESS
Also this confirms:
 {
'use strict';
$(".click1 button").on("click", function click1() {
$(this).parent(".click1").css("background-color", "#f00");
});
$(".click2 button").on("click", function click2() {
$(this).parent(".click2").css("background-color", "#ff0");
});
$(".click3 button").on("click", function click3() {
$(this).parent(".click3").css("background-color", "#f0f");
});
$("clickAll").on("click", function () {
click1();
click2();
click3();
});
}); | You can use `trigger` function.
/*global $*/
$(function () {
'use strict';
$(".click1 button").on("click", function click1() {
$(this).parent(".click1").css("background-color", "#f00");
});
$(".click2 button").on("click", function click2() {
$(this).parent(".click2").css("background-color", "#ff0");
});
$(".click3 button").on("click", function click3() {
$(this).parent(".click3").css("background-color", "#f0f");
});
$("clickAll").on("click", function () {
$(".click1 button").trigger("click");
$(".click2 button").trigger("click");
$(".click3 button").trigger("click");
});
}); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "javascript, jquery, jquery ui, jquery plugins"
} |
Extracting a part of String in SQL Server
I have a field that returns a string value in this format `xxxxxxx(xxxxx)`. Now I need to extract the content of the string inside () as well the ones before (). How can I achieve this? | declare @str varchar(100)
set @str='xxxxx(aaa)'
---- extracts xxxxx
select SUBSTRING(@str,0,CHARINDEX('(',@str))
---- extracts aaa
select SUBSTRING(@str,CHARINDEX('(',@str)+1,CHARINDEX(')',@str)-CHARINDEX('(',@str)-1) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "sql, sql server, sql server 2008, tsql"
} |
New AMD Catalyst driver update screwed things up. Where can I find and older version?
Today I decided that I was going to update my AMD Catalyst divers, this end up being a bad idea. The installation failed and I seem to not be able to run the latest vision of Catalyst Software Suite 14.9. I have a Radeon HD 6700 and my OS is widows 7 home premium 64bit.
I have tried uninstalling Catalyst and everything that goes with it, then update Windows, then reinstalling.
I have tried going to programs the clicking on Catalyst and repairing.
Now I want to downgrade back to and older Catalyst Software Suite. Where can I find and older version? | Download Display Driver Uninstaller and clean your system from the old drivers.
Then download any older version from AMD. | stackexchange-superuser | {
"answer_score": 1,
"question_score": 2,
"tags": "windows 7, drivers, graphics card, amd radeon"
} |
why use q15 over standard int16 for embedded
I'm looking at the ARM CMSIS DSP Library and wondering if there is an advantage speed wise to operating in the q15 1to-1 range vs staying in the standard int16 range 32kto-32k. | 1 * 1 = 1.
32k * 32k > 32k.
The result of Q15 multiplication is guaranteed to fit inside of a Q15. This makes it very convenient in DSP where arrays of numbers must be quickly multiplied and summed. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "c, embedded, signal processing"
} |
How to multiply tensors of different shapes? (broadcasting)
I want to multiple the elements in a tensor of shape [a,b,c], each in the 3rd dimension with a scalar from a tensor of shape [a,b].
For example,
x =
|[1,2][3,4][5,6]|
|[1,2][3,4][5,6]|
|[1,2][3,4][5,6]|
y =
|0 0 1|
|1 0 0|
|0 1 0|
I want to multiply x and y to obtain:
res =
|[0,0][0,0][5,6]|
|[1,2][0,0][0,0]|
|[0,0][3,4][0,0]|
Could you tell me any method to achieve this?
P.S: maybe I can make a `y'` from `y` which is
y' =
|[0,0][0,0][1,1]|
|[1,1][0,0][0,0]|
|[0,0][1,1][0,0]|
then I can use `tf.mul()` to obtain the result. But I don't find anything to duplicate elements in a tensor in this way. | You are right, you can just use `tf.mul()`. In fact, the multiply operation in TensorFlow handles broadcasting, so you don't need to create another vector of shape `[a, b, c]`.
To make sure that the broadcasting is on the expected dimension, you can add a third dimension to your second vector `y`:
x = tf.random_normal([3, 3, 2])
y = tf.constant([[0., 0., 1.], [1., 0., 0.], [0., 1., 0.]])
y = tf.expand_dims(y, 2) # y will now have a matching shape of [3, 3, 1]
res = tf.mul(x, y)
sess = tf.Session()
sess.run(res) | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 5,
"tags": "tensorflow"
} |
combine background image with gradient doesn't work in my case?
demo <
I used this for gradient `background: -webkit-linear-gradient(top, rgba(0, 0, 0, 0)0%, rgba(0, 0, 0, 0.65)100%);` and it work, but after I tried to merge it with a background image it doesn't work, anything wrong with this :
background-image: url( -webkit-linear-gradient(top,rgba(0,0,0,0)0%,rgba(0,0,0,0.65)100%);
? | I think you had the image/gradient in the wrong order.
div {
width: 100px;
height: 100px;
background-image:
-webkit-linear-gradient(top, rgba(0, 0, 0, 0)0%, rgba(0, 0, 0, 0.65) 100%),
url('
}
<div>hi</div>
Basically, the stacking order is first declared is on top and the next is underneath that...and so on. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "html, css"
} |
Word for a process that looks for solutions?
I am looking for a word that describe an approach or process that deals with problems and finding solutions. Somehow opposite of a 'purly creative' endeavor.
Example:
> As creative as art is, it is not a .......... process like science that looks for solutions to actual problems. | Word choices:
\- pragmatic
\- practical
\- utilitarian
(see thesaurus for more...)
Unfortunately, "practical process" is an alliteration.
Here's one proposal:
> Although art is creative, it is not a pragmatic methodology like science that looks for solutions to real-world problems. | stackexchange-ell | {
"answer_score": 1,
"question_score": 0,
"tags": "word request"
} |
How can I move a user account to another domain in the forest, whilst preserving permissions?
I've got user John Doe in the Server 2003 parent domain 'foo', which has a child domain 'bar'. Both domains are at a functional level of Server 2000.
I'd like to move the user to the 'bar' domain, while preserving their access to network resources. I can easily put them into the appropriate groups within the new domain, but some of our file share permissions are per-user. The user also has an Exchange 2003 account.
Is is possible to move the user and retain all their permissions and mailbox? If so, what tools are available to me that could help me accomplish that?
Note: I'm aware that Server 2003 is well beyond end-of-life and unsafe to use. Not my call, unfortunately. | You need the Active Directory Migration Tools. when you use these tools to migrate User accounts the original Security Identifier (SID) is kept. So when a user tries to access resources the new SID or the original SID can be used. This feature is called SID history and is an optional option of the Active Directory Migration tools. There is a link below that will take you to a ADMT guide:
<
Good Luck | stackexchange-serverfault | {
"answer_score": 1,
"question_score": 2,
"tags": "active directory, windows server 2003, domain, user management"
} |
SpriteKit - How do I check if a certain set of coordinates are inside an SKShapeNode?
In my game, I'm trying to determine what points to dole out depending on where an arrow hits a target. I've got the physics and collisions worked out and I've decided to draw several nested circular SKShapeNodes to represent the different rings of the target.
I'm just having issues working out the logic involved in checking if the contact point coordinates are in one of the circle nodes...
Is it even possible? | The easiest solution specific to Sprite Kit is to use the SKPhysicsWorld method `bodyAtPoint:`, assuming all of the SKShapeNode also have an appropriate SKPhysicsBody.
For example:
SKPhysicsBody* body = [self.scene.physicsWorld bodyAtPoint:CGPointMake(100, 200)];
if (body != nil)
{
// your cat content here ...
}
If there could be overlapping bodies at the same point you can enumerate them with `enumerateBodiesAtPoint:usingBlock:` | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "coordinates, sprite kit, skshapenode"
} |
ValidationContext is declared but its value is never read?
I have the following:
const validators:Array<ValidationContext> =
ValidationContainer.getValidationContexts(key);
const value:any = o[propertyName];
So far so good. No errors. Now I want to iterate over the `validators` array like this:
validators.forEach(vc:ValidationContext => {
vc.validate(value);
});
VSCode provides the following error:
[ts] 'ValidationContext' is declared but its value is never read.
[ts] Parameter 'ValidationContext' implicitly has an 'any' type.
(parameter) ValidationContext: any
Any idea what this means? | You must surround your typed parameters of an arrow function with parenthesis
validators.forEach((vc:ValidationContext) => {
vc.validate(value);
}); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "typescript"
} |
News and news archive in different tables
I have encountered a situation where the news and the news archive are in different tables.
Given that those tables contain many records and both share exactly the same structure is it still smart to split them up instead of having a flag that marks them as archived? | Your news table will be faster without the archive. You have to ask yourself if both are often hit in the same query. If they aren't then it may make sense to keep them separate.
Also have to ask yourself what archive actually means? 1 year old, 2 years old. I'm guessing it's just a flag to either show on the News Page or News Archive page. If you do merge into one table perhaps you could just use logic > 1 year old is archive.
You could also create a View that unions both tables together. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "database design"
} |
How to set up wireshark with correct permissions
Ubuntu 13.10, Saucy Salamander here. I am trying to install `wireshark` in order to monitor USB activity with a certain device. The problem is that wireshark does not have access to the USB bus (or any bus, for that matter, no interfaces show up).
Here they describe, that wireshark can be run either as root, or as an ordinary user. I tired executing `dpkg-reconfigure wireshark-common` but after the dialog, nothig happens, and I don't know why.
Here an alternative procedure for other Linux users (non-Debian) is outlined. I haven't tried it, as the `dpkg` method is the recommended one for Ubuntu and I would like to know what is going wrong.
Where should I look? | I have also run into this in the past (cant speak for SS specifically) This helped me out.
<
Basically, this is what needs to be done.
$ sudo apt-get install wireshark
$ sudo dpkg-reconfigure wireshark-common
$ sudo usermod -a -G wireshark $USER
$ sudo reboot
If there are problems, the linked answer provides more information and techniques. | stackexchange-unix | {
"answer_score": 2,
"question_score": 1,
"tags": "permissions, usb, wireshark"
} |
Host wcf service
I can access my WCF service typing
> <
in browser.
However I can't access my service if I put my IP address instead "localhost".
What should I do to make my service hosted on my PC and accessible from other computers?
I created an application in IIS Services and wrote a path to my WCFservice, but it had no effect. It's first time for me when I need to make service "global", so I don't know how to do it
Thanks! | You are currently hosting under the development web service (Cassini) which doesn't accept off machine connections. You will need to host in IIS by creating an application and pointing it to the physical directory where the .svc file lives
There is a "How To" for IIS hosting here | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "wcf, web services, iis, hosting"
} |
Can a variable be produced from an if else statement?
Can I change a variables value based on an if/else statement in javascript?
var $nextLink = $this.next().attr('href'),
$currentLink = $this.attr('href');
if ($currentLink == $nextLink){ // Check if next link is same as current link
var $nextLoad = $this.eq(2).attr('href'); // If so, get the next link after the next
}
else {var $nextLoad = $nextLink;} | The code shown in the question will work. Note, though, that JavaScript doesn't have block scope, only function scope. That is, variables declared inside an `if` or `else` statement's `{}` block (or a `for` statement's `{}`, etc.) will be visible in the surrounding function. In your case I think that's actually what you intend, but still most JS coders would probably find it neater to declare the variable before the if/else and then just set its value with the if/else.
Neater still is to do it in one line using the `?:` conditional (or ternary) operator:
var $nextLoad = $currentLink == $nextLink ? $this.eq(2).attr('href') : $nextLink; | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 0,
"tags": "javascript, jquery"
} |
Does polychromatic light fallows different laws of physics then monochromatic light?
My understanding is that Yang's double-slit experiment only works with monochromatic light.
* Does it mean that polychromatic light behaves differently then monochromatic light? Or are we simply limited in our measurement tools to detect the same effect with polychromatic light?
* Assuming there are different levels of polychromatic and monochromatic light, how does the interference pattern will be effected going from single to many weave lengths. | The spatial period of the fringes on the screen depends on the wavelength of the light, and the distance between the slits. That means, a distinct pattern for each distinct wavelength.
The different wavelengths _do not_ interact with each other. They simply add up. If you use a "white" light source, as Thomas Young did when he originally performed the experiment, you get a pattern that looks like this.
!white light interference pattern
The spacing of the "red" pattern is a bit wider than the spacing of the "blue" pattern because the wavelengths of "red" light are longer than "blue" light. That's why the outer edges of the fringes are reddish and the inner edges are blueish. The farther you get from the center fringe, the more the different patterns diverge.
Of course, there's more than just a single "red" wavelength and a single "blue" wavelength making up that picture. There is a continuum of different wavelengths, which gives the pattern an over-all fuzzy appearance. | stackexchange-physics | {
"answer_score": 1,
"question_score": 0,
"tags": "double slit experiment"
} |
Change LinkedList to accept Objects instead of Int?
I have a fully working LinkedList that functions with int variables. I'm looking to change it work with objects, but I'm feeling stuck when it comes to pointers. Any advice?
This is the Node struct:
typedef struct Node
{
int data;
Node* next;
}* nodePointer;
And this is the AddNode function:
void LinkedList::addNode(int dataToAdd)
{
nodePointer nodeToAdd = new Node;
nodeToAdd->next = NULL;
nodeToAdd->data = dataToAdd;
if(head != NULL)
{
current = head;
while(current->next != NULL)
{
current = current->next;
}
current->next = nodeToAdd;
}//end if
else
{
head = nodeToAdd;
}//end else
}//end addNode
Is it a matter of a few simple changes? | It depends on the type of objects you will be using.
For any class where the default `=` operation makes sense, you could use the same code you have right now, replacing `int` with your object's type.
For a more complicated object (for instance, one holding a pointer to a dynamically allocated member), you would have to either define an appropriate `=` operator for this class or use a copy function to ensure that the object is properly copied | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c++, c, oop, pointers"
} |
Replace 2 spaces with 1
I want to replace all the values within a column that are:
Boston, MA (2 space)
with:
Boston, MA (1 space)
I have gotten as far as:
select [Location], replace(replace(replace([Location],' ','<>'),'><',''),'<>',' ') from [Table]
How can I replace the values in the [location] column with the result of the query above?
note: there are other values in the [location] column, eg.
Hong Kong
London, UK | select [Location], replace([Location],' ', ' ') from [Table]
to update the column
UPDATE [Table]
SET [Location] = replace([Location],' ', ' ') | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "sql server, sql server 2008"
} |
C++ unit testing with VS test professional
Does any one know if I can test native code in VS Test 2010? | As of VS2010, native C++ unit testing is not directly supported by Visual Studio. See MSDN, specifically:
> You cannot have test projects with unit tests that use unmanaged C++.
You can still do native C++ unit testing with Visual Studio, but it won't be as integrated as other VS features. See this SO answer for a number of native unit testing frameworks and libraries. I have not used any of those, so I cannot give any guidance there. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "c++, visual studio, unit testing, testing"
} |
How to do primary maths with cocoa and cocoa touch
I'm quite new to xcode and am making a app where you put two numbers in to a text input and I don't know how to make xcode to do the adding sum, I tried this but it did not work
self.answer.text = self.label.text + self.label2.text
Does anybody know how to do this. | Use :
NSInteger firstNumber=[self.label.text integerValue];
NSInteger secondNumber=[self.label2.text integerValue];
NSInteger total=firstNumber + secondNumber;
NSString *string=[NSString stringWithFormat:@"%d",total];
self.answer.text = string;
If you want to take double value replace `integerValue` with `doubleValue` | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "ios, objective c, cocoa"
} |
How to make a condition based on relation ship count in Laravel Eloquent?
I would like to add a condition based on the `tasks` relationship count,
Here is the code:
return TeamleaderDeal
::withCount('tasks')
->get();
The result is:
[
{
"id": 4,
(...)
"dealPhase": "Refused",
"tasksCount": 5,
(...)
},
{
"id": 5,
(...)
"tasksCount": 0,
"companyLanguage": "nl",
(...)
},
{
"id": 16,
(...)
"dealPhase": "New",
"tasksCount": 17,
(...)
},
{
(...)
How to only return results where `tasksCount` equal to 5? | You may use `has` method like this:
// Retrieve all team-leader deals that have 5 tasks...
return TeamleaderDeal
::has('tasks', '=', 5)
->get();
Check Laravel docs for more info. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "laravel, eloquent"
} |
Is the function $f(x)=\lfloor\sin(\ln(x+2)\rfloor$ differentiable at $x=0$?
Is the function $f(x)=\lfloor\sin(\ln(x+2)\rfloor$ Differentiable at $x=0$ where $ \lfloor .\rfloor$ represents floor function.
I proved that it is continuous at $x=0$.
Since $$\lim_{x \to a} \lfloor(g(x)\rfloor=\lfloor\lim_{x \to a} g(x) \rfloor$$ when $\lim_{x \to a} g(x)$ is not an integer.
Now since $\sin(\ln 2)$ is not an integer we have
$$\lim_{x \to 0} \lfloor\sin(\ln(x+2)\rfloor=f(0)$$
Hence $f$ is continuous.
Now checking the right hand derivative we have
$$f'(0)=\lim_{h \to 0}\frac{\lfloor\sin(\ln(h+2)\rfloor}{h}$$
Now this limit is in indeterminate form. Can I know how to evaluate this limit? | Letting $g(x) =\sin(\ln(x+2))$. Because $0<\ln(2)<\pi/2$, we know $0<g(0)=\sin(\ln(2))<1$.
Furthermore, $g(x)$ is continuous for $x>-2$, in particular it's continuous at $x=0$.
Hence, there is some neighbourhood around $x=0$ where $0<g(x)<1$.
Hence, there is some neighbourhood around $x=0$ where $f(x)=\lfloor g(x) \rfloor =0$ (constant). Hence $f(x)$ is differentiable at $x=0$ - and the derivative is zero. | stackexchange-math | {
"answer_score": 3,
"question_score": 1,
"tags": "algebra precalculus, functions, derivatives"
} |
Django foreign key constraint with Model that lives in different database
I'm trying to use the `oauth2_provider` library which provides a model for AccessToken, which foreign keys into a User model. My User model will actually live in a different database from the OAuth2 token models. I can use a router to direct which DB to use for a particular model, but am I correct in concluding that Django would not support a foreign key to a model in a different DB?
If I still wanted to extend from the `AbstractAccessToken` with my User in a different DB, is there any way that Django allows me to populate the `user_id` foreign key column at all? Or would I simply need to leave it `null` and define and have my custom AccessToken class define its own unconstrained `external_user_id` column? | Django doesn't support any `ForeignKey` operations that span multiple databases. So, as you suggested, I think the best you can do is to provide your own `IntegerField` for the user and use it manually. Unfortunately that may require a lot of fiddling with that third-party library if it has a lot of internal code that's expecting to pull the user from the database. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "django, django models, django orm, django oauth"
} |
Sending E-mails in a schedule that changes with time
I have got two scheduled apex class running.
It sends two E-mails and two Texts twice a day.
1) I wish to send only one E-mail and text after 3 days.
2) After 7 days E-mail and text twice a week.
3) After 14 days once a week.
Q) What would be the best way to implement this.
I was thinking having a custom field and checking that. Is it possible to set something like this in CRON. | You could use Process Builder with `Email Alerts` and `InvocableMethods` to schedule these kind of items one after the other.
Using custom fields with your current Apex Jobs is also a good way to go (keep track of last datetime sent, next datetime to send, etc) | stackexchange-salesforce | {
"answer_score": 0,
"question_score": 0,
"tags": "apex"
} |
subscribing to route change and on init
I have a question on angular 7. I have a view that load some data on init. But this view must reload data on route change. In the url I have an Id that is used to reload the same view, that's why the onInit trigger only once.
Basically what I've done is to call the backend on OnInit then subscribe to route change and duplicate the call to the backend.
What is the best practice in this case? I don't think that duplicate the code is the solution...
I cannot post my code because I have a lot of backend calls and the code would be very long.
Thanks! | yeah, you are right! To avoid duplicate code you can subscribe to parameters of route and make API call again:
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {
this.route.paramMap.subscribe( params => {
this.id = params.get('id');
this.makeYourAPICalls(this.id);
});
}
As `route` is type of `Observable` then you will always be notified whenever your route is changed. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "angular"
} |
Java - Throwable to Exception
I am currently using the play2 framework.
I have several classes which are throwing `exceptions` but play2s global `onError` handler uses throwable instead of an exception.
for example one of my classes is throwing a `NoSessionException`. Can I check a throwable object if it is a `NoSessionException` ? | You can use `instanceof` to check it is of `NoSessionException` or not.
Example:
if (exp instanceof NoSessionException) {
...
}
Assuming `exp` is the `Throwable` reference. | stackexchange-stackoverflow | {
"answer_score": 53,
"question_score": 45,
"tags": "java, exception, throwable"
} |
C - print star pattern in different arrangement
My homework needs to print out the star pattern by using for loop as below:
!!!!!
!!!!
!!!
!!
!
Here is my loop:
int i, j;
for(i=5;i<=1;i--)
{
for(j=1;j<=i;j++)
{
printf("!");
}
printf("\n");
}
Actually I have succeeded to print out the pattern as below already:
!
!!
!!!
!!!!
!!!!!
By the following loop:
int i, j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("!");
}
printf("\n");
}
Now I am confused why pattern 1 can't be printed, as there are no errors found. Also the output window will get down when I go ahead to run the program.
My Xcode is Ver 4.4.1 | This loop cannot execute anything :
for(i=5;i<=1;i--)
It says "start with `i = 5`, and while `i <= 1`; do `i--`".
At the first iteration, i is already > 1, so your loop doesn't even enter.
What you should do is reverse the condition:
for (i = 5; i>= 1; i--)
This way, you'll loop by starting with `i = 5`, and perform `i--` while `i >= 1`.
General rule of thinking for a `for` loop :
for (A; B; C)
{
D;
}
is equivalent to
A;
while (B)
{
C;
D;
} | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 1,
"tags": "c"
} |
How can we edit a Program Stage Instance that is not marked as completed but DHIS2 doesn't allow to edit it?
While being superuser of my DHIS2 Instance, sometimes my users (or even myself) try to edit a Program Stage Instance that is **not** marked as completed but the editing of the elements seems disabled (even after checking that the status is not completed). Clearing browser cache and/or refreshing the page does not help. Sometimes, it becomes available to be edited by itself the next day. | The problem was that we were trying to edit that program instance while not selecting the proper org unit on the left panel. As soon as the proper org unit on the left panel is selected and the program instance selected and incompleted we were able to edit it. Thank you for your help. P.S: the solution came through the email thread but thought to mention it here. | stackexchange-webmasters | {
"answer_score": 0,
"question_score": 1,
"tags": "dhis2"
} |
could not open session as Root
I came across this error that is apparently pretty common among Linux Systems.
"Too many files Open"
In my code I tried to set the Python open file limit to unlimited and it threw an error saying that I could not exceed the system limit.
import resource
try:
resource.setrlimit(resource.RLIMIT_NOFILE, (500,-1))
except Exception as err:
print err
pass
So...I Googled around a bit and followed this tutorial.
However, I set everything to 9999999 which I thought would be as close to unlimited as I could get. Now I cannot open a session as root on that machine. I can't login as root at all and am pretty much stuck. What can I do to get this machine working again? I need to be able to login as root! I am running Centos 6 and it's as up to date as possible. | Did you try turning it off and on?
If this doesn't help you can supply `init=/bin/bash` as kernel boot parameter to enter a root shell. Or boot from a live cd and revert your changes. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "centos, root, configuration files, centos6, sudoers"
} |
Why can the c# compiler not resolve the argument types of a lambda expression in a ternary operator?
I have this code:
Action<A, B> fnUpdate = (someBool) ? (a, b) => a.propOne = b : (a, b) => a.propTwo = d;
Why can the compiler not resolve the types of `a` and `b`, just because it is assigned in a ternary operator? it seems quite straight forward at face value. | The C# compiler tries to create the lambdas independently and cannot unambiguously determine the type. Hence cast it to work as expected....
Action<A, B> fnUpdate = (someBool)
? (Action<A, B> (a, b) => a.propOne = b
: (Action<A, B> (a, b) => a.propTwo = d); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "c#, lambda, type inference, ternary operator"
} |
Adding Vnet to Azure SQLDB
I heard about the new update on Azure SQLDB that it can be connected to vnet but can't find any blogs on this new information.
Can someone throw some light on this information? | Now, it is supported. Please refer to this blog.
> Azure SQL Database will allow you to set firewall rules for specific public IPs, and will give you the option of allowing all Azure Services’ IPs to connect to your Servers. If you're looking for finer grained connectivity limitations, you would have to provision a Static Public IP, which can be hard to manage and costly when done at scale. Virtual Network service endpoints will allow you to limit connectivity to your Azure SQL Database Servers from given subnets within a Virtual Network.
You could do it on Azure Portal. Please refer to this link. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "azure"
} |
Borel Sets on $\mathbb{R}^n$
Define the Borel sigma-algebra on $\mathbb{R}^n$ as the smallest sigma-algebra containing all $n$-rectangles $(a_1, b_1) \times \cdots \times (a_n, b_n)$.
Is it true that the Borel sigma algebra contains all sets of the form $A_1 \times \cdots \times A_n$, where each $A_i$ is some Borel set in $\mathbb{R}$?
I thought this would be trivially true, but I had a lot of trouble trying to prove it, and I'm not even sure its true anymore.
If this is a well-known result, could you please refer me to a text where it has been (dis)proved ? | A way to prove it: 1/ any set of the form $A_1 \times \mathbb R \ldots \times \mathbb R$, where $A_1$ is Borel, or more generally a "Borel rectangle" with only one slice not equal to the whole space, is in the Borel sigma-algebra (this is essentially a 1-dimensional Borel set, and those are generated by open intervals). 2/ any product $A_1 \times \ldots \times A_n$ (with each $A_i$ Borel) is a finite intersection of sets of the above form.
Not sure I should have answered this, it may be a homework problem... I'd have just written a comment but I'm not reputable enough to do so :)
Any standard reference on measure theory will provide a proof of the result you're asking about (say, Dudley's book). | stackexchange-mathoverflow_net_7z | {
"answer_score": 8,
"question_score": 1,
"tags": "reference request, ca.classical analysis and odes"
} |
What are these extra 11 dimensions of human mind?
I posted this question on the physics stack exchange, but I was guided to ask the question here though from the view point of a neuro-scientist which should be more useful if she has already followed the general current of changes in Theoretical physics:
Recently I faced a research result showing the brain works in 11 dimensions. I was wondering if these dimensions have anything possible to do with those of M-theory?
They use algebraic topology techniques to come up with their result.
In string theory there are 3+1+6+1 dimensions, space+time+compactified dimensions+extended dimension on the strings(strings change into branes)
Cliques of Neurons Bound into Cavities Provide a Missing Link between Structure and Function | No, there's no relationship to string theory.
You might imagine brain activity as taking place in an N-dimensional space, where N is the number of neurons in the brain. However, neurons aren't independent of each other, so there aren't really N unique dimensions. Using various dimensionality reduction techniques, for example principle component analysis, you can choose to discard some dimensions that have less variance and if you set some threshold you can say "well really there are X dimensions of brain activity". Of course that number is dependent on the threshold you choose.
The actual meaning of those dimensions varies by the approach taken, but here I think the closest would be that the 11 dimensions represent different functional networks in the brain doing different things. Functional meaning they do similar things at the same time.
Other people get different numbers so 11 is just their particular result, there's nothing special or consistent about 11. | stackexchange-cogsci | {
"answer_score": 1,
"question_score": 3,
"tags": "consciousness, psychophysics"
} |
How to check the current platform of Android OS?
There are 4 common platform such as: ARM, ARM64, x86 and x86_64 on which Android can run.
**How can I check which platform I'm on within Android OS?** So I can check whether my app is compatible with it or not.
I'm using different emulators (BlueStacks on Mac, Genymotion on Demand, etc.), so I'd like to check basically which platform they're exactly emulating, because some apps works for me on BlueStacks, but not on Genymotion. | If you have adb set up, it's a one-liner at the shell prompt:
$ adb shell "getprop ro.product.cpu.abi"
arm64-v8a
In this example, the device asked answered that it has a 64bit ARM V8a CPU (second line).
Note: You can also run the quoted command in a terminal emulator running on the device / emulator. In there, it's just `getprop ro.product.cpu.abi`. | stackexchange-android | {
"answer_score": 10,
"question_score": 7,
"tags": "android x86, compatibility, emulators"
} |
How can I not display a page if a user is not logged in with PHP?
I want to hide everything on a page when a user is not logged in with PHP.
Currently, I redirect the user if they are not logged in, but in case people are trying to get around the redirect, I want to make sure none of the content is displayed.
I understand that you could always use...
// Pseudo-code
if(!logged in){
header("Location: login.php");
}else{
echo "<html>...the whole page";
}
But this is too hard to maintain because I have to escape all quotes and code editors don't display is too well.
What can I use to just stop displaying any code if the user is not logged in. | In PHP you could use this in the beginning of the file you'd like to hide from visitors who are not logged in:
if(!isset($_SESSION['user'])) // The exact conditional depends on your login-system implementation
{
header('Location: login.php'); // Instructs the visitor's browser to redirect
exit; // <-- What you want. Prevents further code from being executed, works as a security measure.
}
Or in your pseudo-code:
if(!logged in)
exit; | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "php, html, authentication"
} |
EC2 Curl to server running on itself
I have a cron job defined on an Amazon Linux EC2 instance. The cron job runs a curl command to a server running on the same EC2 instance. It is supposed to execute every 15 minutes.
*/15 * * * * curl
< doesn't seem to be getting called ever. | Turned out the cron job itself was executing every 15 minutes as expected. The problem was that curl was failing. It was because of the url. When I changed the cron job to following it worked fine.
*/15 * * * * curl
Note that unless you have specifically turned it off, every time the cron job runs it will send an email which in my case was stored in this file /var/spool/mail/ec2-user. You can check the file to see if the cron job is executing and what was the output of the command.
Also note that 54.221.195.78 in my case was an elastic ip asigned to the instance. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "curl, amazon ec2, cron"
} |
Processing time / effort to decrypt stored passwords
I have an Adobe account which, as you might have heard have recently had a breach may have had there encrypted passwords stolen.
The password for that account was not used else where, which is good, but it got me thinking, how easy is it for some one to decrypt the passwords once they have them ?
Obviously it hard to say unless you know the encryption level / method, but could someone give some real world examples, ie. if it was encrypted this way you would have to do x number of processing hours to decrypt it. | Unfortunately that "x numbers of hours" also highly depends on the hardware and encryption/hashing technology used.
Check this page from hashcat - < as they have some "benchmark" based on some hardware that they have tested, and their results to give you some idea.
The better their hardware - more combination per seconds can be tested.
Edit: Also some information from grc.com --> < which gives you some idea how hard it is to break a long password, high-entropy password. And also some information about what make password hard to crack (in short: length - for full story, go to the site and have a bit of read). | stackexchange-superuser | {
"answer_score": 2,
"question_score": 0,
"tags": "security, passwords, encryption"
} |
Dynamic URL aliasing?
Let's say we have a section `/latest-projects` with a menu block listing nodes sorted descending by their post date. Thus, the first item will often change and be the freshest one. Is it possible to make the `/latest-projects` alias always link to (= open) the top-most node? | Indeed it is.
Steps you will need to do:
1. Create a custom module
2. Implement hook_menu()
3. Define the route 'latest-projects', and make the menu callback a function
4. In the custom menu callback function do SQL or whatever to find the latest project (maybe use EnityFieldQuery in Drupal 7)
5. Use drupal_goto() to then redirect the user to the latest project node
Note in the above solution, a redirect is used to send the user to the project node, but if needed you can also simply render the node on the page as another idea. | stackexchange-drupal | {
"answer_score": 2,
"question_score": 2,
"tags": "path aliases, uri"
} |
Use an iOS specific element in a Xamarin Forms app
I'd like to use an iOS specific element (SceneKitView) in my Xamarin Forms app but I'm not sure how to go about it.
I read this article, but I'm not sure if I'll be able to create a visual element (aka a view) this way.
What classes should I implement and what configurations do I have to do to achieve this? Also, I'm using a different D.I. framework than the one provided by Xamarin, is that gonna be a problem (I'm using Ninject)?
Basically, my question is how do you create custom cross-platform views in Xamarin Forms (a github example would be great!).
_I know there is a cross-platform equivalent to SceneKit but right now I don't have the time to redo the code for the 3D scene._ | Ok found it.
The concept is called Custom Renderers.
Here a link to the doc: < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "ios, xamarin.forms, cross platform"
} |
Angular2 SVG filter url
I'm using Angular2 + D3 to create a chart.
I'd like to apply an svg filter to the bars in order to create a drop-shadow effect.
While the filter is created and the bars have a `filter: url("#dropshadow")` style applied, the shadow does not render.
Could this be due to Angulars single page and the `url()` not finding the filter? What would be the correct way to work around this issue? | I finally figured it out. The best solution seems to be to inject the Location via
import { Location } from '@angular/common';
...
constructor(private location: Location)
and then use it to specify the path for the `url()`
.style('filter', 'url(' + this.location.path() + '#drop-shadow)')
Now it works as expected. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "d3.js, svg, angular"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.