qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
list | response
stringlengths 0
115k
|
---|---|---|---|---|
63,570,652 |
New to SQL.
I have two SQL tables T1 and T2 which looks like the following
```
T1
customer_key X1 X2 X3
1000 60 10 2018-02-01
1001 42 9 2018-02-01
1002 03 1 2018-02-01
1005 15 1 2018-02-01
1002 32 2 2018-02-05
T2
customer_key A1 A2 A3
1001 20 2 2018-02-17
1002 25 2 2018-02-11
1005 04 1 2018-02-17
1009 02 0 2018-02-17
```
I want to get T3 as shown below by joining T1 and T2 and filtering on T1.X3 = '2018-02-01'
and T2.A3 = '2018-02-17'
```
T3
customer_key X1 X2
1000 60 10
1001 42 9
1005 15 1
1009 null null
```
I tried doing full outer join in the following way
```
create table T3
AS
select T1.customer_key, T3.customer_key, T1.X1, T1.X2
from T1
full outer join T2
on T1.Customer_key = T2.customer_key
where T1.X3 = '2018-02-01' and T2.A3 = '2018-02-17'
```
It returns lesser number of rows than the total records that satisfying the where clause. Please advice
|
2020/08/25
|
[
"https://Stackoverflow.com/questions/63570652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7933418/"
] |
Full outer join with filtering is just confusing. I recommend filtering in subqueries:
```
select T1.customer_key, T3.customer_key, T1.X1, T1.X2
from (select t1.*
from T1
where T1.X3 = '2018-02-01'
) t1 full outer join
(select t2.*
from T2
where T2.A3 = '2018-02-17'
) t2
on T1.Customer_key = T2.customer_key ;
```
Your filter turns the outer join into an inner join. Moving the conditions to the `on` clause returns all rows in both tables -- but generally with lots of `null` values. Using `(T1.X3 = '2018-02-01' or t1.X3 is null) and (T2.A3 = '2018-02-17' or T2.A3 is null)` doesn't quite do the right thing either. Filtering first is what you are looking for.
|
68,276,673 |
Assume I have `df1`:
```
df1= pd.DataFrame({'alligator_apple': range(1, 11),
'barbadine': range(11, 21),
'capulin_cherry': range(21, 31)})
alligator_apple barbadine capulin_cherry
0 1 11 21
1 2 12 22
2 3 13 23
3 4 14 24
4 5 15 25
5 6 16 26
6 7 17 27
7 8 18 28
8 9 19 29
9 10 20 30
```
And a `df2`:
```
df2= pd.DataFrame({'alligator_apple': [6, 7, 15, 5],
'barbadine': [3, 19, 25, 12],
'capulin_cherry': [1, 9, 15, 27]})
alligator_apple barbadine capulin_cherry
0 6 3 1
1 7 19 9
2 15 25 15
3 5 12 27
```
I'm looking for a way to create a new column in `df2` that gets number of rows based on a condition where all columns in `df1` has values greater than their counterparts in `df2` for each row. For example:
```
alligator_apple barbadine capulin_cherry greater
0 6 3 1 4
1 7 19 9 1
2 15 25 15 0
3 5 12 27 3
```
To elaborate, at row 0 of `df2`, `df1.alligator_apple` has 4 rows which values are higher than `df2.alligator_apple` with the value of 6. `df1.barbadine` has 10 rows which values are higher than `df2.barbadine` with value of 3, while similarly `df1.capulin_cherry` has 10 rows.
Finally, apply an 'and' condition to all aforementioned conditions to get the number '4' of `df2.greater` of first row. Repeat for the rest of rows in `df2`.
Is there a simple way to do this?
|
2021/07/06
|
[
"https://Stackoverflow.com/questions/68276673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11133739/"
] |
I just had the same issue and fixed it. So, you probably installed jest globally on accident. In doing so, it likely ended up installed inside of `users/yourname/node-modules/`. If you can pull up a terminal, try doing a `cd` into `node-modules` from your home folder then do a `ls -a`. If you see `babel-jest`, do a `rm -r babel-jest` and `rm -r jest`. This fixed the problem for me. I'm running Linux, but the same strategy should work on Windows (not sure if the commands are exactly the same).
|
2,314,781 |
I have a class which sets an alarm but I need to set around 10 more of these alarms. Instead of duplicating classes, is there a way I can just make a new instance of the class and set the alarm time?
Here's my code.
```
import java.util.Calendar;
import java.lang.String;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.content.Intent;
import android.widget.Button;
import android.widget.Toast;
public class Alarm extends Activity {
/* for logging - see my tutorial on debuggin Android apps for more detail */
private static final String TAG = "SomeApp ";
protected Toast mToast;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setAlarm();
}
public void setAlarm() {
try {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, 0);
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 01);
cal.set(Calendar.SECOND, 0);
Intent intent = new Intent(Alarm.this, Alarm1.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 1234567, intent, 0);
PendingIntent sende2 = PendingIntent.getBroadcast(this, 123123, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender); // to be alerted 30 seconds from now
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sende2); // to be alerted 15 seconds from now
/* To show how alarms are cancelled we will create a new Intent and a new PendingIntent with the
* same requestCode as the PendingIntent alarm we want to cancel. In this case, it is 1234567.
* Note: The intent and PendingIntent have to be the same as the ones used to create the alarms.
*/
Intent intent1 = new Intent(Alarm.this, Alarm1.class);
PendingIntent sender1 = PendingIntent.getBroadcast(this, 1234567, intent1, 0);
AlarmManager am1 = (AlarmManager) getSystemService(ALARM_SERVICE);
am1.cancel(sender1);
} catch (Exception e) {
Log.e(TAG, "ERROR IN CODE:"+e.toString());
}
}
};
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Intent i = new Intent(getContext(),Alarm.class);
//Code below is from another class which is where im calling the alarm application
// ctx.startActivity (i);// start the Alarm class activity (class)public void onClick(View v) {
Alarm a = new Alarm ();
a.setAlarm();
b1.setText(prod);
}
});
```
The above code is from another class and on the button click the user can set a reminder (the buttom invokes the alarm class, the only to get it to work is using an intent. I simply tried to call the setAlarm method but that didn't work.
Maybe I could make a new instance of calendar and set the time in the button handler. Then I would have to pass that instance to the alarm class. Do you know if that would be possible?
|
2010/02/22
|
[
"https://Stackoverflow.com/questions/2314781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/264905/"
] |
Can't you just create one Calendar instance in onCreate(), set its parameters, then pass the instance to setAlarm(), modify the instance, call setAlarm(), etc, or am I missing something?
e.g. -
```
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, 0);
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 01);
cal.set(Calendar.SECOND, 0);
setAlarm(cal);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 30);
setAlarm(cal);
//etc
}
public void setAlarm(Calendar cal) {
try {
Intent intent = new Intent(Alarm.this, Alarm1.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 1234567, intent, 0);
PendingIntent sende2 = PendingIntent.getBroadcast(this, 123123, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender); // to be alerted 30 seconds from now
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sende2); // to be alerted 15 seconds from now
/* To show how alarms are cancelled we will create a new Intent and a new PendingIntent with the
* same requestCode as the PendingIntent alarm we want to cancel. In this case, it is 1234567.
* Note: The intent and PendingIntent have to be the same as the ones used to create the alarms.
*/
Intent intent1 = new Intent(Alarm.this, Alarm1.class);
PendingIntent sender1 = PendingIntent.getBroadcast(this, 1234567, intent1, 0);
AlarmManager am1 = (AlarmManager) getSystemService(ALARM_SERVICE);
am1.cancel(sender1);
} catch (Exception e) {
Log.e(TAG, "ERROR IN CODE:"+e.toString());
}
}
```
|
978,052 |
I have Alienware 15 R3 with:
* 512GB NVME SSD - Windows 10.
* 1TB HDD - 300GB free space available.
I would like to install Ubuntu using the free space available in 1TB HDD.
I have experience installing Dual Boot Ubuntu on my old laptop, but after a Windows 10 auto-update, the boot loader got corrupted.
So, how should I install Ubuntu without disturbing anything that links to Windows Boot?
|
2017/11/19
|
[
"https://askubuntu.com/questions/978052",
"https://askubuntu.com",
"https://askubuntu.com/users/136502/"
] |
I have been having this issue for a while and I found an answer to a similar questions [here](https://askubuntu.com/questions/31786/chrome-asks-for-password-to-unlock-keyring-on-startup#answer-968149) that seems to resolve this. In short, copy `google-chrome.desktop` file to your home folder and edit it to use the 'Basic' password storage setting:
```
cp /usr/share/applications/google-chrome.desktop ~/.local/share/applications/
```
Then look for the line that looks like this:
```
Exec=/usr/bin/google-chrome-stable %U
```
And change it to:
```
Exec=/usr/bin/google-chrome-stable --password-store=basic %U
```
I also had a number of files in the `~/.local/share/applications/` folder that looked like `Chrome-jdj94r5hsfjnfasdfsdfafp-Default.desktop` that seemed to have been placed there over time based on the timestamps but I deleted them all.
Saved passwords now show up immediately when the page is loaded.
|
9,970,713 |
I am having real trouble with provisioning and code signing issues. I have migrated to a new computer and have a bunch of "Valid signing identity not found" messages. In repeated attempts to fix distribution code signing I have managed to lose my developer code signing as well.
I am the first to admit that the root problem is my **complete and utter failure** to grasp the concepts of code signing, provisioning, and all related subjects. I am asking a [separate question](https://stackoverflow.com/questions/9970910/what-are-good-resources-other-than-apple-to-understand-certificates-code-sign) on SO to address this.
THIS question is to ask for concrete steps to wipe my provisioning and code signing mess completely clean. I am running Xcode 4.3 and have 2 live apps in the App Store that I do not want to interrupt the distribution of. Please help.
**Update:** I have imported my private key from the old mac, and it is showing in Keychain Access. When I try to request a certificate according to Apple docs, I don't get a "Let me specify key/value" checkbox, and when I try to save it to disk anyways I get the error "the specified item could not be found in the keychain". Arrgh.
|
2012/04/02
|
[
"https://Stackoverflow.com/questions/9970713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/401543/"
] |
**Step 1**: Open XCode. In the Organizer, delete all provisioning profiles.
**Step 2**: Open Keychain Access (Utilities>Keychain Access); delete all certificates related to developer/distribution and the WWDCCA (or whatever it's called) intermediate certificate.
**Step 3**: Re-download and resign. Make sure you export and import your private key from your old machine to your new one.
If you need instructions on how to set up code signing, you can look at my answer to this question: [Code Signing Error](https://stackoverflow.com/questions/9287401/code-signing-error/9287639#9287639).
Cheers!
|
57,362,904 |
I'll try to simplify my question:
I have a div container with a fixed height of 200px. Inside, I have a flexbox that shows vertical items. Each item has a FIXED height which should not change. I use `overflow: hidden` to prevent the last item to break out of that 200px. This works well.
**This is what I have with `overflow: hidden`**
[](https://i.stack.imgur.com/AIGU6.png)
**This is what I have without `overflow: hidden`**
[](https://i.stack.imgur.com/6C4VL.png)
But now, I'd like to take one step forward and prevent the rendering of the last item, if it's about to be cut and not displayed fully due to the container fixed height limitations and `overflow: hidden`
**This is what I really want, show only those items which are not cut fully or partially by the overflow: hidden;**
[](https://i.stack.imgur.com/JChAJ.png)
What's the best practice of achieving that? a kind of "**make sure all items fit in their fixed height inside the fixed height component and if one doesn't fit, don't show it at all**".
Using the lastest React. Probably doesn't matter but still.
I've made a small example here.
<https://jsfiddle.net/hfw1t2p0/>
Basically, I want to keep enforcing the 200px max height of the flexbox, but have some kind of automation that kills all elements which are partially or fully invisible, like items "4" and "5" in the example.
Please note the 200px flexbox height, and 50px item height are just examples. In reality, I need a flexbox that can weed out any item that doesn't fit fully in it... the max height of the flexbox or minimum height of elements is unknown until runtime.
|
2019/08/05
|
[
"https://Stackoverflow.com/questions/57362904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/282918/"
] |
First Thing : you should get benefits from using react:
To make Content Dynamically I'll add `gridItem` to state so that they're rendered dynamically.
```
state = {
items: [
"1",
"2",
"3",
" 4 I want this hidden, its partially visible",
"5 I want this hidden, its partially visible"
]
};
```
And For render:
```
render() {
return (
<div className="test">
<div className="gridContainer">
{this.state.items.map(el => {
return <div className="gridItem">{el}</div>;
})}
</div>
</div>
);
}
```
.
[First Demo](https://codesandbox.io/s/hungry-easley-kc88e)
Here is the Cool Part:
----------------------
Based on:
>
> Each item has a FIXED height which should not change
>
>
>
So that all items should have same height. The solution is to add:
1- ItemHeight
2- ContainerHeight
3-BorderWidth
to the state. Now with Some calculations + inline Styling You can achieve Your Goal:
first Your state will be:
```
state = {
containerHeight: 200, // referring to Container Height
gridHeight: 50, // referring to grid item Height
border: 1, // referring to border width
items: [
"1",
"2",
"3",
" 4 I want this hidden, its partially visible",
"5 I want this hidden, its partially visible"
]
};
```
in your `render()` method before return add this:
```
let ContHeight = this.state.containerHeight + "px";
let gridHeight = this.state.gridHeight + "px";
let border = this.state.border + "px solid green";
let gridStyle = {
maxHeight: ContHeight,
};
```
These are the same styles used in css but They're removed now from css and applied with inline styling.
`Container` will take it's max height property as:
```
<div className="gridContainer" style={gridStyle}> //gridStyle defined above.
```
let's see How `gridItems` will b e renderd:
```
//el for element, index for index of the element
{this.state.items.map((el, index) => {
// i now will start from 1 instead of 0
let i = index + 1,
// current height is calculating the height of the current item
// first item will be like: 1*50 + 1*1*2 = 52
// second item will be like: 2*50 + 2*1*2 = 104
// and so on
CurrentHeight =
i * this.state.gridHeight + i * this.state.border * 2,
// now we should determine if current height is larger than container height
// if yes: new Class "hidden" will be added.
// and in css we'll style it.
itemStyle =
CurrentHeight <= this.state.containerHeight
? "gridItem"
: "gridItem hidden";
return (
// YOU'RE A GOOD READER IF YOU REACHED HERE!
// now styleclass will be added to show-hide the item
// inline style will be added to make sure that the item will have same height, border-width as in state.
<div
className={itemStyle}
style={{ height: gridHeight, border: border }}
>
{el}
</div>
);
})}
```
Finally! in css add this:
```
.gridItem.hidden {
display: none;
}
```
[](https://i.stack.imgur.com/CJbRC.png)
**[Final Demo 1](https://codesandbox.io/s/affectionate-leaf-licnu)**
**[Final Demo 2 with 40px gridItem height](https://codesandbox.io/s/charming-snow-ig45r)**
**[Final Demo 3 with 300px container height](https://codesandbox.io/s/vigorous-yalow-h1zv5)**
|
16,602,277 |
I am trying to use the @Scheduled feature. I have followed [this](http://krams915.blogspot.com/2011/01/spring-3-task-scheduling-via.html) and [this](http://blog.springsource.com/2010/01/05/task-scheduling-simplifications-in-spring-3-0/) tutorials but I can not get my scheduled task to be executed.
I have created a worker:
```
@Component("syncWorker")
public class SyncedEliWorker implements Worker {
protected Logger logger = Logger.getLogger(this.getClass());
public void work() {
String threadName = Thread.currentThread().getName();
logger.debug(" " + threadName + " has began to do scheduled scrap with id=marketwatch2");
}
}
```
and a SchedulingService:
```
@Service
public class SchedulingService {
protected Logger logger = Logger.getLogger(this.getClass());
@Autowired
@Qualifier("syncWorker")
private Worker worker;
@Scheduled(fixedDelay = 5000)
public void doSchedule() {
logger.debug("Start schedule");
worker.work();
logger.debug("End schedule");
}
}
```
And tried different wiring in my applicationcontext.
The final version looks like:
```
<beans xmlns=...
xmlns:task="http://www.springframework.org/schema/task"
...
xsi:schemaLocation=" ..
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<context:annotation-config/>
<task:annotation-driven executor="taskExecutor" scheduler="taskScheduler"/>
<task:scheduler id="taskScheduler" pool-size="3"/>
<task:executor id="taskExecutor" pool-size="3"/>
... Other beans...
</beans>
```
The server starts up with out any errors.
Am I missing something?
|
2013/05/17
|
[
"https://Stackoverflow.com/questions/16602277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/162345/"
] |
`<context:annotation-config />` does not detect beans - it just processes the annotations on declared beans. Which means your `@Service` is not actually turned into a bean.
Use `<context:component-scan base-package="com.yourcomany" />` instead.
|
22,468,622 |
While using resque-scheduler to set\_schedule dynamic cron jobs based on user's input the schedules seem to be set but the worker never actually starts at the set schedule.
In the Resque configuration dynamic is set to true like so: Resque::Scheduler.dynamic = true
And I am setting the schedule like so:
```
name = business.name + '_employee_import'
config = {}
config[:class] = 'ImporterWorker'
config[:args] = business.id.to_s
config[:cron] = cron_converter
config[:persist] = true
Resque.set_schedule(name, config)
```
If I do in the command line:
```
Resque.get_schedule("business_employee_import")
```
I get:
```
{"class"=>"MyWorker", "args"=>"87", "cron"=>"19 18 * * * *"}
```
But come 6:19pm the worker does not start. I have a worker running but the job never gets picked up and I have no idea why or how to troubleshoot. It seems to me this should work. I have also tried updating resque-scheduler to the latest release, no luck yet.
Thanks for any help in advanced.
|
2014/03/18
|
[
"https://Stackoverflow.com/questions/22468622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/664675/"
] |
You probably forgot to start the scheduler with the `DYNAMIC_SCHEDULE` environment variable set to `true`.
Here is the command I use to start the scheduler:
```
DYNAMIC_SCHEDULE=true rake resque:scheduler
```
Quote from README:
>
> DYNAMIC\_SCHEDULE - Enables dynamic scheduling if non-empty (default
> false)
>
>
>
|
21,324,330 |
How can I get `[jobNo]` using loop from array below?
```none
Array
(
[date] => 2014-01-13
[totcomdraft] => 400
[comdraft] => 0
[0] => Array
(
[jobNo] => 1401018618
[dateType] => 1
[comdraft] => 200
)
[1] => Array
(
[jobNo] => 1401018615
[dateType] => 1
[comdraft] => 100
)
[2] => Array
(
[jobNo] => 1401018617
[dateType] => 1
[comdraft] => 100
)
)
```
|
2014/01/24
|
[
"https://Stackoverflow.com/questions/21324330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1325668/"
] |
Try this
```
foreach($array as $key=>$val){
if(is_array($val)){
echo $val["jobNo"];
echo "<br />";
}
}
```
|
4,404,711 |
The **differential equation** is the following:
$ydx+(\frac{y^2}{4}-2x)dy=0$
It can be written as:
$\frac{y}{2x-\frac{y^2}{4}}=\frac{dy}{dx}$
However, this is not the linear shape. So we rewrite the equation as:
$\frac{2x-\frac{y^2}{4}}{y}=\frac{dx}{dy}\to\frac{dx}{dy}-\frac{2x}{y}=-\frac{y}{4}$
The **integrating factor** is:
$e^{\int{\frac{-2dy}{y}}}=\frac{k}{y^2}$ and k can't be zero (1).
If you **apply the integrating factor** to the original equation you get:
$\frac{k}{y}dx+(\frac{k}{4}-\frac{-2xk}{y^2})dy=0$
According to the **definition of an exact differential equation**, it must be true that the partial derivative in Y of $\frac{k}{y}$ is equal to the partial derivative in X of $(\frac{k}{4}-\frac{-2xk}{y^2})$. This leaves us with the equality:
$\frac{-k}{y^2}=\frac{-2k}{y^2}$
So the only possible solution is $k=0$, but this a **contradiction** (1).
How is it possible? Am I making a mistake? How can I get an integrating factor other than zero?
|
2022/03/16
|
[
"https://math.stackexchange.com/questions/4404711",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/986528/"
] |
You can not just apply the integrating factor to the original equation. You need to apply it to the equation that you computed it for.
$$
\frac1{y^2}\frac{xy}{xy}-\frac{2x}{y^3}=-\frac1{4y}
$$
is nicely integrable.
|
24,398,937 |
I have a flask running at domain.com
I also have another flask instance on another server running at username.domain.com
Normally user logs in through domain.com
However, for paying users they are suppose to login at username.domain.com
Using flask, how can I make sure that sessions are shared between domain.com and username.domain.com while ensuring that they will only have access to the specifically matching username.domain.com ?
I am concerned about security here.
|
2014/06/25
|
[
"https://Stackoverflow.com/questions/24398937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2982246/"
] |
**EDIT:
Later, after reading your full question I noticed the original answer is not what you're looking for.**
I've left the original at the bottom of this answer for Googlers, but the revised version is below.
Cookies are automatically sent to subdomains on a domain (in most modern browsers the domain name must contain a period (indicating a TLD) for this behavior to occur). The authentication will need to happen as a pre-processor, and your session will need to be managed from a centralised source. Let's walk through it.
To confirm, I'll proceed assuming (from what you've told me) your setup is as follows:
* SERVER 1:
+ Flask app for domain.com
* SERVER 2:
+ Flask app for user profiles at username.domain.com
A problem that first must be overcome is storing the sessions in a location that is accessible to both servers. Since by default sessions are stored on disk (and both servers obviously don't share the same hard drive), we'll need to do some modifications to both the existing setup and the new Flask app for user profiles.
Step one is to choose where to store your sessions, a database powered by a DBMS such as MySQL, Postgres, etc. is a common choice, but people also often choose to put them somewhere more ephemeral such as Memcachd or Redis for example.
The short version for choosing between these two starkly different systems breaks down to the following:
**Database**
* Databases are readily available
* It's likely you already have a database implemented
* Developers usually have a pre-existing knowledge of their chosen database
**Memory (Redis/Memchachd/etc.)**
* Considerably faster
* Systems often offer basic self-management of data
* Doesn't incur extra load on existing database
You can find some examples database sessions in flask [here](https://stackoverflow.com/questions/17694469/flask-save-session-data-in-database-like-using-cookies) and [here](http://flask.pocoo.org/snippets/86/).
While Redis would be more difficult to setup depending on each users level of experience, it would be the option I recommend. You can see an example of doing this [here](http://flask.pocoo.org/snippets/75/).
The rest I think is covered in the original answer, part of which demonstrates the matching of username to database record (the larger code block).
**Old solution for a single Flask app**
Firstly, you'll have to setup Flask to handle subdomains, this is as easy as specifying a new variable name in your config file. For example, if your domain was example.com you would append the following to your Flask configuration.
```
SERVER_NAME = "example.com"
```
You can read more about this option [here](http://flask.pocoo.org/docs/config/).
Something quick here to note is that this will be extremely difficult (if not impossible) to test if you're just working off of localhost. As mentioned above, browsers often won't bother to send cookies to subdomains of a domain without dots in the name (a TLD). Localhost also isn't set up to allow subdomains by default in many operating systems. There are ways to do this like defining your own DNS entries that you can look into (`/etc/hosts` on \*UNIX, `%system32%/etc/hosts` on Windows).
Once you've got your config ready, you'll need to define a `Blueprint` for a subdomain wildard.
This is done pretty easily:
```
from flask import Blueprint
from flask.ext.login import current_user
# Create our Blueprint
deep_blue = Blueprint("subdomain_routes", __name__, subdomain="<username>")
# Define our route
@deep_blue.route('/')
def user_index(username):
if not current_user.is_authenticated():
# The user needs to log in
return "Please log in"
elif username != current_user.username:
# This is not the correct user.
return "Unauthorized"
# It's the right user!
return "Welcome back!"
```
The trick here is to make sure the `__repr__` for your user object includes a username key. For eg...
```
class User(db.Model):
username = db.Column(db.String)
def __repr__(self):
return "<User {self.id}, username={self.username}>".format(self=self)
```
Something to note though is the problem that arises when a username contains special characters (a space, @, ?, etc.) that don't work in a URL. For this you'll need to either enforce restrictions on the username, or properly escape the name first and unescape it when validating it.
If you've got any questions or requests, please ask. Did this during my coffee break so it was a bit rushed.
|
8,412,530 |
I have a hash with the following key/value pair
```
4 => model1
2 => model2
```
I want the following string created from the above hash
```
4 X model1 , 2 X model2
```
I tried the following
```
my %hash,
foreach my $keys (keys %hash) {
my $string = $string . join(' X ',$keys,$hash{$keys});
}
print $string;
```
What I get is
```
4 X model12Xmodel2
```
How can I accomplish the desired result `4 X model1 , 2 X model2`?
|
2011/12/07
|
[
"https://Stackoverflow.com/questions/8412530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/238021/"
] |
You could do:
```
my %hash = (4 => "model1", 2 => "model2");
my $str = join(", ", map { "$_ X $hash{$_}" } keys %hash);
print $str;
```
Output:
```
4 X model1, 2 X model2
```
How it works:
`map { expr } list` evaluates `expr` for every item in `list`, and returns the list that contains all the results of these evaluations. Here, `"$_ X $hash{$_}"` is evaluated for each key of the hash, so the result is a list of `key X value` strings. The `join` takes care of putting the commas in between each of these strings.
---
Note that your hash is a bit unusual if you're storing (item,quantity) pairs. It would usually be the other way around:
```
my %hash = ("model1" => 4, "model2" => 2);
my $str = join(", ", map { "$hash{$_} X $_" } keys %hash);
```
because with your scheme, you can't store the same quantity for two different items in your hash.
|
3,913,574 |
As the title implies, I want to compare two objects whose type may be diffrent.
For eg,
I expects 'true' for comparing 1000.0(Decimal) with 1000(Double) .
Similary, it should return true if I compare 10(string) and 10(double) .
I tried to compare using Object.Equals() , but it did NOT work.It return false if two objects have different data types.
```
Dim oldVal As Object ' assgin some value
Dim newVal As Object 'assgin some value
If Not Object.Equals(oldVal,newVal) Then
'do something
End If
```
**Edit:**
Could it be possible if I do the below?
```
1.check the type of oldVal
2.Covert the type of newVal to oldVal
3.Compare.
```
|
2010/10/12
|
[
"https://Stackoverflow.com/questions/3913574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364412/"
] |
Try this:
```
Dim oldVal As Object 'assgin some value
Dim newVal As Object 'assgin some value
Dim b As Boolean = False
If IsNumeric(oldVal) And IsNumeric(newVal) Then
b = (Val(oldVal) = Val(newVal))
ElseIf IsDate(oldVal) And IsDate(newVal) Then
b = (CDate(oldVal) = CDate(newVal))
Else
b = (oldVal.ToString() = newVal.ToString())
End If
If Not b Then
'do something
End If
```
Or use IIf like this:
```
If Not CBool(IIf(IsNumeric(oldVal) And IsNumeric(newVal),
(Val(oldVal) = Val(newVal)),
IIf(IsDate(oldVal) And IsDate(newVal),
(CDate(oldVal) = CDate(newVal)),
(oldVal.ToString() = newVal.ToString())))) Then
'do something
End If
```
|
49,748,378 |
I am currently creating a math's quiz for kids in python tkinter. In this quiz i have 3 different 'pages' as per say. A start page, a quiz page and a score page for when the quiz is finished. In my start page, i have three different difficulties of the quiz the user can choose from. How do i essentially clear elements of the window from the start page such as my label's and button's once that button "EASY" or "HARD" is clicked so i can start the quiz?
|
2018/04/10
|
[
"https://Stackoverflow.com/questions/49748378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9623512/"
] |
You could use a tabbed view and switch the tabs according to the difficulty selected (see tkinter notebooks <https://docs.python.org/3.1/library/tkinter.ttk.html#notebook>)
Or you could have the quiz in their selected difficulty in their own windows.
|
1,395 |
This question is for anyone who has learned programming in a Spanish speaking country.
Seeing as though the key words for programming languages like Java, C, Python etc are all in English I have a couple of questions:
* Do courses in Spanish speaking countries expect some knowledge of
English as a prerequisite?
* Do they teach you what English keywords mean?
* Are you taught to use English names for variables, classes, methods
etc or Spanish ones (Confusing?!)?
* Lastly, can you get/do you use, things like Javadocs in Spanish?
Thanks = )
|
2012/01/16
|
[
"https://spanish.stackexchange.com/questions/1395",
"https://spanish.stackexchange.com",
"https://spanish.stackexchange.com/users/312/"
] |
Keywords aren't changed and their meaning is explained. But almost everything else is in Spanish, because concepts are taught in Spanish and have their own Spanish terminology, and exercises reflect that. I mean, if the lesson was about trees or stacks, it would be taught in terms of "árboles" and "pilas", and the programs would have their classes "Arbol", "Nodo" and "Pila".
And the comments would also be in Spanish, because nobody is testing your English (neither you the teacher's!) but whether you understand what the code does and can explain it.
In a professional setting, I think, English is more prevalent. Especially now, when international teams are more common. When I last worked in a Spanish-speaking firm, some 10 years ago, we did almost everything is Spanish.
|
27,612,785 |
I have a bunch of different show times in a database and want to display the correct time based on the users time zone by creating an offset.
I'm getting the users time zone offset from GMT and converting that to hours first.
```
NSTimeZone.localTimeZone().secondsFromGMT / 60 / 60
```
Then I need to find a way to add the hours to the date object.. that is where I/m struggling.
```
let formatter = NSDateFormatter()
formatter.dateFormat = "HH:mm"
let date = formatter.dateFromString(timeAsString)
println("date: \(date!)")
```
Then I'm creating a string from the date to use in a label, to have it easy to read with the AM / PM.
```
formatter.dateFormat = "H:mm"
formatter.timeStyle = .ShortStyle
let formattedDateString = formatter.stringFromDate(date!)
println("formattedDateString: \(formattedDateString)")
```
I just can't seem to find out how to add/subtract hours. I've split the string up but it sometimes goes negative and won't work. Maybe I'm going about this wrong.
Thanks for any help.
Keith
|
2014/12/23
|
[
"https://Stackoverflow.com/questions/27612785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3712837/"
] |
If you want to convert a show time which is stored as a string in GMT, and you want to show it in the user's local time zone, you should *not* be manually adjusting the `NSDate`/`Date` objects. You should be simply using the appropriate time zones with the formatter. For example, in Swift 3:
```
let gmtTimeString = "5:00 PM"
let formatter = DateFormatter()
formatter.dateFormat = "h:mm a"
formatter.timeZone = TimeZone(secondsFromGMT: 0) // original string in GMT
guard let date = formatter.date(from: gmtTimeString) else {
print("can't convert time string")
return
}
formatter.timeZone = TimeZone.current // go back to user's timezone
let localTimeString = formatter.string(from: date)
```
Or in Swift 2:
```
let formatter = NSDateFormatter()
formatter.dateFormat = "h:mm a"
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) // original string in GMT
let date = formatter.dateFromString(gmtTimeString)
formatter.timeZone = NSTimeZone.localTimeZone() // go back to user's timezone
let localTimeString = formatter.stringFromDate(date!)
```
|
46,672 |
As a puzzle author, I often write puzzles with red ink and then test-solve them with pencil. What would be the most efficient way to remove the pencil and blue gridlines from the paper to leave only the red puzzle clues behind?
|
2015/01/31
|
[
"https://graphicdesign.stackexchange.com/questions/46672",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/26073/"
] |
As one who has typeset a thick mathematical book (written by various contributors), I would make two points in favour of Computer Modern.
First, the lower-case italic *v* and the lower-case Greek *ν* are clearly distinguished.
Second, parentheses rise higher than ascending letters, so that items in parentheses look more fully enclosed than in other fonts (e.g. Times Roman).
It is sometimes said that headings in Computer Modern make it too obvious that a document was typeset in (La)TeX. But this is easily overcome by setting headings in a contrasting font, e.g. using the "sectsty" package. When Computer Modern is used as a body font -- if I may lapse into opinion -- I find it reasonably neutral.
### P.S. (23 January 2020)
I typeset **[this paper](https://doi.org/10.5281/zenodo.3563468)** in a version of Computer Modern, using the `sectsty` package to set headings in sans-serif, plus the `helvet` package to change the standard sans-serif typeface to the Helvetica-like "Nimbus Sans L". The relevant lines from the preamble are:
```
⋮
\usepackage{cmlgc,amssymb,amsmath}
\DeclareTextCommandDefault{\textbullet}{\ensuremath{\bullet}}
\usepackage[scaled]{helvet}
\usepackage[T1]{fontenc}
⋮
\usepackage{sectsty}
\allsectionsfont{\sffamily\raggedright}
⋮
```
Notes:
* The appearance of the preview is somewhat browser-dependent; you might need to download the PDF in order to see it correctly.
* If your setup uses cm-super fonts by default (my latest setup doesn't), then you won't need the `cmlgc` package.
* *Mea culpa*: I was using the `cmlgc` version of Computer Modern for the first time, only to discover later that it does not scale optimally. If you use `lmodern` instead, you get a significant increase in the width, and a barely discernible increase in the darkness, of footnote-sized characters. One possible reason for using `lmodern` instead of cm-super is that `lmodern` gives a lower `\textasciitilde`.
* Modifying `\textbullet` sometimes gets rid of font-error messages.
* The `scaled` option to `helvet` adjusts the size so as to allow mixing with the serif font in text.
* The `\allsectionsfont` command, provided by `sectsty`, modifies all section headings at once (which is probably what you want).
* Yes, apparently `helvet` needs to come before `sectsty`.
|
86,573 |
I'm using Parallels on my mac. But when I open a software the font are so small, it's very weird. Can anyone help me out!!!

The picture above is when I open up my chrome, how can I fix it?
|
2013/03/24
|
[
"https://apple.stackexchange.com/questions/86573",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/26496/"
] |
I've seen this particular problem many times, and a lot of it has to do with how Windows handles DPI scaling.
Since you are using a Retina MBP - which has an extremely high resolution, you'll want Parallels to manage the DPI of your Windows VM. You can do this under your Virtual Machine's configuration, Hardware, Video Options, and select "Best for Retina".

The next time you reboot, Windows will have its DPI set to 199% (why not 200% I'm not sure).
The only trick to this is when you connect to an external display and you want to show your Parallels VM there. Windows can't change it's DPI without a full logout / login - so if you change displays you'll have to log out of Windows and log back in.
The next problem is that Windows does DPI scaling differently - *some programs do not respect Windows DPI scaling*. It's very bad practices for developers, but some of them always assume a fixed number of points-per-inch, like 96. Windows does its best to fix these issues by bitmap scaling the Window, and translating input, but it won't ever be perfect and it will look like a JPG that's 200% zoomed. It all depends on the program you are using. As unfortunate as it sounds, the best browser on Windows for retina resolution / DPI is Internet Explorer 10.
|
41,061 |
Older French texts often use defunct spellings, such as *-oi* instead of *-ai* in verb conjugations or spellings that contain consonants that were later dropped, like in *doubter*. When these texts are read aloud by modern French speakers, are these words read as if they were written with the modern spelling, or is there generally some attempt to pronounce the words according the old spelling? In other words, does one read *déchiroit* as *déchirait* and *laissoit* as *laissait* in the following?
>
> Pendant que la guerre civile déchiroit la France, sous le regne de Charles IX, l'amour ne laissoit pas de trouver sa place parmi tant de désordres, et d'en causer beaucoup dans son empire.
>
>
>
If yes, does this change with even older texts, where the text cannot be made to fit the conventions of modern French simply by modifying certain (relatively predictable) spellings? For example, at the beginning of *Roman de Fauvel*, does one read *Sui entrez en merencolie* (or *Sui entres en milencolie*, in some other versions) as *Suis entré en mélancolie*?
|
2020/01/27
|
[
"https://french.stackexchange.com/questions/41061",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/4082/"
] |
I'm no expert in old French so I can't tell you if we *should*, but we'd definitely pronounce it as it is written, but following the pronunciation rules of modern French.
So "*déchiroit*" would be pronounced as "*déchiroit*" and "*entrez*" as "*entré*". That's what a native would say naturally, but I have no idea if that's how they should.
I say "would" because it's really not something we do often, and it would most likely be in the context of studying old texts with a French or history professor (that could probably correct us). We'd be hesitant over the pronunciation of "*doubter*" (*b* or no *b*?) and it would be really hard to guess that "*Sui entres*" should be pronounced "*Suis entré*" (if that's the case).
Again, French speakers today don't know how to pronounce old French.
|
26,678,824 |
Whenever I run phpunit tests from PHPStorm I get an error. I have provided more info below. I am not sure where I have miss configured the setup.
### My Setup
* Ubuntu
* PHPStorm 8.0.1
* PHPUnit 4.3.4
### More Info:
PHPUnit.phar is located at `/usr/local/bin/phpunit.phar`. I have setup PHPUnit path directly in PHPStorm. Tests run from bash with no issues. I have also setup my configuration file `phpunit.xml` in PHPUnit, which is located in the root of my project. The `phpunit.xml` file tells phpunit to load the composer `autoload.php` file.
### PHPUnit Output:
```
/usr/bin/php -dxdebug.remote_enable=1 -dxdebug.remote_mode=req -dxdebug.remote_port=9000 -dxdebug.remote_host=127.0.0.1 /tmp/ide-phpunit.php --configuration /home/mkelley/projects/CompanyName/phpunit.xml
Testing started at 10:33 AM ...
PHPUnit 4.3.4 by Sebastian Bergmann.
Configuration read from /home/mkelley/projects/CompanyName/phpunit.xml
PHP Fatal error: Call to undefined method CompanyNameTests\Boundaries\BoardMemberVotingBoundaryTest::hasExpectationOnOutput() in phar:///usr/local/bin/phpunit.phar/phpunit/TextUI/ResultPrinter.php on line 545
PHP Stack trace:
PHP 1. {main}() /tmp/ide-phpunit.php:0
PHP 2. IDE_Base_PHPUnit_TextUI_Command::main($exit = *uninitialized*) /tmp/ide-phpunit.php:500
PHP 3. PHPUnit_TextUI_Command->run($argv = *uninitialized*, $exit = *uninitialized*) /tmp/ide-phpunit.php:243
PHP 4. PHPUnit_TextUI_TestRunner->doRun($suite = *uninitialized*, $arguments = *uninitialized*) phar:///usr/local/bin/phpunit.phar/phpunit/TextUI/Command.php:186
PHP 5. PHPUnit_Framework_TestSuite->run($result = *uninitialized*) /home/mkelley/projects/CompanName/vendor/phpunit/phpunit/src/TextUI/TestRunner.php:423
PHP 6. PHPUnit_Framework_TestSuite->run($result = *uninitialized*) /home/mkelley/projects/CompanName/vendor/phpunit/phpunit/src/Framework/TestSuite.php:703
PHP 7. PHPUnit_Framework_TestCase->run($result = *uninitialized*) /home/mkelley/projects/CompanName/vendor/phpunit/phpunit/src/Framework/TestSuite.php:703
PHP 8. PHPUnit_Framework_TestResult->run($test = *uninitialized*) /home/mkelley/projects/CompanName/vendor/phpunit/phpunit/src/Framework/TestCase.php:771
PHP 9. PHPUnit_Framework_TestResult->endTest($test = *uninitialized*, $time = *uninitialized*) /home/mkelley/projects/CompanName/vendor/phpunit/phpunit/src/Framework/TestResult.php:760
PHP 10. PHPUnit_TextUI_ResultPrinter->endTest($test = *uninitialized*, $time = *uninitialized*) /home/mkelley/projects/CompanyName/vendor/phpunit/phpunit/src/Framework/TestResult.php:378
Process finished with exit code 255
```
I have searched Google and was unable to find a similar issue. I appreciate any help!
### EDIT
Here is my phpunit.xml file. PHPStorm is using this as a "Use alternative configuration file"
```
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
colors="true"
bootstrap="./vendor/autoload.php"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
>
<testsuites>
<testsuite name="Application Test Suite">
<directory>./tests/</directory>
</testsuite>
</testsuites>
</phpunit>
```
|
2014/10/31
|
[
"https://Stackoverflow.com/questions/26678824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1301804/"
] |
This appears to be the autoloading issue. When you bootstrap your app for the test suite you must initialise your autoloader, which doesn't seem to be happening, as something doesn't get found. The easiest way would be to use Composer to manage the PHPUnit dependency and autoload your classes via the `autoload` directive. See the the `psr-4` part in [documentation](https://getcomposer.org/doc/01-basic-usage.md#autoloading).
Then in your PhpStorm PHPUnit configuration window select `Use custom autoloader` and specify path to your `vendor/autoload.php` script.
|
17,015 |
I have moved into a house with a nice Wolf-range griddle, and I would like to know what the primary advantages of the griddle are over a cast-iron skillet, including, is there anything I can do with a griddle that can not be done with a skillet?
I have found that the primary downside to using the griddle is the time it takes to heat up, so when cooking for one, I would choose the skillet. The primary advantage of the griddle is that it provides a larger, easier cooking space.
Am I missing other major advantages of having a griddle?
|
2011/08/21
|
[
"https://cooking.stackexchange.com/questions/17015",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/3418/"
] |
Yes, you don't have the edge of a pan in the way when going to flip things, but it also means that you don't have a mass of metal there to add as a heat sink, which can help dramatically when pre-heating your pans, as they'll be evenly heated across their bottom more quickly (at least, compared to something of the same material, such as a cast iron skillet)
More importantly, in my opinion, is that without the sides, you don't hold in moist air, so when cooking things like hash browns, you can get a better crust on 'em without steaming them.
|
11,368,204 |
I followed a tutorial/instructions online to make a sidebar fixed position by making the sidebars position "fixed" and it worked fine. Now I realize that since my page has a min-width attribute, when the user scrolls sideways the content that doesn't move moves into the sidebar. So basically, I'm looking for a way to produce a fixed sidebar when your scrolling down, but when you move sideways the content doesn't jump into the sidebar. My code is kind of like the following:
CSS
```
#sidebar {
position:fixed;
height:500px;
width: 100px;
background-color: blue;
}
#content {
width:100%;
box-sizing:border-box;
margin-left:100px;
background-color:purple;
}
```
Html
```
<div id="sidebar">
</div>
<div id="content">
</div>
```
JSFiddle: <http://jsfiddle.net/znCF3/1/>
NOTE: This is not my actually code but a minified version of it because my code is really complex. Also, I can't just use a fluid layout.
|
2012/07/06
|
[
"https://Stackoverflow.com/questions/11368204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1218699/"
] |
As said by others, not possible with only css and html. However, you can do this with javascript/jquery.
Just encase you want to use jquery to do this, first as watson said, change index of side bar (I had to make negative), just encase it jquery doesn't work for whatever reason for someone.
Then add to your `<head>`:
```
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
<!--
$(document).ready(function() {
$(window).scroll(function(){
var offSet = - ($(this).scrollLeft());
$('#sidebar').css('left', offSet);
});
});
//-->
</script>
```
[Example](http://jsfiddle.net/znCF3/3/)
|
9,453,761 |
I am debugging a website using firebug. The website opens a window, performs some operations and than closes it. This causes me to lose all of the firebug net history. Is there any way to prevent javastript from closing the window after its done, except changing the code?
|
2012/02/26
|
[
"https://Stackoverflow.com/questions/9453761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/847200/"
] |
I haven't tried to use it, but there's a settings in FF which supposedly lets you do what you wish.
Type about:config in the url bar and press enter. After a warning you'll see the list of config options. Search for dom.allow\_scripts\_to\_close\_windows and set its value to false.
|
35,047,356 |
I have a problem with a post\_save function. The function is correctly triggered but the instance doesn't contains the value insereted. I checked the function using ipdb and there is nothing wrong. Simply the ManyToManyField is empty.
The code:
```
@receiver(post_save, sender=Supplier)
def set_generic_locations(sender, instance, **kwargs):
""" Set the generic locations for the NEW created supplier.
"""
created = kwargs.get('created')
if created:
glocations = LocationAddress.get_generic_locations()
for location in glocations:
instance.locations.add(location)
instance.save()
```
The field used in the instance:
```
locations = models.ManyToManyField(LocationAddress, blank=True)
```
I don't understand why, but the locations is always empty.
I use django 1.8.8
UPDATE
------
The problem is the django admin. I found an explanation here: <http://timonweb.com/posts/many-to-many-field-save-method-and-the-django-admin/>
The code that solve the problem in the django admin
```
def save_related(self, request, form, formsets, change):
super(SupplierAdmin, self).save_related(request, form, formsets, change)
form.instance.set_generic_locations()
```
|
2016/01/27
|
[
"https://Stackoverflow.com/questions/35047356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1640213/"
] |
ManyToManyFields work a little bit differently with signals because of the difference in database structures. Instead of using the post\_save signal, you need to use the [m2m\_changed](https://docs.djangoproject.com/en/1.9/ref/signals/#m2m-changed) signal
|
69,617,819 |
When I search the internet for `react-native` optimizations / best practices (**Especially for `FlatLists` which are often greedy**), I always find the advice not to use the arrow functions `<Component onPress={() => ... }`.
*Example 1 :* <https://reactnative.dev/docs/optimizing-flatlist-configuration#avoid-anonymous-function-on-renderitem> :
>
> Move out the renderItem function to the outside of render function, so it won't recreate itself each time render function called. (...)
>
>
>
*Example 2 :* <https://blog.codemagic.io/improve-react-native-app-performance/> :
>
> Avoid Arrow Functions : Arrow functions are a common culprit for wasteful re-renders. Don’t use arrow functions as callbacks in your functions to render views (...)
>
>
>
*Example 3 :* <https://medium.com/wix-engineering/dealing-with-performance-issues-in-react-native-b181d0012cfa> :
>
> Arrow functions is another usual suspect for wasteful re-renders. Don’t use arrow functions as callbacks (such as click/tap) in your render functions (...)
>
>
>
I understand that it is recommended not to use arrow function (especially in `onPress` button and `FlatList`), and to put the components outside of the render if possible.
**Good practice example :**
```
const IndexScreen = () => {
const onPress = () => console.log('PRESS, change state, etc...')
return (
<>
<Button
onPress={onPress}
/>
<FlatList
...
renderItem={renderItem}
ListFooterComponent={renderFooter}
/>
</>
)
}
const renderItem = ({ item: data }) => <Item data={data} ... />
const renderFooter = () => <Footer ... />
export default IndexScreen
```
But, often, I have other properties to integrate into my child components. The arrow function is therefore mandatory:
```
const IndexScreen = () => {
const otherData = ...(usually it comes from a useContext())...
<FlatList
...
renderItem={({ item: data }) => renderItem(data, otherData)}
/>
}
const renderItem = (data, otherData) => <Item data={data} otherData={otherData} />
export default IndexScreen
```
In the latter situation, are good practices followed despite the presence of an arrow function ?
In summary, if I remove `otherData` (for simplicity), are these two situations strictly identical and are good practices followed ?
**Situation 1 :**
```
const IndexScreen = () => {
return (
<FlatList
...
renderItem={renderItem}
/>
)
}
const renderItem = ({ item: data }) => <Item data={data} ... />
export default IndexScreen
```
**=== Situation 2 ?**
```
const IndexScreen = () => {
return (
<FlatList
...
renderItem={({ item: data }) => renderItem(data)}
/>
)
}
const renderItem = (data) => <Item data={data} ... />
export default IndexScreen
```
|
2021/10/18
|
[
"https://Stackoverflow.com/questions/69617819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3197378/"
] |
The answer has nothing to do with arrow functions, but rather understanding reference equality why react might decide to rerender a component.
You can use useCallback to wrap your function. This will cause the reference to renderItem to only update when one of your callback dependencies updates.
```
const renderItem = useCallback(()=>{
...
},
[otherdata]);
```
|
49,170,893 |
i am creating an angular table using this example from angular material <https://material.angular.io/components/table/overview> is there anyway to export it in excel or pdf?
|
2018/03/08
|
[
"https://Stackoverflow.com/questions/49170893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6280170/"
] |
In your table component.ts
declare a value called
`renderedData: any;`
Then in your constructor subscribe to the data that has been changed in your material table. I am guessing you are using a filterable table.
```
constructor(){
this.dataSource = new MatTableDataSource(TableData);
this.dataSource.connect().subscribe(d => this.renderedData = d);
}
```
`npm install --save angular5-csv`
In your HTML create a button
`<button class="btn btn-primary" (click)="exportCsv()">Export to CSV</button>`
Finally, export the changed data to a CSV
```
exportCsv(){
new Angular5Csv(this.renderedData,'Test Report');
}
```
More details about the exporter can be found here: <https://www.npmjs.com/package/angular5-csv>
I hope this helps :)
|
20,932,644 |
I have the following [example](http://jsbin.com/ohonaYu/1/edit):
```
<div class="container">
<div class="left"></div>
<div class="right">
<span class="number">1</span>
<span class="number">2</span>
</div>
</div>
```
As you can see in the code above left div in not vertically aligned:
But if I remove float: right then left div gets vertically aligned well: [example](http://jsbin.com/ohonaYu/2/edit)

Please help me how could I make vertical align left div with right float right div?
**EDIT**: Could you provide a solution without padding, margin, top, left etc?
|
2014/01/05
|
[
"https://Stackoverflow.com/questions/20932644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1006884/"
] |
How about
```
select * from `post_plus` left join `post` on `post`.`id` = `post_plus`.`news_id` where `post`.`id` IS NULL
```
|
28,318,912 |
I need to write several formulas in CSS (or is there some other way?) and integrate it on my quiz website for students.
I already found some interesting examples in here:
<http://www.periodni.com/mathematical_and_chemical_equations_on_web.html>
But I need one more, as can be seen in this picture:
[](http://www.docbrown.info/page15/Image166.gif)
|
2015/02/04
|
[
"https://Stackoverflow.com/questions/28318912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4527585/"
] |
I upvoted Nplay comment, easychem seems really fun.
Filthy, dirty way to achieve it with HTML (don't try this at home please) :
```html
<p>
<span style="visibility: hidden;">CH<sub>3</sub> - </span>CH<sub>3</sub><br/>
<span style="visibility: hidden;">CH<sub>3</sub> - </span>|<br/>
CH<sub>3</sub> - C - CH<sub>3</sub><br/>
<span style="visibility: hidden;">CH<sub>3</sub> - </span>|<br/>
<span style="visibility: hidden;">CH<sub>3</sub> - </span>CH<sub>3</sub><br/>
</p>
```
|
60,553,264 |
I need to compare the roman letters and get the correct integer out of it.
If I'm correct, there should be a way to compare the hashmap key with the arraylist element and if they match, get the associated value from the key.
The return 2020 is there just for test purposes, since I wrote a JUnit test in a different class. It can be ignored for now.
I hope someone could give me a hint, since I wouldn't like to use the solutions from the web, because I need to get better with algorithms.
```
package com.company;
import java.util.*;
public class Main {
static HashMap<String, Integer> romanNumbers = new HashMap<String, Integer>();
static {
romanNumbers.put("I", 1);
romanNumbers.put("V", 5);
romanNumbers.put("X", 10);
romanNumbers.put("L", 50);
romanNumbers.put("C", 100);
romanNumbers.put("D", 500);
romanNumbers.put("M", 1000);
}
public static void main(String[] args) {
romanToArabic("MMXX");
}
static int romanToArabic(String roman) {
ArrayList romanLetters = new ArrayList();
roman = roman.toUpperCase();
for (int i = 0; i < roman.length(); i++) {
char c = roman.charAt(i);
romanLetters.add(c);
}
// [M, M, X, X]
System.out.println(romanLetters);
// iterates over the romanLetters
for (int i = 0; i < romanLetters.size(); i++) {
System.out.println(romanLetters.get(i));
}
// retrive keys and values
for (Map.Entry romanNumbersKey : romanNumbers.entrySet()) {
String key = (String) romanNumbersKey.getKey();
Object value = romanNumbersKey.getValue();
System.out.println(key + " " + value);
}
return 2020;
}
}
```
|
2020/03/05
|
[
"https://Stackoverflow.com/questions/60553264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13014882/"
] |
The retry policy for App Store server notifications depends on the version of the server notification. It retries as follows:
>
> * For version 1 notifications, it retries three times; at 6, 24, and 48 hours after the previous attempt.
> * For version 2 notifications, it retries five times; at 1, 12, 24, 48, and 72 hours after the previous attempt.
>
>
>
See [here](https://developer.apple.com/documentation/appstoreservernotifications/responding_to_app_store_server_notifications) for details.
|
41,433,932 |
I'm interested in instantiating a pool of workers, `the_pool`, using `multiprocessing.Pool` that uses a `Queue` for communication. However, each worker has an argument, `role`, that is unique to that worker and needs to be provided during worker initialization. This constraint is imposed by an API I'm interfacing with, and so cannot be worked around. If I didn't need a Queue, I could just iterate over a list of `role` values and invoke `apply_async`, like so:
```
[the_pool.apply_async(worker_main, role) for role in roles]
```
Unfortunately, `Queue` object can only be passed to pools during pool instantiation, as in:
```
the_pool = multiprocessing.Pool(3, worker_main, (the_queue,))
```
Attempting to pass a `Queue` via the arguments to `apply_async` causes a runtime error. In the following example, adapted from [this question](https://stackoverflow.com/questions/41413055/how-might-i-launch-each-worker-in-a-multiprocessing-pool-in-a-new-shell), we attempt to instantiate a pool of three workers. But the example fails, because there is no way to get a role element from `roles` into the `initargs` for the pool.
```
import os
import time
import multiprocessing
# A dummy function representing some fixed functionality.
def do_something(x):
print('I got a thing:', x)
# A main function, run by our workers. (Remove role arg for working example)
def worker_main(queue, role):
print('The worker at', os.getpid(), 'has role', role, ' and is initialized.')
# Use role in some way. (Comment out for working example)
do_something(role)
while True:
# Block until something is in the queue.
item = queue.get(True)
print(item)
time.sleep(0.5)
if __name__ == '__main__':
# Define some roles for our workers.
roles = [1, 2, 3]
# Instantiate a Queue for communication.
the_queue = multiprocessing.Queue()
# Build a Pool of workers, each running worker_main.
# PROBLEM: Next line breaks - how do I pass one element of roles to each worker?
the_pool = multiprocessing.Pool(3, worker_main, (the_queue,))
# Iterate, sending data via the Queue.
[the_queue.put('Insert useful message here') for _ in range(5)]
worker_pool.close()
worker_pool.join()
time.sleep(10)
```
One trivial work-around is to include a second `Queue` in `initargs` which only serves to communicate the role of each worker, and block the workers execution until it receives a role via that queue. This, however, introduces an additional queue that should not be necessary. Relevant documentation is [here](https://docs.python.org/2/library/multiprocessing.html). Guidance and advice is greatly appreciated.
|
2017/01/02
|
[
"https://Stackoverflow.com/questions/41433932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3417688/"
] |
Why not use two worker functions, one for just for initialization? Like:
```
def worker_init(q):
global queue
queue = q
def worker_main(role):
# use the global `queue` freely here
```
Initialization is much the same as what you showed, except call `worker_init`:
```
the_pool = multiprocessing.Pool(3, worker_init, (the_queue,))
```
Initialization is done exactly once per worker process, and each process persists until the `Pool` terminates. To get work done, do exactly what you wanted to do:
```
[the_pool.apply_async(worker_main, role) for role in roles]
```
There's no need to pass `the_queue` too - each worker process already learned about it during initialization.
|
74,378,006 |
I do host a gitea server and access git via https. The certificate is **not** self-signed, but from a proper CA, User Trust (<https://www.tbs-certificates.co.uk/FAQ/en/racine-USERTrustRSACertificationAuthority.html>).
I'm using the latest git client for windows (2.38.1, 64bit)
When i do a `git pull`, the error `unable to get local issuer certificate` is shown.
[](https://i.stack.imgur.com/jVkdg.png)
I do understand that git by default uses openssl and the certificate list via the file **ca-bundle.trust** for validating certificates.
The strange thing is that git actually contains the root certificate, but it's not exactly the same. The certificate which is part of the ca-bundle.trust file has some additional content (Marked in green)
[](https://i.stack.imgur.com/F1Z1Z.png)
When i compare the properties of the two certificates, i don't see any difference, but i assume this is the reason why git does reject the certificate.
Certificates in case someone wants to have a look at it:
Official User Trust root certificate
====================================
```
-----BEGIN CERTIFICATE-----
MIIF3jCCA8agAwIBAgIQAf1tMPyjylGoG7xkDjUDLTANBgkqhkiG9w0BAQwFADCB
iDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl
cnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV
BAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAw
MjAxMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNV
BAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVU
aGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBSU0EgQ2Vy
dGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK
AoICAQCAEmUXNg7D2wiz0KxXDXbtzSfTTK1Qg2HiqiBNCS1kCdzOiZ/MPans9s/B
3PHTsdZ7NygRK0faOca8Ohm0X6a9fZ2jY0K2dvKpOyuR+OJv0OwWIJAJPuLodMkY
tJHUYmTbf6MG8YgYapAiPLz+E/CHFHv25B+O1ORRxhFnRghRy4YUVD+8M/5+bJz/
Fp0YvVGONaanZshyZ9shZrHUm3gDwFA66Mzw3LyeTP6vBZY1H1dat//O+T23LLb2
VN3I5xI6Ta5MirdcmrS3ID3KfyI0rn47aGYBROcBTkZTmzNg95S+UzeQc0PzMsNT
79uq/nROacdrjGCT3sTHDN/hMq7MkztReJVni+49Vv4M0GkPGw/zJSZrM233bkf6
c0Plfg6lZrEpfDKEY1WJxA3Bk1QwGROs0303p+tdOmw1XNtB1xLaqUkL39iAigmT
Yo61Zs8liM2EuLE/pDkP2QKe6xJMlXzzawWpXhaDzLhn4ugTncxbgtNMs+1b/97l
c6wjOy0AvzVVdAlJ2ElYGn+SNuZRkg7zJn0cTRe8yexDJtC/QV9AqURE9JnnV4ee
UB9XVKg+/XRjL7FQZQnmWEIuQxpMtPAlR1n6BB6T1CZGSlCBst6+eLf8ZxXhyVeE
Hg9j1uliutZfVS7qXMYoCAQlObgOK6nyTJccBz8NUvXt7y+CDwIDAQABo0IwQDAd
BgNVHQ4EFgQUU3m/WqorSs9UgOHYm8Cd8rIDZsswDgYDVR0PAQH/BAQDAgEGMA8G
A1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAFzUfA3P9wF9QZllDHPF
Up/L+M+ZBn8b2kMVn54CVVeWFPFSPCeHlCjtHzoBN6J2/FNQwISbxmtOuowhT6KO
VWKR82kV2LyI48SqC/3vqOlLVSoGIG1VeCkZ7l8wXEskEVX/JJpuXior7gtNn3/3
ATiUFJVDBwn7YKnuHKsSjKCaXqeYalltiz8I+8jRRa8YFWSQEg9zKC7F4iRO/Fjs
8PRF/iKz6y+O0tlFYQXBl2+odnKPi4w2r78NBc5xjeambx9spnFixdjQg3IM8WcR
iQycE0xyNN+81XHfqnHd4blsjDwSXWXavVcStkNr/+XeTWYRUc+ZruwXtuhxkYze
Sf7dNXGiFSeUHM9h4ya7b6NnJSFd5t0dCy5oGzuCr+yDZ4XUmFF0sbmZgIn/f3gZ
XHlKYC6SQK5MNyosycdiyA5d9zZbyuAlJQG03RoHnHcAP9Dc1ew91Pq7P8yF1m9/
qS3fuQL39ZeatTXaw2ewh0qpKJ4jjv9cJ2vhsE/zB+4ALtRZh8tSQZXq9EfX7mRB
VXyNWQKV3WKdwrnuWih0hKWbt5DHDAff9Yk2dDLWKMGwsAvgnEzDHNb842m1R0aB
L6KCq9NjRHDEjf8tM7qtj3u1cIiuPhnPQCjY/MiQu12ZIvVS5ljFH4gxQ+6IHdfG
jjxDah2nGN59PRbxYvnKkKj9
-----END CERTIFICATE-----
```
Root certificate which is part of the ca-bundle.trust file from git
===================================================================
```
-----BEGIN TRUSTED CERTIFICATE-----
MIIF3jCCA8agAwIBAgIQAf1tMPyjylGoG7xkDjUDLTANBgkqhkiG9w0BAQwFADCB
iDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl
cnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV
BAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAw
MjAxMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNV
BAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVU
aGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBSU0EgQ2Vy
dGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK
AoICAQCAEmUXNg7D2wiz0KxXDXbtzSfTTK1Qg2HiqiBNCS1kCdzOiZ/MPans9s/B
3PHTsdZ7NygRK0faOca8Ohm0X6a9fZ2jY0K2dvKpOyuR+OJv0OwWIJAJPuLodMkY
tJHUYmTbf6MG8YgYapAiPLz+E/CHFHv25B+O1ORRxhFnRghRy4YUVD+8M/5+bJz/
Fp0YvVGONaanZshyZ9shZrHUm3gDwFA66Mzw3LyeTP6vBZY1H1dat//O+T23LLb2
VN3I5xI6Ta5MirdcmrS3ID3KfyI0rn47aGYBROcBTkZTmzNg95S+UzeQc0PzMsNT
79uq/nROacdrjGCT3sTHDN/hMq7MkztReJVni+49Vv4M0GkPGw/zJSZrM233bkf6
c0Plfg6lZrEpfDKEY1WJxA3Bk1QwGROs0303p+tdOmw1XNtB1xLaqUkL39iAigmT
Yo61Zs8liM2EuLE/pDkP2QKe6xJMlXzzawWpXhaDzLhn4ugTncxbgtNMs+1b/97l
c6wjOy0AvzVVdAlJ2ElYGn+SNuZRkg7zJn0cTRe8yexDJtC/QV9AqURE9JnnV4ee
UB9XVKg+/XRjL7FQZQnmWEIuQxpMtPAlR1n6BB6T1CZGSlCBst6+eLf8ZxXhyVeE
Hg9j1uliutZfVS7qXMYoCAQlObgOK6nyTJccBz8NUvXt7y+CDwIDAQABo0IwQDAd
BgNVHQ4EFgQUU3m/WqorSs9UgOHYm8Cd8rIDZsswDgYDVR0PAQH/BAQDAgEGMA8G
A1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAFzUfA3P9wF9QZllDHPF
Up/L+M+ZBn8b2kMVn54CVVeWFPFSPCeHlCjtHzoBN6J2/FNQwISbxmtOuowhT6KO
VWKR82kV2LyI48SqC/3vqOlLVSoGIG1VeCkZ7l8wXEskEVX/JJpuXior7gtNn3/3
ATiUFJVDBwn7YKnuHKsSjKCaXqeYalltiz8I+8jRRa8YFWSQEg9zKC7F4iRO/Fjs
8PRF/iKz6y+O0tlFYQXBl2+odnKPi4w2r78NBc5xjeambx9spnFixdjQg3IM8WcR
iQycE0xyNN+81XHfqnHd4blsjDwSXWXavVcStkNr/+XeTWYRUc+ZruwXtuhxkYze
Sf7dNXGiFSeUHM9h4ya7b6NnJSFd5t0dCy5oGzuCr+yDZ4XUmFF0sbmZgIn/f3gZ
XHlKYC6SQK5MNyosycdiyA5d9zZbyuAlJQG03RoHnHcAP9Dc1ew91Pq7P8yF1m9/
qS3fuQL39ZeatTXaw2ewh0qpKJ4jjv9cJ2vhsE/zB+4ALtRZh8tSQZXq9EfX7mRB
VXyNWQKV3WKdwrnuWih0hKWbt5DHDAff9Yk2dDLWKMGwsAvgnEzDHNb842m1R0aB
L6KCq9NjRHDEjf8tM7qtj3u1cIiuPhnPQCjY/MiQu12ZIvVS5ljFH4gxQ+6IHdfG
jjxDah2nGN59PRbxYvnKkKj9MD0wFAYIKwYBBQUHAwQGCCsGAQUFBwMBDCVVU0VS
VHJ1c3QgUlNBIENlcnRpZmljYXRpb24gQXV0aG9yaXR5
-----END TRUSTED CERTIFICATE-----
```
Question
========
* Why does git not have the exact same root certificate as the one from User Trust?
* What is in the additional content in the certificate file?
Answer
======
As mentioned in a comment by user "qwerty 1999", the command `git config --global http.sslbackend schannel` can be used to force git to use the windows certificate store which solves my problem since the "User Trust" root certificate is part of the certificate store by default.
I still don't understand why git doesn't use the root certificate provided by "User Trust CA". This would avoid having to apply this workaround.
|
2022/11/09
|
[
"https://Stackoverflow.com/questions/74378006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1155873/"
] |
Make a typed getter so it has proper type and you don't have to store it
```
abstract class AbstractView {
get ctx(): typeof AbstractView {
return this.constructor as typeof AbstractView;
}
static getStatus() : string
{
return 'hi';
}
}
class TestView extends AbstractView {
static getStatus() : string
{
return 'hi2';
}
}
console.log(new TestView().ctx.getStatus())
// > "hi2"
```
<https://www.typescriptlang.org/play?#code/FAQwRgzgLgTiDGUAE8A2IISQQUrBUAagJYCmA7kgN7BJ1IDmpyiAHgBQCUAXElAJ4AHUgHsAZjjxxEJCtVr1FMZgFcYAOz4ALYhAB08EeugwViETCQY+Q0RNwmCs8gG4FdAL7uk0EFGLwjMwAylB+KhBcSLwmxOoM3jSKSqoaSADkOuluil5eaBhYACqk0M5IpKxQpOoAJlgO+DJklEn0vv6BTFCh4ZGc0T6wcQmKbclIylBqmpnEAEzZ3nnAwIbGIqikeqgiDOzqciVlLVwGUKx63b3T-ZxAA>
|
8,927 |
I work in a small but growing team of UX designers developing a suite of web applications. It's become obvious that we would benefit from a common pattern library, but are unsure how to get started or what tool we should use.
We want something that we can collaborate on and also share with visual designers and developers - so adding detail such as notes, graphics and snippets of code would be useful.
Has anyone had experience of building a library like this, do you have any tips or recommendations?
|
2011/07/12
|
[
"https://ux.stackexchange.com/questions/8927",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/4500/"
] |
There are several [design pattern repositories listed on Konigi web](http://konigi.com/wiki/design-pattern-repositories). From these, [Patternry](http://patternry.com/) allows you to create public and private collections of patterns.
|
49,109 |
From death to brittleness?
Two bodies, on a bed, in an embrace. Windows and doors closed, so little to no air and light, but not completely air/light tight.
No scavenger animals/rodents, but bugs would obviously be present.
Humid (tropical rain-forest) environment.
The aim is to have my characters stumble across this old castle, and find the bones of two people on the bed. I don't care if the bones are touched they would fall to dust, or if they are moved slightly/disturbed by bugs, or even if some of the bones are dust already, as long as it can be made out that its two skeletons embraced together. (and if not clearly embraced, its at least clear that its two skeletons)
(i know "dust" isn't the appropriate term here, but you get what I mean?)
How many years could this take?
Thankyou
EDIT: Just wanted to re-iterate, I don't so much care about the decomposing bodily fluids and flesh. I know that will decompose and be eaten by bugs and will stain the sheets upon decomposition.
I know that mummification is out, as of the humidity.
I'm wanting to know what happens to the BONES well after the process of rotting flesh is done. I know the joints wont stay together, and I know that the bugs will move the bones around a bit if they are eating the flesh. But say that, after a month or so of the people being dead, their bones would still be on the bed, and it would be obvious that two people were on the bed together, even if not embracing?
how long would it take before their bones became so fragile and brittle that they would turn to "dust." or upon discovery of the bones, and disturbing the bones, would they disintegrate to dust upon a rush or air or a touch of hand?
|
2016/07/31
|
[
"https://worldbuilding.stackexchange.com/questions/49109",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/21849/"
] |
Okay, there's not much data on timescales of human bones decaying away to nothing, because we bury/ cremate our dead. Also when folk come across a pile of bones, they tend to phone the police. So you might have to look at studies of animal bones and extrapolate from that. The search term you'll need is [taphonomy](https://en.wikipedia.org/wiki/Taphonomy). That's the science of death and decay (and fossilisation).
The stages of bone decay are as follows. This scale was invented by Dr Clive Trueman and is based on British chocolates and biscuits, so apologies to those not familiar with them.
1. Fresh bone. The bone is just like one you get from the butcher's for your dog.
2. The [Crunchie](https://en.wikipedia.org/wiki/Crunchie#/media/File:Crunchie_bar.jpg). The bone has dried out but still has a smooth outer cortex. If you split it open it has a 'honeycomb' cellular structure, like in life.
3. The [Ripple](http://thecandybitch.com/galaxy-ripple/). The bone still looks normal from the outside, with the outer cortex still intact. However, inside it is starting to recrystallise.
4. The [Flake](https://en.wikipedia.org/wiki/Flake_(chocolate_bar)). The outer cortex has gone and the recrystallisation is complete. The bone has a crumbly texture and will fall to pieces if you pick it up or handle it roughly.
5. The soggy digestive biscuit. The bone is reduced to lumps of mush.
6. Only a chemical analysis of the soil it was lying on can now detect that the bone was there at all.
Not the same environment as your bones, but animal bones in Amboseli National Park [decayed beyond recognition in 10 to 15 years](http://journals.cambridge.org/action/displayAbstract?fromPage=online&aid=9669155&fileId=S0094837300005820). These bones are out in the open air. I'd say that's the fast end of the scale for bone disappearance.
Here's another paper where bones in Amboselli [are there for at least 26 to 40 years](https://www.researchgate.net/profile/Clive_Trueman/publication/222557629_Mineralogical_and_compositional_changes_in_bones_exposed_on_soil_surfaces_in_Amboseli_National_Park_Kenya_Diagenetic_mechanisms_and_the_role_of_sediment_pore_fluids/links/02bfe50ffbfee2930f000000.pdf).
This [paper on bone decay in different environments](http://onlinelibrary.wiley.com/doi/10.1002/oa.2275/abstract) looks as if it has useful data, but you'll have to pay to get beyond the abstract.
So, your case has humidity, which will speed bone decay as fungi and bacteria get at them, but is indoors, so it won't be as fast as the Amboseli examples. If it is tropical rainforest climate humidity things will decay a lot faster than cold, damp UK humidity.
Given that there are caves full of ice age cave bear bones, your skeletons can survive for thousands of years if you want them to. Or crumble if that fits the story better.
|
102,279 |
I am trying to solve the recurrence below but I find myself stuck.
$T(n) = \frac{n}{2}T(\frac{n}{2}) + \log n$
I have tried coming up with a guess by drawing a recurrence tree. What I have found is
number of nodes at a level: $\frac{n}{2^{i}}$
running time at each node: $\log \frac{n}{2^{i}}$
total running time at each level: $\frac{n}{2^{i}} \log \frac{n}{2^{i}}$
I try to sum this over through n > $\log n$ which is the height of the tree
$$\begin{align}
\sum\limits\_{i=0}^n \frac{n}{2^{i}} \log \frac{n}{2^{i}}&=
n \sum\limits\_{i=0}^n \frac{1}{2^{i}} \log \frac{n}{2^{i}}\\
&=n \sum\limits\_{i=0}^n \frac{1}{2^{i}} (\log n - \log 2^{i})\\
&=n \sum\limits\_{i=0}^n \frac{1}{2^{i}} \log n - \sum\limits\_{i=0}^n \frac{1}{2^{i}} \log 2^{i}\\
&=n \sum\limits\_{i=0}^n \frac{1}{2^{i}} \log n - \sum\limits\_{i=0}^n \frac{ \log 2^{i}}{2^{i}}\\
&=n \sum\limits\_{i=0}^n \frac{1}{2^{i}} \log n - d \sum\limits\_{i=0}^n \frac{i}{2^{i}}\\
&=2 n \log n - d \sum\limits\_{i=0}^n \frac{i}{2^{i}}
\end{align}$$
I am still trying to figure out the sum of the second summation above but I somehow feel that it will be bigger than $2n \log n$ which makes my whole approach wrong.
Is there another way to tackle this problem?
|
2012/01/25
|
[
"https://math.stackexchange.com/questions/102279",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/14078/"
] |
Consider the equality
$$
1+x+x^2+...+x^n=\frac{x^{n + 1} -1}{x-1}
$$
Differentiate it by $x$, then multiply by $x$:
$$
x+2x^2+3x^3+...+n x^n=\frac{nx^{n+2} - (n + 1)x^{n+1} + x}{(x-1)^2}
$$
Now we can substitute $x=\frac{1}{2}$ and obtain
$$
\sum\limits\_{i=0}^n\frac{i}{2^i}=n\left(\frac{1}{2}\right)^{n} - (n + 1)\left(\frac{1}{2}\right)^{n-1} + 2
$$
|
13,383 |
I need a web based project management software. It should basically have:
* Issue tracker
* Wiki (not mandatory)
* Git integration
* Progress
It should be open source and I should be able to install it onto my server.
Currently, I have found the following options :
* [ProjeQtOr](http://www.projeqtor.org/)
* [MyCollab](http://community.mycollab.com/)
Is there anyone who tested one of those software? I'm also open to any other suggestion.
|
2014/10/22
|
[
"https://softwarerecs.stackexchange.com/questions/13383",
"https://softwarerecs.stackexchange.com",
"https://softwarerecs.stackexchange.com/users/8417/"
] |
I'd recommend using **[Trac](http://trac.edgewall.org/)** (for details and screenshots, see my answers [here](https://softwarerecs.stackexchange.com/a/7501/185) and [here](https://softwarerecs.stackexchange.com/a/1560/185). Trac fulfills all your requirements listed:
* **Issue tracker:** Yes.
* **Wiki:** Yes.
* **GIT integration:** Yes, also other VCSs as e.g. SVN or Mercurial are supported. For Git, there's even integration with Github.
* **Progress:** Yes, via multiple plugins you can even chose what fits you best.
* **Self-hosted:** Definitely, that's what I use. Requirements are at least Python and a web server supporting Python; setup is not that difficult using Apache.
A setup [guide for use with SVN can be found on my server](http://www.izzysoft.de/software/ifaqmaker.php?id=1). You can skip the SVN part and take a look at [Installing Trac](http://www.izzysoft.de/software/ifaqmaker.php?id=1;toc=1;topic=trac_install) and [Useful Trac resources](http://www.izzysoft.de/software/ifaqmaker.php?id=1;toc=1;topic=trac_resources). I'm sure there are guides for setting up Trac with Git as well, and probably even more up-to-date ones at that (mine is already a little outdated).
|
9,743,922 |
in a geolocation application, after the recovery of the location I will like to let the user correct the situation by draggable marker on the map.
example: in the image the true position is the red cross then the solution is to drag the blue marker and confirm.

|
2012/03/16
|
[
"https://Stackoverflow.com/questions/9743922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1262858/"
] |
Not so nice approach but way easier to implement: show the center of the map with a little cross plus put a button somewhere that says "use map center" or so. Getting map center from google maps is quite easy.
The map start initially centered at the user (blue marker). Now the user drags the map so the center(\*) of the map is where he is actually located (red cross). Then user hits the button. You take the location of the map center then and can update the location + marker of your user.
(\*) You need something that indicates the center of the map so the user can see where that is.
|
53,573,017 |
I am using lit html to create custom web components in my project. And my problem is when I try to use the CSS target selector in a web component it wont get triggered, but when I am doing it without custom component the code works perfectly. Could someone shed some light to why this is happening and to what would be the workaround for this problem? Here is my code:
**target-test-element.js:**
```
import { LitElement, html} from '@polymer/lit-element';
class TargetTest extends LitElement {
render(){
return html`
<link rel="stylesheet" href="target-test-element.css">
<div class="target-test" id="target-test">
<p>Hello from test</p>
</div>
`;
}
}
customElements.define('target-test-element', TargetTest);
```
with the following style:
**target-test-element.css:**
```
.target-test{
background: yellow;
}
.target-test:target {
background: blue;
}
```
and I created a link in the index.html:
**index.html(with custom component):**
```
<!DOCTYPE html>
<head>
...
</head>
<body>
<target-test-element></target-test-element>
<a href="#target-test">Link</a>
</body>
</html>
```
And here is the working one:
**index.html(without custom component)**
```
<!DOCTYPE html>
<head>
...
</head>
<body>
<a href="#target-test">Link</a>
<div class="target-test" id="target-test">
Hello
</div>
</body>
</html>
```
|
2018/12/01
|
[
"https://Stackoverflow.com/questions/53573017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10558165/"
] |
LitElement uses a Shadow DOM to render its content.
Shadow DOM isolates the CSS style defined inside and prevent selecting inner content from the outide with CSS selectors.
For that reason, the `:target` pseudo-class won't work.
Instead, you could use a standard (vanilla) custom element instead of the LitElement.
With no Shadow DOM:
```js
class TargetTest extends HTMLElement {
connectedCallback() {
this.innerHTML = `
<div>
<span class="test" id="target-test">Hello from test</span>
</div>`
}
}
customElements.define('target-test-element', TargetTest)
```
```css
.test { background: yellow }
.test:target { background: blue }
```
```html
<target-test-element></target-test-element>
<a href="#target-test">Link</a>
```
Alternately, if you still want to use a Shadow DOM, you should then set the `id` property to the custom element itself. That supposes there's only one target in the custom element.
```js
class TargetTest extends HTMLElement {
connectedCallback() {
this.attachShadow( { mode: 'open' } ).innerHTML = `
<style>
:host( :target ) .test { background-color: lightgreen }
</style>
<div>
<span class="test">Hello from test</span>
</div>`
}
}
customElements.define('target-test-element', TargetTest)
```
```html
<target-test-element id="target-test"></target-test-element>
<a href="#target-test">Link</a>
```
|
46,308,541 |
I have a linechart, and by default I need to show just a subset of elements, then show a different subset on dropdown event.
Here is initial code:
```
varlines = svg.append("g")
.attr('id', 'lines')
.selectAll('g')
.data(datum.filter(function(d) {
return d.group == 'default'
}),
function(d) {
return d.name
}
).enter()
.append("g")
.attr("class", 'varline')
.append("path")
.attr("class", "line")
.attr("id", function(d) {
return 'line_' + d.name
})
.attr("d", function(d) {
return line(d.datum);
});
```
And it works fine.
Now, here is the code that meant to update my selection:
```
$('.dropdown-menu a').click(function(d) {
var g = this.text;
dd.select("button").text(g) // switch header
var newdata = datum.filter(function(d) {
return d.group == g
}); # datalines for selected group
varlines.data(newdata, function(d) { return d.name })
.enter()
.merge(varlines)
.append("g")
.attr("class", 'varline')
.attr("id", function(d) {
return 'line_' + d.name
})
.append("path")
.attr("class", "line")
.attr("d", function(d) {
return line(d.datum);
});
varlines.exit().remove()
```
And it works weird. While it adds stuff and does not duplicate dom elements, it doesn't remove old ones.
Also, when I `console.log(varlines);` at any step, it shows only two initial elements in the `_groups` Array, and no `_enter` and `_exit` properties, even having 3 lines in the svg.
I am using d3v4, jquery3.1.1.slim
|
2017/09/19
|
[
"https://Stackoverflow.com/questions/46308541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2286597/"
] |
If you look at your `varlines`, you'll see that it is just an **enter** selection:
```
varlines = svg.append("g")
.attr('id', 'lines')
.selectAll('g')
.data(datum.filter(function(d) {
return d.group == 'default'
}),
function(d) {
return d.name
}
).enter()
.append("g")
//etc...
```
And, of course, you cannot call `exit()` on an enter selection. Therefore, this:
```
varlines.exit().remove()
```
... is useless.
**Solution**: make `varlines` an "update" selection by breaking it (I'm using `var` here, so we avoid it being a global):
```
var varlines = svg.append("g")
.attr('id', 'lines')
.selectAll('g')
.data(datum.filter(function(d) {
return d.group == 'default'
}),
function(d) {
return d.name
}
);
varlines.enter()
.append("g")
//etc...
```
Pay attention to this fact: since you're using D3 v4, you have to use `merge()`, otherwise **nothing** will show up the first time the code runs. Alternativelly, you can just duplicate your code:
```
varlines = svg.append("g")
.attr('id', 'lines')
.selectAll('g')
.data(datum.filter(function(d) {
return d.group == 'default'
}),
function(d) {
return d.name
}
)
varlines.enter()
.append("g")
//all the attributes here
varlines.//all the attributes here again
```
EDIT: the problem in your plunker is clear: when you do...
```
.attr("class", "line")
```
... you are overwriting the previous class. Therefore, it should be:
```
.attr("class", "varline line")
```
Here is the updated plunker: <https://plnkr.co/edit/43suZoDC37TOEfCBJOdT?p=preview>
|
21,889,087 |
I'm using this line of code:
```
$("#middle_child").contents().filter(function(){return this.nodeType == Node.TEXT_NODE;}).text();
```
For now, I'm just placing this in a console.log(). I'm using Chrome for testing & value returns as an empty string, but the value should return "Middle Child".
This is the HTML:
```
<div id='parent'>
Parent
<div id='oldest_child'>
Oldest Child
<div id='middle_child'>
Middle Child
<div id='youngest_child'>
Youngest Child
</div>
</div>
</div>
</div>
<div id='lone'>Lonely Div</div>
```
**EDIT**: I tried making a jsfiddle & that did provide me with some potential insight. In the fiddle I selected jQuery 1.6.4 & it worked just fine. The version of jQuery I'm running on my site is 1.6.2. Does anyone know if that could be part (if not all) of my issue?
|
2014/02/19
|
[
"https://Stackoverflow.com/questions/21889087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3277004/"
] |
You were on the right track. Just needed to make minor changes. The following query will give you the desired results. In inner query got the first 4 columns and to get rank cross joined that to `(SELECT @curRank := 0) r` which is MySQL trick for getting rank. in the end just needed to order by Cnt to make it work.
```
SELECT username
,userid
,category
,Cnt
,@curRank := @curRank + 1 AS rank
FROM (
SELECT b.Username
,B.userid
,A.category
,count(*) Cnt
FROM tblb B
JOIN tbla A
ON B.UserID = A.User
WHERE a.Category = 1
GROUP BY b.username
)a
,(SELECT @curRank := 0) r
Order by cnt desc
```
In order to put it into View you can use hack described by [@Gordon-Linoff](https://stackoverflow.com/users/1144035/gordon-linoff) [in this question](https://stackoverflow.com/questions/16280080/assiging-rank-in-mysql-and-view-creation)
End code will look something like this.
```
CREATE VIEW TestView1
AS
SELECT b.Username
,B.userid
,A.category
,COUNT(*) Cnt
FROM tblb B
JOIN tbla A
ON B.UserID = A.User
WHERE a.Category = 1
GROUP BY b.username
ORDER BY cnt DESC;
CREATE VIEW TestView2
AS
SELECT t1.*
,( SELECT 1 + COUNT(*)
FROM TestView1 AS t2
WHERE t2.Cnt > t1.Cnt
OR (
t2.Cnt = t1.Cnt
AND t2.userid < t1.userid ) ) AS Rank
FROM TestView1 AS t1
```
`TestView1` is used to get first 4 columns that you defined. `TestView2` you just select everything from first view and than add column that checks to see if value that you selecting is ether bigger or smaller than value in first instance of that view.
|
5,391,816 |
i have a javascript file about 6000+ lines of codes created by myself. Now it has functions for different sections of my site.. Now what i want to ask is that should i use that large file or divide it in parts for respective sections and call it in respective section.
|
2011/03/22
|
[
"https://Stackoverflow.com/questions/5391816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/229849/"
] |
I would suggest using 1 large one, as that requires only 1 http request. And with the right server setup it is only loaded once as it becomes cached.
|
32,892,143 |
I have been using nodejs a lot lately but I keep coming up against a similar error. There are a huge amount of projects out there and a lot of them have npm packages, but whenever I attempt `npm install --save some-package` I can't seem to figure out how to use them. I don't mean things like express, or mongoose, which I seem to be able to use just fine. I mean things like Bootstrap, or right now, `masonry-layout`.
For instance I followed the steps on the masonry layout page, and executed the following steps:
`npm install --save masonry-layout`
Then according to the [npm page for masonry-layout](https://www.npmjs.com/package/masonry-layout) I added to following to my general purpose `scripts.js` files (I am keeping small snippets I need in here until I separate code more logically):
```
$('.grid').masonry({
// options...
itemSelector: '.grid-item',
columnWidth: 200
});
```
However I get the following error in my console on page load:
```
TypeError: $(...).masonry is not a function
$('.grid').masonry({
```
I get similar problems when I try and use other frontend node modules or projects. Am I missing something? I always just end up using the cdn or installing the files manually and I am getting tired of working that way.
|
2015/10/01
|
[
"https://Stackoverflow.com/questions/32892143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2091965/"
] |
You still need to include those scripts in your page.
Use a good old `<script src="…">` or some module loader. (e.g. [require.js](http://requirejs.org/))
|
28,824,570 |
So Im keep coming up with typeError: Cannot read property 'style' undefined.
It situated on the last line of javascript.
Anyone any suggestions.
The finished piece is to be a marquee with vertically scrolling text.
```js
window.onload = defineMarquee;
var timeID;
var marqueeTxt = new Array();
var marqueeOff = true;
/* defineMarquee()
Initializes the contents of the marquee, determines the
top style positions of each marquee item, and sets the
onclick event handlers for the document
*/
function defineMarquee() {
var topValue
var allElems = document.getElementsByTagName("*");
for (var i = 0; i < allElems.length; i++) {
if (allElems[i].className == "marqueeTxt") marqueeTxt.push(allElems[i]);
}
//Extract the "top" CSS class from marqueeTxt
for (var i = 0; i < marqueeTxt.length; i++) {
if (marqueeTxt[i].getComputedStyle) {
topValue = marqueeTxt[i].getPropertyValue("top")
} else if (marqueeTxt[i].currentStyle) {
topValue = marqueeTxt[i].currentStyle("top");
}
marqueeTxt[i].style.top = topValue;
}
document.getElementById("startMarquee").onclick = startMarquee;
document.getElementById("stopMarquee").onclick = stopMarquee;
}
/* startMarquee()
Starts the marquee in motion
*/
function startMarquee() {
if (marqueeOff == true) {
timeID = setInterval("moveText()", 50);
marqueeOff = false;
}
}
/* stopMarquee()
Stops the Marquee
*/
function stopMarquee() {
clearInterval(timeID);
marqueeOff = true;
}
/* moveText ()
move the text within the marquee in a vertical direction
*/
function moveText() {
for (var i = 0; i < marqueeTxt.length; i++) {
topPos = parseInt(marqueeTxt[i].style.top);
}
if (topPos < -110) {
topPos = 700;
} else {
topPos -= 1;
}
marqueeTxt[i].style.top = topPos + "px";
}
```
```css
* {
margin: 0px;
padding: 0px
}
body {
font-size: 15px;
font-family: Arial, Helvetica, sans-serif
}
#pageContent {
position: absolute;
top: 0px;
left: 30px;
width: 800px
}
#links {
display: block;
width: 100%;
margin-bottom: 20px;
border-bottom: 1px solid rgb(0, 153, 102);
float: left
}
#links {
list-style-type: none
}
#links li {
display: block;
float: left;
text-align: center;
width: 19%
}
#links li a {
display: block;
width: 100%;
text-decoration: none;
color: black;
background-color: white
}
#links li a:hover {
color: white;
background-color: rgb(0, 153, 102)
}
#leftCol {
clear: left;
float: left
}
h1 {
font-size: 24px;
letter-spacing: 5px;
color: rgb(0, 153, 102)
}
#main {
float: left;
width: 450px;
margin-left: 10px;
padding-left: 10px;
border-left: 1px solid rgb(0, 153, 102);
padding-bottom: 15px
}
#main img {
float: right;
margin: 0px 0px 10px 10px
}
#main p {
margin-bottom: 10px
}
address {
width: 100%;
clear: left;
font-style: normal;
font-size: 12px;
border-top: 1px solid black;
text-align: center;
padding-bottom: 15px
}
.marquee {
position: absolute;
top: 0px;
left: 0px;
width: 280px;
height: 300px;
background-color: rgb(0, 153, 102);
color: white;
border: 5px inset white;
padding: 0px;
overflow: hidden;
position: relative
}
#marqueeTxt1 {
font-size: 1.4em;
letter-spacing: 0.15em;
border-bottom: 1px solid white
}
input {
width: 120px;
margin: 5px;
font-size: 0.9em
}
#marqueeButtons {
width: 280px;
text-align: center
}
#marqueeTxt1 {
position: absolute;
top: 40px;
left: 20px
}
#marqueeTxt2 {
position: absolute;
top: 90px;
left: 20px
}
#marqueeTxt3 {
position: absolute;
top: 170px;
left: 20px
}
#marqueeTxt4 {
position: absolute;
top: 250px;
left: 20px
}
#marqueeTxt5 {
position: absolute;
top: 330px;
left: 20px
}
#marqueeTxt6 {
position: absolute;
top: 410px;
left: 20px
}
#marqueeTxt7 {
position: absolute;
top: 490px;
left: 20px
}
#marqueeTxt8 {
position: absolute;
top: 570px;
left: 20px
}
#marqueeTxt9 {
position: absolute;
top: 640px;
left: 20px
}
```
```html
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--
New Perspectives on JavaScript, 2nd Edition
Tutorial 4
Case Problem 3
BYSO Web Page
Author: Gavin Macken
Date: 28 Feb `15
Filename: byso.htm
Supporting files: bstyles.css, byso.jpg, bysologo.jpg, marquee.js
-->
<title>Boise Youth Symphony Orchestra</title>
<link href="bstyles.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="marquee.js"></script>
</head>
<body>
<form id="marqueeForm" action="">
<div id="pageContent">
<div id="head">
<img src="bysologo.jpg" alt="Boise Youth Symphony Orchestra" />
</div>
<ul id="links">
<li><a href="#">Home Page</a>
</li>
<li><a href="#">About BYSO</a>
</li>
<li><a href="#">Our Director</a>
</li>
<li><a href="#">Join BYSO</a>
</li>
<li><a href="#">Contact Us</a>
</li>
</ul>
<div id="leftCol">
<div class="marquee">
<div id="marqueeTxt1" class="marqueeTxt">
Schedule of Events
</div>
<div id="marqueeTxt2" class="marqueeTxt">
Holiday Concert
<br />December 14, 7:30 PM
<br />Boise Civic Center
</div>
<div id="marqueeTxt3" class="marqueeTxt">
Christmas Concert
<br />Dec. 16, 7 PM
<br />Our Savior Episcopal Church
</div>
<div id="marqueeTxt4" class="marqueeTxt">
Spring Concert
<br />Feb. 27, 7 PM
<br />Boise Civic Center
</div>
<div id="marqueeTxt5" class="marqueeTxt">
Easter Fanfare
<br />March 14, 9 PM
<br />Our Savior Episcopal Church
</div>
<div id="marqueeTxt6" class="marqueeTxt">
High School MusicFest
<br />May 2, 3 PM
<br />Boise Central High School
</div>
<div id="marqueeTxt7" class="marqueeTxt">
Summer Concert
<br />June 15, 7:30 PM
<br />Frontier Concert Hall
</div>
<div id="marqueeTxt8" class="marqueeTxt">
Fourth Fest
<br />July 4, 4 PM
<br />Canyon View Park
</div>
<div id="marqueeTxt9" class="marqueeTxt">
Frontier Days
<br />August 9, 1 PM
<br />Boise Concert Hall
</div>
</div>
<div id="marqueeButtons">
<input type="button" id="startMarquee" value="Start Marquee" />
<input type="button" id="stopMarquee" value="Pause Marquee" />
</div>
</div>
<div id="main">
<h1>Boise Youth Symphony Orchestra</h1>
<img src="byso.jpg" alt="" />
<p>The Boise Youth Symphony Orchestra has delighted audiences worldwide with beautiful music while offering the highest quality musical training to over 1,000 teens throughout Idaho for the past 30 years. BYSO has established an outstanding reputation
for its high quality sound, its series of commissioned works, and collaborations with prominent musical groups such as the Idaho and Boise Symphony Orchestras, the Montana Chamber Orchestra, the Boise Adult Choir and the Western Symphony Orchestra.
Last year the group was invited to serve as the U.S. representative to the 7th Annual World Festival of youth orchestras in Poznan, Poland.</p>
<p>Leading this success for the past decade has been Boise Symphony artistic director Denise Young. In a concert review by John Aehl, music critic for the <i>Boise Times</i>, Roger Adler writes, "It is a pleasure to report that the orchestra is playing
better than ever."</p>
</div>
<address>
BYSO · 300 Mountain Lane · Boise, Idaho 83702 · (208) 555 - 9114
</address>
</div>
</form>
</body>
</html>
```
|
2015/03/03
|
[
"https://Stackoverflow.com/questions/28824570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4318762/"
] |
1. Hmm no, because with your piece of code you make ALL methods on the collection class available for a static call. That's not the purpose of the (abstract) factory pattern.
2. (Magic) methods like `__callStatic` or `call_user_func_array` are very tricky because a developer can use it to call every method.
3. What would you really like to do? Implement the factory pattern OR use static one-liner methods for your MongoDB implementation?!
If the implementation of the book and author collection has different methods(lets say getName() etc..) I recommend something like this:
```
class BookCollection extends Collection {
protected $collection = 'book';
public function getName() {
return 'Book!';
}
}
class AuthorCollection extends Collection {
protected $collection = 'author';
public function getName() {
return 'Author!';
}
}
class Collection {
private $adapter = null;
public function __construct() {
$this->getAdapter()->selectCollection($this->collection);
}
public function findOne($query = array(), $projection = array()) {
$doc = $this->getAdapter()->findOne($query, $projection);
return isset($doc) ? new Document($doc) : false;
}
public function getAdapter() {
// some get/set dep.injection for mongo
if(isset($this->adapter)) {
return $this->adapter;
}
return new Mongo();
}
}
class CollectionFactory {
public static function build($collection)
{
switch($collection) {
case 'book':
return new BookCollection();
break;
case 'author':
return new AuthorCollection();
break;
}
// or use reflection magic
}
}
$bookCollection = CollectionFactory::build('book');
$bookCollection->findOne(array('name' => 'Google'));
print $bookCollection->getName(); // Book!
```
**Edit: An example with static one-liner methods**
```
class BookCollection extends Collection {
protected static $name = 'book';
}
class AuthorCollection extends Collection {
protected static $name = 'author';
}
class Collection {
private static $adapter;
public static function setAdapter($adapter) {
self::$adapter = $adapter;
}
public static function getCollectionName() {
$self = new static();
return $self::$name;
}
public function findOne($query = array(), $projection = array()) {
self::$adapter->selectCollection(self::getCollectionName());
$doc = self::$adapter->findOne($query, $projection);
return $doc;
}
}
Collection::setAdapter(new Mongo()); //initiate mongo adapter (once)
BookCollection::findOne(array('name' => 'Google'));
AuthorCollection::findOne(array('name' => 'John'));
```
|
4,098,022 |
There is an negative number for every positive number and there’s zero.Thus,an odd number of numbers exist right?
|
2021/04/11
|
[
"https://math.stackexchange.com/questions/4098022",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/913449/"
] |
You are right in that agents may *believe* some fact that is not actually true. In this case, as the authors say, the truth axiom does not hold. Moreover, the epistemic relation in models ceases to be the equivalence.
If we are talking about knowledge in the context of epistemic logic, then the notion of knowledge is pretty strong. First, if an agent *knows* some fact, then this fact is true. This is captures by the truth axiom. Second, agents indeed know all logical validities. This is usually called the logical omniscience.
Since the framework of epistemic logic is static, there is no sense in discussing whether agents are truthful or not; there is simply no communication involved for this to play a role.
In a dynamic setting, where agents can perform epistemic actions, like public or private announcements, whether agents are truthful does make the difference. However, in such a setting, we usually do not speak about *knowledge*, and rather we speak about *belief*, as agents may believe true facts.
All in all, in the context of this type of modal logics, everything that is *known* is true in the world, and some things that are *believed* can be false.
|
252,729 |
I know you get 2 set pieces in the new season for reaching level 70, what else do you have to do to get the other 4 pieces?
Can you get a free set again if you complete the parameters with a new character?
|
2016/01/21
|
[
"https://gaming.stackexchange.com/questions/252729",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/73403/"
] |
You get two more set pieces for completing the Chapter 4 objective "Mercy" (Defeat Zoltan Kulle on Torment II) and two pieces for completing the Chapter 4 objective "Great Expectations" (Complete a Level 20 Greater Rift solo).
|
31,655,986 |
I have an asp.net gridview which displays two rows for each record, using the following code below (example).
However using a dropdownlist which is on the top of the page, based on its selection (1 or 2) I want the gridview to update itself on the following way:
option 1 = display two rows per record.
option 2 = display only one row per record (second table row shown on code below I don't want it to be shown when Option 2 is selected.
UPDATE:
Selecting the dropdownlist option and making it work is fine, I don't have a problem there, but I need to know how to manipulate the gridview to display one or two rows per record. So basically how can I (with code) change the format of the gridview from 1 to 2 rows.
Obviously there is the option of using two gridviews and show the one needed based on your selection, but I prefer to use one gridview only (if that's possible).
```
<HeaderTemplate>
<asp:LinkButton ID="lbPN" runat="server" Text="Project Name" style "color:white;" CommandName="Sort" CommandArgument="PN" tabindex="1000" ></asp:LinkButton><br />
<asp:TextBox runat="server" ID="S_PN" CssClass="FilterField" ></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<table >
<tr>
<td class="STD_normal" style="width:150px; font-weight:bold"><%#Eval("PN")%>
</td>
</tr>
<tr>
<td class="STD_Normal_Grey" style="width:150px"><%#Eval("DD", "{0:dd-MMM-yyyy}")%> </td>
</tr>
</table>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left"/>
</asp:TemplateField>
```
|
2015/07/27
|
[
"https://Stackoverflow.com/questions/31655986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1135218/"
] |
There is code based on one of my database, just change parameters (this is *server side* example, someone else provide here client side example) :
aspx :
```
<asp:DropDownList runat="server" ID="ddlChoice" AutoPostBack="true">
<asp:ListItem Text="One row"></asp:ListItem>
<asp:ListItem Text="Two rows"></asp:ListItem>
</asp:DropDownList>
<br /><br />
<asp:GridView runat="server" ID="grdInfo" DataSourceID="sqlInfo">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:LinkButton ID="lbPN" runat="server" Text="Project Name" style="color:white;" CommandName="Sort" CommandArgument="PN" tabindex="1000" ></asp:LinkButton><br />
<asp:TextBox runat="server" ID="S_PN" CssClass="FilterField" ></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<table>
<tr><td runat="server" id="tdFirst" class="STD_normal" style="width:150px; display:block; font-weight:bold"><%# Eval("PNaziv")%></td></tr>
<tr><td runat="server" id="tdSecond" class="STD_Normal_Grey" style="width:150px; display:none;"><%#Eval("PMesto")%></td></tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sqlInfo" runat="server" ConnectionString="<%$ ConnectionStrings:MDFConnection %>" SelectCommand="SELECT PNaziv,PMesto FROM Partneri ORDER BY PNaziv;" ></asp:SqlDataSource>
```
code behind (vb.net)
```
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Private Sub ddlChoice_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlChoice.SelectedIndexChanged
grdInfo.DataBind()
End Sub
Private Sub grdInfo_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdInfo.RowCreated
If e.Row.RowType = DataControlRowType.DataRow Then
Dim td As HtmlTableCell = e.Row.Cells(0).FindControl("tdSecond")
If ddlChoice.SelectedIndex = 0 Then td.Style("display") = "none" Else td.Style("display") = "block"
End If
End Sub
```
Like I wrote in comment, I set to each `td` `id` and `runat="server"`. Dropdownlist must have `AutoPostBack="true"`.
Now, on every `SelectedIndexChanged` must bind Your grid and on every created row find `HtmlTableCell`, now, control (it's `td`) and based on selected index show or hide second `td`. But, under `style` of every `td` I put `display:block/none;` depend of row.
When You start webapp only one row will be visible, and after that, depend of dropdownlist choice.
In this example that table is in first column (`Dim td As HtmlTableCell = e.Row.Cells(0).FindControl("tdSecond")`)... You have to change that `.e.Row.Cells(x)...`; where *x* is Your column index.
**Update :** You not define prog.language so bellow code is in `c#` (converted from vb.net using online conversion tool, sorry I programming in vb.net)
```
private void ddlChoice_SelectedIndexChanged(object sender, System.EventArgs e)
{
grdInfo.DataBind();
}
private void grdInfo_RowCreated(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
HtmlTableCell td = e.Row.Cells[0].FindControl("tdSecond");
if (ddlChoice.SelectedIndex == 0)
td.Style("display") = "none";
else
td.Style("display") = "block";
}
}
```
|
72,341,977 |
I have been trying to find solutions for this for a few days now and can't seem to get anything to work.
The script below shows/hides columns in the tabs and works perfectly in the named sheet. I just need it to run through all of the tabs, **except for the first few**,and be applied in them too.
I just don't understand how it all works so am getting stuck.
All help hugely appreciated!!!!!!
```
function hidecolumns() {
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName('Jun 2025 2HR');
var first_row = sh.getRange(2,1,1,sh.getMaxColumns()).getValues().flat();
first_row.forEach((fr,i)=>{
if(fr==0){
sh.hideColumns(i+1);
}
else {
sh.showColumns(i+1);
}
})
}
```
|
2022/05/22
|
[
"https://Stackoverflow.com/questions/72341977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19176386/"
] |
SQLAlchemy itself only calls the cursor's `execute` method, which does not support executing multiple statements. However it's possible to access the DB API connection directly, and call its `executescript` method:
```py
import sqlalchemy as sa
engine = sa.create_engine('sqlite:///so72341960.db')
# Create a table for our example.
tbl = sa.Table(
'mytable',
sa.MetaData(),
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('name', sa.String),
)
# Ensure we start with a clean table.
tbl.drop(engine, checkfirst=True)
tbl.create(engine)
SQL = """
INSERT INTO mytable (name) VALUES ('Alice');
INSERT INTO mytable (name) VALUES ('Bob');
"""
with engine.begin() as conn:
dbapi_conn = conn.connection
dbapi_conn.executescript(SQL)
```
|
8,188,172 |
I am pretty new to rails so this may be an easy question, but I was looking to create a Rails app that would use youtube in it. I have found that youtube\_it seems to be the gem of choice for a task like this but I am having trouble using it. Basically, I want to use the gem so that I can get videos from specific users, i.e. Stanford University and create a list of those videos with links to another page that has the video information and player. To test this out I tried the follow code:
application\_controller.rb
```
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :yt_client
private
def yt_client
@yt_client ||= YouTubeIt::Client.new(:dev_key => dev_key)
end
end
```
home\_controller.rb
```
class HomeController < ApplicationController
def index
@playlists = yt_client.playlists('stanforduniversity')
end
end
```
index.html.erb
```
<h3>Home</h3>
<% @playlists.each do |playlist| %>
<p>Playlist: <%= playlist %></p>
<% end %>
```
The problem with this is all I get for output on my home page is a list of something like this: #
My questions then are: is there a way to change this output into an actual title? Am I doing something wrong/forgetting a step? Or should I just use python code to use the Google API and put all the videos into my database(I already have some code for this) and just access it using my rails app?
Hope this is clear enough.
|
2011/11/18
|
[
"https://Stackoverflow.com/questions/8188172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1054494/"
] |
it looks like what you want to print out is the name of the playlist - but that is an attribute of the playlist object, so you'll need something like:
```
<% @playlists.each do |playlist| %>
<p>Playlist: <%= playlist.title %></p>
<% end %>
```
otherwise ruby is trying to "print" the playlist object - which just doesn't work the way you expect.
Note: I've not used this gem either, I'm gathering this info from the gem docs here: <https://github.com/kylejginavan/youtube_it>
|
54,264,668 |
Hello everyone i have the following row as a sample in my table
```
id shop_id start_time end_time
1 21 10:00 11:00
```
and i want to check whether start\_time and end\_time exist in table or not
I am using following query but not working correctly, Where i am wrong ?
```
select *
from usr_booking
where shop_id='21'
and start_time between '10:10:00' and '11:01:00'
or end_time between '10:10:00' and '11:01:00'
```
|
2019/01/19
|
[
"https://Stackoverflow.com/questions/54264668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10784895/"
] |
You need to clearly separate the checks on the `shop_id` and the time ranges:
```
SELECT *
FROM usr_booking
WHERE
shop_id = 21 AND
(start_time BETWEEN '10:10:00' AND '11:01:00' OR
end_time BETWEEN '10:10:00' AND '11:01:00');
```
The `AND` operator in MySQL has higher precedence than the `OR` operator. So, your current query is actually evaluating as this:
```
SELECT *
FROM usr_booking
WHERE
(shop_id = 21 AND
start_time BETWEEN '10:10:00' AND '11:01:00') OR
end_time BETWEEN '10:10:00' AND '11:01:00';
```
Clearly, this is not the same logic as you what you probably intended.
|
12,996,365 |
I have coding below:
```
try{
address = "http://isbndb.com//api/books.xml?
access_key=CKEHIG4D&index1=isbn&value1=" +barcode;
URL url = new URL(address);
URLConnection conn = url.openConnection();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());
NodeList nodes = doc.getElementsByTagName("BookData");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList title = element.getElementsByTagName("LongTitle");
Element line = (Element) title.item(0);
titleList.add(line.getTextContent());
}
}
catch (Exception e) {
e.printStackTrace();
}
```
and theXML format is
<http://isbndb.com//api/books.xml?access_key=CKEHIG4D&index1=isbn&value1=1593270615>
the error is the line --> NodeList title = element.getElementsByTagName("LongTitle");
Actually what's wrong with that?
|
2012/10/21
|
[
"https://Stackoverflow.com/questions/12996365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1740540/"
] |
Make sure you are importing the right Element class ([org.w3c.dom.Element](http://developer.android.com/reference/org/w3c/dom/Element.html)).
|
56,630,969 |
I have one json file with 100 columns and I want to read all columns along with predefined datatype of two columns.
I know that I could do this with schema option:
```
struct1 = StructType([StructField("npi", StringType(), True), StructField("NCPDP", StringType(), True)
spark.read.json(path=abc.json, schema=struct1)
```
However, this code reads only two columns:
```
>>> df.printSchema()
root
|-- npi: string (nullable = true)
|-- NCPDP: string (nullable = true)
```
To use above code I have to give data type of all 100 columns. How can I solve this?
|
2019/06/17
|
[
"https://Stackoverflow.com/questions/56630969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5219480/"
] |
According to [official documentation](https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrameReader.json), schema can be either a `StructType` or a `String`.
I can advice you 2 solutions :
### 1 - You use the schema of a dummy file
If you have one light file with the same schema (ie one line same structure), you can read it as Dataframe and then use the schema for your other json files :
```py
df = spark.read.json("/path/to/dummy/file.json")
schm = df.schema
df = spark.read.json(path="abc.json", schema=schm)
```
### 2 - You generate the schema
This step needs you to provide column name (and maybe types too).
Let's assume `col` is a dict with (key, value) as (column name, column type).
```py
col_list = ['{col_name} {col_type}'.format(
col_name=col_name,
col_type=col_type,
) for col_name, col_type in col.items()]
schema_string = ', '.join(col_list)
df = spark.read.json(path="abc.json", schema=schema_string)
```
|
3,945,342 |
I started building an app under an individual developer account.
In preparing to beta and release this I'm switching over to a new company account.
I'm trying to prepare a checklist of the things I will need to update in order to move the project over to the new account.
* Install new development certificate
and profile
* Change bundle identifier
in the -info.plist to match the new
app ID
* In project build settings change code signing identify
Appreciate any words of wisdom from others who may have gone through a similar process or pointers to other questions that address this.
|
2010/10/15
|
[
"https://Stackoverflow.com/questions/3945342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/296003/"
] |
Here is my checklist in addition to your list:
* Change Version of your app to 1.0 in case if this is your first time you submit the app. If it's an update make sure it has higher version number than the one on app store
* Add Code Signing Entitlement file to the project
* Remove debug code like NSLog
* Build the App store distribution. Actually there is a guide for this <https://developer.apple.com/ios/manage/distribution/index.action>
* Remember to keep the dSYM file that generated along with the .app file so that you can symbolicate the crash log later.
* I don't know if that happen to everyone. But before you zip your binary file (.app file) make sure that the file name of the binary file don't have any special character, best to leave it as alphabet only, since it does not affect anything.
* Zip your binary file
* Submit to appstore using app uploader utility.
That what I remember. Correct me If I'm wrong. Hope this help:).
|
25,179,650 |
Is it good practice to declare object inside [`block scope`](http://msdn.microsoft.com/en-us/library/1t0wsc67.aspx) Condition
```
If item.DocType = 1 Then
Dim objass As Assignment = DBFactory.GetAssignmentDB.AssignmentGetByID(vis.AssignmentID)
End If
```
OR should i declare object outside the if condition and then do assignment inside
```
Dim objass As Assignment
If item.DocType = 1 Then
objass = DBFactory.GetAssignmentDB.AssignmentGetByID(vis.AssignmentID)
End If
```
|
2014/08/07
|
[
"https://Stackoverflow.com/questions/25179650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1263981/"
] |
That entirely depends on the scenario.
If you want to use the variable within the condition only, then declare it inside the condition. If you want the variable to be used outside of the If statement, then it's scope must extend to outside the condition.
There is no 'good practice' for all scenarios. Sometimes it'll be inside, sometimes not - depends on it's usage.
<http://msdn.microsoft.com/en-gb/library/1t0wsc67.aspx>
|
18,648,142 |
I was trying to create a brighter color using the default colors that `java.awt.Color` provides
but when I draw using the 2 colors, they appear to be the same?
```
Color blue = Color.BLUE;
Color brighterBlue = blue.brighter();
test.setColor(blue);
test.fillCircle(size);
test.setColor(brighterBlue);
test.drawCircle(size);
```
|
2013/09/06
|
[
"https://Stackoverflow.com/questions/18648142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2752646/"
] |
Quoting [the docs](http://docs.oracle.com/javase/6/docs/api/java/awt/Color.html#brighter%28%29):
>
> This method applies an arbitrary scale factor to each of the three RGB components of this Color to create a brighter version of this Color.
>
>
>
So, assuming that `Color.blue` is the color `rgb(0, 0, 255)`, the brighter method would attempt to:
1. Multiply the `0`s by the scale factor, resulting in 0s again; and
2. Multiply the `255` by a scale factor, which because of capping results in `255` again.
Do note that the *hue-saturation-value* (where "value" is the same as "brightness") colour coordinate model is not the same as the *hue-saturation-**lightness*** model, which behaves somewhat more intuitively. (See Wikipedia on [HSL and HSV](https://en.wikipedia.org/wiki/HSL_and_HSV).) Unfortunately Java doesn't have HSL calculations built in, but you should be able to find those by searching easily.
|
246,823 |
*Prenote: I have asked this question first on [math stackexhange](https://math.stackexchange.com/questions/1882475/gauss-theorem-for-null-boundaries), but a user suggested that mathoverflow might be a better place for this question. Upon thinking about it I have agreed with him and copy-pasted the question here.*
*Note: I have solved this problem on my own, mostly while actually typing it in here, as I was stuck with this problem previously. This is however quite important for my research, so I nontheless would like to verify the correctness of my solution, hence I went forth with posting this "question". If this goes against site principles then please vote close on the question.*
**Introductions**: Let $(M,g)$ be a Riemannian manifold with boundary (or a Lorentzian/pseudo-Riemannian manifold whose boundary is timelike or spacelike everywhere). Gauss' theorem then states that $$ \int\_M\text{div}(X)\mu\_g=\int\_{\partial M}\langle X,n\rangle\mu\_h, $$ where $\mu\_g$ is the volume form associated with $g$, $\mu\_h$ is the volume form associated with the induced metric $h$, and $n$ is the unit normal vector field along the boundary.
This theorem is also available in an intermediate step between Stokes' theorem and the form I have given above. Since $\mathcal{L}\_X\mu\_g=\text{div}(X)\mu\_g$, but $\mathcal{L}\_X\mu\_g=\mathrm{d}i\_X\mu\_g+i\_X\mathrm{d}\mu\_g=\mathrm{d}i\_X\mu\_g$, we have $$ \int\_M\text{div}(X)\mu\_g=\int\_M\mathrm{d}i\_X\mu\_g=\int\_{\partial M}\phi^\*(i\_X\mu\_g), $$ where $\phi$ is the inclusion $\phi:\partial M\rightarrow M$.
**The problem**: I wish to use Gauss' theorem on a Lorentzian manifold, whose boundary is a null surface. Then the normal vector is also tangent, the induced metric is degenerate, and the induced volume is zero. Durr. The "intermediate" form of the Gauss' theorem still applies though, so I seek to use it to define a version of Gauss' theorem which, instead of using the normal vector $n$, it will use an arbitrary **transverse** vector field $N$, which is surely not tangent to $\partial M$.
**Proposed solution**: If $e\_1,...,e\_{n-1}$ is a positively oriented frame on $\partial M$, then $X$ is locally decomposible as $X=\langle X,N\rangle N+Y$, where $Y=Y^ie\_i$, furthermore, I assume if $N$ is globally defined then this decomposition also applies globally in the general form $X=\langle X,N\rangle N+Y$, where $Y$ is tangent to $\partial M$. (*Is this assumption correct?*).
Then plugging $X$ into $\mu\_g$ gives $$ i\_X\mu\_g(e\_1,...,e\_{n-1})=\mu\_g(\langle X,N\rangle N+Y,e\_1,...,e\_{n-1})=\langle X,N\rangle\mu\_g(N,e\_1,...,e\_{n-1})= \\=\langle X,N\rangle i\_N\mu\_g(e\_1,...,e\_{n-1}) $$ where the term involving $Y$ is annihilated, because if $Y$ is tangent to $\partial M$, then the arguments of $\mu\_g$ are linearly dependent.
So from this we have $$ \int\_M\text{div}(X)\mu\_g=\int\_{\partial M}\langle X,N\rangle \phi^\*(i\_N\mu\_g), $$ so apparantly $i\_N\mu\_g$ is such a volume form for $\partial M$, that Gauss' theorem with $N$ instead of $n$ applies.
I also want to obtain a local coordinate formula for this, so if $(U,x^\mu)$ is a local chart for $M$, and $(V,y^i)$ is a local chart for $\partial M$, then in the relevant chart domains we have $$ i\_N\mu\_g=i\_N(\sqrt{-g}\mathrm{d}x^1\wedge...\wedge\mathrm{d}x^n)=i\_N(n!^{-1}\sqrt{-g}\epsilon\_{\mu\_1...\mu\_n}\mathrm{d}x^{\mu\_1}\wedge...\wedge\mathrm{d}x^{\mu\_n})=\\=i\_N(\sqrt{-g}\epsilon\_{\mu\_1...\mu\_n}\mathrm{d}x^{\mu\_1}\otimes...\otimes\mathrm{d}x^{\mu\_n})=\sqrt{-g}N^{\mu\_1}\epsilon\_{\mu\_1...\mu\_n}\mathrm{d}x^{\mu\_2}\otimes...\otimes\mathrm{d}x^{\mu\_n}=\\=\frac{1}{(n-1)!}\sqrt{-g}N^\mu\epsilon\_{\mu\mu\_2...\mu\_n}\mathrm{d}x^{\mu\_2}\wedge...\wedge\mathrm{d}x^{\mu\_n}. $$ Now pulling back gives $$ \phi^\*(i\_N\mu\_g)=\frac{1}{(n-1)!}\sqrt{-g}\epsilon\_{\mu\mu\_2...\mu\_n}N^\mu\frac{\partial x^{\mu\_2}}{\partial y^{i\_1}}...\frac{\partial x^{\mu\_n}}{\partial y^{i\_{n-1}}}\mathrm{d}y^{i\_1}\wedge...\wedge\mathrm{d}y^{i\_{n-1}} .$$ Now, the matrix $e^\mu\_{(i)}=\partial x^\mu/\partial y^i$ maybe identified (with a bit of abuse of notation regarding tangent maps) as the $\mu$th component of the $i$-th coordinate basis vector field on the boundary $\partial M$, with the components being taken with respect to the coordinate system $\{x^\mu\}$.
Then, by the definition of determinants we have $\epsilon\_{\mu\mu\_2...\mu\_n}N^\mu e^{\mu\_2}\_{i\_1}...e^{\mu\_n}\_{i\_{n-1}}=\det(N,e\_{(i\_1)},...,e\_{(i\_{n-1})})$, so $$\phi^\*(i\_N\mu\_g)=\frac{1}{(N-1)!}\sqrt{-g}\det(N,e\_{(i\_1)},...,e\_{(i\_{n-1})})\mathrm{d}y^{i\_1}\wedge...\wedge\mathrm{d}y^{i\_{n-1}}=\\=\sqrt{-g}\det(N,e\_1,...,e\_{n-1})d^{n-1}y, $$ so the modified Gauss' theorem in coordinates is (assuming $M$ can be covered by a single chart) $$ \int\_M \text{div}(X)\sqrt{-g}d^nx=\int\_{\partial M}X^\mu N\_\mu\sqrt{-g}\det(N,e\_1,...,e\_{n-1})d^{n-1}y $$.
**Questions**:
* Is this derivation correct?
* I can work with the form I have gotten, but I don't like the determinant factor in it. Is there any way I can express that in a more pleasant form?
* In case the derivation is incorrect, how can I get a formula I can work with in coordinate notation that does what I want?
|
2016/08/04
|
[
"https://mathoverflow.net/questions/246823",
"https://mathoverflow.net",
"https://mathoverflow.net/users/85500/"
] |
Gauss' Theorem has nothing to do with the (pseudo-)metric. Is just a consequence of Stokes' theorem.
Stokes's theorem says that, for any $n-1$ form $\omega$,
$$ \int\_M d\omega = \int\_{\partial M} \omega. $$
Now fix any smooth measure $\mu$ (i.e. given by a smooth non-vanishing top dimensional form, or a density if $M$ is not orientable). It might be the Riemannian measure of a Riemannian structure, but it's not relevant.
Let $X$ be a vector field. If you apply the above formula to the $n-1$ form $\omega:=\iota\_X \mu$, you get, using one of the many definitions of divergence (associated with the measure $\mu$)
$$\int\_M \mathrm{div}(X) \mu = \int\_{\partial M} \iota\_X \mu, \qquad (\star),$$
where $\iota\_X$ is the contraction. This holds whatever is $X$, on any smooth manifold with boundary.
Now it all boils down to how you want to define a "reference" measure on $\partial M$. As you propose, you can pick a transverse vector $N$ to $\partial M$, and define a reference measure on $\partial M$ as $\eta:=\iota\_T \mu$. Then
$$ \int\_M \mathrm{div}(X) \mu = \int\_{\partial M} f\, \iota\_T \mu, $$
where
$$f := \frac{\mu(X,Y\_1,\ldots,Y\_{n-1})}{\mu(T,Y\_1,\ldots,Y\_{n-1})}. $$
for any arbitrary local frame $Y\_1,\ldots,Y\_{n-1}$ tangent to $\partial M$ (oriented, otherwise take densities and absolute values). In particular, you can easily compute $f$ by looking at the "$T$" component of "$X$":
$$X = f\, T \mod \mathrm{span}\{Y\_1,\ldots,Y\_{n-1}\}.$$
There is no need to use orthonormality, or a (pseudo)-metric.
However, if you are on a Riemannian manifold, $\mu = \mu\_g$ is the Riemannian measure, and $N$ is the normal vector to $\partial M$, then $f= g(N,X)$, and $\iota\_N \mu$ is Riemannian measure of the induced Riemannian metric on $\partial M$, recovering the classical statement.
|
15,024,035 |
I'm experiencing a very slow startup of gvim with tex files and the latex-suite plugin. For example, opening [this tex file](https://bitbucket.org/andrenarchy/funcall/raw/25d83535b4839ae1598a620b4cb7315a467ccc4b/funcall.tex) takes 7 seconds. A minimal .vimrc file only contains the following line:
```
filetype plugin on
```
My .vim folder only contains the [latex-suite plugin](http://vim-latex.sourceforge.net/index.php?subject=download&title=Download) (snapshot 2013-01-16). I suspect the folding functionality in latex-suite but I'm not sure how to track this down properly and fix it. I'm running gvim 7.3 on Ubuntu 12.10.
Does anybody know how to fix this slow startup?
|
2013/02/22
|
[
"https://Stackoverflow.com/questions/15024035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219479/"
] |
The reason for that error lies in the fact that you try to map a Set of plain Objects. Object is not a JPA-entity and therefore it cannot be mapped to a relational type.
You'll need to create an entity named Occurence and map it the way you did it with the Set of Objects.
|
9,648 |
I have various devices to connect to my iMac using good-old RS-232.
Of course, I only have USB connectors on my machine.
I have a couple of Prolific PL2303-based cables, and they seem to work OK, but the kext provided seems a little flaky and I'm not sure about long-term support.
What is the most-stable, best-supported USB-Serial chip-set or cable?
|
2011/03/05
|
[
"https://apple.stackexchange.com/questions/9648",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/1794/"
] |
I have two Prolific USB-to-serial adapters but they are made by different Vendors (one is Prolific, the other ATEN).
I've used their supplied drivers just fine. Note that there are open source drivers for these devices too available here: <https://github.com/failberg/osx-pl2303> FYI my use case is actually patching them through to a VirtualBox Windows VM and using them in Windows, so I have two layers of drivers and have not had any problems yet.
However, I think the best supported USB-to-serial devices are those made by Belkin. This is subjective, but I've used them for years without problem, and they are a large company with a reputation. They will likely be around in the future.
|
14,082,113 |
I didnt quite understand whats is the `effect.World` and `effect.View` etc. and why we put the matricies in them?
```
foreach (ModelMesh mesh in model1.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = Matrix.CreateWorld(Vector3.Zero, Vector3.Forward, Vector3.Up);
effect.View = Matrix.CreateLookAt(Vector3.Zero, Vector3.Zero, Vector3.Up);
}
}
```
|
2012/12/29
|
[
"https://Stackoverflow.com/questions/14082113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1673384/"
] |
effect.World is not a matrix representing the world. It is a matrix representing a 3d object's (mesh, model) position and orientation relative to the 3d game world. Each object will have a different effect.World matrix if they are positioned differently &/or pointed differently.
effect.View is a matrix that represents (in an inverted form) the position & orientation of the camera relative to that same 3d game world. Most of the time, there is only one camera, but there can be more (say, a rear view mirror will have it's own view matrix as opposed to the main screen showing the view out the windshield of a car racing game).
1. a model's vertices are hard valued to model local space.
2. Then the effect.World transforms them to game world space.
3. then the effect.View transforms them to camera space.
4. Then the effect.Projection transforms them to 2d screen space and 'volia', your pixel shader knows where to draw what.
|
10,701,393 |
Should an HTML email message begin like any valid HTML-document and should it even have a DOCTYPE declaration?
|
2012/05/22
|
[
"https://Stackoverflow.com/questions/10701393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92063/"
] |
HTML emails should include a doctype, html and body declaration if you intend to do anything fancy at all.
There are a multitude of guides on this subject which can help you learn how to properly code HTML Email, but most of them disregard the specifics of a doctype, which is how I stumbled on your question.
I suggest you read the following 2 posts which are from reputable teams familiar with the various problems:
[campaign monitor's take](http://www.campaignmonitor.com/blog/post/3317/correct-doctype-to-use-in-html-email/)
[email on acid's take](http://www.emailonacid.com/blog/details/C13/doctype_-_the_black_sheep_of_html_email_design)
|
33,302,235 |
I have a problem with reading from .xlsx (Excel) file. I tried to use:
```
var fileName = @"C:\automated_testing\ProductsUploadTemplate-2015-10-22.xlsx";
var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName);
var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "XLSData");
DataTable data = ds.Tables["XLSData"];
// ... Loop over all rows.
StringBuilder sb = new StringBuilder();
foreach (DataRow row in data.Rows)
{
sb.AppendLine(string.Join(",", row.ItemArray));
}
```
but if failed due to `connectionString`. So I updated the line to support .xlsx:
```
var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;", fileName);
```
but I get:
>
> The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
>
>
>
(Problem here is that, I am not able to install new software on my remote-testing machine, so I am not able to fix it and need to find other solution.)
I do also need to be sure that imported data will be stored in some simple way (I am beginner programmer) to let me iterate through it i.e. to create objects with row's data.
**Other approaches I checked:**
* <https://bytescout.com/products/developer/spreadsheetsdk/read-write-excel.html>
comment: seems to probably work for me, but doesn't support Excel files of unknown dimensions (random number of rows and columns).
* <https://exceldatareader.codeplex.com/>
comment: doesn't support settings column names from different row than first one (in some of my Excel files, there are comments in 4-6 first rows and then is headers row and data below).
* <http://blog.fryhard.com/archive/2010/10/28/reading-xlsx-files-using-c-and-epplus.aspx>
comment: same problem as above.
* <https://freenetexcel.codeplex.com/>
comment: downloaded package weight was over 60MB and it requires me to install it on system, which is not possible in my situation. Anyway, people comment that it is limited to 150 rows.
Meanwhile I will try to check <https://code.google.com/p/linqtoexcel/>, but all other ideas are more than welcome!
EDIT: Just checked that LinqToExcel, same issue as above:
>
> The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
>
>
>
**EDIT2: Ultimately, it seems that this solution solved my issue:**
<https://stackoverflow.com/a/19065266/3146582>
|
2015/10/23
|
[
"https://Stackoverflow.com/questions/33302235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3146582/"
] |
If you are reading data from `Excel` file, you can use `EPPlus` NuGet package, and use following code:
```
//using OfficeOpenXml;
using (ExcelPackage xlPackage = new ExcelPackage(new FileInfo(@"C:\YourDirectory\sample.xlsx")))
{
var myWorksheet = xlPackage.Workbook.Worksheets.First(); //select sheet here
var totalRows = myWorksheet.Dimension.End.Row;
var totalColumns = myWorksheet.Dimension.End.Column;
var sb = new StringBuilder(); //this is your data
for (int rowNum = 1; rowNum <= totalRows; rowNum++) //select starting row here
{
var row = myWorksheet.Cells[rowNum, 1, rowNum, totalColumns].Select(c => c.Value == null ? string.Empty : c.Value.ToString());
sb.AppendLine(string.Join(",", row));
}
}
```
|
55,691,091 |
[](https://i.stack.imgur.com/Uw9j2.jpg)
I am trying to transfer some text files on SFTP Server using Putty command line option.
I have a batch file with the following commands:
```
(
echo cd /inbox
echo mput c:\temp\*.txt
echo bye
echo cd c:\temp\
echo del c:\temp\*.txt
) |echo open <username@ip> <port no> -pw password
```
However, when I execute the batch file I get stuck at "Keyboard interactive prompt from Server"
Appreciate any suggestions on how to get over this point to avoid manual intervention while executing this batch file?
|
2019/04/15
|
[
"https://Stackoverflow.com/questions/55691091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6089571/"
] |
You don't need to make 2 connections to the db for getting the same data. You could create a collection of objects and use them in place like such...
```
<?php
$arr = [];
$sql = "SELECT category.name as cat, article.name as art from category
JOIN article ON category.id = article.id";
$query = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($query)){
$obj = (object) [
"cat" => $row["cat"],
"art" => $row["art"]
];
array_push($arr, $obj);
}
mysqli_close($conn);
?>
<select name="category">
<option value="category">category name</option>
foreach($arr as $obj) {
?>
<option value='"<?php echo $obj->cat; ?>"'><?php echo $obj->cat; ?></option>
<?php
}
```
```
<select name="article">
<option value="articlename">article name</option>
foreach($arr as $obj) {
?>
<option value='"<?php echo $obj->art; ?>"'><?php echo $obj->art; ?></option>
<?php
}
```
|
63,853,893 |
Good day to all! I need Your help.
I have a DataFrame like:
```
df.sort_values('date')
name date mark
0 Jack 2019-03 4
1 Michael 2019-03 6
2 John 2019-03 9
3 Michael 2019-03 2
4 Jerry 2019-03 4
5 Jack 2019-03 5
6 John 2019-03 3
7 Jerry 2019-03 4
...
857 Jerry 2019-08 5
858 John 2019-08 7
859 Jack 2019-08 4
860 Michael 2019-08 6
860 Michael 2019-08 7
```
I want to leave only minimal values of marks for every person.
For example: if Jack had his minimal grade "**4**" several times, I need to delete other rows where Jack got other grades and leave the ones where he got "**4**". The same logic should apply to others too. Here is an example of a DataFrame I want:
```
df.sort_values('date')
name date mark
0 Jack 2019-03 4
3 Michael 2019-03 6
4 Jerry 2019-03 4
6 John 2019-03 3
7 Jerry 2019-03 4
...
859 Jack 2019-08 4
860 Michael 2019-08 6
```
Could you please advise me on how I should approach this?
|
2020/09/11
|
[
"https://Stackoverflow.com/questions/63853893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12935018/"
] |
You can use an `if_else` like so:
```r
library(lubridate)
library(dplyr)
x <- seq(1,5)
y <- c(dmy("04/02/1863", "29/10/1989", "16/03/2000", "14/05/2021", NA))
dat <- tibble(x,y)
dat %>%
mutate(y = if_else(y >= dmy("01/06/2020") | y < dmy("01/01/1900"), NA_Date_, y))
#> # A tibble: 5 x 2
#> x y
#> <int> <date>
#> 1 1 NA
#> 2 2 1989-10-29
#> 3 3 2000-03-16
#> 4 4 NA
#> 5 5 NA
```
|
9,942,275 |
I'm working with two-dimensional array-values that should be inserted into a ArrayList. But this is done in a for-loop and the value of the two-dimensional array-value gets changed as the loop runs since it is just used as an temp-variable (which makes all of the variables stored in the ArrayList gets changed as this variable changes).
So if I try to print out the content of the ArrayList when the loop is done all the values are the same.
```
for(int i = 0; i <= Counter; i++)
{
if(Xhavetomove >= i)
arrayvalue[0][0] = this.Xspeed;
else
arrayvalue[0][0] = 0;
if(Yhavetomove >= i)
arrayvalue[0][1] = this.Xspeed;
else
arrayvalue[0][1] = 1;
System.out.println(arrayvalue[0][1]);
Object.movement.add(arrayvalue);
}
```
Are there anyway I can make it store the value itself?
For example: The first time the loop runs the value is "5,5" but if I print out the ArrayList when the loop is done all the values has turned into "5,1".
|
2012/03/30
|
[
"https://Stackoverflow.com/questions/9942275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1255810/"
] |
The problem is the way Array is added to the Object here. You are not adding the Array to the Object. What is happening is you are adding the address to the location in memory where the Array resides. So every time you add the Array to the Object, you are adding the same address every time. So every Array in the Object is actually the same Array over and over since they all point to a single location in memory. So when you change the Array, it will appear to change all of them inside the Object.
The best thing to do is either create a new Array every time through the loop, essentially creating a new location in memory for the Array to reside, or `clone()` the Array which will create a new reference.
Example:
```
String[] houseOfStark = {"Eddard", "Catelyn",
"Robb", "Sansa", "Arya", "Bran", "Rickon"}; // Sorry Jon
String[] copyOfStark = houseOfStark;
String[] cloneOfStark = houseOfStark.clone();
houseOfStark[1] = "Lady Catelyn";
System.out.println(houseOfStark[1]);
System.out.println(copyOfStark[1]);
System.out.println(cloneOfStark[1]);
```
Will produce:
```
Lady Catelyn
Lady Catelyn
Catelyn
```
[Good blog post explaining the difference](http://geekswithblogs.net/dforhan/archive/2005/12/01/61852.aspx)
|
25,668,796 |
I'm trying to make a function that changes a char array from the main function, that's what I'm trying to do:
```
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
void change(char *a);
int main()
{
char a[] = "hello";
printf("\na = %s", a);
change(a);
printf("%\na = %s", a);
getch();
}
void change(char *a)
{
a = "goodbye";
}
```
|
2014/09/04
|
[
"https://Stackoverflow.com/questions/25668796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3174594/"
] |
Several problems with this code, but first we need to take a step back and talk about how arrays are handled in C.
Except when it is the operand of the `sizeof` or unary `&` operators, or is a string literal used to initialize another array in a declaration, an expression of type "N-element array of `T`" will be converted ("decay") to an expression of type "pointer to `T`", and the value of the expression will be the address of the first element of the array.
In the declaration
```
char a[] = "hello";
```
`"hello"` is a string literal, which has type "6-element array of `char`" (5 characters plus the 0 terminator). Since it is being used to initialize the array `a` in a declaration, the rule above doesn't apply; instead, the size of `a` is set to be the same as the size of the literal (6), and the contents of the string literal are copied to the array.
When you call `change` from `main` as
```
change(a);
```
the *expression* `a` has type "6-element array of `char`". Since it is neither a string literal nor the operand of the `sizeof` or unary `&` operators, that expression will be converted to type "pointer to `char`", and the value of the expression will be the address of the first element of the aray. Hence why the `change` function is declared as
```
void change(char *a);
```
In this context, `a` is simply a pointer. When you write
```
a = "goodbye";
```
the string literal `"goodbye"` is not being used in an initializer, and it's not the operand of the `sizeof` or unary `&` operators, so the expression is converted to type "pointer to `char`", and the value of the expression is the address of the first character. So what happens here is that you're copying the *address* of the string literal `"goodbye"` to `a`. This overwrites the value in `a`, but this `a` is not the same object in memory as the *array* `a` in `main`, so any changes to it are not reflected in `main`.
If you want to update the *contents* of an array, you will need to use the library functions `strcpy/strncpy` (for 0-terminated strings) or `memcpy` (for everything else), or update each element explicitly (`a[0]='g'; a[1]='o'; a[2]='o';`, etc).
To update the contents of `a`, you'd use
```
strcpy( a, "goodbye" );
```
**Except**...
`a` is only large enough to hold 5 characters plus a 0 terminator; `"goodbye"` is 7 characters plus the 0 terminator; it's two characters larger than what `a` is capable of storing. C will happliy let you perform the operation and trash the bytes immediately following `a`, which may lead to any number of problems (buffer overruns such as this are a classic malware exploit). You have a couple of choices at this juncture:
First, you could declare `a` to be large enough to handle either string:
```
#define MAX_LEN 10
...
char a[MAX_LEN] = "hello";
```
Second, you could limit the size of the string copied to `a`:
```
void change( char *a, size_t size )
{
strncpy( a, "goodbye", size - 1 );
a[size - 1] = 0;
}
```
Note that you will need to pass the number of elements `a` can store as a separate parameter when you call `change`; there's no way to tell from a pointer how big the array it points to is:
```
change( a, sizeof a / sizeof *a ); // although in this case, sizeof a would be
// sufficient.
```
|
67,481,013 |
I am using react-select with styled component and it is working but I want to use tailwind classes using twin macro.
```
import tw from 'twin.macro';
import styled from 'styled-components';
import Select from 'react-select';
export const StyledReactSelect = styled(Select)(() => [
`
.Select__control {
height: 40px;
width: 100%;
border: 1px solid #a1a1a1;
border-radius: 0;
cursor: pointer;
}
.Select__control:hover {
border-color: #a1a1a1;
}
.Select__control--is-focused {
box-shadow: 0 0 0 1px black;
outline: none;
}
.Select__indicator-separator {
display: none;
}
.Select__menu {
color: #3c3d3e;
}
`,
]);
```
**Now I want to use tw(twin-macro) with classes of react-select. can anyone help?**
|
2021/05/11
|
[
"https://Stackoverflow.com/questions/67481013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2585973/"
] |
When you define a Coroutine, eg;
```cs
using System.Collections;
public class C {
private void before() { }
private void after() { }
public IEnumerator MyCoroutine()
{
before();
yield return null;
after();
}
}
```
The compiler defines a new type to track the state of the method, including any local variables. You can see that in action by using a [decompiler](https://sharplab.io/#v2:D4AQDABCCMB0DCB7ANsgpgYwC4EtEDsBnAbgFgAoEAZigCYJ4IBvCiNiABwCccA3AQyxooAFggAjNADNEXNAAoAlMwgBfVu259BwkGP5ShXJSvXl2UGgEkAovgCuAWzRdBsiAFkAnki6J7uPgKihpsLOYW7JIyckpkEZFQ0NBQAOwQDqjxiWwGRnGhahSqQA).
While it's more work, and more complicated, you could implement your own `IEnumerable` types instead.
```cs
public class MyCoroutine : IEnumerator
{
private int state = 0;
public object Current { get; private set; }
private void before() { }
private void after() { }
public bool MoveNext()
{
switch (state)
{
case 0:
before();
state++;
Current = null;
return true;
case 1:
after();
state++;
break;
}
return false;
}
public void Reset() => throw new System.NotImplementedException();
}
```
Then it's up to you how you wish to save / load and resume your coroutines.
|
40,142,675 |
The method I am using takes two sorted lists and returns a single list containing all of the elements in the two original lists, in sorted order.
For example, if the original lists are (1, 4, 5) and (2, 3, 6) then the result list would be (1, 2, 3, 4, 5, 6).
Is there something I am missing?
```
public static<E extends Comparable<E>> List<E> mergeSortedLists(List<E> a, List<E> b) {
List<E> result = new ArrayList<E>();
PushbackIterator<E> aIter = new PushbackIterator<E>(a.iterator());
PushbackIterator<E> bIter = new PushbackIterator<E>(b.iterator());
while (aIter.hasNext() && bIter.hasNext()) {
if (aIter.next().compareTo(bIter.next()) < 0) {
result.add(aIter.next());
}
if (bIter.next().compareTo(bIter.next()) > 0){
result.add(bIter.next());
}
}
while (aIter.hasNext()) {
result.add(aIter.next());
}
while (bIter.hasNext()) {
result.add(bIter.next());
}
return result;
}
```
|
2016/10/19
|
[
"https://Stackoverflow.com/questions/40142675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5900887/"
] |
In order to perform a merge, you need to peek at the next value, so see which next value to use.
Eventually, one of the lists will run out of values before the other, so you need to check for that.
One trick is to use `null` as an End-Of-Data marker, assuming that lists cannot contain `null` values, which is a fair assumption since they have to be sorted. In that case, code will be like this:
```
public static <E extends Comparable<E>> List<E> mergeSortedLists(List<E> list1, List<E> list2) {
List<E> merged = new ArrayList<>(list1.size() + list2.size());
// Get list iterators and fetch first value from each, if available
Iterator<E> iter1 = list1.iterator();
Iterator<E> iter2 = list2.iterator();
E value1 = (iter1.hasNext() ? iter1.next() : null);
E value2 = (iter2.hasNext() ? iter2.next() : null);
// Loop while values remain in either list
while (value1 != null || value2 != null) {
// Choose list to pull value from
if (value2 == null || (value1 != null && value1.compareTo(value2) <= 0)) {
// Add list1 value to result and fetch next value, if available
merged.add(value1);
value1 = (iter1.hasNext() ? iter1.next() : null);
} else {
// Add list2 value to result and fetch next value, if available
merged.add(value2);
value2 = (iter2.hasNext() ? iter2.next() : null);
}
}
// Return merged result
return merged;
}
```
*Test*
```
System.out.println(mergeSortedLists(Arrays.asList(1, 4, 5),
Arrays.asList(2, 3, 6)));
```
*Output*
```
[1, 2, 3, 4, 5, 6]
```
|
44,691,438 |
I was trying to restore jenkins on a new machine by tacking up backup from old machine . I replaced the jenkins home directory of new machine from old one. When i launch jenkins it gives me this error.
```
Caused: java.io.IOException: Unable to read /var/lib/jenkins/config.xml
```
There is also
```
Caused: hudson.util.HudsonFailedToLoad
Caused: org.jvnet.hudson.reactor.ReactorException
```
Debug info is
---- Debugging information ----
```
message : hudson.security.ProjectMatrixAuthorizationStrategy
cause-exception : com.thoughtworks.xstream.mapper.CannotResolveClassException
cause-message : hudson.security.ProjectMatrixAuthorizationStrategy
class : hudson.model.Hudson
required-type : hudson.model.Hudson
converter-type : hudson.util.RobustReflectionConverter
path : /hudson/authorizationStrategy
line number : 11
version : not available
-------------------------------
```
This is what my config.xml look like
```
<useSecurity>true</useSecurity>
<authorizationStrategy class="hudson.security.ProjectMatrixAuthorizationStrategy">
<permission>hudson.model.Hudson.Administer:visha</permission>
</authorizationStrategy>
```
Can someone please help ?
|
2017/06/22
|
[
"https://Stackoverflow.com/questions/44691438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2991413/"
] |
This usually happens when the plugin providing the authorization strategy is not installed or enabled.
Make sure the `matrix-auth` plugin is installed and that it's not disabled (no `matrix-auth.jpi.disabled` file (or similar) in `$JENKINS_HOME/plugins/`).
|
52,205,476 |
**Now Playing Activity**
```js
public class NowPlayingActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nowplaying);
// The buttons on the screen
ImageButton playButton = findViewById(R.id.playButton);
ImageButton previousSongButton = findViewById(R.id.previousButton);
ImageButton nextSongButton = findViewById(R.id.nextButton);
ImageButton repeatButton = findViewById(R.id.repeatButton);
ImageButton shuffleButton = findViewById(R.id.shuffleButton);
Button albumsMenu = (Button) findViewById(R.id.albumsMenu);
Button artistsMenu = (Button) findViewById(R.id.artistsMenu);
albumsMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent albumsIntent = new Intent(NowPlayingActivity.this, AlbumsActivity.class);
startActivity(albumsIntent);
}
});
artistsMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent ArtistIntent = new Intent(NowPlayingActivity.this, ArtistsActivity.class);
startActivity(ArtistIntent);
}
});
}
}
```
```html
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFF7DA"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/nowplaying"
style="@style/CategoryStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FD8E09"
android:gravity="center_horizontal"
android:text="Now Playing" />
<ImageView
style="@style/CategoryIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="Now Playing"
android:src="@drawable/playicon" />
<TextView
android:id="@+id/artists"
style="@style/CategoryStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#379237"
android:gravity="center_horizontal"
android:text="Artists" />
<ImageView
style="@style/CategoryIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="Artists"
android:src="@drawable/artisticon" />
<TextView
android:id="@+id/albums"
style="@style/CategoryStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#8800A0"
android:gravity="center_horizontal"
android:text="Albums" />
<ImageView
style="@style/CategoryIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="Albums"
android:src="@drawable/albumicon" />
</LinearLayout>
```
**When I click on the error it takes me to nowPlaying.setOnClickListener(new View.OnClickListener() but I'm not sure what to do.**
```js
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the View that shows the now playing category
LinearLayout nowPlaying = findViewById(R.id.activity_nowPlaying);
//Find the View that shows the artists category
LinearLayout artists = findViewById(R.id.activity_artists);
//Find the View that shows the albums category
LinearLayout albums = findViewById(R.id.activity_albums);
nowPlaying.setOnClickListener(new View.OnClickListener() {
// This method will be executed when the now playing category is clicked on.
@Override
public void onClick(View view) {
// Create a new intent to open the {@link NowPlayingActivity}
Intent nowPlayingIntent = new Intent(MainActivity.this, NowPlayingActivity.class);
// Start the new activity
startActivity(nowPlayingIntent);
}
});
```
```html
**
This is the error I'm receiving.
-----------
**
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.alexaquinones.musicalstructure.MainActivity.onCreate(MainActivity.java:24)
```
|
2018/09/06
|
[
"https://Stackoverflow.com/questions/52205476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10256304/"
] |
Installing @types/moment as a dev dependency solved it for me.
|
20,764,375 |
I have 2 videos. Each 7 seconds long. I need the top video to fadeout after it is halfway done playing, revealing the bottom video for 3.5 seconds, then fading back in, in an infinite loop.
I am unable to get the video to fade and not sure how to make it start at a specific time. This is what I have:
JS
```
<script type="text/javascript">
video.addEventListener('ended', function () {
$('#vid').addClass('hide');
$('video').delay(100).fadeOut();
}, false);
video.play();
var vid1=document.getElementById("video-loop");
vid1.addEventListener(function () {
$('video').delay(100);
}, false);
vid1.play();
</script>
```
HTML
```
<div id="#video">
<video id="vid" autoplay preload="auto">
<source src="videos/interactive2_3.mp4.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' />
</video>
<video id="video-loop" preload="auto" loop>
<source src="videos/interactive2-loop.mp4.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' />
</video>
</div>
```
|
2013/12/24
|
[
"https://Stackoverflow.com/questions/20764375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2482256/"
] |
to track the time in the video and make decisions based on that, you'll want to track the `timeupdate` event on the video, and then use the `currentTime` property to decide what to do.
This fragment will allow you to swap one video out at the 2.5s mark, play the second for 3.5s then swap back to the first ... you can elaborate based on the timer events to make it more flexible for your scenario...
```
<script>
var showing = 1 // which of the two videos are showing at the moment
var video1 = document.getElementById('vid');
var video2 = document.getElementById('video-loop');
video1.addEventListener('timeupdate',function(e){
if ((showing == 1) && (video1.currentTime > 2.5)) {
showing=2
video1.pause()
$('#vid').delay(100).fadeOut();
$('#video-loop').delay(100).fadeIn();
video2.play()
}
});
video2.addEventListener('timeupdate',function(e){
if ((showing == 2) && (video2.currentTime > 3.5)) {
video2.pause()
$('#video-loop').delay(100).fadeOut();
$('#vid').delay(100).fadeIn();
video1.play()
}
});
</script>
```
|
237,697 |
In my [previous question](https://worldbuilding.stackexchange.com/questions/234454/i-designed-a-maglev-space-propulsion-tube-on-mt-everest-do-you-see-any-issues), I was discussing about the possibility of using a mass-driver on Mt. Everest, to propel payloads to space, and reduce the amount of fuel needed (RIP bulky rockets). A diagram below of my former design:[](https://i.stack.imgur.com/g18Ua.png)
However, there was a ton of issues with this design:
* Dangling a tube from a balloon is a really risky idea as the balloon can be torn apart by the wind and jet-stream on top of Mt. Everest. This could result in collapse of the structure. Firing a payload is even worse, as a tube that is dangling could suddenly jerk and tear the balloon cord, with catastrophic consequences.
* The Himalayas are an earthquake zone. The structure would break apart during earthquakes.
* Even if you managed not to exceed 3-4gs acceleration, then the curve above the ground could cause a dramatic acceleration spike, this can lead to serious consequences for astronauts.
* Mass drivers may work on airless planets like Moon and Mercury, but on Earth, the air is thick enough to burn the payload long before it attained orbit.
So, after a lot of thoughts, and ideas, I came up with a grander and more realistic design for the **Mt. Everest Maglev Accelerator**, this time with no ridiculous balloons, or spikes. So here is the design and its principles.
Design
=======
* This design consists of a large tube that is erected on giant graphene rods about 10 inches wide in diameter. This provides immense strength, as graphene is strong enough not to crush its base and be rigid.
* This design is a **ring-gun magnet** type accelerator. This means that the magnets are placed in rings that have the same poles facing the track. The interior of the tube would look sort of like this:[](https://i.stack.imgur.com/B7wYE.png)
* Cross-section of propulsion tube.[](https://i.stack.imgur.com/FIksn.png)
* The ring-magnets are still permanent and have a greater strength of 10 teslas. They are not electromagnets.
* The payload itself is attached with ring-magnets with like poles, i.e. south pole facing outwards. This generates strong repulsion that propel the rocket at high speeds. The ring-magnet themselves are reusable, they are detached from the payload, and fall back to earth, whereas the payload will gain even more momentum, due to conservation of I-can't-remember, as the ring-magnets are detached.
* The tube viewed above from ground, looks sort of like this. (Apologies, I am crappy at photoshop, so this is the best depiction I can make). It is about 30 km tall, and stretches into the lower stratosphere.
[](https://i.stack.imgur.com/LxKJ0.jpg)
* The tube's actual length is however astounding. It is about 500 km long, and is mostly built underground. It is made of titanium in order to withstand the stress and pressure from the weight of the mountains above it, and withstands earthquakes.
* The curve of the tube is gradual instead of sudden, as to prevent "jerks"(i.e. sudden high-Gs)
Principles
===========
The aim of the ~~mass driver~~ Maglev Accelerator is to make it travel so fast, that it won't have time to burn up in the atmosphere. I mean literally fast. The payload's velocity upon exiting the barrel is about 60-70 km/s (yes, Kms per second). The idea came from the [Plumbbob Pascal-B Borecap](https://www.businessinsider.com/fastest-object-robert-brownlee-2016-2?IR=T#since-then-brownlees-concludedit-was-going-too-fast-to-burn-up-before-reaching-outer-spaceafter-i-was-in-the-business-and-did-my-own-missile-launches-he-said-i-realized-that-that-piece-of-iron-didnt-have-time-to-burn-all-the-way-up-in-the-atmosphere-14), where it was theorised that it was moving so fast that it had literally no time to burn up in the atmosphere before reaching space.
Although this would mean that the payload is moving too fast for it to be able to remain in orbit (about 6x Earth's Escape Velocity), that is not a problem as this accelerator is meant for interplanetary journey, such as travelling to Saturn, Mars and Moon. I will discuss a **orbit-grade accelerator** in a future question, but for now, this accelerator cannot be used for orbiting payloads.
The reason why I am using Mt. Everest and not Chimborazo for the accelerator, is that Mt. Everest is actually closer to space than Chimborazo is. This may seem odd, but Mt. Everest's 9km height makes it closer to space than Chimborazo's 6km is. Although Earth being oblate makes Chimborazo cheat and get "taller" technically, Everest is still the victor, as the atmosphere is oblate like the Earth. The air pressure at the top of Mt. Chimborazo is just that at sea-level, whereas the air at the top of Mt. Everest is literally a partial vacuum, with just over a third that at sea-level. Everest's great height also provides structural support to the colossal accelerator to reach the required velocity.
**Is this design more better for propelling payloads/passengers to space? If no, then what flaws do I have to fix?**
Clarifications:
* No, this accelerator is absolutely not used for orbital journeys. This accelerator is used for interplanetary journeys, such as Earth-Mars, or Earth-Saturn journeys
Note: I'd like to avoid extended discussions in comments, as I have created [a chat room](https://chat.stackexchange.com/rooms/140455/mt-everest-maglev-accelerator-v2) for this question.
|
2022/11/06
|
[
"https://worldbuilding.stackexchange.com/questions/237697",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/97694/"
] |
Impossibility 1: Ring magnets as depicted
-----------------------------------------
All magnetic fields need to be closed curves. The ring magnet as depicted would require a magnetic source at the very center of the ring, which is forbidden.
The problem can be alleviated by placing many magnets on the outside in the correct orientation but with small wedge-shaped gaps between every two magnets. Technically you only need a few (1-3) long magnet rail tracks, which allows orientation control of the payload and considerably reduces construction costs.
It's by the way better to use permanent magnets *attracting* to the track than repulsing from it, that way the payload can not *overturn* and slip out of the magnetic track. A simple set of ring motors could be used to give the capsule any wanted orientation by rotating the magnet tracks around the tube or their receptors on the payload - even allowing to simulate *rifling* to achieve spin stabilization.
Impossibility 2: only permanent magnet accelerator
--------------------------------------------------
The maglev track is perfect to get minimal drag, and as explained above, does work. However, it does not accelerate on its own - it simply provides a means to have extremely low friction to the guide rail.
If you take a slice from real Maglev trains, a set of coils inside the train car is electrified to create repulsing forces in some areas and attracting in others, which all in all accelerate the vehicle.
Impossibility 3: architectural constraints
------------------------------------------
You have a $\pu{30 km}$ pipe extending for up to about $\pu{22 km}$ above the point we leave the tip of Mt Everest. It is supported on stilts up to $\pu{25 km}$ long, assuming that the highland below is *just* about $\pu{5 km}$ above sea level. That is well beyond what **any** material can do. Steel is typically blessed with allowing $\pu{25000 psi}\ (\pu{172 MPa})$ compressible force before failure, which is [6 times that of concrete](https://blog.redguard.com/compressive-strength-of-steel). But well-made steel can get better, up to $\pu{250 MPa}$ are possible. That's $\pu{250 000 000 N/m² }$. Above that, the column collapses under its own weight
But the column itself weighs a lot: assuming we have a crossection of one square meter of steel, then each meter height (and thus each cubic-meter) weighs 7.85 tons $(\pu{7850 kg})$, exerting roughly $\pu{78500 N}$ each. At which point *stacking bricks* makes the lowest one crumble? Well... incidentally the compressive strength would itself allow for being 3184.71 meters tall. so roundabout 3 Kilometers. Or at **best** a tiny fraction of the pillar length needed to support the tube - and we haven't even assigned any weight to that.
The pipe goes up to maybe 10 kilometers... and then it breaks down, having to end as it can't be supported with any material or construction.
Exotic materials, such as Graphene fare much worse: Graphene's compressive strength is [only](https://aip.scitation.org/doi/pdf/10.1063/1.5020547) $\pu{8.5 MPa}$ under normal conditions but could be driven to $\pu{28.8 MPa}$ at $\pu{2267 kg/m³}$. As a result for a maximum pillar height of Graphene is just $\pu{375 m}$ or, with the special tricks,
$\pu{1270 m}$
A 10-inch graphene rod fares exactly the same: It has $\pu{78.5 in²}$ or almost exactly $\pu{0.05 m²}$ area. Let's keep that. It can sustain the same pressure before collapsing, so the lowest piece can carry $\pu{0.05m²}\times \pu{28.8 kg/m²}$ load. Each Meter height weighs in at $\pu{0.05m³}\times \pu{2267kg/m³}$. As a result, we get exactly the same height for a stable column as before: 375 to $\pu{1270 m}$.
|
72,630,214 |
I have this laravel project, but due the specific version of it's dependencies it need php 8 to run, but I need it to run with php 7.4, is there a way so that we can downgrade the dependencies?
```
....
"require": {
"php": "^8.0.2",
"barryvdh/laravel-debugbar": "^3.6",
"fruitcake/laravel-cors": "^2.0.5",
"guzzlehttp/guzzle": "^7.2",
"intervention/image": "^2.7",
"laravel/framework": "^9.0",
"laravel/sanctum": "^2.14",
"laravel/tinker": "^2.7",
"laravel/ui": "^3.4",
"laravelcollective/html": "^6.3"
},
"require-dev": {
"brianium/paratest": "^6.4",
"fakerphp/faker": "^1.9.1",
"laravel/sail": "^1.0.1",
"mockery/mockery": "^1.4.4",
"nunomaduro/collision": "^6.1",
"pestphp/pest-plugin-laravel": "^1.2",
"pestphp/pest-plugin-parallel": "^1.0",
"phpunit/phpunit": "^9.5.10",
"spatie/laravel-ignition": "^1.0"
},
...
```
Note: So far I could only found that manually searching for proper version compatible to php 7.4 and adjust it inside composer.json manually is an option.
|
2022/06/15
|
[
"https://Stackoverflow.com/questions/72630214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7995302/"
] |
Laravel 9 [works only](https://github.com/laravel/framework/blob/9.x/composer.json) on PHP 8, so you can't, unless you are up to downgrading Laravel version too. But installing newer PHP will be faster.
|
279,607 |
I've encountered the following notation several times (for example, when discussing Noether's Theorem):
$$\frac{\partial L}{\partial(\partial\_\mu \phi)}$$
And it's not immediately clear to me what this operator $\frac{\partial}{\partial(\partial\_\mu \phi)}$ refers to. Based on the answer to [this question](https://physics.stackexchange.com/questions/88935/derivative-with-respect-to-a-vector-is-a-gradient) and the structure of the covariant derivative, I'm guessing it's just a short-hand for the following operator:
$$\frac{\partial}{\partial(\partial\_\mu \phi)}\equiv\pm(\frac{\partial}{\partial\dot{\phi}},-\frac{\partial}{\partial(\nabla\phi)})$$
I.e.
$$\frac{\partial L}{\partial(\partial\_\mu \phi)}\equiv\pm(\frac{\partial L}{\partial\dot{\phi}},-\frac{\partial L}{\partial(\nabla\phi)})$$
where the $\pm$ comes from your convention for the Minkowski metric.
This is just a guess. Can someone verify, perhaps with a source?
|
2016/09/11
|
[
"https://physics.stackexchange.com/questions/279607",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/52072/"
] |
In field theory usually you have a Lagrangian density function of fields and first derivative of fields or
$$\mathscr{L}(\phi,\partial\_\mu\phi).$$ It is well know that higher derivative of field than first are in some way problematic (Hamiltonian not bounded from below). Field equations follow from Euler-Lagrange equations in which you treat $\phi$ and $\partial\_\mu\phi$ as independent variables. The same happen in Classical Mechanic where your Lagrangian is a function of two variables $q$ and $\dot{q}$. So if you are familiar with $$\frac{\partial L}{\partial\dot{q}}$$ you should become familiar with the field theoretic version.
|
251,179 |
How do I let a few specified non-subscriber email addresses post to an otherwise closed GNU Mailman mailing list?
|
2011/03/24
|
[
"https://serverfault.com/questions/251179",
"https://serverfault.com",
"https://serverfault.com/users/10813/"
] |
I finally figured out how to do this!
Go to the list's Privacy Options, click on Sender Filters, then add the emails to the option called `accept_these_nonmembers`.
|
23,374,985 |
I'm using Susy 2 with breakpoint-sass to create my media queries.
It's outputting like:
```
@media (min-width: 1000px)
```
I'm wondering why the screen is missing? It should read:
```
@media screen (min-width: 1000px)
```
I'm trying to add css3-mediaqueries-js which isn't working and I think that might be why.
|
2014/04/29
|
[
"https://Stackoverflow.com/questions/23374985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/823239/"
] |
If you want to use `HashSet`, you can override `hashCode` and `equals` to exclusively look at those two members.
Hash code: (`31` is just a prime popularly used for hashing in Java)
```
return 31*id_a + id_b;
```
Equals: (to which you'll obviously need to add `instanceof` checks and type conversion)
```
return id_a == other.id_a && id_b == other.id_b;
```
If you don't want to bind these functions to the class because it's used differently elsewhere, but you still want to use `HashSet`, you could consider:
* Creating an intermediate class to be stored in the set, which will contain your class as a member and implement the above methods appropriately.
* Use your string approach
* Use `HashSet<Point>` - `Point` is not ideal for non-coordinate purposes as the members are simply named `x` and `y`, but I do find it useful to have such a class available, at least for non-production code.
---
Alternatively, if you want to use `TreeSet`, you could have your class implement `Comparable` (overriding `compareTo`) or provide a `Comparator` for the `TreeSet`, both of which would compare primarily on the one id, and secondarily on the other.
The basic idea would look something like this:
```
if (objectA.id_a != objectB.id_a)
return Integer.compare(objectA.id_a, objectB.id_a);
return Integer.compare(objectA.id_b, objectB.id_b);
```
|
49,929,034 |
Trying to figure out this error. I am attempting to call on an API, and map the JSON data from the API call to a CurrencyModel. No issues with that, but when I am calling on a method that returns an observable (as it is waiting for two other API calls), it's throwing the following error to the provider property:
>
> Type '{}' is not assignable to type 'CurrencyModel'.
>
>
>
**src/models/currency.ts**
```ts
export class CurrencyModel{
private _base_currency_code: string;
private _base_currency_symbol: string;
private _default_display_currency_code: string;
private _default_display_currency_symbol: string;
private _available_currency_codes: Array<string> = [];
private _exchange_rates: Array<CurrencyExchangeRateModel> = [];
//extension attributes
get base_currency_code(): string{
return this._base_currency_code;
}
set base_currency_code(value: string){
this._base_currency_code = value;
}
get base_currency_symbol(): string{
return this._base_currency_symbol;
}
set base_currency_symbol(value: string){
this._base_currency_symbol = value;
}
get default_display_currency_code(): string{
return this._default_display_currency_code;
}
set default_display_currency_code(value: string){
this._default_display_currency_code = value;
}
get default_display_currency_symbol(): string{
return this._default_display_currency_symbol;
}
set default_display_currency_symbol(value: string){
this._default_display_currency_symbol = value;
}
get available_currency_codes(): Array<string>{
return this._available_currency_codes;
}
getAvailableCurrencyCode(key: number): string{
return this.available_currency_codes[key];
}
set available_currency_codes(value: Array<string>){
this._available_currency_codes = value;
}
setAvailableCurrencyCode(value: string): void{
this.available_currency_codes.push(value);
}
get exchange_rates(): Array<CurrencyExchangeRateModel>{
return this._exchange_rates;
}
getExchangeRate(key: number): CurrencyExchangeRateModel{
return this.exchange_rates[key];
}
set exchange_rates(value: Array<CurrencyExchangeRateModel>){
this._exchange_rates = value;
}
setExchangeRate(value: CurrencyExchangeRateModel): void{
this.exchange_rates.push(value);
}
constructor(response?: any){
if(response){
this.base_currency_code = response.base_currency_code;
this.base_currency_symbol = response.base_currency_symbol;
this.default_display_currency_code = response.default_display_currency_code;
this.default_display_currency_symbol = response.default_display_currency_symbol;
this.available_currency_codes = response.available_currency_codes ;
if(response.exchange_rates){
for(let rate of response.exchange_rates){
this.setExchangeRate( new CurrencyExchangeRateModel(rate) );
}
}
}
}
}
```
**src/providers/store/store.ts**
```ts
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Platform } from 'ionic-angular';
import { CurrencyModel } from '../../models/store/currency';
import { Observable } from 'rxjs/Observable';
import { forkJoin } from "rxjs/observable/forkJoin";
import { map } from 'rxjs/operators';
@Injectable()
export class StoreProvider {
private apiUrl:string;
// Defaults
config: ConfigModel;
countries: Array<CountryModel> = [];
currency: CurrencyModel;
constructor(public http: HttpClient){}
readCurrency(): Observable<CurrencyModel>{
return this.http.get<CurrencyModel>(this.apiUrl + '/directory/currency').pipe(
map(data => new CurrencyModel(data))
);
}
readConfig(): any{
return this.http.get(this.apiUrl + '/store/storeConfigs');
}
//readCountries is the same, just different url
getProperties(): Observable<boolean>{
return Observable.create(observer => {
let requests: Array<any> = [
this.readConfig(),
this.readCountries(),
this.readCurrency()
];
forkJoin(requests).subscribe(data => {
this.config = this.getConfig(data[0][0]);
this.countries = this.getCountries(data[1]);
this.currency = data[2]; // Problem area
observer.next(true);
}, err => {
observer.error(err);
});
});
}
}
```
Purpose with the getProperties is to get data from the website that will need to be loaded first before anything else.
**Data structure of response (Magento 2 Currency)**
```json
{
"base_currency_code": "string",
"base_currency_symbol": "string",
"default_display_currency_code": "string",
"default_display_currency_symbol": "string",
"available_currency_codes": [
"string"
],
"exchange_rates": [
{
"currency_to": "string",
"rate": 0,
"extension_attributes": {}
}
],
"extension_attributes": {}
}
```
EDIT: Added the JSON data structure and CurrencyModel
|
2018/04/19
|
[
"https://Stackoverflow.com/questions/49929034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4008500/"
] |
if you use the `elif` construct, it will be tested only when the previous condition was false, so in the end only one of the code blocks will run.
```
if some_condition:
# code
elif another_condition:
# code
elif yet_another_condition:
# code
else:
# code
```
|
2,185,846 |
I just uploaded my application in the market, but I'm not able to purchase it (it's a pay app).
I saw [here](http://market.android.com/support/bin/answer.py?hl=en&answer=141659) that it seems to be *made by design*, but then why the error message is `Server Error try again` ?
Is there a way to bypass that ?
|
2010/02/02
|
[
"https://Stackoverflow.com/questions/2185846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231417/"
] |
Do you have an Android Developer Phone? If so, you can't purchase your own app by design. Since ADPs are unlocked, there's nothing preventing an ADP from easily pirating any app it downloads, so they are purposely cut off from downloading paid apps.
|
50,046,938 |
I'm working with places, and I need to get the latitude and longitude of my location. I successfully got it like this
```
mLatLang = placeLikelihood.getPlace().getLatLng();
```
where mLatLang is `LatLng mLatLang;`
Now, the output of this line is
```
(-31.54254542,62.56524)
```
but since I'm using an URL to query results by the latitude and longitude, I can't put that data inside the query with the parenthesis `()`.
So far I have searched Stack Overflow for all kinds of Regex to remove this, but it seems I can't do it. I have tried this with no success:
```
types = placeLikelihood.getPlace().getPlaceTypes();
mLatLang = placeLikelihood.getPlace().getLatLng();
String latlongshrink = mLatLang.toString();
latlongshrink.replaceAll("[\\\\[\\\\](){}]","");
```
I have also tried a lot more `replaceAll` Regex, but I can't remove them.
My output should be like this:
```
-31.54254542,62.56524
```
|
2018/04/26
|
[
"https://Stackoverflow.com/questions/50046938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9164141/"
] |
What you are missing in your logic is that `replaceAll` returns the resultant string. But you are not storing the result, and that's why it's not working. So try as following:
```
latlongshrink = latlongshrink.replaceAll("[\\\\[\\\\](){}]","");
```
Now try to print the result. It'll give the expected result. See [this](https://www.javatpoint.com/java-string-replaceall) for more information about `replaceAll()` function.
|
41,196,867 |
This is a question I always had, but now is the time to solve it:
I'm trying to implement the composition of objects using public attributes like:
```
Person {
public Car car;
}
Owner {
public Person person;
public Car car;
}
Car {
public Person person;
}
```
Really my question is: Is a good practice to set that composition properties public or private?
The difference:
a) **Public**: doing public, the access is fast and not complicated, because I only need to reference the property directly with the instance like:
```
$instancePerson.car.getNumberOfGearsGood()
```
The problem: the car propertie is available to be modified by anybody from anywhere.
b) **Private**: doing private, the access if slow and is necessary to use methods to get these properties like:
```
$instancePerson.getCar().getNumberOfGearsGood()
```
When I say slow is because you need to do a method two method call, while in the Public solution only you need to do one.
I know many developers and software engineers here will prefer Private solution, but can you explain the performance there?
|
2016/12/17
|
[
"https://Stackoverflow.com/questions/41196867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5900879/"
] |
If you are doing OO, there should be no such thing as a "public" attribute. All the attributes are implementation details of the object, therefore are hidden from everybody. Only the methods associated with the object's responsibility are public.
So to answer the question:
* All "attributes" should be private
* *And* there should be no getter on a private attribute
Yes, there should be no
```java
person.getCar().getNumberOfGears();
```
This is sometimes called the [Law of Demeter](https://en.wikipedia.org/wiki/Law_of_Demeter). The person should have methods that do stuff connected to the responsibility of the Person class, therefore there is no performance penalty accessing attributes, because this access is always internal to the class and direct.
|
1,015,017 |
Simple as that, can we emulate the "protected" visibility in Javascript somehow?
|
2009/06/18
|
[
"https://Stackoverflow.com/questions/1015017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12540/"
] |
Do this:
```
/* Note: Do not break/touch this object */
...code...
```
Or a bit of google found this on the first page:
<http://blog.blanquera.com/2009/03/javascript-protected-methods-and.html>
|
10,476,265 |
I have a PDF form that needs to be filled out a bunch of times (it's a timesheet to be exact). Now since I don't want to do this by hand, I was looking for a way to fill them out using a python script or tools that could be used in a bash script.
Does anyone have experience with this?
|
2012/05/07
|
[
"https://Stackoverflow.com/questions/10476265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/701409/"
] |
**For Python you'll need the fdfgen lib and pdftk**
@Hugh Bothwell's comment is 100% correct so I'll extend that answer with a working implementation.
If you're in windows you'll also need to make sure both python and pdftk are contained in the system path (unless you want to use long folder names).
Here's the code to auto-batch-fill a collection of PDF forms from a CSV data file:
```
import csv
from fdfgen import forge_fdf
import os
import sys
sys.path.insert(0, os.getcwd())
filename_prefix = "NVC"
csv_file = "NVC.csv"
pdf_file = "NVC.pdf"
tmp_file = "tmp.fdf"
output_folder = './output/'
def process_csv(file):
headers = []
data = []
csv_data = csv.reader(open(file))
for i, row in enumerate(csv_data):
if i == 0:
headers = row
continue;
field = []
for i in range(len(headers)):
field.append((headers[i], row[i]))
data.append(field)
return data
def form_fill(fields):
fdf = forge_fdf("",fields,[],[],[])
fdf_file = open(tmp_file,"w")
fdf_file.write(fdf)
fdf_file.close()
output_file = '{0}{1} {2}.pdf'.format(output_folder, filename_prefix, fields[1][1])
cmd = 'pdftk "{0}" fill_form "{1}" output "{2}" dont_ask'.format(pdf_file, tmp_file, output_file)
os.system(cmd)
os.remove(tmp_file)
data = process_csv(csv_file)
print('Generating Forms:')
print('-----------------------')
for i in data:
if i[0][1] == 'Yes':
continue
print('{0} {1} created...'.format(filename_prefix, i[1][1]))
form_fill(i)
```
*Note: It shouldn't be rocket-surgery to figure out how to customize this. The initial variable declarations contain the custom configuration.*
In the CSV, in the first row each column will contain the name of the corresponding field name in the PDF file. Any columns that don't have corresponding fields in the template will be ignored.
In the PDF template, just create editable fields where you want your data to fill and make sure the names match up with the CSV data.
For this specific configuration, just put this file in the same folder as your NVC.csv, NVC.pdf, and a folder named 'output'. Run it and it automagically does the rest.
|
275,889 |
In quantum mechanics it is usually the case that when degrees of freedom in a system are traced out (i.e. ignored), the evolution of the remaining system is no longer unitary and this is formally described as the entropy of the reduced density matrix ($S = Tr(\rho\ln{\rho}$)) attaining a nonzero value.
Why is it then that there exist certain quantum mechanical systems which have unitary evolution, but for which we clearly do not keep track of all degrees of freedom? Practically any non-relativistic quantum system such as atomic structure, spin chains, any implementation of a quantum computer etc. are clearly just effective theories which ignore the massive number of degrees of freedom underlying the more fundamental physics, i.e. quantum field theory. But somehow we are able to trace away all of this underlying physics into an effective potential/interaction term in a Hamiltonian and thus retain unitarity.
Now this does not work entirely for all systems, particularly it is impossible to hide away the full coupling of an atom to the EM field because you have spontaneous emission, a non-unitary effect. But still a large part of the electron/proton interaction (which is really mediated through the EM field) can be captured by the Coulomb potential, which ignores the EM field yet is still unitary. On the other hand, some systems, such as certain implementations of quantum computing/simulation claim to be able to achieve perfect unitarity and are only limited by imperfections in the system. At least, I have never heard of anyone talking about intrinsic unitarity limitations to a quantum computer.
My questions are:
-Under what conditions can underlying degrees of freedom be hidden away into a unitary interaction?
-Are there intrinsic limits to unitarity of any quantum system (such as an atom's unitarity being limited by spon. emission), assuming that you will always trace out a portion of the underlying field theory?
|
2016/08/23
|
[
"https://physics.stackexchange.com/questions/275889",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/41152/"
] |
The answer to your question is a bit subtle and has to do with the various ways we can ignore degrees of freedom in physics. One way, as you mentioned, is if you have a system interacting with its environment but you don't care about the state of the environment. Then you can perform a partial trace over environmental states and obtain a reduced density matrix describing the quantum state of the system. This reduced density matrix will $not$ evolve unitarily.
However, there is another way to remove degrees of freedom in order to simplify your problem. This is called integrating out variables/fields. Suppose you have a theory that works to arbitrarily high energy, but you only care about low energy excitations of your system. You can "integrate out" the high energy modes of your system and obtain a low-energy effective field theory that is still unitary (as long as you remain at low energy). If you are familiar with QFT, a common example of this is the Four Fermi theory obtained by integrating out the very heavy W and Z bosons of the standard model.
The reason you can integrate out the W and Z bosons at low energy is that they are extremely massive compared to the other particles in the theory. Thus, at low energy they can never be produced. So when you integrate out the W and Z, you are not actually ignoring anything $physical$ as you are if you perform a partial trace over an environment. (If you were working at high enough energies to produce W and Z bosons then you would be ignoring physical particles, so your theory would no longer be unitary).
To use an example you mentioned: why can you not integrate out EM fields to get an effective theory for hydrogen atoms? The reason is that photons are massless, so no matter what energies you are working at, photons can always be created. Thus, integrating out photons would involve ignoring physical objects and would result in non-unitary behavior.
To recap: there are two ways of ignoring degrees of freedom:
(1) If you ignore physical things eg though partial traces, then you will not have unitary behavior.
(2) If you are working at low energy but simplify your theory by ignoring high energy physics, then you can obtain a low energy effective theory that is unitary. However if you push this low energy theory to high energy, it will (usually) fail to be unitary.
|
5,817,526 |
So I was wondering, is there any feasible way in JavaScript to view information about scheduled timeouts and intervals that you don't explicitly know about (I know `setTimeout` and `setInterval` return a handle that can be used to refer to the scheduled instance, but say that this is unavailable for one reason or another)? For instance, is there a way to use a tool like Chrome's JavaScript console to determine what timeouts are currently active on an arbitrary page, when they will fire, and what code will be executed when they fire? More specifically, say a page has just executed the following JavaScript:
```
setTimeout("alert('test');", 30000);
```
Is there some code I can execute at this point that will tell me that the browser will execute `alert('test');` 30 seconds from now?
It seems like there theoretically should be some way to get this information since pretty much everything in JavaScript is exposed as a publicly accessible property if you know where to look, but I can't recall an instance of ever doing this myself or seeing it done by someone else.
|
2011/04/28
|
[
"https://Stackoverflow.com/questions/5817526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/609251/"
] |
how about simply rewriting the setTimeout function to sort of inject custom logging functionality?
like
```
var oldTimeout = setTimeout;
window.setTimeout = function(callback, timeout) {
console.log("timeout started");
return oldTimeout(function() {
console.log('timeout finished');
callback();
}, timeout);
}
```
might work?
|
29,138,498 |
Can I import RDBMS table data (table doesn't have a primary key) to hive using sqoop? If yes, then can you please give the sqoop import command.
I have tried with sqoop import general command, but it failed.
|
2015/03/19
|
[
"https://Stackoverflow.com/questions/29138498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4688490/"
] |
If your table has no primary key defined then you have to give `-m 1` option for importing the data or you have to provide `--split-by` argument with some column name, otherwise it gives the error:
```
ERROR tool.ImportTool: Error during import: No primary key could be found for table <table_name>. Please specify one with --split-by or perform a sequential import with '-m 1'
```
then your sqoop command will look like
```
sqoop import \
--connect jdbc:mysql://localhost/test_db \
--username root \
--password **** \
--table user \
--target-dir /user/root/user_data \
--columns "first_name, last_name, created_date"
-m 1
```
or
```
sqoop import \
--connect jdbc:mysql://localhost/test_db \
--username root \
--password **** \
--table user \
--target-dir /user/root/user_data \
--columns "first_name, last_name, created_date"
--split-by created_date
```
|
3,585 |
I have recently setup Wordpress Multisite and have that working well. Now to complete the branding, I want to use `feeds.mydomain.com` for the MyBrand integration to Feedburner. I have setup the CNAME to point to the server that Feedburner has specified, but when I visit the site (after ensuring the entry could propagate), WordPress takes over thinking I want to create a new website. I am guessing this is a DNS issue, but I am not sure where to begin to troubleshoot this further.
|
2010/10/06
|
[
"https://webmasters.stackexchange.com/questions/3585",
"https://webmasters.stackexchange.com",
"https://webmasters.stackexchange.com/users/835/"
] |
This is probably a DNS issue. Make sure `feeds.mydomain.com` points to Feedburner. You can easily check it running a DNS query.
With Linux/MacOSX, use the `dig` command.
```
$ dig feeds.engadget.com
; <<>> DiG 9.6.0-APPLE-P2 <<>> feeds.engadget.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 19666
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;feeds.engadget.com. IN A
;; ANSWER SECTION:
feeds.engadget.com. 2010 IN CNAME weblogsinc.feedproxy.ghs.google.com.
weblogsinc.feedproxy.ghs.google.com. 28 IN CNAME ghs.l.google.com.
ghs.l.google.com. 200 IN A 74.125.77.121
;; Query time: 78 msec
;; SERVER: 85.37.17.16#53(85.37.17.16)
;; WHEN: Wed Oct 6 20:56:36 2010
;; MSG SIZE rcvd: 118
```
You can also run a DNS query using an online service, e.g. [DNS Query](http://www.dnsqueries.com/en/dns_query.php). The DNS response should be a CNAME record pointing to `ghs.l.google.com`. If it is an `A` record, the DNS hasn't been property set.
|
23,996 |
Let me introduce my idea.
Given:
* sizeof( Blockchain ) = 16Gb
* Downloading of one avi film 16GB from the pirate bay ( 5mb/s ) = 2-3 hours
* Downloading of bitcoin's blockchain ( 5mb/s ) = 2-3 days
* One day = 6 \* 24 = 144 blocks.
* Drag - cryptography.
Task:
* Accelerate boot of fresh client to the torrent speed. Similar to **Bootstrap**.
---
As I can see, downloading of blockchain is the same hard as mining, because there is every time recalculation of hash, comparing, checking of signs, etc...
What if client will only download this 144 blocks for a day and one super block with 144 hashs of the last valid blocks, thereafter only compare current wallet's addresses with addresses in this 144 blocks without any calculation of its hash.
Is there any alt-coin with such accelerator?
---
E.g. this super blocks might be archived into another ultra-block for a month. Than we have similar to sha(sha(text)) cascade shield against bruteforce attack.
Downloading of blockchain should takes at max the same time as downloading of 16GB avi from the pirate bay. Say, 5mb/s internet channel + p2p / 16 Gb = 2, may be 3 hours ( in the `no peers case` ), but I spent 2 - 3 days, and I see that this is no internet speed reason, it is CPU + harddisk very very hard job.
|
2014/03/26
|
[
"https://bitcoin.stackexchange.com/questions/23996",
"https://bitcoin.stackexchange.com",
"https://bitcoin.stackexchange.com/users/12645/"
] |
When a node learns of a transaction, some validity tests are performed and if the transaction is not yet in the blockchain it knows of with the longest height and the transaction also is valid (i.e., not a double spend) then that transaction is added to that node's memory pool.
If a later transaction arrives at a node but is an attempt to double spending of a transaction that is either already in the blockchain with the longest height or is already in the memory pool, then that later transaction is ignored.
A transaction propagates to nearly all miners within seconds, so most miners would immediately reject your later double-spend attempt since they would already know of the earlier transaction.
Blockchain forks happen all the time (i.e., multiple times each day). So it is entirely possible to have conflicts where a transaction is included in a block on one side of the fork but is not yet in the block (or blocks) on the other side of the fork. Eventually one of the several competing blockchain forks will emerge as the longest chain and the transactions in that chain are the ones reflected in the Bitcoin ledger from then on. That's why exchanges wait until three or six confirmations -- as it is technically possible for there to be variations between sides should a fork occur.
Attackers might use this temporary inconsistency in an attempt to defraud by employing a race attack or other approach. This is requisite reading on the topic: <http://en.bitcoin.it/wiki/Double-spending>
|
79,602 |
I'm learning Salesforce Marketing Cloud and experienced some unexpected behavior today.
I sent a message to a number of data extensions. The number of recipients was upwards of 70,000. Before I sent the official email I sent a test specifically to my address. Everything looked good so I used Guided Send to send to the data extensions.
This was 4 hours ago and I have not received the message yet but my coworker who sits across from me has. This coworker and I likely would have been in the same data extension.
I verified that my name and email address are in the data extension. Does it just take this long to distribute to a huge list? Did it not send to me since I received a test send? Or is something likely wrong?
I checked all folders in my email and do not see it.
Thank you
|
2015/06/11
|
[
"https://salesforce.stackexchange.com/questions/79602",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/21233/"
] |
Also you can directly query in child object using relationship fields,
```
[select ISOOffice__Merchant_Location__c,Account__r.Name
from ISOOffice__Merchant_Opportunity__c where
ISOOffice__Opportunity_Type__c = 'New Merchant' AND
Account__r.Name = 'Goodwill of Southwestern Pennsylvania']
```
You need to prefix ISOOffice\_\_Merchant\_Location\_\_c with Account\_\_r, if this field is in account.
|
40,910,892 |
I am trying to call Application insights API using pageviews Event and i get this error message
```
{
"error": {
"message": "Rate limit is exceeded",
"code": "ThrottledError",
"innererror": {
"code": "ThrottledError",
"message": "Rate limit of 0 per day is exceeded.",
"limitValue": 0,
"moreInfo": "https://aka.ms/api-limits"
}
}
}
```
can anyone help me fix this ?
|
2016/12/01
|
[
"https://Stackoverflow.com/questions/40910892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7236177/"
] |
You get this issue if you are on the old pricing model, and you don't if you are on the new pricing model.
Unless you created a brand new Application Insights instance very recently, you are probably are on the old pricing model. Easiest way to tell is if you see "Features + pricing" in your Application Insights, you are on the new model.
[](https://i.stack.imgur.com/YShvQ.png)
There is no difference between changing the pricing plan (between free/standard/premium), the throttle is still there.
If you want to move to the new pricing model, Microsoft offer two options:
>
> If you’re willing to wait until February 1st, 2017, we will handle the transition automatically for you, and this will be the best option for most customers. Under this approach, we will transition your application to Application Insights Basic in most cases. (Applications using continuous export or the Connector for OMS Log Analytics will be transitioned to Application Insights Enterprise.)
>
>
> However, if you prefer to use one of the new pricing options immediately, you can also do this. It involves choosing to stop billing for your existing plan (Standard or Premium), then creating a new Application Insights resource within the Azure portal, choosing the pricing option you prefer, and then updating the Instrumentation Key within your application. One downside of doing this is that you will lose the continuity of reporting because you will have the old Instrumentation Key for your application under the Preview plan, and a new Instrumentation Key for your application under the new pricing model.
>
>
>
This can be found as the last FAQ item on the [Application Insights pricing page](https://azure.microsoft.com/en-us/pricing/details/application-insights/)
|
21,586,409 |
I want to get notified when a test fails. Ideally, I want to know if the test is passed or failed in my @After annotated method. I understand that their is a RunListener which can be used for this purpose but it works only if we run the test with JunitCore. Is there a way to get notified if a test case fails or something similar to RunListener which can be used with SpringJUnit4ClassRunner?
|
2014/02/05
|
[
"https://Stackoverflow.com/questions/21586409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2943317/"
] |
The Spring TestContext Framework provides a `TestExecutionListener` SPI that can be used to achieve this.
Basically, if you implement `TestExecutionListener` (or better yet extend `AbstractTestExecutionListener`), you can implement the `afterTestMethod(TestContext)` method. From the `TestContext` that is passed in you can access the exception that was thrown (if there is one).
Here's the Javadoc for `org.springframework.test.context.TestContext.getTestException()`:
>
> Get the exception that was thrown during execution of the test method.
>
>
> Note: this is a mutable property.
>
>
> Returns: the exception that was thrown, or null if no exception was
> thrown
>
>
>
FYI: you can register your customer listener via the `@TestExecutionListeners` annotation.
Regards,
Sam
|
25,324,860 |
I have to link two containers so they can see each other. Of course the following...
```
docker run -i -t --name container1 --link container2:container2 ubuntu:trusty /bin/bash
docker run -i -t --name container2 --link container1:container1 ubuntu:trusty /bin/bash
```
...fails at line 1 because a container needs to be up and running in order to be a link target:
```
2014/08/15 03:20:27 Error response from daemon: Could not find entity for container2
```
What is the simplest way to create a bidirectional link?
|
2014/08/15
|
[
"https://Stackoverflow.com/questions/25324860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644958/"
] |
Docker 1.10 addresses this very nicely by introducing advanced container networking.
(Details: <https://docs.docker.com/engine/userguide/networking/dockernetworks/> )
First, create a network. The example below creates a basic "bridge" network, which works on one host only. You can check out docker's more complete documentation to do this across hosts using an overlay network.
```
docker network create my-fancy-network
```
Docker networks in 1.10 now create a special DNS resolution inside of containers that can resolve the names in a special way. First, you can continue to use --link, but as you've pointed out your example doesn't work. What I recommend is using --net-alias= in your docker run commands:
```
docker run -i -t --name container1 --net=my-fancy-network --net-alias=container1 ubuntu:trusty /bin/bash
docker run -i -t --name container2 --net=my-fancy-network --net-alias=container2 ubuntu:trusty /bin/bash
```
Note that having --name container2 is setting the container name, which also creates a DNS entry and --net-alias=container2 just creates a DNS entry on the network, so in this particular example you could omit --net-alias but I left it there in case you wanted to rename your containers and still have a DNS alias that does not match your container name.
(Details here: <https://docs.docker.com/engine/userguide/networking/configure-dns/> )
And here you go:
```
root@4dff6c762785:/# ping container1
PING container1 (172.19.0.2) 56(84) bytes of data.
64 bytes from container1.my-fancy-network (172.19.0.2): icmp_seq=1 ttl=64 time=0.101 ms
64 bytes from container1.my-fancy-network (172.19.0.2): icmp_seq=2 ttl=64 time=0.074 ms
64 bytes from container1.my-fancy-network (172.19.0.2): icmp_seq=3 ttl=64 time=0.072 ms
```
And from container1
```
root@4f16381fca06:/# ping container2
PING container2 (172.19.0.3) 56(84) bytes of data.
64 bytes from container2.my-fancy-network (172.19.0.3): icmp_seq=1 ttl=64 time=0.060 ms
64 bytes from container2.my-fancy-network (172.19.0.3): icmp_seq=2 ttl=64 time=0.069 ms
64 bytes from container2.my-fancy-network (172.19.0.3): icmp_seq=3 ttl=64 time=0.062 ms
```
|
5,309,206 |
I use HtmlUnit to fill form.
I have a select `SELECT_A`. After selecting option the additional elements must appear in the page. But it's not working! I simulate Firefox 3.6.
What do you think?
I tried to use `NicelyResynchronizingAjaxController()` but it does not help.
|
2011/03/15
|
[
"https://Stackoverflow.com/questions/5309206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/660203/"
] |
One note: fireEvent should be called with `"change"` parameter, not `"onchange"`. Or `fireEvent(Event.TYPE_CHANGE);` is even better.
|
63,919,101 |
I have one almost completed Java application with authentication and need to add to this project another one app to reuse auth code, for example.
As I heard there could be some kind of two "main activities" with different icons to launch them separately. Also I cannot check this info, because don't know how this named and any tries before leads me in other way.
So the question is how to register those activities in `Manifest` and how to configure `run` menu?
Or if I'm wrong - what else ways exists which could fit for my requiremrnts?
Thanks.
|
2020/09/16
|
[
"https://Stackoverflow.com/questions/63919101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4974229/"
] |
You should consider using flavors for your apps. This allows you setting different app name, icons, code for each flavor.
Here is an example for defining two flavors in your main module's build.gradle:
```
buildTypes {
debug{...}
release{...}
}
// Specifies one flavor dimension.
flavorDimensions "main"
productFlavors {
demo {
// Assigns this product flavor to the "main" flavor dimension.
// If you are using only one dimension, this property is optional,
// and the plugin automatically assigns all the module's flavors to
// that dimension.
dimension "main"
applicationId "com.appdemo"
versionNameSuffix "-demo"
}
full {
dimension "main"
applicationId "com.appfull"
versionNameSuffix "-full"
}
}
```
You can then set the resources of each app (images, code, strings...) by overriding the default files in each flavor's subdirectory i.e. yourmodule/demo/ and yourmodule/full/
|
43,355,774 |
So i'm trying to generate all binaries of a size n but with the condition that only k 1s. i.e
for size n = 4, k=2, (there is 2 over 4 combinations)
```
1100
1010
1001
0110
0101
0011
```
I'm stuck and can't figure out how to generate this.
|
2017/04/11
|
[
"https://Stackoverflow.com/questions/43355774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6915563/"
] |
Using the basic recursive method for printing all binary sequence all that remains is to enforce your constraints:
```
private static void binSeq(int n, int k, String seq) {
if (n == 0) {
System.out.println(seq);
return;
}
if (n > k) {
binSeq(n - 1, k, seq + "0");
}
if (k > 0) {
binSeq(n - 1, k - 1, seq + "1");
}
}
```
|
989,381 |
I have Intel NUC i5 with Latest OpenElec installed on it.
I would like to wake it up from suspend using Wake On Lan feature (sent from another device on my home network), but I am having difficulties with that.
I have verified WOL is enabled in the BIOS, and I have tried to use the WOL Windows GUI provided in Depicious web site - www.depicus.com/wake-on-lan/wake-on-lan-gui
I have put those values in the GUI:
MAC address of the NUC
Internet address - I tried both my router IP and my NUC internal IP
Subnet mask - I've put the mask I found in the OpenElec network screen
Port - I tried ports 7 and 9.
I have also tried to configure my router (DLink) to forward port 7 to the broadcast address (10.0.0.255) - but it doesn't allow configuring port forwarding (or virtual server as it is called) to that address.
Anything I am missing? Would really appreciate help here.
Thanks!
|
2015/10/20
|
[
"https://superuser.com/questions/989381",
"https://superuser.com",
"https://superuser.com/users/511927/"
] |
I was looking for an answer to this and just tested out a number of syncing services on my Mac by trying to copy an OSX framework. The only one that successfully copied the internal symbolic links between folders was...
* **[Copy.com](https://copy.com)** (Edit: **Service will shut down on May 1, 2016**. So that leaves us with... none.)
It seemed to work fine, symbolic links were copied as expected. I don't really know anything else about the service - I just found out about it today.
The following completely ignored the symbolic links: **Google Drive, Box, OneDrive, Mega, iCloud Drive**
The following copied the contents of the symbolic link like it was a folder (thus resulting in duplicate files): **Dropbox**
|
11,230,424 |
I am uncompressing a .gz-file and putting the output into `tar` with php.
My code looks like
```
$tar = proc_open('tar -xvf -', array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'a')), &$pipes);
$datalen = filesize('archive.tar.gz');
$datapos = 0;
$data = gzopen('archive.tar.gz', 'rb');
while (!gzeof($data))
{
$step = 512;
fwrite($pipes[0], gzread($data, $step));
$datapos += $step;
}
gzclose($data);
proc_close($tar);
```
It works great (tar extracts a couple directories and files) until a bit more than halfway in (according to my `$datapos`) the compressed file, then the script will get stuck at the `fwrite($pipes...)` line forever (i waited a few minutes for it to advance).
The compressed archive is 8425648 bytes (8.1M) large, the uncompressed archive is 36720640 bytes (36M) large.
What am I possibly doing wrong here, since I havn't found any resources considering a similar issue?
I'm running php5-cli version 5.3.3-7+squeeze3 (with Suhosin 0.9.32.1) on a 2.6.32-5-amd64 linux machine.
|
2012/06/27
|
[
"https://Stackoverflow.com/questions/11230424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522479/"
] |
`1 => array('pipe', 'w')`
You have tar giving you data (file names) on stdout. You should empty that buffer. (I normally just read it.)
You can also send it to a file so you don't have to deal with it.
`1 => array('file', '[file for filelist output]', 'a')`
if you're on Linux, I like to do
`1 => array('file', '/dev/null', 'a')`
[Edit: Once it outputs enough, it'll wait for you to read from standard out, which is where you are hanging.]
|
2,079,812 |
What is the difference between WPF and Silverlight?
Is it just the same as winforms vs asp as in desktop apps versus web app or is there an overlap?
|
2010/01/17
|
[
"https://Stackoverflow.com/questions/2079812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231822/"
] |
Silverlight is a subset of the functionality in WPF. WPF is desktops, silverlight is cross-platform web apps. Silverlight can run out-of-browser with limited functionality. if you want full blown WPF and access to everything WPF can access on the client, you can't do silverlight out-of-browser - just build a WPF app.
WPF and silverlight use XAML at its core to describe the layout. There is a MS document that highlights the differences between the two. I just can't find it right now.
WPF is not dead like some bloggers are reporting. Due to its web and cross-platform capabilities it is doubtful SL will ever truly contain 100% of the functionality of its bigger brother WPF. WPF includes some very Windows-specific functionality.
Found the document mentioned above. [Here](http://wpfslguidance.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=28278) it is...
|
45,149 |
I imported some 2000 photos into Lightroom 5 on the Mac, and then removed most of the ones in them, bringing it down to 40 photos. I did this by selecting photos I didn't like, pressing the Delete button and selecting Remove (not Delete From Disk). These removed photos are still on the filesystem, taking up 30 GB. How do I move them into the Trash on the Mac? I want to permanently delete them.
I thought Lightroom has its own trash bin, and an Empty Trash option, like iPhoto does, but it doesn't seem to.
Is there a simpler workflow to use here? I want to go through my collection, remove files I don't want, press Cmd-Z to undo a remove if I accidentally removed something and, when I'm all done, permanently delete the removed files. Is there a simpler workflow for this that I can adopt in the future? Thanks.
|
2013/11/13
|
[
"https://photo.stackexchange.com/questions/45149",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/22575/"
] |
The problem is that Lightroom does not know about these images, so it cannot do anything about it. Essentially you want to know which photos are *not* in Lightroom. I have no idea how to do that but I think this will work:
From Lightroom, select the folder or tree where these photos are and synchronize it. It will popup the import dialog, just continue the import as usual. As an extra precaution add a keyword during import, something like "DELETE\_ME\_AGAIN".
Once done, all these photos *should* appear under the Previous Import folder. From there see if you can do a Delete From Disk. If not, go to the library view and do it from there by selecting all images matching the "DELETE\_ME\_AGAIN" keyword.
|
43,675,036 |
I'm quite new to SQL and databases.
I'm trying to make a preference table of an user.
The fields will be `user_id`, `pref_no`, `prg_code`.
Now if I create the table making `pref_no` `auto_increment` then it will automatically increase irrespective of the `user_id`.
So, my question is - Is there a way to define the table in such a way that it will be `auto_incremented` taking `user_id` into account or I have to explicitly find the last `pref_no` that has occurred for an user and then increment it by 1 before insertion?
Any help is appreciated. Thanks in advance.
|
2017/04/28
|
[
"https://Stackoverflow.com/questions/43675036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5771617/"
] |
Following what `Mjh` and `Fahmina` suggested, we can create a procedure for the insertion.
```
DELIMITER //
CREATE PROCEDURE test(IN u_id INT(7), p_code INT(5))
BEGIN
SELECT @pno:= MAX(pref_no) FROM temp_choice WHERE user_id = u_id;
IF @pno IS NULL THEN
SET @pno = 1;
ELSE
SET @pno = @pno + 1;
END IF;
INSERT INTO temp_choice VALUES (u_id, @pno, p_code);
END //
DELIMITER ;
```
Now we can easily insert data by using
```
CALL test(1234567, 10101);
```
|
34,278,600 |
As per Java Concurrency in Practice below code can throw assertion Error:
If a thread other than the publishing thread were to call
assertSanity, it could throw AssertionError
```
public class Holder {
private int n;
public Holder(int n) { this.n = n; }
public void assertSanity() {
if (n != n)
throw new AssertionError("This statement is false.");
}
}
// Unsafe publication
public Holder holder;
public void initialize() {
holder = new Holder(42);
}
```
Question is: If I save, an object which refers to other objects in a ConcurrentHashMap, is there a possibility that certain updates on this object graph will not be in sync, in a multi-threaded environment due to same reasons as mentioned for above example?
Though root node in object graph will always be updated in map for all threads, but what about other objects which are referred as fields in root node, if these are not final or volatile ?
|
2015/12/14
|
[
"https://Stackoverflow.com/questions/34278600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4008171/"
] |
Answering my own question, I should have read complete chapter before asking question. This is what later part of chapter says:
>
> Mutable objects: If an object may be modified after construction, safe
> publication ensures only the visibility of the as-published state.
> Synchronization must be used not only to publish a mutable object, but
> also every time the object is accessed to ensure visibility of
> subsequent modifications. To share mutable objects safely, they must
> be safely published and be either thread-safe or guarded by a lock.
>
>
>
So using CHM or any thread safe collection is unsafe in a multithreaded environment, unless you synchronize changes to your mutable objects in CHM or these objects are immutable.
|
4,968,504 |
I am using spring tags to in my jsp page.
Now I have a situation where I am using form:select for a dropdown.
If I select first value in the dropdown "normal.jsp" page should be diaplayed. If I select second value "reverse.jsp" page should be displayed.
Both these jsp pages should be displayed in the main page below the dropdown.
What is the best way to achieve this in jsp?
I am trying to use jstl tags but the form is not getting displayed.
This is the code I wrote
```
<tr>
<td>Types of Auction :-</td>
<td>
<form:select id="auctionType" path="auctionType">
<form:option value="0" label="Select" />
<form:options items="${auctionTypesList}" itemValue="auctionTypeId" itemLabel="auctionTypeDesc" />
</form:select>
</td>
</tr>
<tr>
<td>
<c:choose>
<c:when test="${param.auctionType == 1}">
<c:import url="/normalAuction.jsp" var="normal"/>
</c:when>
<c:when test="${param.auctionType == 2}">
<c:import url="/reverseAuction.jsp" var="reverse"/>
</c:when>
</c:choose>
</td>
</tr>
```
Can someone let me know where am I going wrong?
Thanks
|
2011/02/11
|
[
"https://Stackoverflow.com/questions/4968504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/557068/"
] |
You've not been very clear with your problem description but I can give you a place to start looking. When ever any subview of a UIScrollView is made a first responder that UISCrollView calls scrollsRectToVisible. If the scrollView is scrolling to the wrong location that may be because the tap gesture is setting the wrong UITextField to the first responder. Why this is happening, I can't say (not without code). Hope this leads you in the right direction.
Nathan
Please remember to vote.
|
3,211,437 |
HI
I have the following (apparently simple) problem: I have to install a simple website, made by someone else, on a web hosting account. The site consists of lot and lot of HTML pages, no dynamic content, created some in MS Word and saved as html, some in frontpage, etc. A mixed bag.
I uploaded initially on a test account on my server (Win Server 2003) and it works ok.
Then I uploaded on the real web hosting (fedora / apache).
When I loaded the site in browser I see lot of odd craracters (instead of diacritics, used in html pages). Duacritics were saved as escape code, like & #350; for Ș (using codepage 1252).
The problem is, when I load the page from my own test server, the browser select automatically correct codepage (1252).
But when I load the site from public host, the same bowser loads the page using utf-8 encoding, rendering page with odd caracrets.
The test site on my server can be seen at <http://radu-stanian.dnsalias.com> and on public server at <http://radustanian.scoli.edu.ro/>
This happens no matter what browser I use (IE, ff or chrome)
What should I do to force browsers to load the pages in correct codepage?
Making changes to every page is not an option, because there are hundreds of pages, created by various peoples which could edit them further for update
Thank you
|
2010/07/09
|
[
"https://Stackoverflow.com/questions/3211437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163124/"
] |
You don't give enough information to confirm this, but I guess the salt is used in its binary form. In that case, changing the encoding of the file will corrupt the salt if this binary stream is changed, even if the characters are correctly converted.
Since the first 128 characters are similar in UTF-8 and Mac OS Roman, you don't have to worry if the salt is written using only these characters.
Let's say the salt is somewhere:
```
$salt = "a!c‡Œ";
```
You could write instead:
```
$salt = "a!c\xE0\xCE";
```
You could map all to their hexadecimal representation, as it might be easier to automate:
```
$salt = "\x61\x21\x63\xE0\xCE";
```
See the table [here](http://en.wikipedia.org/wiki/MacRoman).
The following snippet can automate this conversion:
```
$res = "";
foreach (str_split($salt) as $c) {
$res .= "\\x".dechex(ord($c));
}
echo $res;
```
|
289,429 |
I just added a second user to my Exchange 2010 box, it is in coexistence with exc2003. My account is already set up and working with a personal archive folder.
The user I just set up however is unable to see the archive in Outlook. It is visible in OWA but not outlook. I have created a test profile on my PC with the users account and still no archive, if I jump back to my profile on the same box the archive is there so I know it is not an office versions issue.
UPDATE:
I have deleted all profiles from Outlook (one of which worked with the archive) now any new profiles including my own no longer show up. I think I have broken something In exchange. I get an auto discover certificate error which I am in the process of fixing. Perhaps the 2 problems are related. Also OWA on this server runs on a custom SSL port.
|
2011/07/12
|
[
"https://serverfault.com/questions/289429",
"https://serverfault.com",
"https://serverfault.com/users/87374/"
] |
Change the configuration of the `origin` remote. See the **REMOTES** section of the `git-push(1)` man page for details.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.