INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to get the first value of class attribute of a tag?
Let's say the body tag has a few class attributes:
<body class="html logged-in frontpage no-sidebar">
...
</body>
Currently, I use jQuery to get all class attributes of body tag using:
$('body').attr('class');
I want to get the very beginning/first class attribute (which is 'html' class here). How?
|
$('body').attr('class').split(" ")[0];
You could also use plain old javascript (see Vega's answer)
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "javascript, jquery"
}
|
Creating an Array with PHP
I have a form with multiple text inputs that all have the same name. How would I process that with my PHP when the user submits the form?
HTML:
<input type="text" name="interest"/>
|
I've assumed you're using `POST`.
You would use
<input type="text" name="interest[]">
Then on the post page, you could use:
foreach($_POST['interest'] as $i){
echo $i. "<br>";
}
or whichever method you wanted to use to get the `POST` data.
You could also do something like:
<input type="text" name="interest[music]"/>
<input type="text" name="interest[food]"/>
You can then call this data by using:
<?php echo $_POST['interest']['music']; ?>
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "php, html"
}
|
Get variables from a Regex Expression
I'm trying to validate the following:
/w username message
Here is my regex expression:
if (input.toLowerCase().matches("^/w(\\s+)([0-9a-zA-Z].*)(\\s+)([0-9a-zA-Z ].*)$")) {
...
How do I get the username and the message as variables?
String username = ???
String message = ???
|
Pattern pattern = Pattern.compile("^\\/w\\s+(?<username>\\w+)\\s+(?<message>.+)$");
Matcher matcher = pattern.matcher("/w username message");
if(matcher.matches()) {
String username = matcher.group("username");
String message = matcher.group("message");
}
www.regex101.com
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "java"
}
|
Accidentally deleted the content of apache2/logs/wsgi.x.x.sock now getting Unable to connect to WSGI daemon process in log
I accidentally deleted the content of apache2/logs on my webserver. The folder containeed two files a pid file and a sock file now I am getting the error
Unable to connect to WSGI daemon process 'xxxx' on '/home/admin/webapps/myapp/apache2/logs/wsgi.18851.161.1.sock' as user with uid=1122.
Any suggestions on how I can resolve this. I think I need to change the sock filename to the new file which was created when I restarted the apache server. The new file is `wsgi.4397.1.1.sock`now.
|
Just restart Apache. It will recreate it and it should be good. The name of the socket file will change with each restart as it includes the process ID of the Apache root process.
Although, if you deleted the whole logs directory, you will need to make sure you create the directory again with correct owner and permissions as was before. Don't do that and the user that Apache runs as may not be able to see inside of the directory to connect to the socket.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "apache, apache2"
}
|
Does every $A$ is $B$ and every $B$ is $A$ imply that there is some element that is either $A$ or $B$?
Apologies if I'm being vague with the title, I will try to hammer down a concrete example.
I am given the following fact (*): Every wealthy person is happy, and every happy person is wealthy. Does this imply that there is some person who is wealthy or happy?
My initial thought was yes, but then I thought about the event where there was no one happy or wealthy. Would * still hold? If * is still true, but the conclusion is false, then * would not imply the conclusion.
In general, I guess what this boils down to is if the "for all" quantifier holds for empty sets. If $S$ is an empty set, would $\forall s\in S, P(S)$ be true, no matter what statement $P(S)$ was?
|
Your last sentence is correct. If a set $S$ is empty then $\forall s\in S, P(s)$ holds.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "logic"
}
|
Member variable prefix ("m") in getters and setters in Android studio 1.1
How do I configure Android Studio "v 1.1" to correctly generate getters and setters for member variables with prefixes and not to generate getters like: `getmName()` and instead generate `getName()`?
I've looked at many questions like : Intellij (Android studio) member variable prefix, but it seems to be removed in "Version 1.1"
Am i right?
|
in `preferences -> code style -> java` you'll find the tab _code generation_. There you will find a matrix of text box, where you can define prefix and suffix for field, static field, parameter and local variable. Enter `m` for the pair ( _Name Prefix, Field_ ) and it should work
!enter image description here
|
stackexchange-stackoverflow
|
{
"answer_score": 18,
"question_score": 11,
"tags": "android, android studio"
}
|
ListView Alternate colors
I need to make a ListView with alternate color.
code:
public View getView(int position, View convertView, ViewGroup parent) {
if(position %2==0)
{
view.setBackgroundColor(Color.BLUE);
}
return view;
}
but I don't know how to use it in my Adapter:
SimpleAdapter adapter = new SimpleAdapter(this, propositions, android.R.layout.simple_list_item_2,
new String[] {"Date", "Trajet"},
new int[] { android.R.id.text1,
android.R.id.text2});
lvTrajets.setAdapter(adapter);
Can someone help me about how to do this please ?
|
Override `getView` for the adapter
SimpleAdapter adapter = new SimpleAdapter(this, propositions, android.R.layout.simple_list_item_2,
new String[] {"Date", "Trajet"},
new int[] { android.R.id.text1,
android.R.id.text2})
{
@Override
public View getView (int position, View convertView, ViewGroup parent)
{
View v = super.getView(position, convertView, parent);
if(position %2==0)
{
v.setBackgroundColor(Color.BLUE);
}
else
{
v.setBackgroundColor(Color.WHITE);
}
return v;
}
};
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "android, listview, colors, alternate"
}
|
How to make the script command append to a file?
The script command typecasts the terminal activity to a particular file. I understood that part, but is there a way it can be made to append to an existing file?
The end goal for me is to make the `script` append the data to an existing file with a timestamp that is achieved by the `date` command. And ultimately have a launcher that pre-executes this upon its launch and I have a logfile of every output on my terminal. I think I have the puzzle solved except for making the script command append.
|
As the man pages says, the `-a` option is for append
script -a file
If file is missing, the default `typescript` filename is used.
|
stackexchange-askubuntu
|
{
"answer_score": 8,
"question_score": 9,
"tags": "command line"
}
|
Alternative use of the word "otherwise"
Otherwise, apart from its usual meaning, can also indicate **"in other respects"** (found it in the dictionary).
When constructing a sentence using aforementioned meaning of "otherwise" are these structures acceptable and natural?
> An otherwise great movie ruined by his acting.
>
> His acting ruined an otherwise great movie.
Are there any distinct rules to follow when creating sentences in similar fashion?
|
Yes. It's just an adverb modifying the adjective _great_. Nothing special to see here; you have used it correctly in both cases. You are saying that the movie would have been great, but _his_ acting ruined it.
|
stackexchange-ell
|
{
"answer_score": 1,
"question_score": 1,
"tags": "sentence construction"
}
|
Find total area under infinite curves
My question is finding the total area covered by curves, such as the total area every curve in the following picture covers (from 100 on y axis to 200 on x axis):
t + y_0 $
This has probably been answered before, but I cannot find it. If there were 2 curves, the answer would be easy: just sum two areas and subtract the overlap.
|
In example 5 of < it is shown that the envelope of a family of parabolas with constant initial velocity and different initial angles is also a parabola.
The equation is derived nicely.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "integration, area, curves"
}
|
FOR LOOP in windows cmd and batch file not working
I am trying to call a batch file that runs a `for` loop and calls a second script:
for /f "usebackq" %%i in (`dir/b /o:d %partionHome%\tmp\queue\*.t~#`) do %partitionHome%\conf\SQLLoader\SQL_Loader_%DSNname%\Script.bat %1 %2 %3 %4 %5 %6 %7 %%i %has_prefix% %partionHome%
`Script.bat` never runs; I've tried adding do `call` but i believe this gets ignored with `FOR /F`, I just cannot get the loop to call the script. All parameters are available and paths etc. are correct?
|
The DIR command is probably not returning anything, so there is nothing for FOR /F to iterate.
Looks to me like you have a spelling mistake: `%partionHome%` vs. `%partitionHome%`.
Also, make sure your variables `partitionHome` and `DSNname` are defined properly.
The CALL is definitely needed (once you fix the other problems)
Lastly, you should enclose your paths in quotes, just in case there are spaces and/or poison characters within the value.
for /f "usebackq" %%i in (`dir/b /o:d "%partitionHome%\tmp\queue\*.t~#"`) do call "%partitionHome%\conf\SQLLoader\SQL_Loader_%DSNname%\Script.bat" %1 %2 %3 %4 %5 %6 %7 "%%I" %has_prefix% "%partitionHome%"
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "batch file, for loop"
}
|
Range Base loops for objects
Hi I want to use range base loops for objects , but it doesnt seem to work . here is my code:
#include <iostream>
#include <vector>
using namespace std;
class animal
{
public:
animal ();
void speak() {cout << "hi" ;}
};
int main()
{
animal a;
animal b;
animal c;
for ( animal * ptr : { &a , &b , &c } )
{
ptr->speak();
}
}
|
You need to provide a definition for your constructor:
animal () { }
Or remove it, since it doesn't do anything. The compiler will provide one for you.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "c++, c++11"
}
|
html radio button array
I have an HTML form with radio buttons in a loop with same name like this:
Post Id 1:<input type="radio" name="radiob[]" id="radio" value="Yes" />
Post Id 2:<input type="radio" name="radiob[]" id="radio" value="Yes" />
I want to save radio button selected post into database but I want the user to select only one post. When I put post id with radio button name like radiob[2], the user can select multiple radio buttons so how can the user only check one radio button and the form send both the radio button id and value?
Thanks.
|
Use the ID as value, and you don't need to use `radiob[]` because only one value will be transmitted to the server anyway.
Post Id 1:<input type="radio" name="radiob" value="1" />
Post Id 2:<input type="radio" name="radiob" value="2" />
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, html, arrays"
}
|
How to receive data on other server with wp_remote_post
So basically, I'm posting data with wp_remote_post, and I want to receive sent data (username and password) on other server. How would I do that? I tried `<?php echo $_POST['username']; ?>` (nothing else before or nothing else after), but it didn't work. Can't find it either in Wordpress Codex.
|
Wordpress protects you from so it's harded to exploit your code.
Use this code to make it work:
in functions.php add:
add_filter('query_vars', 'add_my_var');
function add_my_var($public_query_vars) {
$public_query_vars[] = 'username';
return $public_query_vars;
}
and then you can use in your code to read the variable:
get_query_var('username');
This thread helped: <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "php, html, wordpress"
}
|
jQuery accordion hiding tabs in CSS
I have a jQuery UI accordion with Markup structure
<div id="accordion2">
<h3>title</h3>
<div>stuff texty</div>
<h3>title2</h3>
<div>stuff texty</div>
</div>
However, the second tab of the accordion is in a plainer format than the first (i.e. it has less pictures and is hence more mobile friendly).
I am want to use a media query to hide the first tab and its contents when screen width is less than 640px. I tried giving the first h3 and the first div tags a class of first and then used
@media (max-width: 640px) {
.first {
display: none;
}
}
To make them disappear... but it didn't work. Does anyone know how I can go about doing this?
|
try this as a CSS3 option:
#accordion2 h3:first-of-type
{
display:none;
}
if you cannot support CSS3 then give that first heading a class name and target that.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "jquery ui, tabs, media queries, accordion"
}
|
How translate python command to curl command
I need to use the curl command instead of python code to call the api but it is not work .The python code is working with any problems but we want the command to be run as curl command
> ` import requests params = {'username': 'testuser'} params['access_token'] = 'c3NhbmthMDJjsd' params['region'] = 'test' params['role'] = 'guide' params['ipaddr'] = '192.168.0.37' params['name'] = 'test-testhost-001' params['check'] = 'enable' url = ' r = requests.post(url, data=params) r.json() `
I dont know how to run the above using the curl command
|
## Heading ##Here's your python params put into raw post format ... Good luck!
curl \
-X POST \
-d "username=testuser&access_token=c3NhbmthMDJjsd&role=guide&name=test-testhost-001&check=check®ion=test&ipaddr=192.168.0.37" \
<
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "python, curl"
}
|
Get list of database names using psql
I'm trying to get a list of database names using the `psql` command. So far I have:
psql -h example.com -U backup -c '\l'
This however gives me the results in a table-like format. I ONLY want the table names (one on each line). How would I accomplish this?
|
This does it:
psql -h example.com -U backup -t -A -c "SELECT datname FROM pg_database WHERE datname <> ALL ('{template0,template1,postgres}')"
Using the system catalog `pg_database`.
Read the manual about psql.
|
stackexchange-stackoverflow
|
{
"answer_score": 20,
"question_score": 6,
"tags": "bash, postgresql, psql"
}
|
How to append elements in a list within a list?
I'd like to append elements to a sub-list within a main-list. The number of elements to be appended corresponds to the sub-list position in the main-list.
My code:
# define the maximum level of the game
max_level = 3
# create list with length = level
lsx = []
# append empty lists in lsy for every element in lsx
empty = []
lsy = []
def create_list(max_level):
for i in range(max_level):
integer = random.randint(1,5)
lsx.append(integer)
for j in lsx:
lsy.append(empty)
return(lsy)
create_list(max_level)
Output:
[[], [], []]
Desired output:
[[1], [1, 2], [1, 2, 3]]
|
You don't need (and shouldn't) use globals. When appending `empty` to `lsy` multiple times you are appending the same object - changing one will change other as well.
You can create the nested lists inside the loop:
import random
def create_list(max_level):
# top level list
res = []
for i in range(max_level):
# nested list
next_l = []
for j in range(i+1):
next_l.append(random.randint(1, 5))
res.append(next_l)
return res
print(create_list(3))
Output:
[[5], [4, 3], [2, 3, 2]]
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -3,
"tags": "python"
}
|
background image does not fill the full div size
Here is the css being applied to the div:
#header{
background-size: 100%;
background: url('../img/header.png');
width: 100%;
height: 200px;
border-bottom: 10px solid #b2d234;
}
as you can see in the picture !picture, the bottom border fits the whole width, but the background image does not fill neither the full width nor the height, even though there is no padding or margins applied.
Any guidance is much appreciated.
Update:
I have zoomed out and so the problem is easily seen. The problem is that the background image is being repeated and there are small spaces between each repetition. I have tried no-repeat option, but then i get the background only once and it does not fill the whole screen.
Please, take a look at the picture:
!enter image description here
|
Use:
background-size: cover;
Updated CSS.
#header{
background-size: cover;
background: url('../img/header.png');
width: 100%;
height: 200px;
border-bottom: 10px solid #b2d234;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "css"
}
|
How to depend on a sub-project of multimodule SBT project from Github
I can add a dependency on the `commons` root like this:
lazy val commons = RootProject(uri("ssh://[email protected]:foo/commons.git"))
lazy val thisProject = project.in(file(".")).dependsOn(commons)
But what if I want to depend on a specific `commons` sub-project (the `commons` repository contains a multi-module SBT project). E.g. (in pseudo-code):
lazy val commonDbStuff = RootProject(uri("ssh://[email protected]:foo/commons.git")).sub("commons-db") // pseudo-code
lazy val thisProject = project.in(file(".")).dependsOn(commonsDbStuff)
Is it possible?
|
lazy val commonDbStuff =
ProjectRef(uri("ssh://[email protected]/foo/commons.git"), "commons-db")
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "scala, sbt"
}
|
Find package name of Android app by uid without root permissions
I have a problem of an app that open a site every time open the browser. I found the id of the app with this intent by adb and now I'm wondering if there is a way to find the package name by the app id without root permissions.
|
> For UnRooted devices following works for me:
Set up `adb` in a PC, connect the device to the PC, launch a `shell` on the PC and enter:
adb shell "dumpsys package | grep -A1 'userId=UID'"
Replace `UID` with the `ID` you're looking for, such as `10102`.
Example:
bash-4.2# adb shell "dumpsys package | grep -A1 'userId=10102'"
userId=10102
pkg=Package{46171ce com.android.chrome}
bash-4.2#
The line containing Package`{would show the package name of the app in between whitespace and}`. You can do adb shell dumpsys package `PKG_NAME (PKG_NAME → package name of an app)` to know more details about that package/app.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "android, adb, app id, package name"
}
|
Attach multiple times to a single screen session
I've been using `screen -dRaA -S x` to open up a single session between different workstations as I move about. Handy.
Is it possible to connect multiple times to a single session, though, without disconnecting others? When I have two machines I'm quickly moving between even reconnecting starts to slow me down.
|
Try
screen -aAxR -S x
`-x` is the option that does what you want.
|
stackexchange-unix
|
{
"answer_score": 23,
"question_score": 33,
"tags": "gnu screen"
}
|
Django Admin - how to forbid to create already existing object
I have a Model:
class Category(models.Model):
CATS = (
('CT', 'Cool Things'),
('II', 'Internet & IT'),
('BT', 'Beautiful Things'),
)
cat = models.CharField(max_length=2, choices=CATS)
def __unicode__(self):
return self.get_cat_display()
I have created objects to all three categories. Now I want to forbid my co-workers to create another object which already exists. How is it possible? I googled but cannot seem to have found something...
|
Set `unique=True` for a `cat` field (docs):
> This is enforced at the database level and by model validation. If you try to save a model with a duplicate value in a unique field, a `django.db.IntegrityError` will be raised by the model’s `save()` method.
cat = models.CharField(max_length=2, choices=CATS, unique=True)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, django, django admin"
}
|
C# .NET WinForms. Visual studio won't recognise namespaces in subfolders
When I create a new folder, in this case `Model`, as a subfolder to the solution directory, and add a class in there, which is wrapped in a namespace, the namespace cannot be found.
Yes, I have tried both adding a `using` directive, and referring to the class directly, like `Model.Class`, from the main source file.
What is going on? In the class explorer, the `Model` folder is not visible, while it is visible in the solution explorer, it is visible. The other subfolders are visible in the class explorer.
|
What is the namespace in the class file?
If you have a class file in the `Model.Class` folder, but the namespace in the file is `Model`, you still have to use `using Model;`
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, .net, class, namespaces, projects and solutions"
}
|
Insert current postgres server timestamp in jdbc
I have an mobile application that make a insert in a Postgres database via JDBC. In the database table, i have a timestamp column and I need to insert the real timestamp of the server, to ensure that no one is inserting a fake date/time. It will be something like:
INSERT INTO some_table VALUES(...,now());
This code seems right, but if the mobile device have a different timezone, this difference reflect in the now() function. Example:
Date/time of server: 00:00:00 -04
Date/time of mobile: 00:12:34 +00
Result of insert above: 04:00:00
I already tried some other approaches, like:
INSERT INTO some_table VALUES(...,now()::timestamp)
INSERT INTO some_table VALUES(...,current_timestamp)
|
It'd make sense if you use the UTC timestamp to avoid having the timezone constantly in the middle. Let the client be concerned about the conversion to the current timezone.
Try it like this:
INSERT INTO some_table VALUES(..., now() at time zone 'utc')
Source: Using current time in UTC as default value in PostgreSQL
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "sql, postgresql, jdbc, timestamp"
}
|
How to remove duplicate records in grid?
Good morning !
What is the best way to remove duplicate records from grid control? I use Delphi 2009 and devEx quantumGrid component.
I tried looping through all the records and when a duplicate record is found then add it to list and apply filter on grid. I found this as time consuming logic. There are also two downsides of this approach.
[1] When the duplicate records are considerably more say 10K records then applying filter takes lot of time, because of lot of entries to filter out.
[2] Looping through all the records is itself time consuming for big result set like 1M rows.
SQL query returns me distinct rows, but when the user hides any column in grid, then it resembles as if there are duplicate records(internally they are distinct).
Is there any other way of doing this?
Any ideas on this are greatly helpful !
Thanks & Regards, Pavan.
|
With thousands of rows I would add an additional field to the DB called say Sum or Hash or if you can't change the DB add a calculated field if it is a ClientDataSet but this carries overhead at display time
Calculate the contents of the hash field with something fast and simple like a sum of all the chars in your text field. All dupes are now easily identified. Add this field to your Unique or Distinct Query parameters or filter out on that.
Just an Idea.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "delphi, delphi 2009"
}
|
Getting previous months in php
I need to display 3 month from the previous month in php
Here is what I have tried so far
<select style='width: 112px;' name='PayMonth'>
<option name="PayMonth" value=''>Select Month</option>
<?php
for($i = 1 ; $i <= 12; $i++)
{
$allmonth = date("F",mktime(0,0,0,$i,1,date("Y")))
?>
<option value="<?php echo $i; ?>" ><?php echo date("F",mktime(0,0,0,$i,1,date("Y")));?>
</option>
<?php
}?>
This will display all months
But how can I display on 3 months from current month
i.e.,
**If current month is april it should show Feb, Mar, Apr**
**If current month is jan it should show nov, dec, jan**
I tried..
<?php
$month = date("m");
?>
But in the loop I am confused with
for($i = 1 ; $i <= $month; $i++)
|
If you are getting `$month = date("m");` Then your forloop should be
for($i = $month-3 ; $i <= $month; $i++)
Sidenote :
As you are using
<option value="<?php echo $i; ?>" ><?php echo date("F",mktime(0,0,0,$i,1,date("Y")));?>
You may get -1, -2 inside the values. So you should change
<option value="<?php echo date("m",mktime(0,0,0,$i,1,date("Y"))); ?>" ><?php echo date("F",mktime(0,0,0,$i,1,date("Y")));?>
To get
<select style='width: 112px;' name='PayMonth'>
<option name="PayMonth" value=''>Select Month</option>
<option value="11" >November </option>
<option value="12" >December </option>
<option value="01" >January </option>
<option value="02" >February </option>
</select>
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, date, select"
}
|
Merge data from 2 tables
I have two tables, both of which have a KEY and a few columns, I'd like to merge them into a single table when the key is the same
e.g: Table 1: Key | Attr 1 | Attr 2 | Attr 3
Table 2: Key | Attr 1 | Attr 2 | Attr 4
I'm trying to end up with: Table 3: Key | Attr 1 | Attr 2 | Attr 3 | Attr 4
I tried using this:
SELECT
T1.KEY,
T1.ATTR1,
T1.ATTR2,
T1.ATTR3,
CASE
WHEN T1.KEY = T2.KEY
THEN T2.ATTR4
ELSE 0
END AS ATTR4
FROM TABLE_1 AS T1, TABLE_2 AS T2
but for some reason, I get a ton of duplicates
|
I am guessing that you really want a `LEFT JOIN`:
SELECT T1.*, COALESCE(T2.ATTR4, 0) as ATTR4
FROM TABLE_1 T1 LEFT JOIN
TABLE_2 AS T2
ON T1.KEY = T2.KEY
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "sql server"
}
|
If my site opens 3rd party sites via iframes, will the 3rd party sites successfully set their own cookies?
I am considering the design of an interface which will enable users of my site to open multiple 3rd party sites at the same time into iframes. That part is easy enough. However, I want to be sure that the 3rd party sites are able to set their OWN cookies into the user's browser. **I don't care about interacting with those cookies**. I don't want to have any knowledge of the cookie data, I just want to be sure that when the user browses the 3rd party site via the iframe on our site, that they can persist a session throughout that site.
|
No, you cannot rely on 3rd party cookies being enabled. Any cookies set by your framed websites will be treated as 3rd party cookies by modern browsers.
Chrome (and other browsers) allow the user to specifically block 3rd party cookies:
!Chrome Cookie Settings
In addition, Internet Explorer requires that a valid P3P policy has been set on the framed websites, otherwise it could reject the 3rd party cookies, regardless of browser settings.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript, security, iframe, cookies, browser"
}
|
Element id by javascript
I am using document.getElementsByTagName("input") to get all the input elements in my form.While iterating through them I need to find an element with a particular id say "data" and process it.How can search in the elements such that an element of a particular id exists.
|
If there's some reason you don't want to do:
var el = document.getElementById('data');
...you could iterate over the collection:
var inputs = document.getElementsByTagName("input"),
len = inputs.length,
el;
while( len-- ) {
if( inputs[ len ].id === 'data' ) { // Test the "id" property.
el = inputs[ len ]; // If a match, grab that one,
break; // and break the loop.
}
}
* * *
**EDIT:** Fixed error where I had `el = inputs[ len ].id;` instead of `el = inputs[ len ];`
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "javascript, forms"
}
|
How can i use a tags input or editext for android
Hello I'm new developing in Android, I want to insert in a edittext a Word and make it like a tag with the space or enter key I was looking for it a lot but could not find an answer.
I want to make something like this:
!example
|
If I were approaching this problem, I would first look into `TextWatcher` (or the `String.split()` method) and `SpannableString`.
"Tags" are normally separated manually by a space or a comma, so you could use `String[] words = sentence.split(",");` to split by commas, and then use a `for` loop to set a `BackgroundColorSpan` of light blue, a `ForegroundColorSpan` of deep blue, an `ImageSpan` for the cross and a `ClickableSpan` for links.
To update it more dynamically would require using `TextWatcher`.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "android, android edittext, tags, add"
}
|
HTML5 Video Tag Width/Height
I'm trying to create a video tag for use with Chrome only. I don't always know the dimensions of the video, but I would like to have it be the size of the window. I thought I could accomplish this by using "width=100%" and "height=100%", but I found that the built-in controls were hard to see. I reduced height to 98%. Most of the videos I am currently trying to play are 720p MP4's. I tried playing a 1080p (actual dimensions being 1920x1040), and it wouldn't work (the video player acted as if my source was wrong, but I could right click and successfully download the file). The file size was more than 3 gig, I'm not sure if that had anything to do with it.
Edit: I also checked that the codecs were the exact same, and they are between the smaller and larger videos.
Anybody else having the same or like issues?
|
I just wanted to post on here now that I've fixed this issue. The issue was the file size information is apparently at the end of normal MP4's. For streaming, we want this information at the front of the file so the player can decide how to buffer and what-not. Chrome must do some sort of quick file size check if it doesn't find the file size information at the beginning. I used a program called QT-Faststart which moves the file size information to the front of the file. Thus solving the issue.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "html, google chrome, html5 video"
}
|
Why don't we need to define global variables before they are actually used in functions in Python?
I was looking at the following code:
def f():
print(x)
if __name__ == '__main__':
x = [1,2,3]
f()
which to my amazement works. I would have expected that NOT to work because I would have expected needing `x` to be defined BEFORE the function definition of `f` (otherwise, how does `f` know what `x` refers to?). So I expected the following to be the only version that should have worked:
x = [1,2,3]
def f():
print(x)
if __name__ == '__main__':
#x = [1,2,3]
f()
though I am obviously wrong. Why? What part of how Python is supposed to work did I get wrong?
* * *
Note as coding practice I'd never use globals. They are dangerous and unclear. I'd personally always pass variables to functions (or something that is more clear and safe like that). This was just out of curiosity.
|
Why shouldn't it work? When you're creating the function it's just a code snippet that it isn't executed (kind of lazy evaluation) until it's called. That's the difference between Python and other compiled languages such as C++, which would raise `undefined variable x` error.
You'll just need the variable `x` to exist when you call the function `f`. It will first look at some variable x in the local scope and then in the global scope, so that's why it works anyway, even if x it's been defined after the function!
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "python"
}
|
Android Studio 2.2.2 LLDB 2.2 update issue
Today I updated my android studio to version V-2.2.2. When I am trying to debug my android application with native code(app-native) I am always getting error message
> C++ debugger package is missing or incompatible, do you want to fix it.
 2\. Now from android studio Tools->Android->SDK Manager->SDK Tools and update lldb option. Click on Apply. It will download LLDB 2.2 3\. Now try to debug C++ code and debugging is working fine as expected.
Issue was arising due to some conflict between older downloaded version LLDB 2.1 and newer LLDB version 2.2
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 6,
"tags": "android, c++, android studio, android ndk, lldb"
}
|
How to use a class type as a typed variable? (Typescript)
Lets say you have an interface then classes that implement it.
interface A { /*do stuff*/ }
class B implements A { /*do stuff*/ }
class C implements A { /*do stuff*/ }
Then if you have a variable that can store the class type, not a specific instance of an object, what do you put as the type?
let x: Something = B; // or C
I know for objects you can use typeof, but for interfaces you can't. However I am able to specify variables to store implementations of interfaces so I don't see why I shouldn't be able to store classes of an interface.
|
You can use a constructor signature (similar to a function signature, but with a `new` in front of it):
interface A { /*do stuff*/ }
class B implements A { /*do stuff*/ }
class C implements A { /*do stuff*/ }
let x: new () => A = B;
let x2: new () => A = C;
Playground Link
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "typescript"
}
|
Convergence in $L_{\infty}$
Let $(X,\Sigma,\mu)$ be a measure space and $E_n\in\Sigma$ such that $\mu(E_n)>0$, and we define $f:=a_n\chi_{E_n}$, where $a_n>0$ for each $n\in\mathbb{N}$.
I want to prove that if $f_n\to 0$ in $L_{\infty}$ then there isn't $C>0$ such that $a_n\ge C$ for each $n\in\mathbb{N}$.
So, if there is $C>0$ such that $a_n\ge C$ for each $n$, I want to prove that $f_n$ doesn't converge to $0$ in $L_{\infty}$.
To do this, I want to find an $\epsilon >0$ such that for every $n\in\mathbb{N}$ we have $\left\|{f_n}\right\|_{\infty}\ge \epsilon$.
Can you give me a hint to do this? Can we take $\epsilon = C$?
|
You have $\|f_n,L^\infty\|=a_n$. If $f_n\to 0$ in $L^\infty$, then you have by definition $\|f_n-0,L^\infty\|\to 0$, hence $a_n\to 0$ and you can conclude.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "real analysis"
}
|
OpenGl library dont work
i have a problem with the opengl library (glut). i install this 2:
sudo apt-get install freeglut3 freeglut3-dev
sudo apt-get install binutils-gold
and when i write :
g++ -lGL -lglut test1.cpp -o test
i have this error:
/usr/bin/ld: error: cannot open /usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux- gnu/libGL.so: No such file or directory
/tmp/cc0332Hc.o:test1.cpp:function draw(): error: undefined reference to 'glClearColor'
/tmp/cc0332Hc.o:test1.cpp:function draw(): error: undefined reference to 'glClear'
/tmp/cc0332Hc.o:test1.cpp:function draw(): error: undefined reference to 'glFlush'
collect2: ld returned 1 exit status 0
i use the last version of Elementary Os and gcc compiler
|
GLUT is _not_ "the" OpenGL library. Quite the contrary. It is just some utility library for openGL.
It seems like you don't have a OpenGL implementation installed, which are typically part of the graphics drivers or the OS itself. On Linux, there are the proprietary drivers from NVIDIA and AMD, and the Open Source ones which are developed in the Mesa3D project. Which one is the best for you depends on the GPU you are using.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c++, linux, opengl, ubuntu"
}
|
What does "not syncing" mean in kernel panic?
What is meant by "not syncing" in a kernel panic message?
I have read that it means that the kernel successfully synced data to disk, but am not sure.
A typical context would be: "Kernel panic - not syncing - Attempted to kill init!"
|
`not syncing` means that the device buffers have not been flushed to the actual devices. We do this to prevent damage to the data.
If we synced on kernel panic, we could cause a lot of trouble to the user. This is because the kernel panic could have happened anywhere and it might cause side-effects to other modules and parts of the kernel.
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 8,
"tags": "linux, kernel, panic"
}
|
Statistical modeling terminology
Based on Wikipedia's definition, I believe that _statistical model_ refers to a certain sort of family of distributions, such as univariate Gaussian distributions in general.
Is there special statistical terminology for the result of applying specific parameters to a given model? For example, if $\mu = 5.48$ and $\sigma = 0.3$, then that's a specific Gaussian distribution. I assume it's not _also_ called a statistical model, though it may represent an attempt to summarize or "model" (in the layperson's sense) some dataset. Intuitively it would seem to be an "instantiated model" though I'm not looking to invent my own terminology unless I have to.
|
When it's necessary to draw a distinction you can say "completely specified model", or "model without unknown parameters", "model with all parameters known" & the like; when the parameters have been estimated from data, "fitted model", to emphasize that. When it's not necessary you can just say "model". That seems to do the job & agree with common usage--though according to the "Formal Definition" section of the Wikipedia article you cite a model is a _collection_ of distributions, in these cases it would be a collection comprising one distribution.
|
stackexchange-stats
|
{
"answer_score": 2,
"question_score": 1,
"tags": "modeling, terminology"
}
|
Rest POST API With file_get_contents Not Working IN PHP
i am writing new php post api how to get output.
URL : <
currently i am using postman for development purpose.when i get request as json i am able to handle.
**JSON Example Request :**
{"firstName":"Ram","lastName" :"R"}
$request = file_get_contents('php://input');
$parameters = json_decode($request,true);
$firstName = $parameters['firstName'];
echo $firstName ; // output will be Ram
Now My Question is how can i get reponse from Request Like This
firstName=Ram&lastName=R
Now how can Get First Name ?
Thanks in advance.
|
You can Use following Method to get Values from Header.
$fname = $_GET['firstName'];
echo $fname;
your Url will be like:
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "php"
}
|
obter os 3 maiores números de uma lista em python
alguém pode me ajudar a encontrar o erro?
> """Returns a list of the three largest elements input_list in order from largest to smallest. If input_list has fewer than three elements, return input_list element sorted largest to smallest/"""
# TODO: implement this function
def top_three(input_list):
list1 = [2,3,5,6,8,4,2,1]
input_list = sorted(list1, reverse=True)
return input_list[:3]
print (top_three(1))
|
## Heapq
Uma alternativa seria o uso de heapq:
import heapq
lst = [2, 3, 5, 6, 8, 4, 2, 1]
# Os 3 maiores:
heapq.nlargest(3,lst)
[8, 6, 5]
# Os 3 menores
heapq.nsmallest(3,lst)
[1, 2, 2]
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "python, python 3.x"
}
|
Character limitation in regular expression won't work
I want to check the string if it obeys these rules:
* **First part:** 2 digits
* 1 space
* **Second part:** Capital letters. 1, 2 or 3 characters
* 1 space
* **Third part:** 2, 3 or 4 digits
My regular expression:
/\d{2}\s.[A-Z]{1,3}\s.\d{2,4}/
It works with most strings but it doesn't with some like these:
* 134 HY 723 (It shouldn't allow 3 digits in first part)
* 34 H 723 (It should allow one letter in second part)
* 34 HD 723435 (It shouldn't allow over 4 digits in third part)
|
Use this one:
/^\d{2}\s[A-Z]{1,3}\s\d{2,4}$/
You were missing the anchors (`^` and `$`). Your original one would match, say, `134 HY 723`, by matching `34 HY 723`.
I also removed two random `.`s. (I have no idea why they were there)
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 0,
"tags": "regex"
}
|
Clarification on the definition of irreducible polynomial.
Suppose for a UFD $R,$ we have $F \in R[X]$ factor into $F = GH$ for $G \in R$ a non-unit. By definition, does this mean $F$ is reducible?
Furthermore, why do we only care about irreducibles in UFDs? The definition of irreducible polynomials seems to only be stated in fields or UFDs but not in any other context. I know $R[X]$ is a UFD iff $R$ is a UFD. But what is so important about _uniqueness_ that we define them only in these rings?
|
By definition, $F\in R[X]$ is irreducible in $R[X]$ if and only if _whenever_ we write $F=GH$, for $G,H\in R[X]$, then either $G$ or $H$ is a unit. So $F$ is reducible if and only if there exists a factorization of $F$ as $F=GH$ with _both_ $G$ and $H$ non units. (As an aside: The units of $R[X]$ are precisely the units of $R$, i.e. $(R[X])^\times = R^\times$.)
So, assuming $F=GH$ and $G\in R$ is a nonunit, this _does not_ necessarily mean that $F$ is reducible. As a silly example, in $\Bbb Z[X]$, let $F=G=2$, and $H=1$. Then $2=2\cdot 1$, with $G=2$ a non unit. But $2$ is not reducible in $\Bbb Z[X]$.
As to your question about why we care about irreducibles in UFDs: Well, "UFD" = unique factorization domain. And this unique factorization of each element is, by definition, a factorization into _irreducibles_.
So, when you ask "why do we care about irreducibles in UFDs", you're essentially asking, "Why do we care about irreducibles in a ring which we care about irreducibles?"
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 1,
"tags": "abstract algebra, field theory"
}
|
Bootstrap 3 grid system with table component not working
My code works fine so I am just interested in using Bootstrap 3 grid system with my table component and I went through documentation I couldn't find anything. I do have all my `css` and `js` files. I've tried adding `row` or a `container`div tag and it still didn't work. Any thoughts on what I am doing wrong ?
I have this
<table align="right" cellpadding="0" cellspacing="0">
<tr>
<td class="col-md-4"><a href="file.html"><img src="someImage.png"/></a></td>
<td class="col-md-8"><a href="file2.html"><img src="someImage2.png"/></a></td>
</tr>
</table>
Thanks in Advance.
|
Try this:
<table align="right" cellpadding="0" cellspacing="0" class="table table-bordered" >
<tr>
<td class="col-md-4"><a href="file.html">
<img src="someImage.png" /></a></td>
<td class="col-md-8"><a href="file2.html">
<img src="someImage2.png" /></a></td>
</tr>
</table>
# DEMO
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "twitter bootstrap, responsive design, twitter bootstrap 3, grid system"
}
|
What is the difference between a knuckle and spindle?
Surprised I didn't see this asked before but when watching videos about suspension components and installs I've commonly seen people refer to, what I would imagine a spindle, but call it a knuckle. So what is the difference between a spindle and a knuckle or are they both the same?
|
The knuckle is the part the spindle attaches to. The spindle carries the hub and bearing(s). Generally the spindle is used on non-driven wheels, but there are some where the spindle is hollow and the CV shaft extends through e.g. Some Nissan's. The bearing(s) and hub assembly are still on the spindle, there will be a drive flange that bolts to the hub.
A spindle attached to a knuckle.

@RunWith(MockitoJUnitRunner.class)
public class loginUnit {
@Mock
TextUtils mMockTextUtils;
@Test
public void checkStringEmpty(){
String empty = "";
when(mMockTextUtils.isEmpty(empty)).thenReturn(true);
assertThat(LoginActivity.isStringEmpty(empty),is(equalTo(true)));
}
UUT(unit under test) from LoginActivity
public static boolean isStringEmpty(String s){
return TextUtils.isEmpty(s);
}
I always get android.text.TextUtils not mocked error, please help me?
|
In your src/test/java folder, add android.text package and create TextUtils.java
public class TextUtils {
public static boolean isEmpty(CharSequence str) {
return str == null || str.length() == 0;
}
}
Detail Here : <
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 5,
"tags": "android, mockito"
}
|
An exercise about nuclear C*-algebra
Definition 2.3.1. A C*-algebra $A$ is nuclear if the identity map id$_{A}:A \rightarrow A$ is nuclear.
**Exercise 2.3.7.** If for each finite set $F\subset A$ and $\epsilon>0$ one can find a nuclear subalgebra $B\subset A$ such that $B$ almost contains $F$, within $\epsilon$ in norm, then $A$ is nuclear. In particular, the class of nuclear C*-algebras is closed under taking inductive limits with injective connecting maps.
My question are
**1\. I do not know the definition of "almost contain, within $\epsilon$ in norm".**
**2\. Could someone give show me more details of this exercise or give me some hints?**
Thanks
|
1. Likely means that for every $a\in F$ there exists $b\in B$ with $\|a-b\|<\varepsilon$.
2. You fix $F=\\{a_1,\ldots,a_n\\}\subset A$ finite and $\varepsilon >0$. By hypothesis there exists $B$ nuclear, and $\\{b_1,\ldots,b_n\\}\subset B$ with $\|a_j-b_j\|<\varepsilon/3$. As $B$ is nuclear there exist $k\in \mathbb N$, $\varphi:B\to M_k(\mathbb C)$, and $\psi:M_k(\mathbb C)\to A$, both completely contractive, such that $\|\psi\circ\varphi(b_j)-b_j\|<\varepsilon/3$ for all $j$. Then, extending $\varphi$ to $A$, $$ \|\psi\circ\varphi(a_j)-a_j\|\leq\|\psi\circ\varphi(a_j-b_j)\|+\|\psi\circ\varphi(b_j)-b_j\|+\|b_j-a_j\|\\\ \leq2\|a_j-b_j\|+\|\psi\circ\varphi(b_j)-b_j\|<3\varepsilon/3=\varepsilon. $$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "functional analysis, operator algebras, c star algebras, von neumann algebras"
}
|
What happens with doubles `articles.id` statements in a `WHERE` clause?
I am using MySQL and I would like to know what exactly happens (or what may happens) in the following cases when I run SLQ queries as-like
## Case 1
SELECT ...
WHERE 'articles'.'author_id' = 2
AND (articles.id IN (46,4,5))
AND (articles.id IN (4,5,16,40))
## Case 2
SELECT ...
WHERE 'articles'.'author_id' = 2
AND (articles.id NOT IN (46,4,5))
AND (articles.id IN (4,5,16,40))
_?_
In particular, I mean what happens with doubles `articles.id` statements in the `WHERE` clause?
|
Is just a logical AND
1 && 1 = 1
0 && 1 = 0
1 && 0 = 0
0 && 0 = 0
Applied to the 1. case:
Value IN (46,4,5) AND IN (4,5,16,40) Result
4 1 1 1
5 1 1 1
46 1 0 0
16 0 1 0
40 0 1 0
Applied to the 2. case:
Value NOT IN (46,4,5) AND IN (4,5,16,40) Result
4 0 1 0
5 0 1 0
46 0 0 0
16 1 1 1
40 1 1 1
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "mysql, sql, database, where clause"
}
|
How Admin Can Unset All The Cookies Of The Users
I have a website that makes art contest every day and at 9 pm the admin decides someone as the winner he also wants to unset all the cookies of all the users.
My Cookie that I am setting for one day
$cookie_name = "participated";
$cookie_value = "yes";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
Is there any way that It can be unset every day at 9 pm or is there any way that the admin can unset all the cookies every day at 9 pm?
Edited : Code tried
<?php
date_default_timezone_set('Asia/Kolkata');
if(date("H") <= 12){
$date = date("H");
}else{
$date = date("H")-12;
}
echo 9-$date;
?>
|
Using the DateTime builtin class you can simply do
$cookie_name = "participated";
$cookie_value = "yes";
// get the timestamp of today @ 9PM to use as the expiry time
$expire = (new DateTime('today 21:00:00'))->getTimestamp();
// or with a specific timezone
//$expire = (new DateTime('today 21:00:00', new DateTimeZone('Asia/Kolkata')))->getTimestamp();
setcookie($cookie_name, $cookie_value, $expire, "/");
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "php, cookies, session cookies"
}
|
I cant add elements to the list - c++
void Student::addStudent()
{
int studentAdd;
cout<<"How many student do you want to add?"<<endl;
cin>>studentAdd;
list<string>::iterator it;
cout<<"Enter the name of student"<<endl;
for(int i=0;i<studentAdd;++i)
{
cin>>studentName;
for(it=studentList.begin();it!=studentList.end();++it)
{
studentList.insert(it,studentName);
}
}
}
im trying to add string elements to list but when i try to display with another function, i cant see the elements.
void Student::displayAllStudents()
{
list<string>::iterator display;
cout<<"Students:\n"<<endl;
for(display = studentList.begin();display!= studentList.end();++display)
{
cout<<*display<<endl;
}
}
Can you please help me?
|
you can't loop with an iterator if you don't have element in you list. this is the error:
for(it=studentList.begin();it!=studentList.end();++it)
{
studentList.insert(it,studentName);
}
begin() and end() point at the same element at the start.
You can use push_bask() to add elements.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "c++, list"
}
|
Como identificar o elemento filho clicado através do evento click no elemento pai
Tenho o seguinte código:
<div class="tipo-cadastro">
<div class="box-logista active">Logista</div>
<div class="box-distribuidor">Distribuidor</div>
</div>
e o seguinte código em javascript/jQuery:
$('.tipo-cadastro').click((e) => {
$('.tipo-cadastro').find('div').removeClass('active');
$(e.currentTarget).addClass('active');
});
O meu problema é que dentro da minha function `e.currentTarget` corresponde ao elemento pai, ou seja, o elemento que possui o evento `click`.
Eu sei que poderia usar o evento click diretamente em cada elemento filho. Mas gostaria de saber se é possível através do evento click no elemento pai saber qual elemento filho foi clicado?
|
Você pode usar o `target`:
$('.tipo-cadastro').click((e) => {
console.log(e.target);
});
<script src="
<div class="tipo-cadastro">
<div class="box-logista active">Logista</div>
<div class="box-distribuidor">Distribuidor</div>
</div>
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, jquery, html, ecmascript 6"
}
|
Can an airliner be refueled while the APU is running?
Race cars can be refueled while the engine is running. I assume this is a dangerous task done by highly specialised technicians.
If ground support is not available, an airliner may keep the APU running to be able to provide power to restart the engines.
If ground support is not available and refuel is needed, can an airliner refuel while the APU is running (technically and legally)?
If the question is too broad, it can be narrowed to best sellers (B737 and A320 families).
|
Refueling an airliner with APU running is a perfectly normal procedure and it is done daily all around the world. The APU is located at the tail cone partially to reduce the risk of fire spreading to the fuel tanks, which are normally in the wings and center fuselage.
Some operators and authorities (not all) restrict starting and/or stopping the APU while fueling.
|
stackexchange-aviation
|
{
"answer_score": 8,
"question_score": 5,
"tags": "ground operations, refueling"
}
|
Is the set of natural numbers that are multiples of at least 3 numbers (including 1 and themselves) asymptotically even?
I was just thinking about this in my head, I am curious as to whether I am thinking about this correctly, or if there is a flaw in my thinking (especially about infinity)
My conjecture is that the set of all numbers that are multiples of at least 3 natural numbers (1, themselves, and one other number) must be asymptotically 100% even, given that odd numbers require all multiples to be odd. So as the number of multiples extends towards infinity, numbers become more and more even, and thus this set would be asymptotically 100% even. I wanted to post this question here to see if there are flaws in my thinking or if my understanding of infinity (which I know can be tricky) isn't correct
|
This is not true. As numbers get large primes get rare. The natural density of even composites is $50\%$. The natural density of odd composites goes to $50\%$ so the natural densities are equal.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": -1,
"tags": "infinity, even and odd functions"
}
|
How to write an exception catching code works in Python2.4 to Python3
Is there anyway to write an exception catch code that's compatible from python 2.4 to python 3?
Like this code:
# only works in python 2.4 to 2.7
try:
pass
except Exception,e:
print(e)
# only works in python 2.6 to 3.3
try:
pass
except Exception as e:
print(e)
|
Trying to write code that works in both Python 2 and Python 3 is ultimately rather futile, because of the sheer number of differences between them. Indeed, a lot of projects are now maintained in separate Python 2 and Python 3 versions as a result.
That said, if you're hell-bent on doing this in a super-portable way...
import sys
try:
...
except Exception:
t, e = sys.exc_info()[:2]
print(e)
|
stackexchange-stackoverflow
|
{
"answer_score": 17,
"question_score": 12,
"tags": "python, python 3.x"
}
|
Cast geometry field as different type on insert?
How can I cast or otherwise insert field `geom_one` of type `geometry(MultiLineString,4326)` into field `geom_two` of type `geometry(MultiLineStringZM,4326)`?
When I attempt to insert using `ST_Force_3D(geom_one)`, it produces the following error:
ERROR: Column has M dimension but geometry does not
********** Error **********
ERROR: Column has M dimension but geometry does not
------------------------------------------------------------------------
SQL state: 22023
------------------------------------------------------------------------
Note:`ST_Force3D()` is used for PostGIS 2.1 and newer.
|
You're using the wrong function,
> `ST_Force3D` Force the geometries into XYZ mode. This is an alias for ST_Force3DZ.
What you want..
> `ST_Force4D` — Force the geometries into XYZM mode.
`MultiLineStringZM` has a `Z` and an `M` dimension. That makes it 4D.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "postgresql, postgis, spatial"
}
|
Controlling mat-tab item position in angular
I'm trying to reach the following result with the angular material tab component: 
2. Swap elements 0 and whatever number you generate
3. Generate a random number between 1 and 49
4. Swap elements 1 and whatever number you generate
5. Etc.
That would probably be the most efficient way.
Sample code (not tested):
srandom(time(NULL));
for (NSInteger x = 0; x < [array count]; x++) {
NSInteger randInt = (random() % ([array count] - x)) + x;
[array exchangeObjectAtIndex:x withObjectAtIndex:randInt];
}
Also, you could use two NSMutableArray objects, and simply loop through while the first has objects, choose one randomly, and add it to the end of the other one. The in place method is probably faster though.
|
stackexchange-stackoverflow
|
{
"answer_score": 15,
"question_score": 2,
"tags": "objective c, sorting, random, nsarray"
}
|
Lower bound for a trace of a matrix product
Let $A$ and $B$ be positive definite Hermitian matrices. They need not necessarily commute. Let $a_m$ be the minimum eigenvalue of $A$.
Is it true that $$ \text{Tr} (AB) \geq a_m \text{Tr} (B) $$
My attempt: let $a_i$ and $b_i$ be the eigenvalues (which are all real and positive) of $A$ and $B$. If $A$ and $B$ are simultaneously diagonalizable by a similarity transformation then $ \text{Tr} (AB) = \sum_i a_i b_i \geq a_m \sum_i b_i = a_m \text{Tr} (B) $. But is this generalizable to arbitrary $A$ and $B$ as laid out above?
|
Note that this is equivalent to proving that $\text{tr}((A - a_m I)B) \ge 0$. In fact the following more general claim is true:
> The trace of a product of two positive semidefinite matrices $A, B$ is nonnegative.
To see this we use the fact that there exist matrices $C, D$ such that $A = C^{\dagger} C, B = D^{\dagger} D$ where $^{\dagger}$ denotes the adjoint. Then we compute that
$$\text{tr}(AB) = \text{tr}(C^{\dagger} CD^{\dagger} D) = \text{tr}(DC^{\dagger} CD^{\dagger}) = \text{tr}(E^{\dagger} E) \ge 0$$
where $E = CD^{\dagger}$.
|
stackexchange-math
|
{
"answer_score": 10,
"question_score": 5,
"tags": "linear algebra, spectral theory"
}
|
Mongoose number of documents referenced in a collection
I have 2 collections
User:
email: { type: String, required: true, unique: true },
team: { type: ObjectId, ref: 'team', required: true},
And Team:
name: { type: String, required: true },
active: { type: Boolean, required: true, default: true},
I want to get all the teams and the number of users in that team, How would I approch this using Mongoose ?
|
Use the `Teams` model and perform an aggregate query.
First we join all users from the `users` collection. Then we create an extra field called `user_amount` in which we store the size of the `users` array. In the last step we remove the `users` property but if you need this array just remove the last step of this pipeline.
Playground
Teams.aggregate([
{
"$lookup": {
"from": "users",
"localField": "_id",
"foreignField": "team",
"as": "users"
}
},
{
"$addFields": {
"user_amount": {
"$size": "$users"
}
}
},
{
"$unset": "users"
}
])
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "mongodb, mongoose"
}
|
LM317LZ LED driver circuit - wrong output current
I built a minimal LED driver circuit using a LM317LZ and a 12 Ohm resistor between OUT and ADJ (identical to e.g. Understanding this LM317 LED Driver circuit). According to the datasheet this should give 100 mA output current but in fact it it is around 60 mA. Input voltage is about 40 V, the LED is a COB LEB which has aprox. 32 V forward voltage at 100 mA. The voltage drop across the resistor is 0.55 V. What am I doing wrong?
|
LM317LZ has internal thermal overload protection. TO-92 can not dissipate 600 mW. (40-32-1.25)*0.1=0.675. Your chip overheated.
|
stackexchange-electronics
|
{
"answer_score": 1,
"question_score": 0,
"tags": "led, constant current"
}
|
div not lining up correctly
I have a header where I have a background image that repeats horizontally. It has content inside it setup as ul list. I wanted to float some of them left and one of the right. I also have a div after the ul list acting as a cap for the end of my header. This cap has a rounded corner. I also have this set to float right and here lies the issue. I'm posting a dummy version for you to view. Can anyone tell me how I can have the input field holder float right and still have my cap float right without getting set below the header like it is right now.
Link to header html
|
This works:
<ul>
<li class="live"><a href="#">button1</a></li>
<li class="schedule"><a href="#">button2</a></li>
<li class="dvr"><a href="#">button3</a></li>
<li class="leftCap"></li>
<li class="tools">
<form class="search" action="get">
<input class="searchField" name="q" maxlength="40">
</form>
</li>
</ul>
Your leftcap was outside the ul as a div, but placing it inside the ul will correct this.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "html, css"
}
|
An example of discontinuous function on $\mathbb{R}$
Is there any example of a function which is discontinuous on $\mathbb{R}$
|
If you mean a function that is nowhere continuous on $\mathbb{R}$, you may consider the indicator function of $\mathbb{Q}$.
|
stackexchange-math
|
{
"answer_score": 7,
"question_score": -6,
"tags": "calculus, real analysis"
}
|
Stereo Calibration Worked Scaled Images?
Does stereo calibration still work if the right image is scaled a bit different than the left, or vice versa?
|
No, for two reasons:
1. The triangulation of the 3D point will be affected
2. Your correspondences will be inaccurate if you are using scale-variant interest point.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "opencv, computer vision"
}
|
Windows batch equivalent for linux cut, paste and pipe to file
I'm having a folder with CSVs like:
A.csv
pet1;dog
pet2;monkey
B.csv
pet1;cat
pet2;wolf
I can now reformat those in bash (Linux):
for filename in *.csv; do
CSVBody=$(cat $filename | cut -d ";" -f2 | paste -sd ";" -)
echo -e "$CSVBody" >> ./converted/merged.csv
done
To get
merged.csv
dog;monkey
cat;wolf
Unfortunately, I'm a long time away of windows. How would I cut, paste and pipe to a file in bash?
|
An alternative to reading files in parallel is storing one set in a pseudo hash table
:: Q:\Test\2019\09\03\SO_57771554.cmd
@Echo off & Setlocal EnableDelayedExpansion
for /f "tokens=1* delims=;" %%A in (A.csv) do Set "File1[%%A]=%%B"
for /f "tokens=1* delims=;" %%A in (B.csv) do Echo !File1[%%A]!;%%B
* * *
> Q:\Test\2019\09\03\SO_57771554.cmd
dog;cat
monkey;wolf
# EDIT due to Aacini's valuable hint, I did it wrong.
:: Q:\Test\2019\09\03\SO_57771554.cmd
@Echo off & Setlocal EnableDelayedExpansion
for %%F in (*.csv) do (
Set "Line="
for /f "tokens=1* delims=;" %%A in (%%F) do Set "Line=!Line!;%%B"
Echo(!Line:~1!
)
* * *
> SO_57771554_2.cmd
dog;monkey
cat;wolf
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "batch file, window"
}
|
Fixed-size array issue
Maybe this question it seems to be stupid but is it possible to change elements of fixed-size array like bytes32. For example:
bytes32 _b32 = sha3(1);
_b32[0] = 100; // => Error
|
It's possible to mutate elements of a fixed-sized array, but not a fixed-sized **byte array** (like `bytes32`).
So this is valid:
byte[32] myBytes;
myBytes[3] = 0x5;
but this is _not_ valid:
bytes32 myBytes;
myBytes[3] = 0x5; // TypeError: Expression has to be an lvalue.
|
stackexchange-ethereum
|
{
"answer_score": 3,
"question_score": 1,
"tags": "arrays, bytes32"
}
|
Where can I find Cardano Dapp code and demo examples?
I am checking Cardano documentation to develop Cardano POC for my Dapp, found some good examples to create contracts using online application i.e. Plutus (<
However, there are no examples given to create end-to-end applications like those provided in Ethereum documentation i.e. Ethereum has provided web3 applications examples to create Dapps using Web3 / React/ Solidity contracts connecting the dapp to Ethereum testnet/mainnet - many examples are available on internet and ethereum documentation website for reference.
I have not found demo examples of how Dapps can be built using Cardano.
Please can someone share some code and demo examples or links to them?
|
You can find a number of dApps demo examples in the Plutus Pioneer Program repository.
|
stackexchange-cardano
|
{
"answer_score": 2,
"question_score": 7,
"tags": "decentralized applications"
}
|
JavaScript not getting pixel width of window correct on mobile devices
My project is located at the following URL:
<
The div and the canvas contained on the document are set to be 480 pixels wide on most devices, but on mobile devices (my iPhone and android phone are the only devices I've tested, but I'm assuming it's pretty much universal) they are 480 pixels on the document, but the document is wider than the number of pixels on the screen (you'll understand what I mean when you look on a mobile device if you don't already understand). The weird thing is it works perfectly fine on a computer.
How can I fix this?
|
Use a valid DOCTYPE and then
<meta name="viewport" content="width=device-width, initial-scale=1">
The important part is `width=device-width`.
<
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "javascript, android, iphone, html, css"
}
|
Check if map entry is last in a range based for?
I'd prefer to loop through a c++ `map` in the same way as in this answer:
for (auto& kv : myMap) {
std::cout << kv.first << " has value " << kv.second << std::endl;
}
Using a range-based for such as this, is it possible to determine that `kv` is the last element in the range? If so, how?
|
You can get the last key in the map and check for it.
const auto& lastKey = myMap.rbegin()->first;
for (auto& kv : myMap) {
if(kv.first == lastKey) {
std::cout << "The last one" << std::endl;
}
std::cout << kv.first << " has value " << kv.second << std::endl;
}
You can also use `std::prev` (reference) if you need the second last or something like that:
const auto& lastKey = std::prev(myMap.end(),2)->first; // gives the 2nd last
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 2,
"tags": "c++, for loop, dictionary, range"
}
|
Should documentation use images with code snippets?
As per the title, should we be approving or rejecting documentation that uses images with code snippets?
E.g. <
|
I think **NOT AT ALL**.
Screenshots of code in the body of questions is usually a main reason for having the question downvoted on SO, and the Documentation project should have high standard of examples, and to allow uses to copy the code and try it locally, without needing to rewrite the code in the image.
If people can't put the code in the example, the should not create it in the first place
|
stackexchange-meta_stackoverflow
|
{
"answer_score": 9,
"question_score": 2,
"tags": "discussion, documentation"
}
|
In Python is there a better way to assign the first result from lxml xpath()?
I'm working on converting some of my scripts that transform XML documents from Perl to Python.
In Perl using XML::LibXML I can do
`my ($target) = $dom->findnodes('/root/child1');`
to assign the first node from the nodelist that is returned.
In Python so far I got this to work:
`target = (tree.xpath('/root/child1'))[0]`
but I'm wondering if there is a better or more Python like way to do this.
|
That's a normal and reasonable way to do it (except get rid of the unneeded parenthesis). Its common to do the selection in xpath as much as possible so that `lxml` doesn't have to create extra objects,
target = tree.xpath('/root/child1[1]')[0]
or to skip the root specification assuming you are already at the root level of the document
target = tree.xpath('child1[1]')[0]
but I think the most common option is to use the `find` method instead.
target = tree.find('child1')
`find` is from the `ElementTree` API and uses `ElementPath` instead of `XPath` (they are very similar). It finds the first matching element and returns. `ElementPath` has other methods like `iterfind` for handling large documents.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "python, lxml"
}
|
Efficiently laying track: diagonally or straight w/ one turn?
Because of how Minecraft's block measurement system operates is it more efficient to lay track (rails) diagonally or along the axes ( i. e. from start to finish, lay all track for x direction, then all track in z direction). Looking for both efficient use of materials and efficient use of minecart inertia/speed ( I know that long diagonals sap speed rather quickly).
If possible, factor the mod Railcraft into your answer, please.
|
Regarding materials, there will be no difference. Here is a picture.
!enter image description here
The picture shows two 10x10 squares. The number of blocks (ie. Railway) will be the same to create a path from one corner to the other.
I also conducted an experiment using a Minecart without passenger (I initially sat in it, but the inertia brought me very far away thus I did it without a passenger) and it turns out that the one on the left travelled 8 blocks whereas the one on the right travelled 11 blocks.
Therefore, to answer your question based on this little experiment:
1. The materials used will be the same.
2. A diagonal track is more efficient in terms of distance.
However, do note that if doing this in the nether and digging a path through netherrack, a diagonal path is a lot more inconvenient to dig and walk through (you'll just hit your arms and body on the wall left and right :P), unless the diagonal path is widened.
Hope this helps!
|
stackexchange-gaming
|
{
"answer_score": 8,
"question_score": 5,
"tags": "minecraft java edition"
}
|
Cheese camera problem in ubuntu 14.10
There is a problem with Cheese on my computer. I am running Ubuntu 14.10 (everything is upgraded to the last version ). As seen here:
> Kernel version : 3.17.1-031701-generic
>
> Cheese version : 3.12.2
Whenever I take a picture, the picture is black using Cheese of course, but I do not have a problem with videos.
What is my problem? How can I fix it?
|
Cheese 3.10 ships with Ubuntu 14.04, while Cheese 3.12 ships with Ubuntu 14.10. This may explain why it stopped working.
Try this:
sudo apt-get remove cheese
sudo echo "deb trusty main" > /etc/apt/sources.list.d/cheese.list
sudo apt-get update
sudo apt-get autoremove
Now install cheese 3.10 with Synaptic. If you don't have Synaptic yet, you can install it:
sudo apt-get install synaptic
Force the version like so: Package -> Force version (choose 3.10)
To fix broken packages, close Synaptic and do this:
sudo apt-get -f install
Don't forget this:
sudo rm /etc/apt/sources.list.d/cheese.list
sudo apt-get update
Now it should work. Never update Cheese again. :) This is a guide to lock the version.
Although this method is not recommended to apply for every package, it may provide a workaround for your problem.
|
stackexchange-askubuntu
|
{
"answer_score": 0,
"question_score": 0,
"tags": "camera, 14.10, cheese"
}
|
how should I share a function in an angular service with non-angular code?
I might need to investigate _why_ I'm sharing code between Angular and other objects in my page. Fair enough. But in the meantime:
I've got a bit of code that creates IDs. It's in an Angular service:
angular.module("Gamma.services").service "idService", () ->
@newId = ->
id = String.fromCharCode(Math.floor(Math.random() * 25) + 65) +
((@someNumber + Math.floor(Math.random() * 1e15) +
new Date().getMilliseconds()).toString(36)).toUpperCase()
OK so that's nifty and all, but I need to share this little chunk of code with some non-Angular code in my app. I've got a solution to it (moved this code into a function off of the window object), but I think the more-correct solution might be to pass a function pointer that points to the Angular service.
How can I pass an Angular service to non-Angular code?
|
**Updated per @jcollum's comment/tip**
angular.module('myApp', []).
factory('myService', [function() {
return function() {
alert('hello from the service')
};
}]);
angular.element(document).ready(function(){
angular.bootstrap(document, ['myApp']);
var doc = angular.element(document),
injector = doc.injector(),
myService = injector.get('myService');
myService(); // alerts
});
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "angularjs"
}
|
Excel - How to fill in incrementing numbers in column starting from 1 until the value in another columns stays the same
I'm having this test case spreadsheet that I need to convert into different format in order to export it to another test management system.
Currently, our spreadsheet looks like this:
A | B | C..
------|---|---
TC-01 |MED|
| |
TC-02 |Hi-|
| |
| |
TC-03 |Low|
| |
We need to convert it to:
A | B | C
----|---|---
TC-01 |MED|-1-
| |-2-
TC-02 |Hi-|-1-
| |-2-
| |-3-
TC-03 |Low|-1-
| |-2-
...where each TC in column A would start with '1' in column C, and end whenever new TC starts.
New Test management system supports this specific format only, so we have to convert it only this way. Is there a possibility to automate this? We have tens of sheets with thousands of lines in each.
|
In **C1** enter _1_. In **C2** enter:
=IF(A2<>"",1,C1+1)
and copy down
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "excel"
}
|
Precisely scheduling sound in iOS 7
I'm working on an iOS7-only app that needs to display a clock complete with ticking sound. I've used a NSTimer of 1s and I use AVAudioPlayer to play the tick sound every second.
Unfortunately, there's something slightly off with the timing. I've measured that timer is off by between 2 and 22 thousands of a second, which you wouldn't think would matter a great deal, but the lag creates a nail biting tension.. kind of like a heart flutter :-)
I've looked around a bit but it sounds like using audio queue services is the only way to go.. and I really don't fancy delving into the depths of that particular framework again.
My question: Is there some other way of getting precisely scheduled sound events in iOS 7 and failing that is there a decent wrapper framework for audio queue services available somewhere? Or better still is there a way of more precisely scheduling NSTimers?
|
Using any of `NSTimer`, `libdispatch`, or spawning a thread that sleeps for the tick duration rely on the underlying thread getting scheduled in time. The kernel provides no guarantee of this, and it is not surprising that the you observe timing jitter; the latency you observe looks reasonable.
`NSTimer` running on the main thread is likely to perform worst of these as you are also contending against other events delivered through it.
I think your options here are either to use audio queue services, a real-time thread to schedule the events with AVAudioPlayer, or render the audio yourself to a `remoteIO` unit.
I don't think AVPlayer provides any particular guarantees about timing either.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ios, cocoa touch, audio, avaudioplayer, audioqueueservices"
}
|
Python - Add item to lists of list
I have list "X":
X = ["'A':", [], "'B':", [], "'C':", [], "'D':", [], "'E':", []]
At indexes 1,3,5,7,... in my list I have another empty list.
How can I add some items to lists in list?
My list should be like:
X = ["'A':", [1,2], "'B':", [2,3,4], "'C':", [3,4,6], "'D':", [1,2], "'E':", [3]]
|
If you have a rule, then please tell us. If you want to give the additional items manually, then here is the example:
X[1].extend([1,2])
X[3].extend([2,3,4])
X[5].extend([3,4,6])
X[7].extend([1,2])
X[9].extend([3])
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -4,
"tags": "python, python 3.x"
}
|
Spotify / Rdio Bottom Toolbar View Controller Transition
Could anybody point me in the right direction for implementing the type of functionality that Spotify and Rdio use for their "Now Playing" bottom toolbar? There is an ability to touch and drag a view controller over the top of another view controller. The entire transition is interactive. Any help would be appreciated! Thanks!!
|
Likely they're just using UIPanGestureRecognizers and maybe UITapGestureRecognizer if you can tap the bottom bar to make it slide up.
Maybe make some container controller that holds your main nav stack, with the mini player at the bottom, and the full player hidden off screen. Then using the gesture recognizer, you can drag it up to reveal the full player.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "iphone, ios, objective c, xcode, ipad"
}
|
Configuration Files in java
I have created a Swing Application- GUI containing fields like TextFields, Labels, CheckBoxes and ComboBoxes. When the user enters some information, I want the details of the textfields, comboboxes and checkboxes to be saved into a file, and the next time when a user opens this Window, I want the details that have been saved in the file, i.e. those that have been entered by the user the previous time to be loaded into the GUI. Can anyone please help me in doing this? I hope you understand the question, if not I will explain in a more detailed manner.
Thank you so much in advance.
|
Here is a simple example using the java.util.prefs package:
// Retrieve the user preference node for the package com.mycompany
Preferences prefs = Preferences.userNodeForPackage(com.mycompany.MyClass.class);
// Preference key name
final String PREF_NAME = "name_of_preference";
// Set the value of the preference
String newValue = "a string";
prefs.put(PREF_NAME, newValue);
// Get the value of the preference;
// default value is returned if the preference does not exist
String defaultValue = "default string";
String propertyValue = prefs.get(PREF_NAME, defaultValue); // "a string"
The way preferences are saved is OS-dependent. On Windows, it will use the registry.
Examples of use: <
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": "java, file, swing, configuration, configuration files"
}
|
Extract min/max by group in R
(Using Iris for reproducibility)
I want to calculate min/max row by Petal.Width & grouped by Species in R. I have done that using two approaches, I want to understand is there a better approach (preferably tidyverse) , also note because of ties answer might vary in both. Please correct if there is anything wrong in both these approaches.
**Approach 1**
library(tidyverse)
iris %>%
group_by(Species) %>%
slice_max(Petal.Width, n = 1, with_ties=FALSE) %>%
rbind(
iris %>%
group_by(Species) %>%
slice_min(Petal.Width, n = 1, with_ties=FALSE))
**Approach 2**
iris %>%
group_by(Species) %>%
arrange(Petal.Width) %>%
filter(row_number() %in% c(1,n()))
|
You could also use `slice` like below:
iris %>%
group_by(Species) %>%
slice(which.min(Petal.Width),
which.max(Petal.Width))
Output:
# A tibble: 6 x 5
# Groups: Species [3]
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
<dbl> <dbl> <dbl> <dbl> <fct>
1 5 3.5 1.6 0.6 setosa
2 5.9 3.2 4.8 1.8 versicolor
3 6.3 3.3 6 2.5 virginica
4 4.9 3.1 1.5 0.1 setosa
5 4.9 2.4 3.3 1 versicolor
6 6.1 2.6 5.6 1.4 virginica
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "r, dplyr, tidyverse"
}
|
Is it possible to have gestures with trackpads?
On a Macbook Pro in Chrome, sliding two fingers across the screen allows you to move backwards and forwards. How do I go about disabling this, and creating custom gestures in jQuery or Javascript?
All I really need to know is how do you detect when two fingers are on the trackpad, which I assume is the best way to do this. You can do it on mobile with e.touches!
|
Touchpads do not trigger touch-related events (but usually control the mouse pointer instead. This cannot be affected by a website for obvious reasons) so that's not possible.
If gestures done on a touchpad have non-standard behaviour this is usually done by the touchpad's driver/software.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 4,
"tags": "javascript, jquery, google chrome, touch, gesture"
}
|
Button that displays and hides a sliding menu
I'm trying to build a header with a menu button that triggers a sliding menu. I can make the menu appear when I press the button, but I also want it to dissappear when I click the button again.
This is the event that triggers when the button is clicked.
$('#nav-button').click(function () {
$("#slidermenu").animate({right: "0px"}, 200);
$("body").animate({right: "300px"}, 200);
});
I looked up the animate method and saw that it has a function called **done** , which takes two parameters. A promise and a boolean. So I figured I can use a **if-statement** to check if the animation is done, and if the animation is done, the button would send the slidermenu back.
But how can I test if animate().done() is true? Or is there a more simple way of achiveing this?
Here is my fiddle.
|
`.is(':animated')` will return `true` if it's currently being animated.
In the context of what you're trying to do:
if(!$('#slidermenu').is(':animated'))
{
// Animation has finished
}
_As an aside:_
I try and do this with CSS only now where possible. If you use jQuery `toggleClass` and predefine the `right` attributes in your CSS for the toggled classes, you can add a CSS transition to deal with the animation. Just thought it was worth mentioning (this does come with it's own compatibility issues).
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript, jquery, events"
}
|
Can this whiskey be a result of combining whiskey A, B, and C in any ratio?
There is a whiskey made up of 64% corn, 32% rye, and 4% barley that was made by blending other whiskies together. I am trying to figure out if there is a chance the ratio of this whiskey could be the result of blending two, maybe three whiskies of different ratios.
The possible whiskies:
Whiskey A is 60% corn, 36% rye and 4% barley.
Whiskey B is 81% corn, 15% rye, and 4% barley.
Whiskey C is 75% corn, 21% rye, and 4% barley
I have a feeling there is a possibility because these whiskies all have 4% barley, but I can't figure out if the other percentages match up in any 1:2:3 ratio in the blend. Any help will be greatly appreciated. Thank you.
|
Yes, and in infinitely many different ways!
Row reduce $\begin{bmatrix} 60&81&75&64\\\ 36&15&21&32\\\ 4&4&4&4\\\ \end{bmatrix}$ to get $\begin{bmatrix} 1&0&\frac{2}{7}&\frac{17}{21}\\\ 0&1&\frac{5}{7}&\frac{4}{21}\\\ 0&0&0&0\\\ \end{bmatrix}$.
Let's say:
$A$=ratio of Whiskey A in mixture
$B$=ratio of Whiskey B in mixture
$C$=ratio of Whiskey C in mixture
From the row reduction we get the relations: $$(*)A=\frac{17}{21}-\frac{2}{7}C, B=\frac{4}{21}-\frac{5}{7}C$$
Since $A,B,C$ are all between $0$ and $1$, these relations put a restriction on $C$: namely $C\leq\frac{4}{15}$. So choose your favorite value for $C$ in the appropriate range, plug it into the equations in $(*)$. That will give you the amounts of whiskeys A and B you need to get the desired mixture.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "linear algebra"
}
|
When boost::lock_guard was moved
In which version of library `boost::lock_guard` was moved from "boost/thread/locks.hpp" to "boost/thread/lock_guard.hpp"?
|
Checking the beautiful Boost online versioned documentation leads me to believe there was a change from version 1.52.0 to version 1.53.0. I doubt it was "moved" though. It seems to me that including `locks.hpp` will now just include `lock_guard.hpp`.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "c++, boost"
}
|
Clustering a set of points with circles
I have a group of 100 points in a 2-D plane with known x-y coordinates . I want to draw 25 circles such that exactly 4 points are present in each circle.Each point has to be in exactly one circle. Can you provide the basic algorithm as to how to proceed.
Note: I have been looking at some algorithms which involve k-means ,but none had exactly what I want. I know python/go/matlab/c in case there are some specific modules in that language which could be of use.
|
I think there are some configurations that would have no solution.
?
`hook_add_form()` gets `$entity_type` and `$entity` as parameters, but `hook_form_alter()` does not have any of those parameters.
How do I get the entity type and the entity object in `hook_form_alter()`in Drupal 7?
|
I think that it should be possible to do something like this.
if ($form_state->getFormObject() instanceof \Drupal\Core\Entity\EntityFormInterface) {
$entity = $form_state->getFormObject()->getEntity();
$entity_type = $entity->bundle();
}
UPDATE: In Drupal 7 it should be done like this:
$node = $form['#entity_type']; // E.g this could be, (#node, #user etc.)
Take a look at this site, drupal discussion.
|
stackexchange-drupal
|
{
"answer_score": 7,
"question_score": 2,
"tags": "7, entities, hooks"
}
|
How to call a function when the block visibility changes?
When the user clicks on the map, the address_box code block becomes visible.
<div id="adress_box" style="visibility: hidden">We are looking for delivery to <span id="address_confirm"></span></div>
How do I make the code below run when the visibility changes to visible?
alert('div is display!!!');
so far, I have only achieved that when the page loads, a similar code is executed:
<div id="adress_box" style="visibility: hidden">Ищем доставку по адресу <span id="address_confirm"></span></div>
<script>
let element = document.getElementById('address_confirm');
let cssObj = window.getComputedStyle(element);
if (cssObj.getPropertyValue("visibility") == 'visible') {
alert('div is display!!!');
}
</script>
|
When we click on the map, with changing visibility changed div's text.
Much easier listen text changing in the div.
<div id="adress_box" style="visibility: hidden">Ищем доставку по адресу <span id="address_confirm"></span></div>
<script>
document.getElementById("address_confirm").addEventListener("DOMSubtreeModified", function() {
alert('div is display!!!');
});
</script>
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript"
}
|
ASP.NET MVC Code First
When building an MVC application from scratch without a pre-existing database, is using the code-first approach the best way to do it? While most applications are database-centric, it is perhaps the schema rather than the database itself that governs how the app is built around it. As such, I think a code-first approach isn't too bad. It was late to the party (happened after database-first and model-first), but I think the code-first approach will become the norm soon. What's your opinion?
|
First i think that this link can provide you with more information
In my opinion both of the approaches are useful. A developer/company needs to decide what is the best approach for there system, in some situation.
I think one good distinguish is Big and complex against small and simple applications
I think that developers or companies will prefer "DataBase First" approach when they builds complex application. In most cases DBA's will be needed in such project. In those cases the project will include Store Procedures/ Triggers and maybe also a Data-ware house
In the other hand when you build a small application with one of small group of developers you probably prefer using "Code First" approach
again this is my opinion...
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "asp.net mvc, entity framework, ef code first"
}
|
pop art images generation, flex, as3, flash
My client has asked to generate pop art images for the user uploaded images, !enter image description here
Does any one of you has done some work related to this? is this sort of work is possible in flex, flash, as3, etc,
There is one software named pop art studio, which generates such images. we have Image magic software with us, does image magic generates these sort of pop art images? i don't have much idea about Image magic.
one solution for this would have been, if these images were our images, then we would haven taken them as the separate parts of one image, and applied color transform or any other thing on those parts, and would have generated these sort of poparts displayed in the picture , but client requires this option on user uploaded images, so all this is not possible in that case.
so waiting for your answers.
Thank you
Regards
Alan
|
You're gonna need pixel bender and you're gonna have to write it yourself, I spent about 15 minutes googling for you to no avail. Here are some tutorials on how to get started with pixel bender:
<
<
<
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "flash, apache flex, actionscript 3, flex3, flex4"
}
|
Change values over specific indexes in DataFrame
Let's say I have a Series of flags in a DataFrame:
a=pd.DataFrame({'flag':[0,1,0,0,1]})
and I want to change the values of the flags which are in a specific indexes:
lind=[0,1,3]
This is a simple solution:
def chnflg(series,ind):
if series.ix[ind]==0:
series.ix[ind]=1
else:
series.ix[ind]=0
map(partial(chnflg,a),lind)
It works fine but there are two issues: the first is that it makes the changes in-place, while I would like a new series in DataFrame. This is not a big deal after all.
The second point is that it does not seems pythonic enough. Is it possible to do better?
|
An easier way to describe your function is as x -> 1 - x, this will be more efficient that apply/map.
In [11]: 1 - a.iloc[lind]
Out[11]:
flag
0 1
1 0
3 1
_Note: I like to use iloc here as it's less ambiguous._
If you wanted to assign these inplace then do the explicit assignment:
In [12]: a.iloc[lind] = 1 - a.iloc[lind]
In [13]: a
Out[13]:
flag
0 1
1 0
2 0
3 1
4 1
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "python, pandas"
}
|
Displaying the contents of a Map over iterator
I am trying to display the `map` i have created using the Iterator. The code I am using is:
private void displayMap(Map<String, MyGroup> dg) {
Iterator it = dg.entrySet().iterator(); //line 1
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove();
}
}
Class MyGroup and it has two fields in it, named `id` and `name`. I want to display these two values against the `pair.getValue()`. The problem here is Line 1 never gets executed nor it throws any exception.
Please Help.
PS: I have tried every method on this link.
|
Map<String, MyGroup> map = new HashMap<String, MyGroup>();
for (Map.Entry<String, MyGroup> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
using iterator
Map<String, MyGroup> map = new HashMap<String, MyGroup>();
Iterator<Map.Entry<String, MyGroup>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, MyGroup> entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
For more iteration information see this link
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 6,
"tags": "java, dictionary, iterator"
}
|
Remove "Silent Process Exit" folder from temp directory
How to disable processes the monitoring of silent process exits and get rid of the `%userprofile%\AppData\Local\Temp\Silent Process Exit` folder?
I looked it up and found that it has something to do with gflags or silent process exit monitoring in windows debugger, it is saving dumps of `cmd.exe` every time I exit the program regularly, when I use `taskkill /im cmd.exe` it doesn't save a dump.
|
You or some installed program have somehow enabled the CMD process for the tracing of silent exits (non-crash). This is usually done by driver programs, but I don't know of a driver that traces CMD...
See the article Monitoring Silent Process Exit. It lists the following registry keys where this could be set:
* `HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\ProcessName\GlobalFlag`
* `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit`
* `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\ProcessName`
`ProcessName` might be CMD in the above.
Check the above registry keys. In my computer these keys do not exist, so can probably be deleted from yours. Reboot afterwards. I suggest creating at least a System Restore Point before doing any registry modifications.
|
stackexchange-superuser
|
{
"answer_score": 0,
"question_score": 1,
"tags": "windows 10, debug"
}
|
The new item is added twice at the end of the column
I am trying to update the store column by adding new item (string) to the end of the column, But what happens is the new item is added twice at the end of the column, This is the code:
$query = "SELECT * FROM users";
$result = $conn->query($query);
while($row = $result->fetch_assoc()){
$item = 'item_name';
$store = $row['store'];
$newstore = $store . '|' . $item;
echo 'newstore : ' . $newstore . '<br>'; // It looks normal : store|item
$sql = "UPDATE users SET store='" . $newstore . "' WHERE username='" . $row['username'] . "'";
$conn->query($sql);
}
In in the database I find: **store|item|item**
|
Rather than reading the entire table and looping through it with PHP, run just a single UPDATE query to concatenate the extra data onto the column.:
$item = 'item_name';
$query = "UPDATE users SET store=concat(store,'|','$item')";
$result = $conn->query($query);
Note: this form is potentially open to SQL injection if you can't trust the value in `$item`. You'd do better to use a prepared query if that's the case.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, mysql, sql update"
}
|
GAE, Search API, Documents to JSON serialization
How can I serialize the entire result set from a search api query on GAE into json? I'm using python and the standard library.
Ive got my results :
index = search.Index(name=Myindex)
query_string = "amount > 0"
results = index.search(query_string)
json_results = {}
I was trying to iterate through them and construct a json output bit by bit,
for i in results:
x = {'result':
{'name' : i.field('name').value,
'value' : i.field('value').value
'geo' : i.field('location').value
}}
json_results = dict(list(json_results)+list(x))
json.dump(json_results,self.response.out)
but I'm totally new to coding and just teaching myself as I go along on this project...Ive tried all manner of variation in the last couple of days, to no avail. There must be a simple way.
|
You are on the right path, but there are a few errors in your code, I assume you want to pass back an ordered list of dictionaries holding the results. At the moment you are constructing a dict of dicts, and the outer dictionary all share the same key "results" which means you will end up with a single entry.
json_results = []
for i in results:
x = {'name' : i.field('name').value,
'value' : i.field('value').value
'geo' : i.field('location').value}
json_results.append(x)
self.response.write(json.dumps(json_results,self.response.out))
In addition you will want to set your content type in the header appropriately. See SO question What is the correct JSON content type? for correct types.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "python, json, google app engine"
}
|
Calculate percentage of missing string variables in each column
I have a data frame with some columns which are strings with missing values. Is there a way (using dplyr) to efficiently calculate the percentage of each column that is missing i.e. "". So I dont have to calculate each column percentage missing individually ?
I have tried the following but dosnt seem to work
library(dplyr)
#Create data frame
a<- c(1,"",3,4)
b<- c(2,2,3,4)
c <- c("",2,"",3)
x<- data.frame(a,b,c)
x %>%
summarise_each(funs(100*mean(is.null(.))))
#Result is
#a b c
#0 0 0
Want to get something like
#a b c
#0.75 0 0.50
|
in base:
colSums(x!="")/nrow(x)
a b c
0.75 1.00 0.50
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "r, dplyr"
}
|
Publish Android App for Phone and Watch in Play store
I'm implementing Same App for Android Phone and Watch .Both are having same package name.How to upload both apps in Play store?
Thanks In advance.
|
Use Multi-APK delivery method.
As per documentation:
> To make your app appear in the on-watch Play Store, you upload the watch APK in the Play Console just as you would any other APK. If you only have a watch APK and no phone APK, no other steps are required. If you have a phone APK in addition to a watch APK, you must use the Multi-APK delivery method.
Reference:
<
<
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "android, google play"
}
|
Iterating through the same enumerated set twice
Problem: What mathematical notation for iterating over the same enumerated set $\\{\dots\\}$ twice is most consistent with existing conventions?
Context: The specific use is for pseudocode that describes the iteration using indices $i$ and $j$ over a square $n \times n$ matrix, so $\\{\dots\\}$ becomes $\\{1, \dots, n\\}$. The use of indices is needed for reference in the subsequent lines of the pseudocode.
The following notation uses ordered pairs and applies the Cartesian product operator on the set enumeration as inspired by the answer on this question:
$\forall (i,j) \in \\{\dots\\}^2$
And what about this notation:
$\forall i,j \in \\{\dots\\}$
What is 'better'? Would the latter be confusing because the reader may think that only $j$ iterates over the set?
|
I would prefer the latter ("for all $i, j\in\\{\dots\\}$"). But your first suggestion means the same; so it is also correct.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "matrices, elementary set theory, notation"
}
|
Is there any way to tag more than 50 people in Facebook photo?
My dear friend is stuck with a problem. He's tagged his wedding invitation to his friends but he has a lot of friends and those not tagged are upset.
Please tell me is there any way to tag more than 50 Persons on a photo?
Do I have to send request mail to Facebook for above?
|
Assuming that your friend has a wedding photo with, say, 100 guests in four rows, then he could post the photo twice and tag the front two rows in one photo and the back two rows in the other photo.
That should avoid any angriness amongst his friends.
|
stackexchange-webapps
|
{
"answer_score": 14,
"question_score": 8,
"tags": "facebook"
}
|
jquery найти даты ранее n-минут
Есть даты
<span class="posted-time">[20-11-2015 04:31:57]</span>
<span class="posted-time">[20-11-2015 03:31:10]</span>
....
нужно найти даты, которые актуальны, если вычесть от текущей n-минут
|
Не очень понял, что имеется в виду под "актуальны". Будем считать, что нам нужны те даты, которые были раньше, чем n минут назад.
var nMinutesBeforeNow = new Date(Date.now() - n * 60000);
$('.posted-time').each(function() {
var m = this.textContent.match(/^\[(\d\d)-(\d\d)-(\d\d\d\d) (\d\d):(\d\d):(\d\d)/);
var n = m.slice(1).map(function(s) { return parseInt(s, 10); });
var time = new Date(n[2], n[1] - 1, n[0], n[3], n[4], n[5]);
if (time < nMinutesBeforeNow)
console.log(time);
});
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, jquery"
}
|
Measure transient memory and performance programmatically
We have an application where we have a use case to have tests around the application performance. We run the candidate build against the build currently being used and compare stats like time taken for different operations, memory consumption of the operations and various other general metrics like the total heap size etc...
My problem here is the measurement of transient memory during an operation. We have observed that to be fluctuating(too much to be reliable). I am using JMX and polling the JMX bean at an interval of 1 second...
One silution we tried(still testing) is to reduce the polling time to 10 ms. Not sure if that will help...
anybody has any other better ideas or have encountered same problems ?
Thanks, Kichu
|
Another tool which might be useful is jstat. This records periodically how much memory is consumed in each generational space and a cause for a GC being performed.
However, it sounds like you are creating so much garbage that the tools are giving you noisy information. The best tool sounds like using a memory profiler, which will give you much more detail about object allocation and where memory is being consumed. I suggest you try YourKit on eval and look at object allocation hot spots and try to reduce the amount of objects you create.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "java, performance, memory management"
}
|
Why cant Dolphin FM access, browse mounted SSH shares
Installed Dolphin from the App Store, like that split plane feature. Alas I cannot seem to access mounted SSH devices from my local network. Probably something very obvious?
|
This is due to access permissions. Flatpak installations do not have complete access to your system, so you need to explicitly grant permissions. Fortuntaely, it's not too difficult.
To give any software you've installed from the App Store permission to access a file location, do this:
1. Open Terminal
2. Grant permission:
sudo flatpak override <package_name_here> --filesystem=<path_here>
**Note:** If you have a path with spaces or special characters, be sure to wrap the `<path_here>` value like `"<path_here>"`.
Later, if you need to remove access to a location, use the `--nofilesystem` option to remove permissions:
1. Open terminal.
2. Revoke permission:
sudo flatpak override <package_name_here> --nofilesystem=<path_here>
If you would like to know more about the different options that are available for App Store-installed app permissions, you can read about the Flatpak sandbox here.
|
stackexchange-elementaryos
|
{
"answer_score": 0,
"question_score": 0,
"tags": "pantheon files, ssh"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.