qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
list | response
stringlengths 0
115k
|
---|---|---|---|---|
1,036,892 |
We have encountered a peculiar problem.
If we deploy our application and then restart the weblogic portal server; and we do a load test, the load test fails with very high response time and low throughput. If we the load test a second time, it runs just fine.
If we just deploy our application, but don't restart the weblogic portal server then the loadtest runs fine.
ANy hints are very helpful
|
2009/06/24
|
[
"https://Stackoverflow.com/questions/1036892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
It sounds like the HotSpot JVM warming up - when you restart the server as well, there is just more code to compile. Whenever you're benchmarking or load testing a Java application, it's a good idea to give it a gentle hammering beforehand to get all the code compiled that's going to be compiled. This is particularly true of server applications that will be running for a long time.
Update: I thought I should clarify that of course everything is already compiled to bytecode and I was referring to the JVM's additional compilation in to native code.
|
3,943,486 |
I got two classes, "A" and "B". In the application logic no one is allowed to create an object of class "B", except for class "A".
But, since I dont want to have the two classes in the same file I cant restrict it with the "private" properity.
Is it possible to create this kind of restriction? If someone other then "A" tries to create an object of class "B", you say piss off!?
|
2010/10/15
|
[
"https://Stackoverflow.com/questions/3943486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/477031/"
] |
You could inspect the backtrace:
```
class B
{
public function __construct()
{
$chain = debug_backtrace();
$caller = $chain[1]['class'];
if ('A' != $caller) {
throw new Exception('Illegal instantiation');
}
}
}
```
|
14,233,406 |
I am new with android this is my 1st demo app. I am trying to navigate from one page to another. But i am not able to navigate to another page i have a button in may main xml file and on licking it is moving to an another xml nextpage. I have 2 java class : 1st MianAcitvity, nextpagejava. 2 xml : activity\_main, nextpage
My code : manifest
```
<activity
android:name="com.example.androiddemo.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="nextpagejava" ></activity>
```
MainActivity.java
```
package com.example.androiddemo;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.drm.DrmStore.Action;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt = (Button)findViewById(R.id.bnt);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/ / TODO Auto-generated method stub
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.bnt:
Intent in = new Intent(this, nextpagejava.class);
startActivity(in);
break;
}
}
}
```
acitivity\_main.xml
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/clicktxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click"
/>
<Button
android:id="@+id/bnt"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Click Me"
/>
```
nextpage.xml
```
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="I am i a next page..."
/>
<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Back"
/>
```
nextpagejava.java
```
package com.example.androiddemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class nextpagejava extends Activity implements OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt = (Button)findViewById(R.id.btn1);
bt.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
```
i am getting message that "Unfortunately, androiddemo has stopped" this message as a popup.
can anybody tell me why this error is coming and please tell me from where i can find line by line debug logs.
|
2013/01/09
|
[
"https://Stackoverflow.com/questions/14233406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1846589/"
] |
Just remove this from your `MainActivity.java` file:
>
>
> ```
> bt.setOnClickListener(new View.OnClickListener() {
> @Override
> public void onClick(View v) {
> / / TODO Auto-generated method stub
> }
> });
>
> ```
>
>
Instead of Write like this:
>
>
> ```
> bt.setOnClickListener(this);
>
> ```
>
>
Also do the changes in `Manifest` file as below:
>
>
> ```
> <activity android:name=".nextpagejava" ></activity>
>
> ```
>
>
Then check out . I think it should work now.
|
50,163 |
I've been working for a large company that I got the job through by my school's co-op office. Sometimes my manager can be nice, but often times I feel like he’s mistreats me and acts in a way that is inappropriate. I had taken action to remedy this, and it got better for a while, but now it’s happening again.
I’ve complained to my school’s co-op office about the way my boss speaks to me, and the coordinator said “sometimes you have to work with people you don’t like”. How do you respond to that (for example you could say that about any bully)? I’ve complained to my boss’s manager who told me that my boss grew up in a very different culture. I don't think he realizes how serious the problem is.
I understand there's a fine line between firm management and bullying. How can one be certain they’re being bullied? **Is it bullying if it’s unintentional?** I fear going to work because I’ll have to talk to him and he is very unpleasant to talk to. He seems to always be mad at me and speak to me in a rude tone. Though some of the things he does I find offensive, like [telling me to act mature](https://workplace.stackexchange.com/questions/50128/responding-to-question-with-act-mature/5015), they may not really be bullying. The fact that each time I speak with him 2 things like this happen (and involve shouting) it is a problem. Most people know he is difficult to work with and the one other person who saw him spoke to me told me he speaks very offensively. If it's not bullying, then what do you call it?
|
2015/07/26
|
[
"https://workplace.stackexchange.com/questions/50163",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/38364/"
] |
Tricky situation but you are by no means powerless here. You can take charge of the situation and potentially improve it.
1. Whatever happens, stay professional. Regardless of other people getting emotional, you need to stay calm, collected, constructive and communicate to the point at hand. Your emotions need to stay out of it for a bit. Never say a single negative word about your boss!!
2. Clearly communicate to your boss the behavior that you are unhappy as constructively as possible. "I feel uncomfortable if you yell it me. I think we could communicate more effectively in a regular tone of voice ". "I'm uncomfortable if you criticize me in from front of others. I really appreciate your feedback but it would be way more productive if we could do in private" . "please don't make jokes about my race/gender/passport/education, etc.". Do this in a private meeting. Then send a follow up e-mail that says exactly the same thing "as discussed today". Clearly date it and keep a copy.
3. Keep a detailed written record going forward. Make a note whenever your manager goes against your ask. Write down date, occasion and as much detail as you can.
4. Keep also a record of how your boss is behaving towards other people and how other people behave towards you. If he/she never yells at anyone else, write this down as well.
5. Do this for a few weeks. Study you records and see if there are any clear trends and themes in there. If he yells at everyone, but yelling is unusual in the company, than it's a behavioral issue on his side. If you are the only one getting yelled at, this may indeed be bullying. If there is only one incident in three weeks and in happens to everyone, than you may be overthinking this.
6. If there is a friendly or neutral person, that you trust, review the data with them. A second pair of eyes is really helpful here.
7. If the data clearly shows signs of bullying or a significant behavioral problem go to your manager's boss and to HR. A well documented paper trail is a huge red flag and they are unlikely to ignore it since the next person you might talk to is a lawyer. However, you would never ever even hint at taken legal actions, but frame the discussion as "here is what's happening", "here is what I tried", "it's not working and I need the situation to change, how do you suggest we proceed here?"
8. Depending on your relationship with your boss at the time, you may chose to go to him first and review the data with him. This is dicey since in all likelihood she/he will perceive that as a threat (which it is). This makes only sense if there is strong indication that the behavior is largely unintentional and that he/she would change once being aware of it.
Granted this may not make a you lot of friends but since this is a co-op this is probably not the end of the world and if the prevalent company culture is bad (for you), then why would you care? Who knows, perhaps if you can show that you handle the situation way more professionally and constructively than your boss, you might gain some respect and friends as well.
While this currently is a stressful situation, it's actually a great learning opportunity if you are willing to put the effort into it. Conflict is a part of work life and learning to effectively handle it is a great skill to have. "you just need to put with it" is utter non-sense. There are always things you can do. It's your life and you are in charge.
|
211,796 |
This is kind of a reverse question.
A few years back I was presented with a functional equation problem, I don't remember it completely, and now I would appreciate the help of the math.SE hivemind to recreate it.
It concerned a function $f:\Bbb Q^+\to \Bbb Q$, with $\Bbb Q^+$ being the strictly positive rationals. The problem gave two identities for $f$, one of them being $f(x) = f(x^{-1})$. I can't for the life of me recall what the second one was. However, I believe it related $f(x)$ and $f(x+1)$. There is a possibility that $f(1) = 1$ was also included as a restraint.
What I do remember, though, is the solution. With $a, b\in \Bbb Z$ coprime, $f(\frac{a}{b}) = ab$. Also, that the two identities together is in some way related to the Euclidian algorithm.
Long story short, does anyone know what the second identity is / could be?
|
2012/10/12
|
[
"https://math.stackexchange.com/questions/211796",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/15500/"
] |
This has nothing to do with $f(x+1)$, but what about: $$f(x^2)=f(x)^2$$
**Edit:**
what about this one:
$$f(x+1)+f(x-1)=2\cdot f(x)$$
|
407,654 |
Is there a command to view all users on a Windows domain?
|
2012/04/02
|
[
"https://superuser.com/questions/407654",
"https://superuser.com",
"https://superuser.com/users/72053/"
] |
Yes,
>
> net user
>
>
>
lists all users.
|
23,822,382 |
I have a simple form like this
```
<form ng-submit="checkValidation()" >
</form>
```
js code
```
function checkValidation() {
//if some condition then cancel form submission
}
```
|
2014/05/23
|
[
"https://Stackoverflow.com/questions/23822382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277696/"
] |
Easy! Try this:
```
using Windows.Web.Http;
using Windows.Web.Http.Headers;
private async void Foo()
{
// the image
var fileStream = await file.OpenReadAsync();
var streamContent = new HttpStreamContent(fileStream);
var filename = "myImage.png";
// the text
var text = "oompa loompas";
var stringContent = new HttpStringContent(text);
// Putting all together.
var formDataContent = new HttpMultipartFormDataContent();
formDataContent.Add(streamContent, "myImage", fileName);
formDataContent.Add(stringContent, "myString");
// Send it to the server.
var response = await (new HttpClient()).PostAsync(uri, formDataContent);
}
```
|
13,182,316 |
i am trying to make a code which takes an image from a file path which i type in manually.
here is my code:
`pieceImage = Image.FromFile(@"O:\Projects\imagename.png");`
This code is saved on my USB flash drive.
However, whenever i run this code on a different computer, the path is different (obviously) and doesn't necessarily start with O:\ but something else, for example F:.
What can i use so that the path will change accordingly to the computer on which it runs? many thanks in advance.
|
2012/11/01
|
[
"https://Stackoverflow.com/questions/13182316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1509812/"
] |
Create an auxiliary method to do the recursion. It should have two arguments: the base and the exponent. Call it with a value of 10 for the exponent and have it recurse with (exponent-1). The base case is `exponent == 0`, in which case it should return 1. (You can also use `exponent == 1` as a base case, in which case it should return the base.)
|
174 |
It seems to me a fairly high proportion of questions on ELU that are concerned with [determiners](http://www.testmagic.com/knowledge_base/lists/grammar/determiners.htm) (*a, the, some, any, my, its, this, that*, etc.) are from non-native speakers asking things like *"Which one do I use?"*, or *"What does **that** refer to?"*.
There's no such tag yet on ELL. Apparently I already have enough rep to just go ahead and create one, but I'd like to know whether it would be considered useful, given most examples probably have more specific tags anyway (*definite/indefinite article, possessive pronoun,* etc).
|
2013/02/01
|
[
"https://ell.meta.stackexchange.com/questions/174",
"https://ell.meta.stackexchange.com",
"https://ell.meta.stackexchange.com/users/126/"
] |
I believe that *determiner* is a very useful term. Since I first encountered it on ELU I have found that it has sharpened my sense of how, *inter alia*, articles are used. I think we would be doing a service to our audience by introducing and encouraging its use.
|
16,036,466 |
How could I traverse a structure like below:
```
$this->user[$userid] = array(
"initial" => array(
"amount" =>$amount,
"cards" =>$cards
),
"userturn" => array(
"userturn1" => array(
"action"=>$action,
"amount"=>$amount,
"date"=>$datetime
),
"userturn2" => array(
"action"=>$action,
"amount"=>$amount,
"date"=>$datetime
),
.
.
.
.
n times
)
);
```
|
2013/04/16
|
[
"https://Stackoverflow.com/questions/16036466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Assuming you want to get to turns..
```
foreach($this->user[$userid]['userturn'] as $k=>$turn){
print_r($turn);
}
```
|
47,152,416 |
I Know this question has been asked many times, I've looked at all the answers and tried many things but I still have the same problem. It's a simple web application with asp.net MVC using ADO.net. I can read, create and delete so far without problem. I don't have a date format problem in creation. However, when I want to Edit(The data of the model to be modified is passed to the view), even if the same date is re-entered in the same format I get the error message. Here is the method for updating in my persistence class:
```
public static void UpdateContact(Contact c) {
string requete = "UPDATE Contact SET nom='@nom', Telephone='@telephone',
Courriel='@Courriel',
Datenaissance='@DateNaissance'," +
" CodePostal='@CodePostal', StatutCivil='@StatutCivil'
WHERE IdContact = @idContact";
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand(requete, conn);
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("idContact", c.IdContact);
cmd.Parameters.AddWithValue("nom", c.Nom);
cmd.Parameters.AddWithValue("Telephone", c.Telephone);
cmd.Parameters.AddWithValue("Courriel", c.Courriel);
cmd.Parameters.AddWithValue("DateNaissance", c.DateNaissance);
cmd.Parameters.AddWithValue("CodePostal", c.CodePostal);
cmd.Parameters.AddWithValue("StatutCivil", c.StatutCivil);
conn.Open();
cmd.ExecuteNonQuery();
}
}
```
In the database DateNaissance is `datetime2(7)` and in my model it's a `DateTime`. I paused the program before `cmd.ExecuteNonQuery();` to check the value of `c.DateNaissance` which was at the right format. Thank you in Advance!
EDIT: As I was reading my question I realised I put
comas in `DateNaissance='@dateNaissance'` I removed them and tested and I got this error :
```
String or binary data would be truncated.
The statement has been terminated.
```
**SOLVED :** I lost 3 hours on something like that lol -.- It was a syntax error, that's how my query should have been written ( without commas):
```
string requete = "UPDATE Contact SET nom=@nom, Telephone=@telephone, Courriel=@Courriel, Datenaissance=@DateNaissance," +
" CodePostal=@CodePostal, StatutCivil=@StatutCivil WHERE IdContact = @idContact";
```
|
2017/11/07
|
[
"https://Stackoverflow.com/questions/47152416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8114490/"
] |
You can add any system properties to run configurations within IntelliJ. To have that as a default, you can add the properties to JUnit default configuration in the same dialog (either choose JUnit from the ‘Defaults’ category or press the ‘Edit Defaults’ button).
That’s the answer to your question pertaining the global property. However, fixing the setup for tests to simply run woyld be better. Cannot help there for the moment, however.
|
2,483,235 |
I have a DataGridView in a Winforms app that has about 1000 rows (unbound) and 50 columns. Hiding a column takes a full 2 seconds. When I want to hide about half the rows, this becomes a problem.
```
private void ShowRows(string match)
{
this.SuspendLayout();
foreach (DataGridViewRow row in uxMainList.Rows)
{
if (match == row.Cells["thisColumn"].Value.ToString()))
{ row.Visible = false; }
else
{ row.Visible = true; }
}
this.ResumeLayout();
}
```
I did some testing by adding by adding`Console.WriteLine(DateTime.Now)`around the actions, and`row.Visible = false`is definitely the slow bit. Am I missing something obvious, like setting `IsReallySlow = false`? Or do I have to go ahead and enable Virtual Mode and code up the necessary events?
|
2010/03/20
|
[
"https://Stackoverflow.com/questions/2483235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1206/"
] |
It looks to me like you should be using row filters instead.
Try using a DataView as your binding source and use DataView.RowFilter to hide rows or show rows of your choosing.
```
DataGridView myGridView = new DataGridView();
DataView myDataView = myTable.DefaultView;
myGridView.DataSource = myDataView; // DataView that allows row filtering
myDataView.RowFilter = string.Format("thisColumn <> '{0}'",match); // this will hide all rows where "thisColumn" = match
```
|
70,456,548 |
Background
----------
I have an old umbrella app that I am trying to bring to life once again. To do this I decided to add a phoenix project under the umbrella using:
```
mix phx.new.web hello_test --no-ecto
```
Notice the `--no-ecto` part, this is important.
Setup
-----
After running said command inside my umbrella `apps` folder I changed my umbrella's `config/config.exs` file by adding the following:
```
config :phoenix, json_library: Jason
```
With this out of the way, I went to `apps/hello_test/lib/hello_test/application.ex` and added to the `start` function the following:
```
children = [
# Start the Telemetry supervisor
HelloTest.Telemetry,
# Start the Endpoint (http/https)
HelloTest.Endpoint,
# Start a worker by calling: HelloTest.Worker.start_link(arg)
# {HelloTest.Worker, arg}
{Phoenix.PubSub, name: HelloTest.PubSub}
]
```
Then I ran `mix assets.deploy` inside of the `hello_test` apps folder followed by `mix phx.server`.
Problem
-------
Now at this point I was expecting to see some nice welcome page when loading to localhost:4000.
Instead I get a page with no css and an error message:
```
16:17:44.695 [debug] Processing with HelloTest.PageController.index/2
Parameters: %{}
Pipelines: [:browser]
16:17:44.737 [info] Sent 200 in 51ms
16:17:44.821 [info] GET /assets/app.js
16:17:44.887 [info] GET /assets/app.css
16:17:44.887 [debug] ** (Phoenix.Router.NoRouteError) no route found for GET /assets/app.js (HelloTest.Router)
(hello_test 0.1.0) lib/phoenix/router.ex:406: HelloTest.Router.call/2
(hello_test 0.1.0) lib/hello_test/endpoint.ex:1: HelloTest.Endpoint.plug_builder_call/2
(hello_test 0.1.0) lib/plug/debugger.ex:136: HelloTest.Endpoint."call (overridable 3)"/2
(hello_test 0.1.0) lib/hello_test/endpoint.ex:1: HelloTest.Endpoint.call/2
(phoenix 1.6.5) lib/phoenix/endpoint/cowboy2_handler.ex:54: Phoenix.Endpoint.Cowboy2Handler.init/4
(cowboy 2.9.0) c:/Users/User/Workplace/market_manager/deps/cowboy/src/cowboy_handler.erl:37: :cowboy_handler.execute/2
(cowboy 2.9.0) c:/Users/User/Workplace/market_manager/deps/cowboy/src/cowboy_stream_h.erl:306: :cowboy_stream_h.execute/3
(cowboy 2.9.0) c:/Users/User/Workplace/market_manager/deps/cowboy/src/cowboy_stream_h.erl:295: :cowboy_stream_h.request_process/3
16:17:44.897 [debug] ** (Phoenix.Router.NoRouteError) no route found for GET /assets/app.css (HelloTest.Router)
(hello_test 0.1.0) lib/phoenix/router.ex:406: HelloTest.Router.call/2
(hello_test 0.1.0) lib/hello_test/endpoint.ex:1: HelloTest.Endpoint.plug_builder_call/2
(hello_test 0.1.0) lib/plug/debugger.ex:136: HelloTest.Endpoint."call (overridable 3)"/2
(hello_test 0.1.0) lib/hello_test/endpoint.ex:1: HelloTest.Endpoint.call/2
(phoenix 1.6.5) lib/phoenix/endpoint/cowboy2_handler.ex:54: Phoenix.Endpoint.Cowboy2Handler.init/4
(cowboy 2.9.0) c:/Users/User/Workplace/market_manager/deps/cowboy/src/cowboy_handler.erl:37: :cowboy_handler.execute/2
(cowboy 2.9.0) c:/Users/User/Workplace/market_manager/deps/cowboy/src/cowboy_stream_h.erl:306: :cowboy_stream_h.execute/3
(cowboy 2.9.0) c:/Users/User/Workplace/market_manager/deps/cowboy/src/cowboy_stream_h.erl:295: :cowboy_stream_h.request_process/3
```
To be fair the setup done until now was not trivial, but I managed it by searching endlessly in old github issues and in this community.
However, now its different. This is as simple as any phoenix umbrella app can be and yet it still does not work out of the box.
The only solutions I found were for very old Phoenix versions, ones that still use NPM. I am using the latest version of phoenix, so those solutions do not apply:
```
λ mix phx.new --version
Phoenix installer v1.6.5
λ elixir -v
Erlang/OTP 24 [erts-12.1.4] [source] [64-bit] [smp:6:6] [ds:6:6:10] [async-threads:1] [jit]
Elixir 1.13.1 (compiled with Erlang/OTP 22)
```
How can I get rid of this error and make my app run correctly?
|
2021/12/23
|
[
"https://Stackoverflow.com/questions/70456548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1337392/"
] |
Answer
------
So after some research I ended up creating a fresh new umbrella project with a child phoenix app inside. The issue was nowhere to be seen and everything worked properly.
```
mix new koko --umbrella
cd koko/apps
mix phx.new.web hello --no-ecto
cd hello
mix assets.deploy
```
So everything points to some issue in my old umbrella app. Because I wanted to do more tests, I created another phoenix app alongside the `hello` one.
Then I was able to replicate the issue.
At this point, I suspect that umbrella apps will have issues if you try to:
* Add multiple phoenix child apps
* Add a new phoenix child app when the project already had one in the past (and got deleted)
Why this is the case is beyond me, but what is not beyond me is the implication here: I have to remake my project with a fresh umbrella app and start over.
|
28,228,132 |
My context.xml file:
```
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/candy"/>
```
How can i get rid of this warning? My project is running on Netbeans and Tomcat 8.0.9:
**Setting property 'antiJARLocking' to 'true' did not find a matching property**
|
2015/01/30
|
[
"https://Stackoverflow.com/questions/28228132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4192611/"
] |
Remove the attribute from the context.xml file. Tomcat does not support it.
|
22,210,795 |
I started using static constants in my main class, but now the number is very large and I would like to refactor them into their own config file/class (say, Constants.java). However, all references must now access these constants by first applying the Constants.\*-prefix. Instead of doing a manual search and replace for each constant, is there a way to do it quickly for all constants?
|
2014/03/05
|
[
"https://Stackoverflow.com/questions/22210795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1165790/"
] |
The problem is your array is storing *references* to the objects. When you assign `_Player.EqiuipArmor` to a *new* object, it points to a different instance but the reference stored in the array does not change.
You could create a class that takes a `Player` class and exposes the various properties as an array:
```
public class InvertorySlots
{
private Player _Player;
public InventorySlots(Player player)
{
}
public InventoryItem[] GetItems()
{
return new InventoryItem[] {
_Player.EqiupAmulet,
_Player.EqiupArmor,
_Player.EqiupBelt,
_Player.EqiupBoots,
_Player.EqiupCloak,
_Player.EqiupArmor,
_Player.EqiupGauntlets,
_Player.EqiupHelmet };
}
}
```
|
35,421,247 |
When opening the [demo](https://mtr.github.io/core-layout/examples/) application from [core-layout](https://www.npmjs.com/package/core-layout) with the embedded browser in the Facebook app on iOS 9.x (at least), the footer element is not visible when the device is in portrait mode. If you rotate the device to landscape mode, the footer will be partially visible. However, the footer (with a button) should be completely visible.
The first image shows how the demo app *should* look, while the second image shows how the demo app is missing the footer when viewed with the Facebook app's embedded web view (the images were grabbed from a Chrome desktop browser illustrating how the bug is manifested):
>
> [](https://i.stack.imgur.com/Pv4W8.png) [](https://i.stack.imgur.com/X3NgI.png)
>
>
>
After testing a lot of different hypotheses, we concluded that the bug was caused by the browser making the page/viewport higher than the visible area.
This bug seemed related to [iOS9 Safari viewport issues, meta not scaling properly?](https://stackoverflow.com/questions/33618595/ios9-safari-viewport-issues-meta-not-scaling-properly) and [Web page not getting 100% height in Twitter app on iOS 8](https://stackoverflow.com/questions/27379581/web-page-not-getting-100-height-in-twitter-app-on-ios-8).
|
2016/02/15
|
[
"https://Stackoverflow.com/questions/35421247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/126273/"
] |
The solution we came up with was a *combination* of other answers we found on StackOverflow, while paying strong attention to details. I will stress that implementing just *some* of the below changes did *not* fix the bug; *all* the changes had to be made.
* The CSS defining the height of the wrapping `div` element (`#outer-wrap`) had to be changed from
```
outer-wrap {
position: absolute;
width: 100%;
height: 100%;
overflow: hidden;
}
```
to
```
html, body, #outer-wrap {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
overflow: hidden;
}
```
* The following function was added to the library, and is called upon initialization:
```
function _fixViewportHeight() {
var html = document.querySelector('html');
function _onResize(event) {
html.style.height = window.innerHeight + 'px';
}
window.addEventListener('resize', _.debounce(_onResize, 125, {
leading: true,
maxWait: 250,
trailing: true
}));
_onResize();
}
_fixViewportHeight();
```
* The `viewport` meta tag had to be
```
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, target-densityDpi=device-dpi">
```
However, the scale values had to be `1.0`, *not* `1`; that caused the fix to break in one of our build processes where we applied [html-minifier](https://github.com/kangax/html-minifier), which replaced the decimal values with integer ones. The html-minifier problem was fixed by surrounding the `viewport` meta tag with `<!-- htmlmin:ignore -->` comments.
|
16,745,972 |
I am working on a very simple application for a website, just a basic desktop application.
So I've figured out how to grab all of the JSON Data I need, and if possible, I am trying to avoid the use of external libraries to parse the JSON.
Here is what I am doing right now:
```
package me.thegreengamerhd.TTVPortable;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import me.thegreengamerhd.TTVPortable.Utils.Messenger;
public class Channel
{
URL url;
String data;
String[] dataArray;
String name;
boolean online;
int viewers;
int followers;
public Channel(String name)
{
this.name = name;
}
public void update() throws IOException
{
// grab all of the JSON data from selected channel, if channel exists
try
{
url = new URL("https://api.twitch.tv/kraken/channels/" + name);
URLConnection connection = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
data = new String(in.readLine());
in.close();
// clean up data a little, into an array
dataArray = data.split(",");
}
// channel does not exist, throw exception and close client
catch (Exception e)
{
Messenger.sendErrorMessage("The channel you have specified is invalid or corrupted.", true);
e.printStackTrace();
return;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dataArray.length; i++)
{
sb.append(dataArray[i] + "\n");
}
System.out.println(sb.toString());
}
}
```
So here is what is printed when I enter an example channel (which grabs data correctly)
```
{"updated_at":"2013-05-24T11:00:26Z"
"created_at":"2011-06-28T07:50:25Z"
"status":"HD [XBOX] Call of Duty Black Ops 2 OPEN LOBBY"
"url":"http://www.twitch.tv/zetaspartan21"
"_id":23170407
"game":"Call of Duty: Black Ops II"
"logo":"http://static-cdn.jtvnw.net/jtv_user_pictures/zetaspartan21-profile_image-121d2cb317e8a91c-300x300.jpeg"
"banner":"http://static-cdn.jtvnw.net/jtv_user_pictures/zetaspartan21-channel_header_image-7c894f59f77ae0c1-640x125.png"
"_links":{"subscriptions":"https://api.twitch.tv/kraken/channels/zetaspartan21/subscriptions"
"editors":"https://api.twitch.tv/kraken/channels/zetaspartan21/editors"
"commercial":"https://api.twitch.tv/kraken/channels/zetaspartan21/commercial"
"teams":"https://api.twitch.tv/kraken/channels/zetaspartan21/teams"
"features":"https://api.twitch.tv/kraken/channels/zetaspartan21/features"
"videos":"https://api.twitch.tv/kraken/channels/zetaspartan21/videos"
"self":"https://api.twitch.tv/kraken/channels/zetaspartan21"
"follows":"https://api.twitch.tv/kraken/channels/zetaspartan21/follows"
"chat":"https://api.twitch.tv/kraken/chat/zetaspartan21"
"stream_key":"https://api.twitch.tv/kraken/channels/zetaspartan21/stream_key"}
"name":"zetaspartan21"
"delay":0
"display_name":"ZetaSpartan21"
"video_banner":"http://static-cdn.jtvnw.net/jtv_user_pictures/zetaspartan21-channel_offline_image-b20322d22543539a-640x360.jpeg"
"background":"http://static-cdn.jtvnw.net/jtv_user_pictures/zetaspartan21-channel_background_image-587bde3d4f90b293.jpeg"
"mature":true}
```
Initializing User Interface - JOIN
All of this is correct. Now what I want to do, is to be able to grab, for example the 'mature' tag, and it's value. So when I grab it, it would be like as simple as:
```
// pseudo code
if(mature /*this is a boolean */ == true){ // do stuff}
```
So if you don't understand, I need to split away the quotes and semicolon between the values to retrieve a Key, Value.
|
2013/05/25
|
[
"https://Stackoverflow.com/questions/16745972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1925638/"
] |
It's doable with the following code :
```
public static Map<String, Object> parseJSON (String data) throws ParseException {
if (data==null)
return null;
final Map<String, Object> ret = new HashMap<String, Object>();
data = data.trim();
if (!data.startsWith("{") || !data.endsWith("}"))
throw new ParseException("Missing '{' or '}'.", 0);
data = data.substring(1, data.length()-1);
final String [] lines = data.split("[\r\n]");
for (int i=0; i<lines.length; i++) {
String line = lines[i];
if (line.isEmpty())
continue;
line = line.trim();
if (line.indexOf(":")<0)
throw new ParseException("Missing ':'.", 0);
String key = line.substring(0, line.indexOf(":"));
String value = line.substring(line.indexOf(":")+1);
if (key.startsWith("\"") && key.endsWith("\"") && key.length()>2)
key = key.substring(1, key.length()-1);
if (value.startsWith("{"))
while (i+1<line.length() && !value.endsWith("}"))
value = value + "\n" + lines[++i].trim();
if (value.startsWith("\"") && value.endsWith("\"") && value.length()>2)
value = value.substring(1, value.length()-1);
Object mapValue = value;
if (value.startsWith("{") && value.endsWith("}"))
mapValue = parseJSON(value);
else if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false"))
mapValue = new Boolean (value);
else {
try {
mapValue = Integer.parseInt(value);
} catch (NumberFormatException nfe) {
try {
mapValue = Long.parseLong(value);
} catch (NumberFormatException nfe2) {}
}
}
ret.put(key, mapValue);
}
return ret;
}
```
You can call it like that :
```
try {
Map<String, Object> ret = parseJSON(sb.toString());
if(((Boolean)ret.get("mature")) == true){
System.out.println("mature is true !");
}
} catch (ParseException e) {
}
```
But, really, **you shouldn't do this, and use an already existing JSON parser**, because this code will break on any complex or invalid JSON data (like a ":" in the key), and if you want to build a true JSON parser by hand, it will take you a lot more code and debugging !
|
10,061,128 |
I'm trying to do this:
```
SELECT
userId, count(userId) as counter
FROM
quicklink
GROUP BY
userId
HAVING
count(*) >= 3'
```
In doctrine with the querybuilder, I've got this:
```
$query = $this->createQueryBuilder('q')
->select('userId, count(userId) as counter')
->groupby('userId')
->having('counter >= 3')
->getQuery();
return $query->getResult();
```
Which gives me this error:
```
[Semantical Error] line 0, col 103 near 'HAVING count(*)': Error: Cannot group by undefined identification variable.
```
Really struggling with doctrine. :(
|
2012/04/08
|
[
"https://Stackoverflow.com/questions/10061128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/155227/"
] |
Your SQL is **valid**, Your query builder statement is **invalid**
All cause db will execute that query in following order:
```
1. FROM $query = $this->createQueryBuilder('q')
2. GROUP BY ->groupby('userId') // GROUP BY
3. HAVING ->having('counter >= 3')
4. SELECT ->select('userId, count(userId) as counter')
```
So as You can see `counter` is defined **after** its use in having.
Its SQL Quirk. You **can not** use definitions from select in `where` or `having` statements.
So correct code:
```
$query = $this->createQueryBuilder('q')
->select('userId, count(userId) as counter')
->groupby('userId')
->having('count(userId) >= 3')
->getQuery();
return $query->getResult();
```
Do note repetition in `having` from `select`
|
9,673,729 |
There's no doubt that in-out parameters leads to confused code since they may increase unexpected/unpredictabled side-effects.
So, many good programmers say :
>
> Avoid in-out parameters for changing mutable method parameters. Prefer to keep parameters unchanged.
>
>
>
For a perfectionist programmer who expects his code to be the most clean and understandable, does this "rule" must be applied in all case ?
For instance, suppose a basic method for adding elements to a simple list, there's two ways :
**First way (with in-out parameter):**
```
private void addElementsToExistingList(List<String> myList){
myList.add("Foo");
myList.add("Bar");
}
```
and the caller being :
```
List<String> myList = new ArrayList<String>();
//.......Several Instructions (or not) .....
addElementsToExistingList(myList);
```
**Second way without out parameter :**
```
private List<String> addElementsToExistingList(List<String> originalList){
List<String> filledList = new ArrayList<String>(originalList); //add existing elements
filledList.add("Foo");
filledList.add("Bar");
return filledList;
}
```
and the caller being :
```
List<String> myList = new ArrayList<String>();
//.......Several Instructions (or not) .....
myList.addAll(addElementsToExistingList(myList));
```
Pros of second way :
Parameter are not modified => no risk of unexpected side-effects for a new code reader.
Cons of second way :
Very verbose and very less readable ...
Of course, you would tell me that for a code as simple as this one, first way is really more convenient.
But, if we don't consider the difficulty of any concept/code, I juge the second way more logical and obvious for any readers (beginners or not).
**However, it violates the CQS principle that consider "command" methods having void return with potential (but allowed since it's the convention) side-effects and "query" methods having a return type and without side-effects.**
So, what should a motivate programmer adopt ? Mix of two accorging to the code case ? Or keep the "law" expecting to always avoid in-out parameters...
(Of course, method for adding Element is named for expliciting the example, and would be a bad name choice in real code).
|
2012/03/12
|
[
"https://Stackoverflow.com/questions/9673729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/985949/"
] |
I think the law should be:
>
> Use what is more straight-forward, but *always*, **always** document the behavior of your methods extensively.
>
>
>
Your second example is a very nice case where without documentation you would have a guaranteed bug: the name of the method is `addElementsToExistingList`, but the method *does not add elements to the existing list - it creates a new one*. A counter-intuitive and misleading name, to say the least...
|
46,397,492 |
I got a some questions about using bootstrap modal.
First of all, sorry for my English skill, maybe there are some problems to understand my question.
I made a button as a `directive` to add dynamically with reference to below links.
.
[Angularjs dynamically adding and removing elements using directive](https://stackoverflow.com/questions/35429854/angularjs-dynamically-adding-and-removing-elements-using-directive)
<http://jsfiddle.net/Stepan_Kasyanenko/4ktmvzcm/1/>
^^^^^ above link is just what I consulted.
.
And my problem is in this fiddle.
.
<https://jsfiddle.net/CRDeity/6kmszgL0/>
.
When I put this into a `modal`, even though I click this, it didn't work.
If outside of `modal`, this worked well.
Are there any interruption in `event` of `modal`?
|
2017/09/25
|
[
"https://Stackoverflow.com/questions/46397492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8645993/"
] |
SAML Response is fairly complicated and contains a range of values which expire over time, need to correspond to the originally send SAML Authentication Request and depend on configuration of the particular SAML federation. For these reasons there's no way to craft a generic CURL Command.
|
5,413,899 |
I have a string which is something like this :
```
a_href= "www.google.com/test_ref=abc";
```
I need to search for test\_ref=abc in thisabove strinng and replace it with new value
```
var updated_test_ref = "xyz";
a_href ="www.google.com/test_ref=updated_test_ref"
```
i.e
```
www.google.com/test_ref=xyz.
```
How can we do this ?
EDIT:
test\_ref value can be a URL link in itself something like <http://google.com?param1=test1¶m2=test2>. I need to capture complete value not till first &.
|
2011/03/24
|
[
"https://Stackoverflow.com/questions/5413899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247560/"
] |
```
a_href = a_href.replace(/(test_ref=)[^\&]+/, '$1' + updated_test_ref);
```
|
4,785,366 |
I am not really that good at patterns. (But I do realize that they are very important.) I have a scenario that needs a singleton but also needs to take a parameter. Normally for a singleton I just make a static method that does a:
```
return _instance ?? (_instance = new SingletonClass());
```
But when a parameter is involved you either have to pass the parameter every time to access things (just in case that is the time you are going to be doing the constructing) or do something like I did here:
```
public class PublicFacingSingleton
{
private readonly string _paramForSingleton;
public PublicFacingSingleton(string paramForSingleton)
{
_paramForSingleton = paramForSingleton;
}
private PrivateFacingSingleton _access;
public PrivateFacingSingleton Access
{
get
{
// If null then make one, else return the one we have.
return _access ??
(_access = new PrivateFacingSingleton(_paramForSingleton));
}
}
}
public class PrivateFacingSingleton
{
private readonly ClassWithOnlyOneInstance _singleInstance;
public PrivateFacingSingleton(string paramForSingleton)
{
_singleInstance = new ClassWithOnlyOneInstance(paramForSingleton);
}
public WorkItem ActualMethodToDoWork()
{
return _singleInstance.UseTheClass();
}
}
```
and then create the `PublicFacingSigleton` and use that. For example:
```
var publicFacingSingleton = new PublicFacingSingleton("MyParameter")
publicFacingSingleton.Access.ActualMethodToDoWork();
```
There are several problems with this. A few of them are:
1. I have two classes now instead of one
2. An unknowing developer could still easily create a `PrivateFacingSingleton` instance.
Is there a better way that addresses my concerns but does not have me passing in a param every time I want to call `ActualMethodToDoWork()` (ie `publicFacingSingleton.Access("MyParameter").ActualMethodToDoWork()`)
NOTE: The above code is an example taken from my actual code. If you want to see my actual code it is [here](https://gist.github.com/793623).
|
2011/01/24
|
[
"https://Stackoverflow.com/questions/4785366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16241/"
] |
This might be considered as not a solution but I do think it should be mentioned here:
When a singleton needs a parameter it probably is not a singleton.
Chances are that you will need an instance that was created with an other value for the parameter (now or in the long run)
|
57,177,470 |
I have a simple code
```sql
SELECT @Setting =(CASE
WHEN @capName = 'role1'
AND .....?
THEN 1
...... --More than 1 case
ELSE 0
END)
FROM table1 t
WHERE t.accountId = 'nameA'
AND t.capName IN ('role1','role2')
```
I want to have a condtion of column **capName** here so that when table1 is **having no rows**, the @Setting will return 1.
|
2019/07/24
|
[
"https://Stackoverflow.com/questions/57177470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11062349/"
] |
Maybe COALESCE is what you're looking for:
```
SELECT @Setting = COALESCE((CASE
WHEN @capName = 'role1'
AND .....?
THEN 1
ELSE 0
END), 1)
FROM table1 t
WHERE t.accountId = 'nameA'
AND t.capName IN ('role1','role2')
```
|
67,991 |
I [read](https://motherboard.vice.com/en_us/article/zmakk3/researchers-find-critical-backdoor-in-swiss-online-voting-system) that the Swiss post had an [e-voting solution](https://www.post.ch/en/business/a-z-of-subjects/industry-solutions/swiss-post-e-voting) developed, made it possible to [obtain the source code for review](https://www.post.ch/en/business/a-z-of-subjects/industry-solutions/swiss-post-e-voting/e-voting-source-code), and that vulnerabilities were found.
Apparently we are *not* talking about the inherent and well-known issues of e-voting: it can't prevent purchasing of vote, and penetration of the voter's device can allow turning a vote around. Nor are we talking about the (reportedly laughable) code quality for the IT infrastructure, or its vulnerability to Denial of Service attack.
No. It was found a cryptographic flaw of some kind, by three independent teams:
* Sarah Jamie Lewis, Olivier Pereira and Vanessa Teague: [*Ceci n’est pas une preuve*, The use of trapdoor commitments in Bayer-Groth proofs and the implications for the verifiabilty of the Scytl-SwissPost Internet voting system](https://people.eng.unimelb.edu.au/vjteague/UniversalVerifiabilitySwissPost.pdf) (see [introduction](https://people.eng.unimelb.edu.au/vjteague/SwissVote))
* Rolf Haenni: [Swiss Post Public Intrusion Test: Undetectable Attack Against Vote Integrity and Secrecy](https://e-voting.bfh.ch/app/download/7833162361/PIT2.pdf) ([referring page](https://e-voting.bfh.ch/publications/2019/)).
* Thomas Edmund Haines ([NTNU](https://www.ntnu.edu/employees/thomas.haines)).
How was the proposed system supposed to work, and what was wrong with it or its implementation ?
We can stand [reassured by the officials](https://www.bk.admin.ch/bk/en/home/dokumentation/medienmitteilungen.msg-id-74307.html): the deployed e-voting systems can't have *this* flaw.
|
2019/03/13
|
[
"https://crypto.stackexchange.com/questions/67991",
"https://crypto.stackexchange.com",
"https://crypto.stackexchange.com/users/555/"
] |
In the Swiss Post electronic voting protocol, after voters submit ballots, they are scrambled individually and shuffled together so that they cannot be traced back to voters to find who voted for whom—variously called **ballot secrecy**, **privacy**, or **anonymity**—before they are tallied.
But since the ballots are bits in an electronic system, not physical artifacts, it would be easy to fabricate shuffled ballots inside the magic vibrating silicon crystals in the computer that implements the shuffler. So the shuffler must *also* print a receipt that anyone in the world can use to verify that it is *just* a shuffling and not any other kind of alteration—part of **universal verifiability** of the election—while still keeping it secret who voted for whom.
The method of universal verifiability in the Swiss Post protocol, as in any electronic voting protocol with ballot secrecy, involves a lot of complicated math. And it turns out that the way the math was designed enables the vote shuffler to trivially forge a receipt for a fraudulent ‘shuffle’ that changes the outcome of the election.
How does it work?
---
Let $m\_1, m\_2, \dots, m\_n$ represent filled-out ballots in an election. We want to keep the ballots secret, but compute the vote tally, and let the public verify the vote tally.
* The *poll workers* see who submitted each ballot $m\_i$, so we first encrypt the ballot as $c\_i = E\_k(m\_i, \rho\_i)$ to conceal it from the poll worker who puts it in the pile of ballots, where $E\_k(m, \rho)$ is a randomized public-key encryption scheme with randomization $\rho$. Randomization means the poll worker can't just check whether $c\_i = E\_k(b)$ for each possible ballot $b$ to recover what $m\_i$ is.
* The *vote counter*, who knows the secret key, then takes the pile of encrypted ballots, decrypts them, and tallies the results.
+ Since the poll worker could pass along who voted in which order, we enlist the aid of a *vote shuffler* to shuffle the votes into the order $c\_{\pi(1)}, c\_{\pi(2)}, \dots, c\_{\pi(n)}$ for a secret permutation $\pi$.\*
+ Since the vote counter could eyeball $c\_{\pi(i)}$ to discern whether it is the same as $c\_j$ and thereby recover what $\pi$ is, we *also* ask the vote shuffler to scramble each vote without changing the ballot it conceals.
If $E\_k$ is *homomorphic* in the message and randomization, meaning $$E\_k(m\_1 m\_2, \rho\_1 + \rho\_2) = E\_k(m\_1, \rho\_1) \cdot E\_k(m\_2, \rho\_2),$$ then we can scramble the votes by $$c'\_i = c\_{\pi(i)} \cdot E\_k(1, \rho'\_i) = E\_k(m\_{\pi(i)}, \rho\_{\pi(i)} + \rho'\_i)$$ for secret randomization $\rho'\_i$.\* Then we pass $c'\_1, c'\_2, \dots, c'\_n$ on to the vote counter.
* *Members of the public* only have their own receipts $c\_i$, which without the private key are indistinguishable from one another and from the $c'\_i$. **To have *confidence* that the vote counter or vote shuffler isn't fraudulently changing the outcome of the election by replacing $m\_i$ by some malicious $\hat m\_i$, the system must be *verifiable* to members of the public.**†
The canonical example of a homomorphic randomized public-key encryption scheme is Elgamal encryption $E\_k(m, \rho) := (g^\rho, k^\rho \cdot m)$ where $g, k, m \in G$ are elements of a group $G$ in which discrete logs are hard, and the secret key for $k$ is the exponent $x$ such that $k = g^x$. Here multiplication of ciphertexts $(a, b) \cdot (c, d)$ is elementwise, $(a \cdot c, b \cdot d)$.
There have been many systems over the years, of varying degrees of efficiency, to prove that what the vote shuffler sends to the vote counter to tally is, in fact, the set of $c\_{\pi(i)} \cdot E\_k(1, \rho'\_i)$.‡ One of them is [Bayer–Groth](https://link.springer.com/chapter/10.1007%2F978-3-642-29011-4_17 "Stephanie Bayer and Jens Groth, ‘Efficient Zero-Knowledge Argument for Correctness of a Shuffle’, in David Pointcheval and Thomas Johansson, eds., Advances in Cryptology—EUROCRYPT 2012, Springer LNCS 7237, pp. 263–280.") ([full paper](http://www.cs.ucl.ac.uk/staff/J.Groth/MinimalShuffle.pdf "Stephanie Bayer and Jens Groth, ‘Efficient Zero-Knowledge Argument for Correctness of a Shuffle’, full version of paper in EUROCRYPT 2012.")). There's a lot of cryptidigitation building on decades of work to make an efficient non-interactive zero-knowledge proof—a receipt that any member of the public can use offline to verify that the $c'\_i$ are in fact the $c\_{\pi(i)} \cdot E\_k(1, \rho'\_i)$, without learning what $\pi$ or the $\rho'\_i$ are.
The key part in question is the use of **Pedersen commitments** to commit to exponents $a\_1, a\_2, \dots, a\_n$ with randomization $r$ by sharing the *commitment* $$\operatorname{commit}\_r(a\_1, a\_2, \dots, a\_n) := g\_1^{a\_1} g\_2^{a\_2} \cdots g\_n^{a\_n} h^r,$$ where the group elements $g\_1, g\_2, \dots, g\_n, h \in G$ are independently chosen uniformly at random.
The commitment itself gives no information about $(a\_1, a\_2, \dots, a\_n)$ without $r$ because all commitments are equiprobable if $r$ is uniform—that is, Pedersen commitments are *information-theoretically hiding*. But the commitment *and randomization* $r$ enable anyone to verify the equation for any putative $(a'\_1, a'\_2, \dots, a'\_n)$ to get confidence that they are the $(a\_1, a\_2, \dots, a\_n)$ used to create the commitment in the first place: *if* you could find a distinct sequence $(a'\_1, a'\_2, \dots, a'\_n) \ne (a\_1, a\_2, \dots, a\_n)$ and randomization $r'$ for which $$\operatorname{commit}\_r(a\_1, a\_2, \dots, a\_n) = \operatorname{commit}\_{r'}(a'\_1, a'\_2, \dots, a'\_n),$$ *then* you could compute discrete logs of $h$ and $g\_i$ with respect to one another—a pithy summary of which is that Pedersen commitments are *computationally binding* under the discrete log assumption. (Proof: If $g\_1^{a\_1} h^r = g\_1^{a'\_1} h^{r'}$, then $\log\_{g\_1} h = \frac{a'\_1 - a\_1}{r - r'}$.)
The Bayer–Groth shuffler uses Pedersen commitments to commit to one $\pi$ and to the randomization values $\rho'\_i$ in the receipt that the public can use to verify the set of votes submitted to the vote counter. **If the vote shuffler could *lie* and claim to use a permutation $\pi$, while they actually use a function that repeats some votes and discards others, then they could fraudulently change the outcome of the election.** The [Lewis–Pereira–Teague paper](https://people.eng.unimelb.edu.au/vjteague/UniversalVerifiabilitySwissPost.pdf "Sarah Jamie Lewis, Olivier Pereira, and Vanessa Teague, ‘Ceci n'est pas une preuve’, manuscript, 2019-03-12.") goes into some details of how this works.
* One way to look at this reliance on Pedersen commitments is that the discrete logarithm problem seems hard, so we just have to choose the commitment bases $g\_1, \dots, g\_n, h$ independently uniformly at random.
**The obvious method to pick group elements independently uniformly at random is to pick exponents $e\_1, \dots, e\_n, f$ independently uniformly at random and set $g\_1 := g^{e\_1}, \dots, g\_n := g^{e\_n}, h := g^f$.** This is what the Scytl/Swiss Post system did.
* Another way to look at this is **holy shit, the exponents $e\_1, \dots, e\_n, f$ are a secret back door**, knowledge of which would enable the vote shuffler to commit essentially arbitrary vote fraud—**just like the Dual\_EC\_DRBG base points**.
The election authority could mitigate this by choosing commitment bases using another method, like [FIPS 186-4](https://csrc.nist.gov/publications/detail/fips/186/4/final "FIPS 186-4, ‘Digital Signature Standard (DSS)’, United States NIST, July 2013.") [Appendix A.2.3](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf#page=51), which probably makes it difficult to learn the back door exponents, and which can be verified; this is allegedly what Scytl has elected to do to fix the issue, although I have no idea whether they have published the hash preimages necessary to conduct the verification.
---
This may sound like a trivial mistake: oops, we forgot to zero a secret. But it illustrates a deeper problem.
The commitment bases $g\_1, \dots, g\_n, h$ serve as a **common reference string** in a [standard technique](https://dl.acm.org/citation.cfm?id=62222 "Manuel Blum, Paul Feldman, and Silvio Micali, ‘Non-Interactive Zero-Knowledge and Its Applications’, in Proceedings of the 20th annual ACM Symposium on Theory of Computing—STOC '88, ACM, 1988, pp. 103–112.") ([paywall-free](https://sci-hub.tw/https://dl.acm.org/citation.cfm?id=62222)) for converting an *interactive* zero-knowledge proof system into a *non-interactive* zero-knowledge proof receipt like the vote shuffler is supposed to print out.
In an interactive proof system, the verifier might choose an unpredictable challenge—like which tunnel to come out of in the story of [Ali Baba and the 40 thieves](https://link.springer.com/chapter/10.1007%2F0-387-34805-0_60 "Jean-Jacques Quisquater, Myriam Quisquater, Muriel Quisquater, Michaël Quisquater, Louis Guillou, Marie Annick Guillou, Gaïd Guillou, Anna Guillou, Gwenolé Guillou, and Soazig Guillou, ‘How to Explain Zero-Knowledge Protocols to Your Children’, in Gilles Brassard, ed., Advances in Cryptology—CRYPTO '89, Springer LNCS 435, pp. 628–631.")—which the prover must answer correctly. What if we want to make a non-interactive proof receipt that we can publish on a web site for anyone in the public to download and verify?
* In some protocols, like signature schemes such as [Schnorr's](https://link.springer.com/chapter/10.1007/0-387-34805-0_22 "Claus P. Schnorr, ‘Efficient Identification and Signatures for Smart Cards’, in Gilles Brassard, ed., Advances in Cryptology—CRYPTO'89 Proceedings, Springer LNCS 435, pp. 239–252.") derived using the [Fiat–Shamir heuristic](https://link.springer.com/chapter/10.1007%2F3-540-47721-7_12 "Amos Fiat and Adi Shamir, ‘How To Prove Yourself: Practical Solutions to Identification and Signature Problems’, in Andrew M. Odlyzko, ed., Advances in Cryptology—CRYPTO '86, Springer LNCS 263, pp. 186—194."), the challenges can be replaced by a *random oracle*: a random function that the prover can *evaluate* on the transcript so far to imitate an unpredictable challenge that the verifier might have submitted, but that the prover has *no control* over. To instantiate such protocols, we choose a hash function like SHAKE128 that we hope has no useful properties the prover can exploit to forge fraudulent proofs.
Addendum: This post was getting too long already, but two weeks after the flaw detailed here was reported, the same researchers reported [another fraud-enabling flaw](https://people.eng.unimelb.edu.au/vjteague/HowNotToProveElectionOutcome.pdf "Sarah Jamie Lewis, Olivier Pereira, and Vanessa Teague, ‘How not to prove your election outcome’, manuscript, 2019-03-25.") in the misuse of the Fiat–Shamir heuristic—the designers neglected to feed in the *entire* transcript of committed values into the hash function (‘random oracle’), which is crucial to the security of the Fiat–Shamir heuristic. That flaw also appeared in the [New South Wales Electoral Commission's iVote system](https://people.eng.unimelb.edu.au/vjteague/iVoteDecryptionProofCheat.pdf "Vanessa Teague, ‘Faking an iVote decryption proof’, manuscript, 2019-11-14.") based on Scytl's software, despite the [NSWEC's public claims to be unaffected](https://www.elections.nsw.gov.au/About-us/Media-centre/News-media-releases/NSW-Electoral-Commission-iVote-and-Swiss-Post "NSW Electoral Commission iVote and Swiss Post e-voting update, New South Wales Electoral Commission, press release, 2019-03-22.") ([archived](https://web.archive.org/web/20190327014522/https://www.elections.nsw.gov.au/About-us/Media-centre/News-media-releases/NSW-Electoral-Commission-iVote-and-Swiss-Post)).
* Similarly, in some protocols like Bayer–Groth we can use a *common reference string*: a predetermined bit string chosen randomly and known in advance to the verifier and prover. To instantiate such protocols, we need a system to pick a random string in advance with negligible probability that the prover can exploit properties of, like we get with FIPS 186-4 Appendix A.2.3. **If the prover can *influence* the common reference string, the proof means nothing.**
This is part of the **security contract** of a cryptosystem. To get any security out of AES-GCM, your obligation is to choose the key uniformly at random and keep it secret and never reuse it with the same nonce. To get any security out of a Bayer–Groth vote shuffler, the verifier and prover must agree *in advance* on a common reference string that the prover has no control over. **In the Scytl system, the *prover chose the common reference string*.** Not only did this violate the security contract, but it demonstrated a profound failure to understand the basic premises of the non-interactive zero-knowledge proof system they used.
---
The public evidence is unclear about whether the authors *knew* this would serve as a back door, and the [Lewis–Pereira–Teague paper](https://people.eng.unimelb.edu.au/vjteague/UniversalVerifiabilitySwissPost.pdf "Sarah Jamie Lewis, Olivier Pereira, and Vanessa Teague, ‘Ceci n'est pas une preuve’, manuscript, 2019-03-12.") cautions that this could be a product of incompetence rather than malice—the technical nature of the flaw was [known internally since 2017](https://www.post.ch/en/about-us/company/media/press-releases/2019/error-in-the-source-code-discovered-and-rectified "Swiss Post, ‘Error in the source code discovered and rectified’, press release, 2019-03-12.") ([archived](https://web.archive.org/web/20190312222111/https://www.post.ch/en/about-us/company/media/press-releases/2019/error-in-the-source-code-discovered-and-rectified "Swiss Post, ‘Error in the source code discovered and rectified’, press release, 2019-03-12. Internet Archive, 2019-03-12.")) but it's unclear the whether consequences were understood. It could have been incompetence on the part of NIST that they adopted Dual\_EC\_DRBG—NIST [recognized early on](https://csrc.nist.gov/csrc/media/projects/crypto-standards-development-process/documents/email_oct%2027%202004%20don%20johnson%20to%20john%20kelsey.pdf "John Kelsey, ‘[Fwd: RE: Minding our Ps and Qs in Dual_EC]’, email to [email protected], 2004-10-27.") that there was something fishy about the base points and was [told not to discuss it by NSA](https://csrc.nist.gov/csrc/media/projects/crypto-standards-development-process/documents/dualec_in_x982_and_sp800-90.pdf#page=23 "John Kelsey, ‘Dual EC in X9.82 and SP 800-90’, United States NIST, presentation, May 2014.").
The first order of business is not to argue about whether the software vendor Scytl was malicious or incompetent, but to be [taken seriously](https://twitter.com/SarahJamieLewis/status/1105387409716404225 "Sarah Jamie Lewis, Tweet by @SarahJamieLewis about being taken seriously, 2019-03-12.") enough by election authorities to demand *real scrutiny* on designs, not a sham bug bounty hampered by an NDA just before deployment, and to review the process of how we got here to ensure that **designs with back doors like this must never even come close to being deployed in real elections because they enable extremely cheap arbitrarily massive unverifiable vote fraud**.
(One can argue whether the larger problems arise from undetectable centralized [fraud in electronic voting](https://freedom-to-tinker.com/2011/09/13/nj-election-cover/ "Andrew Appel, ‘NJ election cover-up’, Freedom to Tinker blog, Center for Information Technoogy Policy, Princeton University, 2011-09-13."); distributed [fraud in voting by mail](https://www.newsobserver.com/news/politics-government/article227128739.html "Carli Brosseau, ‘5 were indicted in alleged ballot fraud scheme. Now all have been arrested.’, Raleigh News & Observer, 2019-03-05."); or voter suppression by [gerrymandering](https://www.washingtonpost.com/politics/courts_law/2018/08/27/fc04e066-aa46-11e8-b1da-ff7faa680710_story.html?noredirect=on "Robert Barnes, ‘North Carolina’s gerrymandered map is unconstitutional, judges rule, and may have to be redrawn before midterms’, Washington Post, 2018-08-27."), [felony disenfranchisement](https://www.nytimes.com/2018/06/13/us/texas-woman-voter-fraud.html "Sandra E. Garcia, ‘Texas Woman Sentenced to 5 Years in Prison for Voter Fraud Loses Bid for New Trial’, New York Times, 2018-06-13."), and [closure of polling stations](https://www.ajc.com/news/state--regional-govt--politics/voting-precincts-closed-across-georgia-since-election-oversight-lifted/bBkHxptlim0Gp9pKu7dfrN/ "Mark Niesse, Maya T. Prabhu, and Jacquelyn Elias, ‘Voting precincts closed across Georgia since election oversight lifted’, Atlanta Journal-Constitution, 2018-08-31."). One can argue about other IT issues, about the [importance of paper trails and mandatory risk-limiting audits](https://www.stat.berkeley.edu/~stark/Preprints/RLAwhitepaper12.pdf "Jennie Bretschneider, Sean Flaherty, Susannah Goodman, Mark Halvorson, Roger Johnston, Mark Lindeman, Ronald L. Rivest, Pam Smith, and Philip B. Stark ‘Risk-Limiting Post-Election Audits: Why and How’, Risk-Limiting Audits Working Group, whitepaper, version 1.1, October 2012."), *etc.* Such arguments should be had, but this question is not the forum for them—consider volunteering as an election worker instead or talking to your parliament! This question is specifically about the technical nature of the misapplication of cryptography, whether negligent or malicious, by Scytl and Swiss Post.)
---
\* We assume that there is an omniscient mass surveillance regime monitoring the every action of the vote shuffler to ensure they do not collude with anyone else to reveal secret ballots. The omniscient mass surveillance regime is also honest and would never dream of colluding with anyone themselves—not wittingly.
† We assume that the public consists entirely of people with PhDs in cryptography, like the country of Switzerland.
‡ The vote *counter* must also be able to prove that the tally it returns is the sum of the plaintexts of the encrypted ballots that are fed to it, which we will not address here—the specific back door under discussion here is in the vote shuffler.
|
560,376 |
I'm trying to write a Rakefile that both builds my code normally when I run `rake compile` but puts the targets in a different directory and builds with `-DTEST` when I run `rake test`. I cannot for the life of me figure out how to do it, though. I've got something like this at the moment:
```
SRC = FileList['src/*.erl']
OBJ = SRC.pathmap("%{src,ebin}/X.beam")
rule ".beam" => ["%{ebin,src}X.erl"] do |t|
sh "erlc ... -o ebin #{t.source}"
end
task :compile => OBJ
```
What I'd like is a `task :test` that put the compiler output into `ebin_test` (basically changed all instances of `ebin` into `ebin_test` in the above code) and added a -DTEST to the `sh` call. Anyone got any ideas?
|
2009/02/18
|
[
"https://Stackoverflow.com/questions/560376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60003/"
] |
Well, that wasn't a positive first question... no answers.
For the record, I solved the problem by having a task for both build and test that defined the compilation rules differently, and then had the public task call that task before doing the actual build/test run. A couple of scoping issues, but nothing exciting. I won't bother pasting the full resulting rakefile, but let me know if you're interested in taking a look.
|
19,827,188 |
I have a site currently under development which I allow users to post comments. I want to know if there is a potential security issue if a user maliciously posts HTML elements. I know allowing javascript or CSS is dangerous, but what about HTML?
|
2013/11/07
|
[
"https://Stackoverflow.com/questions/19827188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2193432/"
] |
Yes, there are security issues like iframe as mentioned in the comments. OWASP has a very detailed page on dealing with 3rd party content here: <https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet> .
Various languages offer libraries to deal with this:
* Rails: <http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html>
* PHP: <http://htmlpurifier.org/comparison>
|
33,539,663 |
I am trying to connect to Oracle DB from my local computer and I use the following libname statement.
```
libname liblibb oracle path='galaxy' defer=no
connection=globalread readbuff=4000 ;
```
this works... as it uses the windows AD details to login.
However, the problem is when i run this libname statement with rsubmit(server UNIX).
```
rsubmit;
libname liblibb oracle path='galaxy' defer=no
connection=globalread readbuff=4000 ;
endrsubmit;
```
Error:
```
ORA-01017 Invalid Username/Password
Error in the LIBNAME statement
```
But when I use it with username and password it works.
```
rsubmit;
libname liblibb oracle path='galaxy' user=xxxx password='xxxx'
defer=no
connection=globalread readbuff=4000 ;
endrsubmit;
```
Is there any possible way to logon to Oracle on rsubmit without writing the user and password details in the libname statement or atleast like a dbprompt for the username and password? or how can the we make UNIX work with the windows AD in sync with Oracle so it takes the single sign on concept.
|
2015/11/05
|
[
"https://Stackoverflow.com/questions/33539663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3658367/"
] |
If we just need the `mean` of 'Age' where 'State' is 1, subset the 'Age' values that corresponds to 'State' of 1 and get the `mean`
```
mean(df1$Age[df1$State==1])
```
Or if we need `mean` of 'Age' per each 'State' group, one option is `aggregate`
```
aggregate(Age~State, df1, FUN=mean)
```
Or we use `data.table` where we convert the 'data.frame' to 'data.table' (`setDT(df1)`), get the 'mean` of 'Age', grouped by 'State'.
```
library(data.table)
setDT(df1)[, list(Age=mean(Age)), State]
```
|
221,555 |
What is the difference between the two sentences?
>
> I have not played hockey **in** six years.
>
> I have not played hockey **for** six years.
>
>
>
|
2019/08/17
|
[
"https://ell.stackexchange.com/questions/221555",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/99772/"
] |
I don't think there is all that much of a discernible difference. If one of my friends told me,
>
> "I have not played hockey **in** six years,"
>
>
>
and another said,
>
> "I have not played hockey **for** six years,"
>
>
>
then I would assume both of them are former hockey players, but neither of them had laced up their hockey skates over the past six years.
Prepositions are very flexible words that sometimes have overlapping meanings. One definition of *in* is:
>
> **in** (*preposition*) used for showing when something happens within a period of time
>
> ([Macmillan](https://www.macmillandictionary.com/us/dictionary/american/in_1), definition 4c)
>
>
>
while one definition of *for* is:
>
> **for** (*preposition*) used for saying a length of time; in particular, for how long something lasts or continues
>
> ([Macmillan](https://www.macmillandictionary.com/us/dictionary/american/in_1), definition 3a)
>
>
>
Therefore, either preposition can be used to explain how long it has been since someone has last done something.
Again, I'd say the two sentences are more synonymous than different.
|
63,170,308 |
I want to use the ServiceBusConnectionStringBuilder to connecto to the Azure Service Bus.
When I enter the connection string generated on Azure to the constructor with one parameter
`public ServiceBusConnectionStringBuilder (string connectionString);`
the entitypath is null.
When I want to create the connection string with the 4 parameter constructor
`public ServiceBusConnectionStringBuilder (string endpoint, string entityPath, string sharedAccessKeyName, string sharedAccessKey);`
and I enter into entityPath null or an empty string an exception is thrown. The Visual Studio Debugger shows that the values of the both connection string builders are the same.
**What should I enter in the entityPath so that the builder is properly executed?**
I have no idea since the documentation on this object is missing. Here a link to the documentation page [SerbiceBusConnectionStringBuilder Documentation](https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.servicebus.servicebusconnectionstringbuilder?view=azure-dotnet)
|
2020/07/30
|
[
"https://Stackoverflow.com/questions/63170308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9038968/"
] |
>
> What should I enter in the entityPath so that the builder is properly
> executed?
>
>
>
It should be the name of the entity. In case of a Queue or Topic, it should be the name of that Queue or Topic respectively. In case of a Subscription, it should be the path of the Subscription in `<topic-name>/subscriptions/<subscription-name>` format.
If you're accessing deadletter queue, simply append `/$DeadLetterQueue` to the path from above.
|
181,044 |
I am following the instructions to install Drush that are listed on this page: <https://github.com/drush-ops/drush/blob/master/docs/install.md>
I seem to be getting a syntax error within the code:
```
[user@localhost ~]$ wget https://github.com/drush-ops/drush/releases/download/8.0.0-rc4/drush.phar
--2015-11-16 16:23:02-- https://github.com/drush-ops/drush/releases/download/8.0.0-rc4/drush.phar
Resolving github.com (github.com)... 192.30.252.131
Connecting to github.com (github.com)|192.30.252.131|:443... connected.
HTTP request sent, awaiting response... 302 Found
2015-11-16 16:23:05 (1.47 MB/s) - drush.phar saved [3496991/3496991]
[user@localhost ~]$ php drush.phar core-status
Parse error: syntax error, unexpected '[' in phar:///home/user/drush.phar/includes/output.inc on line 188
```
I am not seeing this error on Google. Any idea how to fix it?
|
2015/11/16
|
[
"https://drupal.stackexchange.com/questions/181044",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/24169/"
] |
You're using Drush 8, which requires a minimum PHP version of 5.4.5 (<http://docs.drush.org/en/master/install/>).
Your current version (5.3) doesn't understand short array syntax, hence the error you're seeing.
To fix, either upgrade PHP, or switch to an older branch of Drush.
|
9,699,082 |
I've implemented a JQGrid table with `loadonce:true` like this :
```
jQuery("#list").jqGrid({
datatype: 'jsonstring',
datastr : maVarJSON,
colNames:['AA','BB', 'CC','DD','EE','FF'],
colModel :[
{name:'invid', index:'invid', align:'center'},
{name:'invdate', index:'invdate'},
{name:'amount', index:'amount', align:'right'},
{name:'tax', index:'tax', align:'right'},
{name:'total', index:'total', align:'right'},
{name:'note', index:'note'}
],
pager: jQuery('#pager'),
rowNum: 50,
rowList: [50, 100],
caption: '',
height: 470,
width: 1000,
loadonce: true
});
jQuery("#list").jqGrid('filterToolbar',{afterSearch: function(){
var rowsFiltered = jQuery("#list").getRowData();
}});
```
My problem is :
I have 500 rows in `maVarJSON`. I see 50 rows and 10 pages.
I decide to filter my column AA. Only 100 rows accept this filter. So, I see 50 rows and 2 pages.
I would get the 100 rows data. (The method `jQuery("#list").getRowData()` give me only the 50 first rows data.)
Thanks
|
2012/03/14
|
[
"https://Stackoverflow.com/questions/9699082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1268560/"
] |
The method `getRowData` get the data from the *current* page only. If you need get all the grid data you can use `getGridParam` to get `'data'` parameters and get *all* grid data. I don't really understand what you want to do with the data inside of `afterSearch` callback. The goal of `filterToolbar` to display the data for the user and not to get you JavaScript interface to filter some JavaScript data.
By the way you can remove `caption: ''` option which is default, remove `loadonce: true` which will be ignored for local data inclusive `datatype: 'jsonstring'` and replace `pager: jQuery('#pager')` option to `pager: '#pager'`. If you would use `pager: jQuery('#pager')` jqGrid will have to convert it to `pager: '#pager'` itself internally.
|
5,052,231 |
I have a nice object that describes a relatively large data set. I decided to implement some helper functionality in the object.
Basically, instead of using the standard setter for a NSString, I define my own setter and set another object at the same time.
For example:
```
-(void) setNumber:(NSString *)number_in
{
number = [number_in copy];
title = @"Invoice ";
title = [title stringByAppendingString:number];
}
```
I know I will need "title" as a property in a certain format. Title is based on the number, so I created a setter to set number and title in one punch. (title has the default synthesized setter...I don't define it elsewhere)
For some reason, I'm getting the message sent to deallocated instance error. If I delete this setter, the code works fine.
My property definition is here:
```
@property (nonatomic, copy) NSString *number;
@property (nonatomic, copy) NSString *title;
```
I've tried retaining, to no avail. I setup malloc stack logging and logged this:
```
Alloc: Block address: 0x06054520 length: 32
Stack - pthread: 0xa003f540 number of frames: 30
0: 0x903ba1dc in malloc_zone_malloc
1: 0x102b80d in _CFRuntimeCreateInstance
2: 0x102d745 in __CFStringCreateImmutableFunnel3
3: 0x10824dd in _CFStringCreateWithBytesNoCopy
4: 0xae222e in -[NSPlaceholderString initWithCStringNoCopy:length:freeWhenDone:]
5: 0xaf9e8e in _NSNewStringByAppendingStrings
6: 0xaf9a76 in -[NSString stringByAppendingString:]
7: 0x112ba in -[Invoice setNumber:] at Invoice.m:25
8: 0x11901 in -[Invoice copyWithZone:] at Invoice.m:47
9: 0x107c7ca in -[NSObject(NSObject) copy]
10: 0x1117632 in -[NSArray initWithArray:range:copyItems:]
11: 0x107f833 in -[NSArray initWithArray:copyItems:]
12: 0x5595 in -[InvoicesTableViewController wrapper:didRetrieveData:] at InvoicesTableViewController.m:96
13: 0x4037 in -[Wrapper connectionDidFinishLoading:] at Wrapper.m:288
14: 0xb17172 in -[NSURLConnection(NSURLConnectionReallyInternal) sendDidFinishLoading]
15: 0xb170cb in _NSURLConnectionDidFinishLoading
16: 0x18ca606 in _ZN19URLConnectionClient23_clientDidFinishLoadingEPNS_26ClientConnectionEventQueueE
17: 0x1995821 in _ZN19URLConnectionClient26ClientConnectionEventQueue33processAllEventsAndConsumePayloadEP20XConnectionEventInfoI12XClientEvent18XClientEventParamsEl
18: 0x18c0e3c in _ZN19URLConnectionClient13processEventsEv
19: 0x18c0cb7 in _ZN17MultiplexerSource7performEv
20: 0x10fd01f in __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__
21: 0x105b28b in __CFRunLoopDoSources0
22: 0x105a786 in __CFRunLoopRun
23: 0x105a240 in CFRunLoopRunSpecific
24: 0x105a161 in CFRunLoopRunInMode
25: 0x1c29268 in GSEventRunModal
26: 0x1c2932d in GSEventRun
27: 0x39542e in UIApplicationMain
28: 0x2199 in main at main.m:14
29: 0x2115 in start
```
In the end, I keep getting this error:
```
-[CFString release]: message sent to deallocated instance 0x4b5aee0
```
Thanks a million in advance :)
|
2011/02/19
|
[
"https://Stackoverflow.com/questions/5052231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/334457/"
] |
Use `self.title` to invoke your synthesized setter as well as release the old value for `number`.
```
- (void)setNumber:(NSString *)number_in
{
[number release];
number = [number_in copy];
self.title = [NSString stringWithFormat:@"Invoice %@", number];
}
```
|
65,175 |
I have a full suit of iron armour but I can't kill any spiders without dying myself. I was wondering if there was a simple yet efficient spider trap/killer in Minecraft. I do not have any cacti on my island and i havent found lava yet either. What i am looking for is the plans for a spider grinder.
|
2012/05/05
|
[
"https://gaming.stackexchange.com/questions/65175",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/-1/"
] |
[This Link](http://www.minecraftwiki.net/wiki/Tutorials/Traps) from Minecraft wiki shall guide you through a huge number of simple traps. These are designed to trap or trick other players or mobs automatically. Some traps even kill...
However, I shall briefly sum up the most popular designs for trapping spiders.
**Land Mine**
For a simple land mine a 1 by 1 hole two blocks deep. Next put one piece of TNT at the bottom and cover it with a block that looks natural to the area(a stone block in a cave ect.). After that just put a pressure plate on top and it's done. If a mob or player steps on it, It will go off.
Note: When using a wooden pressure plates dropped items will trigger the TNT and the delay and noise of the TNT may alert the victim.
**More Advanced** I pay attention to Kiershar's youtube channel, and based my mob trap off of his [videos](http://www.youtube.c...notation_999551). The biggest problem with his grinder as well as many other traps is that it does not kill spiders very efficiently, and sometimes, not at all. I've seen videos of elaborate fixes to this problem, but I can't believe someone hasn't seemed to have done what I've done.

Here is my grinder. Just like Kiershar's, I have a 3X2 lava pool running over a couple of ladders with a 1X2 space below where items but not mobs can fall through. The sand block at the bottom left is where a cactus would sit if this were Kiershar's trap. As you can see, I have omitted this as well as a block below the ladders for keeping spiders from falling through because this is not where they will be dying (note the string floating by).
This is how they die:

Here is the start of that same channel that has the lava at the end. The beginning of the channel should have another channel one block higher flowing into it and a cactus sitting on top of that sand block. The length of the channel after that doesn't matter, but this part is crucial. This creates a 2 block high, one block wide space that all other mobs can go through, but not spiders. Taking advantage of the fact that spiders are the only 2 block wide mob is what makes this work.

Here is another view of the beginning of this channel with the cactus placed and the other channel filled in. A water block should be placed to the right of the cactus.

Placing that water block leads to a water current that looks like this. 1 block wide mobs will fall in and most likely float behind the cactus, but soon after will float to the lava and die. Spiders however, will sit here unless there is another mob behind them. They will block the entire 2 block wide entrance to this channel, so they must die first, which they will because the mob behind them will push them directly into the cactus at the 2 block high level. This always works, and no other mobs will flow through until the spider dies.

Here's the spider killer in action. As you can see, the spider floats to the block at the level of the cactus and dies there. This doesn't depend on whether the spider is jumping; it's just somehow levitating above thin air. The ceiling should be filled in at the block above the cactus, though, to make sure the spider stops here.

Spiders will also kill each other this way. No more spiders clogging your trap!
Taken from [here](http://www.minecraftforum.net/topic/266253-easiest-way-to-kill-spiders-in-your-mob-trap/).
|
28,894,560 |
I'm trying to animate a circle that is being drawn, I know how to do that, however, I do not seem to be able to find any information on how to trigger an animation after a button has been clicked or after data has been updated by a service.
The easiest solution for this would be to use CAShapeLayers. I need to update the time and then show that in the form of a few circles on top of each other.
I also have code to be able to do this in the drawRect method but I don't know yet which is the better solution for updating the circles. Do you guys know how to do this?
This is my code while using CAShapeLayers:
```
private var _greyCircleLayer: CAShapeLayer = CAShapeLayer()
private var _transpartentOrangeOneCircleLayer: CAShapeLayer = CAShapeLayer()
private var _transpartentOrangeTwoCircleLayer: CAShapeLayer = CAShapeLayer()
private var _transpartentOrangeThreeCircleLayer: CAShapeLayer = CAShapeLayer()
private var _transpartentOrangeFourCircleLayer: CAShapeLayer = CAShapeLayer()
private var _solidOrangeCircleLayer: CAShapeLayer = CAShapeLayer()
private var _currentDisplayedTime: Double = Double(0.0)
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
private func configure() {
addCAShapeLayer(self._greyCircleLayer, colour: StyleGlobals.StrokeColor.CGColor)
addCAShapeLayer(self._transpartentOrangeOneCircleLayer, colour: StyleGlobals.TransparentOrange.CGColor)
addCAShapeLayer(self._transpartentOrangeTwoCircleLayer, colour: StyleGlobals.TransparentOrange.CGColor)
addCAShapeLayer(self._transpartentOrangeThreeCircleLayer, colour: StyleGlobals.TransparentOrange.CGColor)
addCAShapeLayer(self._transpartentOrangeFourCircleLayer, colour: StyleGlobals.TransparentOrange.CGColor)
addCAShapeLayer(self._solidOrangeCircleLayer, colour: StyleGlobals.SolidOrange.CGColor)
}
```
And then I try to animate the layers with the following method, however it does not work. It only works when calling it after having added the layers to the view hierarchy:
```
func animateCircle(duration: NSTimeInterval, shapeLayer: CAShapeLayer, timeStart: CGFloat, timeEnd: CGFloat) {
/*//let duration = 1.0
let delay = 0.0 // delay will be 0.0 seconds (e.g. nothing)
let options = UIViewAnimationOptions.CurveEaseInOut // change the timing curve to `ease-in ease-out`
UIView.animateWithDuration(duration, delay: delay, options: options, animations: {
// any changes entered in this block will be animated
shapeLayer.strokeEnd = timeEnd
}, completion: { finished in
// any code entered here will be applied
// once the animation has completed
})*/
// We want to animate the strokeEnd property of the circleLayer
let animation = CABasicAnimation(keyPath: "strokeEnd")
// Set the animation duration appropriately
animation.duration = duration
// Animate from 0 (no circle) to 1 (full circle)
animation.fromValue = timeStart
animation.toValue = timeEnd
// Do a linear animation (i.e. the speed of the animation stays the same)
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
// Set the circleLayer's strokeEnd property to 1.0 now so that it's the
// right value when the animation ends.
shapeLayer.strokeEnd = timeEnd
// Do the actual animation
shapeLayer.addAnimation(animation, forKey: "strokeEnd")
}
```
|
2015/03/06
|
[
"https://Stackoverflow.com/questions/28894560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1235505/"
] |
Use a correlated subquery to find each product's last date:
```
select date, product, price
from table t1
where date = (select max(date) from table t2
where t1.product = t2.product)
```
(After reading Damien\_The\_Unbeliever's comment I want to add that if several entries exist with same max date for a product, they will all be returned.)
|
50,071,261 |
In [this autocomplete example](https://stackoverflow.com/questions/5465590/auto-append-complete-from-text-file-to-an-edit-box-delphi/5465826#) by @KenWhite, the Next function has an access violation when `TPointerList()[]` is called ( by the windows autocomplete interface.)
D10.1u2, Win10.64
```
function TEnumString.Next(celt: Integer; out elt;
pceltFetched: PLongint): HResult;
var
I: Integer;
wStr: WideString;
begin
I := 0;
while (I < celt) and (FCurrIndex < FStrings.Count) do
begin
wStr := FStrings[FCurrIndex];
TPointerList(elt)[1] := PWideChar('abcd'); //access violation
TPointerList(elt)[1] := CoTaskMemAlloc(8); //access violation
TPointerList(elt)[I] := CoTaskMemAlloc(2 * (Length(wStr) + 1)); //access violation
StringToWideChar(wStr, TPointerList(elt)[I], 2 * (Length(wStr) + 1));
Inc(I);
Inc(FCurrIndex);
end;
if pceltFetched <> nil then
pceltFetched^ := I;
if I = celt then
Result := S_OK
else
Result := S_FALSE;
end;
```
|
2018/04/27
|
[
"https://Stackoverflow.com/questions/50071261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5071605/"
] |
`(elt)` needs to be `(@elt)`, and `[1]` needs to be `[I]`:
```
TPointerList(@elt)[I]
```
Then the code will not AV anymore.
Also, the output strings must be allocated with either `SysAllocString...()` or `CoTaskMemAlloc()`, as the caller is going to use the COM memory manager to free them. You can use the RTL's `ComObj.StringToLPOLESTR()` function to handle that for you, which makes a COM-allocated wide string copy of a Delphi `String`:
```
TPointerList(@elt)[I] := StringToLPOLESTR(FStrings[FCurrIndex]);
```
Alternatively, you can simply take ownership of the `WideString`'s data pointer instead of making yet another copy in memory after `WideString` has already made one:
```
wStr := FStrings[FCurrIndex];
TPointerList(@elt)[I] := Pointer(wStr);
Pointer(wStr) := nil;
```
|
163,454 |
In this setting, the family unit is based around a clan system. An individual's wealth and status is related to the clan they are born in, and its ancestry is based on matrilineal lines. Due to certain environmental factors caused by a devastating calamity on the continent, travel between regional areas can be somewhat difficult and expensive. Therefore, most breeding takes place between clans in relative proximity of each other.
Marriage does not exist in the form we would recognize. Women remain in the clan they were born into, while men are the ones who leave the home to join other families. Men marry into clans, which lead to many offspring coming from the same group of fathers. This can unfortunately lead to cases of inbreeding. The solution to this that have become the norm are "genetic peddlers". These merchants go from village to village, collecting sperm and egg samples and selling to the populace of that area. Since most relations occur between villages located near one another, these merchants take their wares to far away locations to keep up diversity in the gene pool. Every sample comes with a bio of the donor from which it came from, as well as other necessary information that individuals would want to know.
As stated, travel between areas is difficult, requiring much preparation before the journey. Technology is scarce and expensive, lacking the sophistication for cryo-preservation. I need an alternative way to store these samples for these journeys for as long as possible. what tools or methods would provide the best outcome to make this happen, while keeping the sample viable for the long term?
|
2019/12/12
|
[
"https://worldbuilding.stackexchange.com/questions/163454",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/52361/"
] |
**You've solved the problem already**
This might sound weird, but the genetic peddlers themselves carry a good dose of fresh non-connected genetic material to all but 1 of the clans. That is to say, themselves. And this in turns leads to the solution of 'send off the males but keep the females.
So, if I'm reading your scenario right, in every offspring generation, the men leave and the women stay. In other words, for a Generation X, the female offspring stay and the male leave. That means that the females get males from other clans. Thus, *all* the fathers for generation Y must be males from other clans, and thus *cannot* be directly related to the woman. Generation Y is safe from inbreeding.
I suppose there can be a case of something like:
1. A Generation 1 couple produces a Gen 2 male and female.
2. The Generation 2 man fathers a Gen 3 male in the away clan. The Gen 2 female has a Gen 3 female back in the home clan.
3. The Gen 3 male can head back and form a couple with his Gen 3 cousin back in the first clan.
This could lead to inbreeding.
However, that's going to be rare, and cousin relationship aren't inbreeding problematic unless they happen repeatedly, and even under these circumstances, it shouldn't be hard to direct the incoming Gen 3 male away from his cousin. No need for 'genetic peddlers'.
|
69,824,980 |
i'm trying to create columns to represent min/max after every row within a group.
original df
```
╔═══════╦═══════╦════════╗
║ color ║ panel ║ result ║
╠═══════╬═══════╬════════╣
║ blue ║ b ║ 4 ║
║ blue ║ b ║ 3 ║
║ blue ║ b ║ 3 ║
║ blue ║ b ║ 5 ║
║ blue ║ b ║ 4 ║
║ blue ║ b ║ 7 ║
║ blue ║ b ║ 1 ║
║ blue ║ b ║ 5 ║
║ blue ║ b ║ 3 ║
║ blue ║ b ║ 2 ║
╚═══════╩═══════╩════════╝
```
result trying to get
```
╔═══════╦═══════╦════════╦═════╦═════╗
║ color ║ panel ║ result ║ min ║ max ║
╠═══════╬═══════╬════════╬═════╬═════╣
║ blue ║ b ║ 4 ║ 4 ║ 4 ║
║ blue ║ b ║ 3 ║ 3 ║ 4 ║
║ blue ║ b ║ 3 ║ 3 ║ 4 ║
║ blue ║ b ║ 5 ║ 3 ║ 5 ║
║ blue ║ b ║ 4 ║ 3 ║ 5 ║
║ blue ║ b ║ 7 ║ 3 ║ 7 ║
║ blue ║ b ║ 1 ║ 1 ║ 7 ║
║ blue ║ b ║ 5 ║ 1 ║ 7 ║
║ blue ║ b ║ 3 ║ 1 ║ 7 ║
║ blue ║ b ║ 2 ║ 1 ║ 7 ║
╚═══════╩═══════╩════════╩═════╩═════╝
```
```
data = {'color':['blue','blue','blue','blue','blue','blue','blue','blue','blue','blue'],
'panel':['b','b','b','b','b','b','b','b','b','b'],
'result':[4,3,3,5,4,7,1,5,3,2]}
```
kindly advise. thank you
|
2021/11/03
|
[
"https://Stackoverflow.com/questions/69824980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11925464/"
] |
You want [`cummin`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.cummin.html) and `cummax`
```
data.result.cummin()
data.result.cummax()
```
|
6,914 |
Could someone explain the grammar/words behind this and similar phrases? I did some research and probably found the explanation, but I am not sure if this is correct.
The phrase may be found in a variety of places (e.g. [here](http://thejapanesepage.com/ebooks/sparrow/2)) where it is usually translated as "can't stop worrying" or just "so worried"
心配 means "worry", this is clear.
The meaning of たまらず is not this clear, though. My dictionary says that あず is the archaic negative form (same as in in the phrase "Vずに"). This means that the verb should be たまる. The closest verb I found is 堪る which means something like "to endure", "to bear", "to resist" [(see goo jisho)](http://dictionary.goo.ne.jp/leaf/jn2/138927/m0u/%E3%81%9F%E3%81%BE%E3%82%8B/). So the phrase would literally mean "Cannot resist worrying". Does this explanation make any sense? Is there some other, better, explanation?
|
2012/09/24
|
[
"https://japanese.stackexchange.com/questions/6914",
"https://japanese.stackexchange.com",
"https://japanese.stackexchange.com/users/1442/"
] |
>
> what is the verb and its form?
>
>
>
The verb is tamar- (堪る) "bear, endure". The form is irrealis (未然形), hence tamara. To this -zu is attached and expresses negation.
From the commentary, you seem to understand the grammar and meaning, but are unable to interpret it as a whole. Think of it as "I am so *worried* that I *cannot endure* it anymore."
|
14,730,883 |
I submit for your consideration, this fiddle: <http://jsfiddle.net/alexdresko/HFFUL/5/>
There are two identical grids in the HTML, but only one of them populates when you click the "Load" button.
Is this due to my own fundamental misunderstanding of knockout, or is it a jqxgrid problem?
Here's the code:
```
<a href="#" data-bind="click: load">Load</a>
<div class="aGrid" data-bind="jqxGrid: { source: Stuff().People, columns: [ {text: 'Name', datafield: 'Name'} ], autoheight: true, sortable: true, altrows: true, enabletooltips:true }"></div>
<div class="aGrid" data-bind="jqxGrid: { source: Stuff().People, columns: [ {text: 'Name', datafield: 'Name'} ], autoheight: true, sortable: true, altrows: true, enabletooltips:true }"></div>
var dataFromServer = {
People: ko.observableArray([{
Name: "George"
}, {
Name: "Scot"
}])
};
var viewModel = function () {
this.Stuff = ko.observable({});
this.load = function () {
this.Stuff(dataFromServer);
};
};
$(function () {
var vm = new viewModel();
ko.applyBindings(vm);
});
```
|
2013/02/06
|
[
"https://Stackoverflow.com/questions/14730883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/250094/"
] |
The problem is somewhere in `source : Stuff().People` because you explicitly get the *value* of the `Stuff` observable here and access the `People` property of that. Changing `Stuff` itself does not change *this* bound observable array.
However, there is a overall more elagant solution, where you also don't have to make the `dataFromServer` an observable itself:
**HTML:**
```
<a href="#" data-bind="click: load">Load</a>
<div class="aGrid" data-bind="jqxGrid: { source: Stuff.People, columns: [ {text: 'Name', datafield: 'Name'} ], autoheight: true, sortable: true, altrows: true, enabletooltips:true }"></div>
<div class="aGrid" data-bind="jqxGrid: { source: Stuff.People, columns: [ {text: 'Name', datafield: 'Name'} ], autoheight: true, sortable: true, altrows: true, enabletooltips:true }"></div>
```
**JavaScript:**
```
var dataFromServer = [{
Name: "George"
}, {
Name: "Scot"
}];
var viewModel = function () {
this.Stuff = { People: ko.observableArray([]) }
this.load = function () {
for (i=0; i < dataFromServer.length; ++i) {
this.Stuff.People.push(dataFromServer[i]);
}
};
};
$(function () {
var vm = new viewModel();
ko.applyBindings(vm);
});
```
[Forked JSFiddle](http://jsfiddle.net/2ZmnP/)
|
52,152,341 |
Can someone tell me, what is wrong with this code? Why this is showing Index error. Encoder and Decoder are defined separately, and when I am combining both models by the last line as shown, it is throwing the index error.
```
def Encoder():
x= Conv2D(128, (3, 3),padding='same',activation='relu')(input_img)
x= Conv2D(128, (3, 3), activation='relu', padding='same')(x)
x= MaxPooling2D(pool_size=(2, 2), strides=(2, 2))(x)
x= Conv2D(64, (3, 3), activation='relu', padding='same')(x)
x= Conv2D(64, (3, 3), activation='relu', padding='same')(x)
x= MaxPooling2D(pool_size=(2, 2), strides=(2, 2))(x)
x= Conv2D(32, (3, 3), activation='relu', padding='same')(x)
x= Conv2D(32, (3, 3), activation='relu', padding='same')(x)
x= Conv2D(32, (3, 3), activation='relu', padding='same')(x)
x= MaxPooling2D(pool_size=(2, 2), strides=(2, 2))(x)
x= Conv2D(16, (3, 3), activation='relu', padding='same')(x)
x= Conv2D(16, (3, 3), activation='relu', padding='same')(x)
x= Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x= Conv2D(4, (3, 3), activation='relu', padding='same')(x)
encoded =Flatten()(x)
return Model(input_img,encoded)
# Encoder.add(Flatten())
# autoencoder.add(Reshape((28, 28, 4)))
def Decoder():
encoded=Input(shape=(28, 28, 4))
#encoded = Reshape((28, 28, 4))(encoded)
x= Conv2D(4, (3, 3), activation='relu',padding='same')(encoded)
x= Conv2D(8, (3, 3), activation='relu',padding='same')(x)
x= Conv2D(16, (3, 3), activation='relu', padding='same')(x)
x= Conv2D(16, (3, 3), activation='relu', padding='same')(x)
x= UpSampling2D(size=(2, 2))(x)
x= Conv2D(32, (3, 3), activation='relu', padding='same')(x)
x= Conv2D(32, (3, 3), activation='relu', padding='same')(x)
x= Conv2D(32, (3, 3), activation='relu', padding='same')(x)
x= UpSampling2D(size=(2, 2))(x)
x= Conv2D(64, (3, 3), activation='relu', padding='same')(x)
x= Conv2D(64, (3, 3), activation='relu', padding='same')(x)
x= UpSampling2D(size=(2, 2))(x)
x= Conv2D(128, (3, 3), activation='relu', padding='same')(x)
x= Conv2D(128, (3, 3), activation='relu', padding='same')(x)
decoded= Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x)
return Model(encoded,decoded)
x = Input(shape=(224, 224, 3))
autoencoder = Model(x, Decoder()(Encoder()(x)))
```
The stacktrace is:
```
IndexError Traceback (most recent call last) in ()
6
7 # make the model:
----> 8 autoencoder = Model(x, Decoder()(Encoder()(x)))
9
10
~/VirtualEnvs/deep/lib/python3.5/site-
packages/keras/engine/base_layer.py in call(self, inputs, **kwargs)
455 # Actually call the layer,
456 # collecting output(s), mask(s), and shape(s).
--> 457 output = self.call(inputs, **kwargs)
458 output_mask = self.compute_mask(inputs, previous_mask)
459
~/VirtualEnvs/deep/lib/python3.5/site-
packages/keras/engine/network.py in call(self, inputs, mask)
568 return self._output_tensor_cache[cache_key]
569 else:
--> 570 output_tensors, _, _ = self.run_internal_graph(inputs,
masks)
571 return output_tensors
572
~/VirtualEnvs/deep/lib/python3.5/site-
packages/keras/engine/network.py in run_internal_graph(self, inputs,
masks)
722 if 'mask' not in kwargs:
723 kwargs['mask'] = computed_mask
--> 724 output_tensors = to_list(layer.call(computed_tensor,
**kwargs))
725 output_masks = layer.compute_mask(computed_tensor,
726 computed_mask)
~/VirtualEnvs/deep/lib/python3.5/site-
packages/keras/layers/convolutional.py in call(self, inputs)
166 padding=self.padding,
167 data_format=self.data_format,
--> 168 dilation_rate=self.dilation_rate)
169 if self.rank == 3:
170 outputs = K.conv3d(
~/VirtualEnvs/deep/lib/python3.5/site-
packages/keras/backend/tensorflow_backend.py in conv2d(x, kernel,
strides, padding, data_format, dilation_rate)
3563 strides=strides,
3564 padding=padding,
-> 3565 data_format=tf_data_format)
3566
3567 if data_format == 'channels_first' and tf_data_format == 'NHWC':
~/VirtualEnvs/deep/lib/python3.5/site-
packages/tensorflow/python/ops/nn_ops.py in convolution(input,
filter, padding, strides, dilation_rate, name, data_format)
777 dilation_rate=dilation_rate,
778 name=name,
--> 779 data_format=data_format)
780 return op(input, filter)
781
~/VirtualEnvs/deep/lib/python3.5/site-
packages/tensorflow/python/ops/nn_ops.py in init(self, input_shape,
filter_shape, padding, strides, dilation_rate, name, data_format)
826
827 if data_format is None or not data_format.startswith("NC"):
--> 828 input_channels_dim = input_shape[num_spatial_dims + 1]
829 spatial_dims = range(1, num_spatial_dims + 1)
830 else:
~/VirtualEnvs/deep/lib/python3.5/site-
packages/tensorflow/python/framework/tensor_shape.py in getitem(self,
key)
613 return TensorShape(self._dims[key])
614 else:
--> 615 return self._dims[key]
616 else:
617 if isinstance(key, slice):
**IndexError: list index out of range
```
|
2018/09/03
|
[
"https://Stackoverflow.com/questions/52152341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10245413/"
] |
The shapes do not match. The `encoder` returns a flattened representation of the encoded image, i.e. the data has the shape `(BS, -1)`. In your decoder you are defining the input like this
```
encoded=Input(shape=(28, 28, 4))
```
i.e. you are assuming that the input has the shape `(BS, 28, 28, 4)` which is not compatible with the output of the encoder.
|
31,936,252 |
I've got Entity Framework Code First Entities:
```
public class Customer
{
public long Id { get; set; }
public ICollection<ServiceAccount> Accounts { get; set; }
}
public class Service
{
public long Id { get; set; }
}
public class ServiceAccount
{
public long Id { get; set; }
public Customer Customer { get; set; }
[Required()]
public Service Service { get; set; }
}
```
It is supposed that a Customer has some Accounts for the Services. But there can be some default Accounts, which are not bounded to any Customer. And each Account is used for a concrete Service.
This Entities have the following Configuration:
```
// Customer Configuration:
base.ToTable("Customers");
base.HasKey(x => x.Id);
base.HasMany(x => x.ServiceAccounts)
.WithOptional(x => x.Customer)
.WillCascadeOnDelete();
// For Service:
base.ToTable("Services");
base.HasKey(x => x.Id);
// For Account:
base.ToTable("Accounts");
base.HasKey(x => x.Id);
base.HasOptional(x => x.Customer)
.WithMany(x => x.Accounts);
base.HasRequired(x => x.Service)
.WithMany();
```
The problem is, when I load a Customer, all his Accounts are loaded too, but they have their Service set to null. Why it is not loaded?
Thanks in advance
|
2015/08/11
|
[
"https://Stackoverflow.com/questions/31936252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2239977/"
] |
You need to load the entities. Based on your comment:
```
IQueryable<Customer> customers = Customers.Include(x => x.Accounts.Select(y => y.Service));
```
They should also be `virtual` if you want proxies for lazy loading... but for eager loading it's not necessary
|
56,830,228 |
I would request some help with a basic shell script that should do the following job.
1. File a particular word from a given file (file path is always constant)
2. Backup the file
3. Delete the specific word or replace the word with ;
4. Save the file changes
Example
* File Name - abc.cfg
* Contains the following lines
`network;private;Temp;Windows;System32`
I've used the following SED command for the operation
`sed -i -e "/Temp;/d" abc.cfg`
The output is not as expected. The complete line is removed instead of just the word **Temp;**
Any help would be appreciated. Thank you
|
2019/07/01
|
[
"https://Stackoverflow.com/questions/56830228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11722122/"
] |
sed matches against lines, and `/d` is the delete directive, which is why you get a deleted line. Instead, use substitution to replace the offending word with nothing:
```
sed 's/Temp;//g' abc.cfg
```
The `/g` modifier means "globlal", in case the offending word appears more than once. I would hold off on the `-i` (inline) flag until you are sure of your command, in general, or use `-i .backup`.
|
8,546,227 |
I hope this was not asked over and over again before, but I didn't get further to an answer using google, w3schools and so on. So here is my question:
I'm writing a script that creates kind of an index of projects that I have on my homepage and makes a nice list with images and teaser text based on an info file. I mostly have my projects on github and the readme is in markdown so I thought I could dynamically generate the HTML from the markdown of the latest blob from github on demand using PHP so it gets updated automatically.
My directory structure looks like this:
```
projects
project1
.remoteindex
.info
project2
.remoteindex
.info
index.php
.htaccess
```
So when just `domain.tld/projects/` is requested I get the info from `.info` and make a nice index of all projects. But if `domain.tld/projects/project1/` is request it, I want to internally redirect it to `domain.tld/projects/?dir=project1` to do my markdown parsing and so on. But `domain.tld/projects/project1/image.png` should not be redirected.
This is what I tried:
```
.htaccess
RewriteEngine on
RewriteRule ^([^/]+)/?$ index.php?dir=$1 [R,L]
```
I made it redirect instead of rewrite so that I can see what the error is because I just got an 404. The URL that I get redirected to is `domain.tld/home/www/web310/html/projects/index.php?dir=project1` so obviously there is something going wrong with the internal structure of the web server an paths an whatever.
I hope you can understand my problem an I would be very pleased if someone could help me, because I'm totally lost on `.htaccess` anyway.
### Edit:
See my answer below for the used `.htaccess`.
The strange thing is that if I have an `index.html` in on of the subdirectories, my local web server (Apache with XAMPP for Mac OS X 1.7.3) does not rewrite and the `index.html` gets displayed, without one it works correctly.But on my real web server that serves my homepage it rewrites both with and without `index.html` (which is what I want). Any hints on that?
|
2011/12/17
|
[
"https://Stackoverflow.com/questions/8546227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/894166/"
] |
Thanks for all the help so far! You guys are just awesome!
I figured out that a symbiosis of both of your solutions works well for me:
```
RewriteEngine on
RewriteBase /projects
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} -d
RewriteRule ^([^/]+)/?$ index.php?dir=$1 [QSA,L]
```
Of course only without `[R]`, this was my fault. (See my question edit for another question please).
|
11,688,274 |
I am using text to speech in my app and I have been able to get it to work on all of my buttons fine. However, when I try to use the text to speech in my splash activity it crashes the app. It is a nullpointer exception so I know I am just coding it incorrectly. To clarify what I want it to do. I want it to talk during the splash activity. When the splash activity sleeps I want it to talk again to tell the user it is done loading.I have included the java for my splash activity.
```
public class mainj extends Activity implements OnInitListener {
private TextToSpeech myTTS;
// status check code
private int MY_DATA_CHECK_CODE = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loadscreen);
Thread logoTimer = new Thread() {
public void run() {
try {
try {
sleep(5000);
speakWords("loading");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent menuIntent = new Intent("android.intent.action.MENU");
startActivity(menuIntent);
Intent checkTTSIntent = new Intent();
checkTTSIntent
.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
}
finally {
finish();
}
}
};
logoTimer.start();
}
// speak the user text
private void speakWords(String speech) {
// speak straight away
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
}
// act on result of TTS data check
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// the user has the necessary data - create the TTS
myTTS = new TextToSpeech(this, this);
} else {
// no data - install it now
Intent installTTSIntent = new Intent();
installTTSIntent
.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
}
// setup TTS
public void onInit(int initStatus) {
// check for successful instantiation
if (initStatus == TextToSpeech.SUCCESS) {
if (myTTS.isLanguageAvailable(Locale.US) == TextToSpeech.LANG_AVAILABLE)
myTTS.setLanguage(Locale.US);
} else if (initStatus == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...",
Toast.LENGTH_LONG).show();
}
}
}
```
|
2012/07/27
|
[
"https://Stackoverflow.com/questions/11688274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1523534/"
] |
You can subclass most common controls and draw their appearance yourself. However, unless for novelty applications I doubt your users will thank you for doing so.
|
22,814,842 |
I want to save current TIMESTAMP to a SQLite database in Android.
But it should be in MySQL TIMESTAMP format which is `2014-04-02 20:04:05`
How to make it in `db.execSQL();`
Please help!
|
2014/04/02
|
[
"https://Stackoverflow.com/questions/22814842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3172722/"
] |
You should consider using Angular [`$resource`](http://docs.angularjs.org/api/ngResource/service/%24resource) because it handles a lot of your abstractions. Either way, if you want to make a new request based on changes in the scope variable, you can `$watch` it:
```
$scope.$watch('currentCompanyId', function() {
if(!$scope.currentCompanyId) return;
$http.get().success(); // replace with whatever mechanism you use to request data
});
```
|
32,218 |
I have read several questions on topic, e.g. [1](https://drupal.stackexchange.com/questions/25148/views-and-contextual-filters-with-entity-reference-field) [2](https://drupal.stackexchange.com/questions/1966/display-referenced-node-field-in-view) [3](https://drupal.stackexchange.com/questions/4148/display-a-field-of-a-node-that-is-referenced-on-another-node-via-a-relationship), but couldn't manage to get it work.
**My setup:**
In a Drupal 7 environment, I have a node type called `organizer`, which contains two fields: node title (default) and a link (to the organizer's website).
A second node type called `event` contains several fields one of which is an entity reference to `organizer`.
My site's design only has the node title and node body of an event being displayed in main content. All other fields are displayed in a sidebar using a views block with filter on node type (`= event`) and a contextual filter on node id. Among these fields is also the field `organizer` and it's displaying the organizer's name (title field) alright.
**My goal:**
Now I want to have the organizer's name link to the organizer's website. But the link is actually a field inside the `organizer` content type.
**My approach:**
I've added a relationship to `Entity Reference: organizer`. Then I added the link field that is used in the `organizer` content type to the list of fields using the relationship. I rearrange the fields to have this link field being loaded before the entity reference field. Then I set up the latter field to being rewritten as link using the plain url from the link field.
[The link field is currently being displayed for debug purposes, later I want to exclude it from display, of course.]
**My result:**
The link field is always empty. Hence, the organizer's name is never linked to the respective website.
***Questions I stumbled upon:***
When I add a relationship, I have two options like
```
Entity Reference: Referenced Entity
A bridge to the Content entity that is referenced via field_organizer
Entity Reference: Referencing entity
A bridge to the Content entity that is referencing Content via organizer
```
My understanding is that I have to user the first one, because I want to load the organizer that is referenced in the event. [The second one I would be using, if I have a organizer and want to get all events that are referencing this organizer, right?] However, I tried both options to no avail.
Is the ordering of fields relevant? I've tried both having the link field before and after the entity reference field, it stays empty in both cases.
Since each event could have more than only one organizer, the entity reference field is set to allow unlimited values. Could that cause a problem?
Could anyone point me into the right direction of what I am missing?
---
***UPDATE:*** It seems to break the system if you have both relationship types set up at the same time or maybe the ordering plays a role, too. However, when the first relationship in list is the one I need it kind of works.
It is working absolutely fine for a **single** organizer, the name is displayed and linked to the organizer's website. But it will not work for any additional organizers. The block lists all organizers (when having more than one) but each of them is linked to the first organizer's website.
Thinking about how that works, that is reasonable, since the relationship only adds **one** related object. When displaying a field (e.g.) from that relationship it will be the same for each delta of entity reference field.
Actually, in that case I should be able to define how the entity reference field is displayed. It already has an option to link to the entity itself but you can't define any fields from the entity to be shown (e.g. instead of title).
|
2012/05/25
|
[
"https://drupal.stackexchange.com/questions/32218",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/4822/"
] |
The solution is a two step solution, but first you need to decided if you are going from Parent to Child or Child to Parent.
**Background info**
If you are going from Parent to Child, you setup a relationship using the "referenced" variable.
If you are going from Child to Parent, you setup a relationship using the "referencing" variable.
To make life simple for myself, when I specify the relationship, I also using the Administrative Option on the Reference Window and enter a more understandable name for the relationship. In you case, since I would make the Admin Name Event reading Organizer or something like that.
1. Setup a relationship for Event reading Organizer in the Relationship
field under the Advanced tab.
2. Once you have related your Event content type to the Organizer
content type, you should now be able to see the Organizer fields
appear in your list of available fields. Select the fields from the
Organizer content type that you want to appear in your view and hit
Apply. Here is the CRITICAL part, once you have defined a
Relationship, a new drop down menu (Relationship) will appear on the
Configure field windows. For any fields that is in another table,
you MUST choose the appropriate relationship for the field. In your
case, you would choose the Event reading Organizer relationship.
This relationship instructs view to go Organizer table and bring
back that field. If you do not specify the relationship in the
Configure field windows, this will not work.
Attached is a copy of the Configure field with a relationship. Note: In your example, you would want the referenced variable. But in my example, I was working with the referencing variable. Please do not let that confuse you. Just image the word in the relationship is referenced.

If you have any questions, please post them here and I will respond.
|
68,143 |
I understand that when being metaphorical you're saying that something IS something, for example: "The moon is a ball of cheese". Because I'm saying that the moon IS a ball of cheese it is of course metaphorical.
Would this count as metaphorical language?:
>
> "He fell down the bottomless pit to his death".
>
>
>
(Of course, a pit can't be bottomless, that's impossible). So, although this isn't necessarily saying that the pit is bottomless as opposed to appearing bottomless, could it still be classed as metaphorical explanation of the pit? Could this bottomless pit be classed as metaphorical? Could one interpret the sentence into saying that the pit is bottomless?
|
2012/05/18
|
[
"https://english.stackexchange.com/questions/68143",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/20951/"
] |
No, your bottomless pit is not metaphorical.
To be metaphorical, X has to spoken of as Y. For example, in "Juliet is the sun", Juliet is spoken of as the sun. In Ovid's "Time is the devourer of all things", time is spoken of as a devouring beast eating all things. In your "The moon is a ball of cheese", the moon is being spoken of as a ball of cheese.
In "He fell down the bottomless pit to his death", the pit is spoken of only as a pit.
|
776,636 |
I have a stock image of `Ubuntu Server 16.04` [exported as an OVA](https://www.virtualbox.org/manual/ch01.html#ovf) from VirtualBox. After the proper permissions are [set up to import](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instances_of_your_vm.html) that OVA into AWS EC2 as an image, and it's loaded into S3, the process haults during the import with a status of:
`deleted ClientError: Unsupported kernel version 4.4.0-21-generic`
My first reaction is to search the AWS documentation for what kernel versions they **WOULD** accept. That eludes me.
What versions are acceptable for import, and where is the documentation on that in AWS?
### Import
```
aws ec2 import-image --description "Ubuntu Server 16.04 LTS" --disk-containers file://ubuntuContainer.json
```
### ubuntuContainer.json
```
[{
"Description": "Import Task",
"Format": "ova",
"UserBucket": {
"S3Bucket": "myBucket",
"S3Key": "somePath/UbuntuServer16.04LTS.ova"
}
}]
```
### Check status
```
aws ec2 describe-import-image-tasks --cli-input-json "{ \"ImportTaskIds\": [\"import-ami-abcd1234\"]}"
```
### Results
```
IMPORTIMAGETASKS Shindig Ubuntu Server 16.04 LTS import-ami-abcd1234 deleted ClientError: Unsupported kernel version 4.4.0-21-generic
SNAPSHOTDETAILS 1006215680.0 VMDK
USERBUCKET myBucket somePath/UbuntuServer16.04LTS.ova
```
|
2016/05/13
|
[
"https://serverfault.com/questions/776636",
"https://serverfault.com",
"https://serverfault.com/users/174560/"
] |
I had the same problem with my kernel version not being supported. In August of 2019, the kernel-5.0.0 on my Ubuntu-18.04.2 was not accepted. To compare what Amazon's AMIs were using, I launched their Ubuntu-18.04.2 and found that it was using kernel-4.4.0. So I ended up using an Lubuntu-16.04.3.VMDK that I had locally with kernel-4.10.0-28-generic, converted it to .OVA (OVF version 2.0) using VirtualBox, uploaded it to S3, and was able to successfully get it to import to .AMI using the "aws ec2 import-image" command. So based on my tests, it seems that as of now, AWS is accepting kernel-4, but not kernel-5. Hope this helps!
|
20,254,389 |
I'm creating an android app and I want to have an activity happen when the app starts for the FIRST time. When the user closes the app and re-opens the app the same screen will not show again. Kind of like an initial registration. I have no databases. Please keep the answer simple as I'm only just beginning in android. So far none of the other similar questions have made no sense. Any help will do. Thanks, J.
|
2013/11/27
|
[
"https://Stackoverflow.com/questions/20254389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2863432/"
] |
If you are unable to use a database then I would suggest using the [SharedPreferences](http://developer.android.com/reference/android/content/SharedPreferences.html) class to store a [boolean variable](http://developer.android.com/reference/android/content/SharedPreferences.html#getBoolean%28java.lang.String,%20boolean%29) indicating if your one-time `Activity` had been displayed. In your initial `Activity`, you can check this preference. If the value is false, you launch your one time `Activity` and within that one-time `Activity`, you set the preference to true. Subsequent launches will never show the one-time `Activity` as long as the preference value is set properly.
|
15,677,194 |
I have two script.
Script1
Script2
In Script1 i declared a arraylist it contains value 2, 4, 6, etc...
```
public static ArrayList aArray= new ArrayList();
function update(){
if(bool1)
{
aArray.Add(i);
}
}
```
I have to check a value 5 exist in arraylist from Script2.
**if value exists i have to get its key.**
How to get it?
|
2013/03/28
|
[
"https://Stackoverflow.com/questions/15677194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1522741/"
] |
Try using Contains. This code will detect if you have already the value in the ArrayList and will stop code from adding it a second time.
```
public static ArrayList aArray= new ArrayList();
function update()
{
if(aArray.Contains(i)==false)
{
aArray.Add(i);
}
}
```
If you want to remove a value it is just as easy as **aArray.Remove(i)**
|
17,111,978 |
I have an array looks like this: (1, 4, 2, 3).
I want to select all threads that contains column tid, one of these numbers in the array:
```
$get = $pdo->prepare("SELECT * FROM mybb_threads ORDER BY replies DESC LIMIT 10");
$get->execute();
$array = $get->fetchAll(PDO::FETCH_COLUMN, 0);
$new = $pdo->prepare("SELECT * FROM mybb_posts WHERE replyto = 0 AND tid IN (:ids) LIMIT 10");
$new->execute(array(":ids" => implode(",", $array)));
```
But, it only fetches one item from the database, while I have more than one results?
Why is it doing that?
I think it only fetches the first array item, I am not to sure, but do you see anything wrong?
What I am trying to do is:
I have tabs.
The tabs shows the most popular threads, by replies .
I want to do so, when you click on the tab, it will switch to the right post.
```
<div class="container row">
<h2>Top 10 Stories</h2>
<div id="story-tab">
<ul>
<?php
$test = $pdo->prepare("SELECT * FROM mybb_threads ORDER BY replies DESC LIMIT 10");
$test->execute();
// while ($row = $test->fetch(PDO::FETCH_ASSOC))
//{
//echo'<li><a href="#st-'.$row['tid'].'-'.$row['fid'].'">'. $row['subject'].'</a></li>';
echo'<li><a href="#st-1-1">1</a></li>';
echo'<li><a href="#st-2-1">2</a></li>';
//}
$get = $pdo->prepare("SELECT * FROM mybb_threads ORDER BY replies DESC LIMIT 10");
$get->execute();
$array = $get->fetchAll(PDO::FETCH_COLUMN, 0);
?>
</ul>
<?php
$test = $pdo->prepare("SELECT * FROM mybb_threads ORDER BY replies DESC");
$test->execute();
$fetch = $test->fetch(PDO::FETCH_ASSOC);
$new = $pdo->prepare("SELECT * FROM mybb_posts WHERE replyto = 0 AND tid IN (:ids) LIMIT 10");
$new->execute(array(":ids" => implode(",", $array)));
while ($row = $new->fetch(PDO::FETCH_ASSOC))
{
echo '<br /><br /><br /><br />'. $row['tid'].','.$row['fid'];
}
?>
</div>
<br class="clear">
<h2>Top 10 Popular Threads</h2>
<div id="thread-tab">
</div>
</div>
```
Any ideas?
|
2013/06/14
|
[
"https://Stackoverflow.com/questions/17111978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2441317/"
] |
Try the alternative binaries at [www.lfd.uci.edu/~gohlke/pythonlibs/#pybluez](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pybluez)
|
53,614,511 |
I am currently implementing a small client-server application in which the user can load different files. My application requires the files to be loaded in a certain order. File loading is done via interface buttons that, when clicked, trigger the sending of a GET request to the server on a certain route.
The buttons are disabled when the file loading requires the loading of other files. I guess I should still send an error message with a certain status if a route is called before the ones it depends on. I've thought of using the 403 status code to indicate that the access to the route is forbidden but this prohibition is only temporary and is not linked to the possession of certain access rights. Any idea of a better HTTP status ?
|
2018/12/04
|
[
"https://Stackoverflow.com/questions/53614511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10210572/"
] |
If by permission not asked you mean that the user isn't being prompted to allow internet permission then that is normal. Internet is in the normal permissions list so it is auto granted. For more information about normal permissions take a look at: <https://developer.android.com/guide/topics/permissions/normal-permissions.html>
Also, adding permissions is a two step process; once you have declared the permission you need in your manifest, you will also have to do some setup in your java file. Take a look at <https://developer.android.com/training/permissions/requesting>
Additionally, if you are looking for easier ways to deal with permissions then there are libraries out there for that too such as RxPermissions: <https://github.com/tbruyelle/RxPermissions>
Hopefully this helps!
|
74,646,408 |
What I want is to send encypted data from my app to PostgreSQL database via formatted string (query) by using Npgsql. Problem is that after sha256.ComputeHash() I get byte array which I'm trying to send by inserting it into my string query. It works fine but then in my dbms column I see System.Byte[] instead of byte array. How can I fix that?
My string query is something like that:
```
private readonly SHA256 sha256 = SHA256.Create();
string sql = $"""
INSERT INT table(encrypted_column) VALUES (
'{sha256.ComputeHash(data)}');
""";
```[What in db after Query][1]
[1]: https://i.stack.imgur.com/9Ch7t.png
```
|
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16632154/"
] |
Well, I'm assuming you actually just have `picture` instead of `**picture:**`, and that you may need to deal with line breaks, so...
```
$ cat sl.txt
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Quis picture lobortis scelerisque fermentum dui faucibus in ornare quam.
Est ullamcorper eget nulla facilisi etiam dignissim diam quis.
Quis viverra nibh cras pulvinar mattis nunc sed.
Turpis massa sed elementum picture tempus egestas.
Condimentum vitae sapien pellentesque habitant.
Et molestie ac feugiat sed lectus vestibulum mattis ullamcorper.
Tincidunt lobortis feugiat vivamus at augue eget arcu picture
dictum varius. Donec massa sapien faucibus et molestie ac feugiat sed.
Tincidunt eget nullam non nisi est.
Ornare arcu dui vivamus arcu.
Mattis enim ut tellus elementum sagittis vitae et leo duis
$ cat sl.txt | tr '\n' ' ' | grep -o 'picture [^ ]*' | cut -d' ' -f2
lobortis
tempus
dictum
```
Edit: Explanation:
`tr '\n' ' '` replaces every (unix) line break with a space -- makes the whole thing one line.
The `-o` flag tells `grep` to return only the matched string. The search pattern starts with picture and a space `picture` , and then everything that follows that is not a space: `[^ ]*`.
Finally `cut` using the space character for a delimiter `-d ' '` prints the second field: `-f 2`
|
19,251,360 |
I'm trying to build a simple linked list where each element would be aligned to some round address.
I've tried the following code (shortened as much as possible to be SSCCE):
```
#include "stdio.h"
#define N 10
typedef struct __attribute__((aligned(0x100)) _element {
int val;
char padding[64];
struct _element *next;
} element;
int main() {
element* head = new element;
element* current = head;
for (int i = 0; i < N; ++i) {
current->val = i;
if (i == N - 1)
break;
current->next = new element;
current = current->next;
}
current->next = NULL;
current = head;
printf("sizeof(element) = 0x%x\n", (unsigned int)sizeof(element));
while (current) {
printf("*(%p) = %d\n", ¤t->val, current->val);
current = current->next;
}
return 0;
}
```
Built with g++ 4.2.2, no optimizations, and produced:
```
sizeof(element) = 0x100
*(0x501010) = 0
*(0x501120) = 1
*(0x501230) = 2
*(0x501340) = 3
*(0x501450) = 4
*(0x501560) = 5
*(0x501670) = 6
*(0x501780) = 7
*(0x501890) = 8
*(0x5019a0) = 9
```
Why aren't the addresses aligned to 0x100? Note that it did affect the struct "size", looks like it's being padded somehow, but it doesn't start at aligned addresses like I wanted.
From [this answer](https://stackoverflow.com/questions/1468513/attribute-aligned-not-working-with-static-variables) I understood that there might be a max alignment, but even lowering it to 0x20 didn't change the alignment (only the sizeof).
[This answer](https://stackoverflow.com/questions/841433/gcc-attribute-alignedx-explanation) doesn't help since it's about stack allocation. Couldn't find any other source to explain this. Am I asking too much from this attribute? or doing something else wrong?
Thanks in advance!
|
2013/10/08
|
[
"https://Stackoverflow.com/questions/19251360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016408/"
] |
You're using gcc's C extension to define your alignment. That will affect the size of the object (which needs to be a multiple of the alignment) and *might* affect the storage layout of objects with static alignment, but only to the extent to which the linker is prepared to align such objects. It does not affect the alignment of dynamically allocate objects, even in C++.
The C++ `new` operator calls an allocator function to provide storage, and then proceeds to initialize the storage by invoking the object constructor. The standard requires the allocation function to return a pointer "suitably aligned so that it can be converted to a pointer of any complete object type with a fundamental alignment requirement." (§3.7.4.1p2). The default standard library global allocator must conform to this requirement (§18.6.1). The definition of "fundamental alignment requirement" is implementation-specific, but it must be at least as large as the alignment requirement of any *scalar* type, and does not need to be any larger.
The global allocation function, as specified by the C++ standard, has only a single parameter, which is the size of the requested object. It is not passed any information about the alignment of the object, or the type, so it cannot perform an alignment-specific allocation.
You're free to define an allocation function for a given type, which can take that type's alignment into account. However, it would have to either use a non-standard (i.e. system-specific) underlying allocator, or over-allocate and then adjust the pointer. (C++11 provides a standard-library function [`align`](http://en.cppreference.com/w/cpp/memory/align) for this purpose.)
As I read the standard, C++11 requires the `new` expression to fail if the alignment of the object type exceeds the capability of the underlying allocator:
>
> §3.11p9 If a request for a specific extended alignment in a specific context is not supported by an implementation, the program is ill-formed. Additionally, a request for runtime allocation of dynamic storage for which the requested alignment cannot be honored shall be treated as an allocation failure.
>
>
>
That won't apply to your program, since you are using a GCC-specific C-oriented alignment attribute, and certainly not C++11, so I suppose the compiler is within its rights to call an allocator which will return insufficiently aligned storage rather than throwing `bad_alloc`.
By the way, gcc 4.2.2 just celebrated its sixth birthday. You should consider sending it off to grade school and updating to something more modern.
|
16,591,169 |
I currently only have two controller methods: index and create
I've got a form on the index page. I want it to resolve to my create method in the controller. It seems to actually be resolving there as a new object is created and saved in the database, but the single parameter I have is not passed on. It shows as nil in the db.
I have a lot to learn about Rails and the conventions used. I don't think it's a routing issue, since the objects are being created. Just have no params getting pushed.
Here's my controller:
```
class MitchismsController < ApplicationController
def index
@mitchisms = Mitchism.all
@mitchism = Mitchism.new
end
def create
@mitchism = Mitchism.new(params[:mitchsim])
@mitchism.save
redirect_to mitchisms_path
end
end
```
And here's my view:
```
<h1>Mitchisms</h1>
<%= form_for(@mitchism) do |f| %>
<ul>
<% @mitchism.errors.full_messages.each do |error| %>
<li><%= error %></li>
<% end %>
</ul>
<p>
<%= f.label :body, "Add your Mitchism:" %><br />
<%= f.text_field :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
<% @mitchisms.each do |mitchism| %>
<div id="mitchisms">
<%= mitchism.body %>
</div>
<% end %>
```
|
2013/05/16
|
[
"https://Stackoverflow.com/questions/16591169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1612935/"
] |
Not quite got what you mean by *"but the single parameter I have is not passed on"*. If your objects are being created (as you said), how can your database be nil? `Mitchism.all` must give back all the saved objects.
And, this is how your controller must look like:
```
class MitchismsController < ApplicationController
def index
@mitchisms = Mitchism.all
@mitchism = Mitchism.new #creates a new object
end
#after form is submitted, it will reach to create action below
def create
@mitchism = Mitchism.new(params[:mitchism])
if @mitchism.save
redirect_to mitchisms_path
else
render 'index'
end
end
end
```
|
28,390,045 |
How can I pass a single item value from array starting from index/item 0 into function and loop through the array until all items have been passed?
This scripts intended purpose is to pull lines from a text file called array\_list and pass them into an array, then perform a function on each array item in a loop until all items have been passed and echo out results to a text file called results.txt showing HTTP Status Codes to associated URL's
```
#!/bin/bash
#
#Script to lookup URL address and capture associated HTTP Status Code (EG: 200, 301, 400, 404,500, 503)
#
#
declare -a array
array=()
getArray()
{
i=0
while read line
do
array[i]=$line
i=$(($i + 1))
done < $1
}
getArray "array_list"
for url in ${array[@]}
do
function call()
{
curl -s -o /dev/null -w "%{http_code}" $url
}
done
response=$(call)
echo $url $response >> result.txt
```
|
2015/02/08
|
[
"https://Stackoverflow.com/questions/28390045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4227533/"
] |
This is a loop which defines the function `curl` many times, but never calls it:
```
for url in ${array[@]}
do
function call()
{
curl -s -o /dev/null -w "%{http_code}" $url
}
done
```
It's not obvious why you want a function here. You could just do this:
```
for url in ${array[@]}; do
printf "%s " "$url" >> results.txt
curl -s -o /dev/null -w "%{http_code}" "$url" >> results.txt
done
```
Of course, you could define the function (taking an argument):
```
function getfile() {
curl -s -o /dev/null -w "%{http_code}" "$1"
}
```
and then call it in a loop:
```
for url in ${array[@]}; do
result=$(getfile "$url")
printf "%s %s\n" "$url" "$result" >> results.txt
done
```
---
Not directly related to your question, but:
You entire `getArray` function already exists as a bash built-in, so you might as well just use it:
```
mapfiles -t array < array_list
```
See `help mapfiles` for more options.
|
32,390,478 |
I can't seem to find this anywhere, but does strcspn() return -1 when str1 does not contain str2? For example, say I have:
```
strcspn(argv[1], " ");
```
Will the function return -1 or something else if argv[1] does not contain a space?
|
2015/09/04
|
[
"https://Stackoverflow.com/questions/32390478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3735278/"
] |
See [strcspn reference on cplusplus.com](http://www.cplusplus.com/reference/cstring/strcspn/)
```
strcspn(str1, str2)
```
>
> **returns**
>
>
> The length of the initial part of str1 not containing any of the characters that are part of str2.
> This is the length of str1 if none of the characters in str2 are found in str1.
>
>
>
So your call `strcspn(argv[1], " ");` should return the length of `argv[1]`.
|
15,766,218 |
I developed WP7 application using the emulator. Everything was great. To communicate with the server I used WebClient and RestClient. But to test the application on a real device - I threw a shock.
1)
```
private void LoadData()
{
var webClient = new WebClient();
webClient.DownloadStringCompleted += DownloadStringCompleted;
webClient.DownloadStringAsync(new Uri(Constants.Url1));
//Point_1
}
private void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//Point_2
}
```
On emulator between Point\_1 and Point\_2 0.8-1.2 seconds.
On real device (HTC Radar WP7.8) between Point\_1 and Point\_2 15-20 seconds.
2)
```
var request = new RestRequest(url) {Method = Method.POST};
//Point_3
RestClient.ExecuteAsync(request, response =>
{
//Point_4
}
```
On emulator between Point\_3 and Point\_4 0.3-0.5 seconds.
On real device (HTC Radar WP7.8) between Point\_3 and Point\_4 18-22 seconds.
My computer and phone in same wi-fi network.
I have three questions:
First: It's normal?
Second: Why it's happening?
Third: How can I solved it?
|
2013/04/02
|
[
"https://Stackoverflow.com/questions/15766218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1616443/"
] |
You have a raft of hurdles to overcome. Just a few are
* OLEDB is not supported under Windows CE.
* Pocket Excel has no automation object model or even any published file format specification
* Desktop libraries (like Microsoft.Office.Interop.Excel) will not work under Windows CE
Basically I think you're straying down a poor choice path.
What's the actual business problem you're trying to solve here? Do you have Pocket Excel files created on the device you need to merge into a local SQL Compact Database? Is there an option for not using Excel? Or is it that you have desktop Excel files on a PC and you want the data over on the device? If so, how are the files getting to the device? Can you convert them to CSV? Can you put a service on a server somewhere to do the conversion for you?
There's likely a way to solve the overall problem, just not on the path you're trying. We'd need to understand the actual problem to help you get a better solution, though.
|
65,103 |
In a week I'm traveling from Seoul to Bangkok with AirAsia. On my ticket it says Air Asia X, however searching up similar flights on their website they call it "Thai AirAsia X". What is the difference between Thai AA X and AA X? I've tried searching around a bit but still haven't found anything that answers it. My question is related to the safety reports at airlinerratings, where Thai AirAsia scores only 3/7 while AirAsia X scores 6/7 (I didn't find Thai Air Asia X). I would also appreciate if anyone could shed some light on why there's such a huge difference in ratings within the same company.
|
2016/03/11
|
[
"https://travel.stackexchange.com/questions/65103",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/41112/"
] |
Don't worry: **it's all the same company, run to the same standards.**
For legal reasons, in South-East Asia you can generally only operate flights originating from a country if you have a locally incorporated airline, so Air Asia (originally Malaysian) has a series of franchises across the continent: Thai Air Asia, Indonesia Air Asia, Air Asia Philippines, Air Asia India, Air Asia Japan, you get the idea. But procedures, maintenance etc are all standardized across the group, so this really makes very little difference to the traveler.
Air Asia, as a whole, has a pretty good safety record. It's one of Asia's largest airline groups and has been flying since 2001, with one single accident of note ([Indonesia AirAsia Flight 8501](https://en.wikipedia.org/wiki/Indonesia_AirAsia_Flight_8501)). As far as I'm aware, neither the Malaysian nor the Thai affiliates have never had an accident, so I'm not sure where the difference in the score comes from: perhaps just that aviation in Thailand is generally considered more dangerous than in Malaysia.
And oh, the "AirAsia X" designation is reserved for larger planes flying longer routes, and again for legal reasons this too has to be duplicated in each country (Thai AirAsia X, Indonesia AirAsia X, etc.) This doesn't really have much bearing on safety, except to note that the X's generally fly long-distance to developed countries like Australia and Japan with very strict aviation safety procedures, meaning that they're arguably better inspected and thus safer than the domestic/short-haul non-X affiliates.
|
71,636,967 |
I am trying to export a table from AnyLogic's database to an excel file in a parameters variation using this code:
```
Database myFile = new Database(this, "A DB from Excel", "DataBaseExport.xlsx");
ModelDatabase modelDB = getEngine().getModelDatabase();
modelDB.exportToExternalDB("flowchart_stats_time_in_state_log", myFile.getConnection(), "Sheet 1", true, true);
```
I am then given this error
[](https://i.stack.imgur.com/fVqJz.png)
With this after
[](https://i.stack.imgur.com/amQVb.png)
|
2022/03/27
|
[
"https://Stackoverflow.com/questions/71636967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13143177/"
] |
It turns out that the name of the excel sheet "sheet1" is the culprit. Upon removing the "1" and creating matching column names in the excel file, the data is able to be exported.
|
65,967,254 |
I am trying to deploy my project on heroku but I am stumbling on the above error. Everything works fine when i run the code locally. Below are my setting and views file
template settings
```
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'Templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
```
]
views of my Home app
```
def Home(request):
return render(request,'Home/index.html')
```
|
2021/01/30
|
[
"https://Stackoverflow.com/questions/65967254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13932088/"
] |
By adding a file ending (`css\open-iconic\FONT-LICENSE.txt`) the build could proceed.
However, why this was suddenly an issue still perplexes me.
|
34,305,604 |
I'm expecting output like this using for loop
```
name : abc
school : A
year : 2007
name : xyz
school : b
name : 2005
name : pqr
school : c
year : 2003
```
this for loop
```
<?php
if(count($name) > 1){
$p = 0;
for($i=0;$i<count($name); $i++){
?>
<div>name : <?php echo $name[$p];?></div>
<?php
$p++;
}
}
?>
<!-- school -->
<?php
if(count($school) > 1){
$g = 0;
for($i=0;$i<count($school); $i++){
?>
<div>school : <?php echo $school[$g];?></div>
<?php
$g++;
}
}
?>
<!-- year -->
<?php
if(count($year) > 1){
$y = 0;
for($i=0;$i<count($year); $i++){
?>
<div>year : <?php echo $year[$y];?></div>
<?php
$y++;
}
}
?>
```
how can i use nested loop to get output like in above.
currently because of above 3 different for loop I'm getting out put like this
```
name : abc
name : xyz
name : pqr
school : A
school : b
school : c
year : 2007
year : 2005
year : 2003
```
|
2015/12/16
|
[
"https://Stackoverflow.com/questions/34305604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4242640/"
] |
First of all, use the loop variable and not a loop and a separate variable!
The code below assume that all three arrays have the same length.
```
for($i=0;$i<count($name); $i++)
{
?>
<div>name : <?php echo $name[$i];?></div>
<div>school : <?php echo $school[$i];?></div>
<div>year : <?php echo $year[$i];?></div>
<?php
}
?>
```
|
17,369,792 |
i have a form which has two dates pickup and return date now i want to make charges based on number of days but i am stuck in loop.
i want to charge if days 1,2,3,4 than no charge for 5,6,7,8 than charge again for 9,10,11,12 than again no charge for 13,14,15,16 like this how to write code for this pattern,i have tried code but not wokring
So i can add charge alternatively.
```
if($rental_days%5==0 && $rental_days <10):
$charge = ($rental_days-1)*$result['rent'];
elseif($rental_days%6==0):
$charge = ($rental_days-2)*$result['rent'];
elseif($rental_days%7==0):
$charge = ($rental_days-3)*$result['rent'];
elseif($rental_days%5==0 && $rental_days >8):
$charge = ($rental_days-3)*$result['rent']+$result['rent'];
else:
$charge = ($rental_days-4)*$result['rent']+$result['rent'];
endif;
```
|
2013/06/28
|
[
"https://Stackoverflow.com/questions/17369792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2532600/"
] |
You're not looking at sets of four, but actually sets of 8... the first half of the 8 you charge, the 2nd half you don't, so you want to divide by 8 and see if the remainder is 4 or less...
```
if ( $rental_days % 8 <= 4 && $rental_days % 8 != 0 )
```
This will work no matter how many days we have (ex: what if it's been 300 days). You wouldn't want to use a loop because this could go on forever.
|
94,995 |
I am developing a Web API which will back several applications: a website, a companion mobile application(s) and possibly several third-party applications. Every application is expected to get an access token from auth server and then feed it to the API, user will enter their credentials either on auth server web interface (for third-party applications) or directly in the website or app (for "trusted" applications). The client apps themselves are not expected to require user identity.
I've started implementing it via OAuth 2, and it matches my use cases exactly. But later I found several discussions in the 'net that sent me thinking whether my scenario really requires OpenID Connect, and now, after a few thousands of words read I still cannot *grok* which one is better for my case.
(For example, GitHub, which roughly matches my use cases, [uses](https://developer.github.com/v3/oauth/) OAuth 2)
I'd like to hear some guidelines on how does one choose whether one's API requires OAuth 2 or OpenID Connect.
**Update**
What confuses me is the following: there is a valid point in not using OAuth for *authentication*. But consider this case (assume that there's a simple business rule: each user can see only their own documents):
* app goes to auth server for token
* user authorizes the app, so the token is granted
* app goes to api with the token for data
* api returns documents for user that authorized the token (so somehow the token can be traced back to user)
Is this an authentication scenario or authorization scenario?
PS. I am aware of [this question](https://security.stackexchange.com/questions/37818/why-use-openid-connect-instead-of-plain-oauth), but the best answer there doesn't address my doubts.
|
2015/07/26
|
[
"https://security.stackexchange.com/questions/94995",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/81862/"
] |
From what you have explained it seems that OAuth 2.0 would better suit your needs. OpenID Connect was developed to add secure authentication to OAuth 2.0. Large providers i.e. Google, Facebook, Yahoo, etc began using OAuth 2.0 as a way to authenticate users with "login with" services so users could use their credentials to authenticate to a variety of third-party services. Standard OAuth 2.0 cannot securely satisfy this requirement because of deficiencies within the protocol. OpenID Connect solves these deficiencies and allows providers to securely use OAuth 2.0 as an authentication framework. OAuth 2.0 was originally developed as an authorization framework which allows a user to grant a third party service access to their data stored on the provider. The scenario you described seems like exactly what OAuth 2.0 was developed to do. If you do not plan to offer a "login with" mechanism use OAuth 2.0.
If a user will have their own credentials for the third-party services and not use your providers credentials to log into the service, you won't need OpenID Connect.
[This](http://www.thread-safe.com/2012/01/problem-with-oauth-for-authentication.html) was the most useful resource I found. It's a blog post by one of the designers of OpenID Connect that addresses Facebook's different uses for OAuth 2.0.
|
3,972,068 |
I want to do something when 2 document.write() statements have successfully occured. I tried the following but it didn't work:
```
function loadFields() {
var load1 = document.write("<input type='text' name='StoreLocation' value='"+storeLocation+"' />");
var load2 = document.write("<input type='text' name='couponType' value='"+couponType+"' />");
}
if (loadFields()) {
alert('both items have loaded.');
}
```
I also tried this and again same result:
```
var load1 = document.write("<input type='text' name='StoreLocation' value='"+storeLocation+"' />");
var load2 = document.write("<input type='text' name='couponType' value='"+couponType+"' />");
if (load1 && load2) {
alert('both items have loaded.');
}
```
|
2010/10/19
|
[
"https://Stackoverflow.com/questions/3972068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/480800/"
] |
```
function loadFields() {
document.write("<input type='text' name='StoreLocation' value='"+storeLocation+"' />");
document.write("<input type='text' name='couponType' value='"+couponType+"' />");
return true;
}
if (loadFields()) {
alert('both items have loaded.');
}
```
OR
```
function loadFields() {
document.write("<input id='StoreLocation' type='text' name='StoreLocation' value='"+storeLocation+"' />");
document.write("<input id='cuponType' type='text' name='couponType' value='"+couponType+"' />");
}
if (document.getElementById("StoreLocation") && document.getElementById("cuponType")) {
alert('both items have loaded.');
}
```
|
2,448,831 |
I'm running an animation in a WinForms app at 18.66666... frames per second (it's synced with music at 140 BPM, which is why the frame rate is weird). Each cel of the animation is pre-calculated, and the animation is driven by a high-resolution multimedia timer. The animation itself is smooth, but I am seeing a significant amount of "tearing", or artifacts that result from cels being caught partway through a screen refresh.
When I take the set of cels rendered by my program and write them out to an AVI file, and then play the AVI file in Windows Media Player, I do not see any tearing at all. I assume that WMP plays the file smoothly because it uses DirectX (or something else) and is able to synchronize the rendering with the screen's refresh activity. It's not changing the frame rate, as the animation stays in sync with the audio.
Is this why WMP is able to render the animation without tearing, or am I missing something? Is there any way I can use DirectX (or something else) in order to enable my program to be aware of where the current scan line is, and if so, is there any way I can use that information to eliminate tearing without actually using DirectX for displaying the cels? Or do I have to fully use DirectX for rendering in order to deal with this problem?
**Update**: forgot a detail. My app renders each cell onto a PictureBox using Graphics.DrawImage. Is this significantly slower than using BitBlt, such that I might eliminate at least some of the tearing by using BitBlt?
**Update 2**: the effect I'm seeing is definitely not flicker (which is different from tearing). My panel is double-buffered, sets the control styles for AllPaintingInWmPaint, UserPaint, OptimizedDoubleBuffer etc., overrides onPaintBackGround and so on. All these are necessary to eliminate flicker, but the tearing problem remains. It is especially pronounced when the animation has very fast-moving objects or objects that change from light to dark very quickly. When objects are slow-moving and don't change color rapidly, the tearing effect is much less noticeable (because consecutive cels are always very similar to each other).
|
2010/03/15
|
[
"https://Stackoverflow.com/questions/2448831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14606/"
] |
Tearing occurs when your image update is not in sync with the refresh rate of the monitor. The monitor shows part of the previous image, part of the new image. When the objects in the image move fast, the effect is quite noticeable.
It isn't fixable in Windows Forms, you can't get to the video adapter's v-sync signal. You can in a [DirectX app](http://msdn.microsoft.com/en-us/library/ee421725%28v=VS.85%29.aspx).
|
266,264 |
As stars **always** propagate light, I was thinking that we should see them even during the day. I searched a lot and I find three questions related to the current one.
1. [Why do two beams of light pass through one another without interacting?](https://physics.stackexchange.com/questions/184656/why-do-two-beams-of-light-pass-through-one-another-without-interacting)
2. [Can photons pass through each other?](https://physics.stackexchange.com/questions/145505/can-photons-pass-through-each-other)
3. [Star visibility in outer space even during the day?](https://physics.stackexchange.com/questions/71866/star-visibility-in-outer-space-even-during-the-day)
I couldn't get the answers given to these questions, but I could find some clues!
I guess beams of light pass through one another without interacting (and so we should see stars during the day) because of
1. This sentence of Anna's answer to the first question: ***"Thus two light beams have no measurable interactions when crossing"***
2. The **"Because"** in the beginning of John Duffield's answer to the first question.
3. This sentence of Anna's answer to the second question: ***"Thus we can say that for all intents and purposes photons scatter on each other without interacting"***
In other hand, I guess we cannot see stars during the day because of this sentence of udiboy1209's answer to the third question: ***"if you can sustain the heat and the blinding radiation from the sun, you should be able to see stars when you are facing the sun"***
May someone please clarify me by (as much as possible) simple explanations?
|
2016/07/05
|
[
"https://physics.stackexchange.com/questions/266264",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/111951/"
] |
The daylight sky has a brightness of about magnitude 3 per square arcsecond. The brightest stars have an integrated intensity of about zeroth magnitude.
If your eyes had an angular resolution approaching 1 arcsecond then you would easily be able to see bright stars in the daylight sky - they would be about 10 times as bright as the sky. Unfortunately, the resolution of the eye is more like 1 arcminute. That means when comparing the starlight to the sky, the star is blurred over an area such that the contrast ratio with the sky is no longer large enough to discern it. However, even with this, if you knew *exactly* where to look, you could make out the very brightest stars, if your eyesight were good and this is obviously the case of bright objects like Venus, which are visible in the daytime sky.
If you look through a telescope (which increases collection of *both* starlight and daylight equally) then you can easily see stars. This is because the angular resolution of the telescope is around $1.22\lambda/D$, where $\lambda$ is the wavelength and $D$ the telescope diameter. A 10cm telescope can give you an angular resolution approaching 1 arcsecond (atmospheric conditions permitting) and thus a 3rd magnitude star has a similar brightness to the daytime sky through such a telescope.
|
14,000,737 |
I have one page in which multiple anchor links are present.
And i want to open a single pop-up window from onclick of all these anchors.
Please suggest any idea.
Thanks
|
2012/12/22
|
[
"https://Stackoverflow.com/questions/14000737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1327029/"
] |
**`dtc -O dts`**
```
sudo apt-get install device-tree-compiler
dtc -I dtb -O dts -o a.dts a.dtb
```
gives a well indented textual representation of the device tree `a.dtb`, which is easy to understand with a text editor. Or dump it to stdout with:
```
dtc -I dtb -O dts -o - a.dtb
```
The source code for `dtc` is present in the kernel tree itself at [`scripts/dtc/dtc.c`](https://github.com/torvalds/linux/blob/v4.17/scripts/dtc/dtc.c#L166)
Tested on Ubuntu 16.04, with the device tree of Raspberry Pi 2, found in the first partition of `2016-05-27-raspbian-jessie-qemu.img`.
For convenience I have in my `.bashrc`:
```
dtbs() ( dtc -I dtb -O dts -o - "$1" )
dtsb() ( dtc -I dts -O dtb -o - "$1" )
```
`dtc` can also extract the DTS from `/proc` of a live kernel as shown at: <https://unix.stackexchange.com/questions/265890/is-it-possible-to-get-the-information-for-a-device-tree-using-sys-of-a-running>
|
13,748,770 |
>
> **Possible Duplicate:**
>
> [Validate email address in Javascript?](https://stackoverflow.com/questions/46155/validate-email-address-in-javascript)
>
>
>
This is my first post and I have a small issue. I'm trying to validate an email address on a form, but with no luck. I found this snippet on the internet but it doesn't seem to be working. I'm using Javascript at the moment to validate it. I don't usually use JS, so any help would be appreciated.
```
<script type="text/javascript">
function ValidateEmail(inputText)
{
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.value.match(mailformat))
{
document.forms.emailform();
return true;
}
else
{
alert("You have entered an invalid email address!");
document.forms.emailform();
return false;
}
}
```
```
<?php
$addemail .= '
<form method="post" action="cart2.php" name="emailform" onsubmit="return validateEmail">
';
$addemail .= '
E-mail Address: <input type="text" name="email" value="'.$row6['email'].'" size="19" /><input type="hidden" name="cartid" value="'.$cart.'" />';
if ( $emailerror != '' )
{
$addemail .= '<img src="images/email_error.png" width="16" height="16" hspace="4" alt="E-mail Error" />';
}
$addemail .= '
<input type="image" name="Add E-mail Address" alt="Add E-mail Address" src="images/addemail.gif" style="vertical-align:middle" />
</form>
';
if ( $row6['email'] == '' )
{
$emailpresent = 0;
}
else
{
$emailpresent = 1;
}
}
$addemail .= '
</td>
</tr>
';
}
?>
```
|
2012/12/06
|
[
"https://Stackoverflow.com/questions/13748770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1883096/"
] |
Look at this example of how it can be done in Javascript:
```
<html>
<head>
<script type="text/javascript">
<!--
function validateEmail() {
var emailText = document.getElementById('email').value;
var pattern = /^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*@[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$/;
if (pattern.test(emailText)) {
return true;
} else {
alert('Bad email address: ' + emailText);
return false;
}
}
window.onload = function() {
document.getElementById('email_form').onsubmit = validateEmail;
}
</script>
</head>
<body>
<form id="email_form">
<input type="text" id="email">
<input type="submit">
</form>
</body>
</html>
```
**Edit:**
If you are sure that the users of your web page are using *HTML5* compatible browsers you can use the following neater example for the same purpose:
```
<!DOCTYPE html>
<html>
<body>
<form>
<input type="email" pattern="^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*@[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$">
<input type="submit">
</form>
</body>
</html>
```
|
46,788,731 |
I have two tables shown below:
TableOwner:
```
UserID Name Initials
1 Peter Pet1
2 Mary Mar1
3 Petra Pet2
```
TableAsset
```
AssetID AssetName OwnerUserID
1 Samsung 3
2 Apple 1
3 Huawei 2
```
Now I want to insert into TableAsset these records:
```
AssetID AssetName OwnerUserID
4 Doro 2
5 Sony 1
```
How to use `insert` query and `select` query in one step?
|
2017/10/17
|
[
"https://Stackoverflow.com/questions/46788731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8789309/"
] |
You can do something like this in a single query. Passing the parameter will depend on you how you do it.
```
insert into TableAsset(AssetName, OwnerUserID)
select 'Doro', (select UserID from TableOwner where Initials = 'Mar1')
union all
select 'Sony', (select UserID from TableOwner where Initials = 'Pet1');
```
|
162,320 |
I noticed in my kitchen that the toast oven and the range hood had a ground fault, first by using a voltage detector pen, when getting near it the pen would activate from a distance (around 5cm without touching the case). Both of these didn't have a ground wire so I replaced the entire AC wires to put one with a ground wire that I tied to the metal chassis of both devices


The faults are "fixed", or at least gone to ground, however, I still wonder: When these devices when designed they knew both were going to be near water sources, why weren't they designed with a ground wire plug cable in the first place?
What defines when the case of a device should or should not be grounded?
What happens when a device has a fault and it's fixed like this to the ground wire in the home? Will the ground voltage go up? I'm currently sitting around 2v last time I checked (measuring neutral and GND with AC mode in a multimeter that doesn't have RMS values).
|
2015/03/30
|
[
"https://electronics.stackexchange.com/questions/162320",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/52466/"
] |
It would appear that LeCroy follow Agilent/Keysight in this respect (or, at least, Tektronix's presentation of what Agilent's method is). This can be seen from their probe manuals, for example for the [ZS4000 active (single-ended) probe](http://teledynelecroy.com/probes/probemodel.aspx?modelid=8259&categoryid=3&mseries=424&capid=102&mid=508). They provide the probe impedance as a function of frequency and advocate that the user corrects for it when interpreting the measurement, using the formula:
$$V\_\mathrm{out} = Z\_\mathrm{probe}/(Z\_\mathrm{probe}+Z\_\mathrm{source}) \times V\_\mathrm{in}$$
I avoid quoting further from their manual to avoid potential copyright issues (because it would require the whole section to be quoted to reproduce it properly here), but if you follow the link and read the manual, you will find that everything is quite clearly stated.
For the differential probes operating in the 10 GHz range (for example, the [WaveLink D1030](http://teledynelecroy.com/probes/probemodel.aspx?modelid=7052&categoryid=3&mseries=435&capid=102&mid=508)), their approach is slightly different to either of the ones presented in the Tektronix technical brief. The probes measure the loaded signal, as per Agilent, but they provide equalization software (*Virtual Probe*) to recover the unloaded signal. One models the circuit impedances and indicates the type and location of the probe, and the de-embedding is done accordingly. They summarize it as follows (quoting from the WaveLink probe manual):
>
> Teledyne LeCroy probes are calibrated at the factory using a Vector Network Analyzer (VNA) to measure a system (probe plus test fixture) frequency response. The test fixture is de-embedded from the measurement using Teledyne LeCroy's *Eye Doctor* tools so the remaining frequency response is due to the combination of the test signal and the probe loading on the test circuit. The system frequency response is then calculated for these remaining circuit elements.
>
>
> If you wish to de-embed the effect of probe loading on your circuit, you can use the appropriate equivalent circuit model ... and Teledyne LeCroy's *Eye Doctor* tools to accomplish this.
>
>
> You can also use Teledyne LeCroy’s *Virtual Probe* option. This option allows you to select the probe tip from a list of supported tips. Your selection applies a corresponding s-parameter file that is derived from the equivalent circuit model of the tip.
>
>
>
However, I haven't actually used these probes, so I can't comment on how good the software is.
|
44,389,666 |
I have a host file that looks roughly like this:
```
[kibanamaster]
efk host_ip host user passwd
[elasticnode]
esnode host_ip user passwd
```
and I am trying something in the style of
```
- name: get ip address node1
debug: var=hostvars[inventory_host]['esnode']['ansible_default_ipv4']['address']
register: es_node1
```
But I get variable not defined. Anyone outthere able to help?
EDIT:
If I do
```
debug: var=hostvars[LOG1]['esnode']['ansible_default_ipv4']['address']
register: node_1
```
I get
`{"hostvars[LOG1]['ansible_default_ipv4']['address']": "VARIABLE IS NOT DEFINED!"}`
|
2017/06/06
|
[
"https://Stackoverflow.com/questions/44389666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7991309/"
] |
`hostvars` [magic variable](http://docs.ansible.com/ansible/playbooks_variables.html#magic-variables-and-how-to-access-information-about-other-hosts) is a dictionary with keys named after hosts in your inventory.
So you may want to try:
```
hostvars['esnode']['ansible_default_ipv4']['address']
```
to get ip address of `esnode` host.
|
3,159,729 |
I'm struggling to get iPhone OS4 to produce the default tap highlight on a DIV, in a UIWebView (ie embedded in an application, not in Safari).
The markup is:
```
<a href="...">
<div class="item">
<div class="imgWrapper">
<img...>
</div>
<div class="Title">
Title text
</div>
</div>
</a>
```
I'm aiming for a display that looks like the native photos view - ie a scrolling list with an image at the left followed by some text, with list entries separated by a thin border line. A tap anywhere in the list entry should fire the link - on the image, on the text or on the whitespace between the list item separators.
I can't replace the element with an onclick=location.href=... on the DIV, because I'm using a custom URL schema to feed the click back to the application, and the location.href= doesn't trigger the UIWebView delegate.
Here's what I've tried so far:
1. Plain HTML, no CSS - I get a tap highlight, but the text flows beneath the image
2. item width 320px float left, img float left - the tap highlight no longer appears on the whitespace or text, but does on the image
3. A bunch of other things!
I'm stumped as to how to make the tap highlight work properly on this HTML - anybody got any ideas/examples of how to make this work?
|
2010/07/01
|
[
"https://Stackoverflow.com/questions/3159729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83132/"
] |
I'm just finishing up a mobile site project and ran in to some similar issues. First, I would reconsider your HTML structure with the div's inside of anchor. I'm not sure that fits the HTML spec. I know that the webviews and safari and all the other mobile devices handle html validation differently, some more strict than others so watch out for that and be sure to validate your doc type and content type. Content type is still burning me on pages. Second, to get the tap highlight to work you have to put in on a higher node and then it will only apply to anchors I think. so you could do something like this on the body with CSS:
```
body {
-webkit-tap-highlight-color: #ccc;
}
```
Third, couldn't you try an `onlick="window.location=your_href;"`
Hope this helps, or gives you an idea of what to watch out for.
|
64,005,603 |
I have published a native app with package name e.g (com.hamzamuazzam.foo) in Google Playstore and I want to update my app that is now made in flutter , also have made all the necessary changes in my code.
new flutter app made with same package name (com.hamzamuazzam.foo) as old native app that is already published in google playstore.
Now, my main question is that can I update my new flutter App with Native app without changing the Package name in google play store ,
will Google play console allow me to update flutter app with same package name over the same native app?
|
2020/09/22
|
[
"https://Stackoverflow.com/questions/64005603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12440539/"
] |
Yes, you can update your app. Generally speaking, only three rules apply for updates:
1. The package name must be identical.
2. The `versionCode` must be greater than the `versionCode` of the previously released app.
3. The app must be signed with the same signing key as before.
Besides that, it doesn't matter if you create your APK or Android App Bundle with Kotlin/Java, Flutter, Xamarin, React Native, Cordova or any other technology.
|
469,068 |
This picture is given in my textbook regarding an n-p-n transistor circuit:
[](https://i.stack.imgur.com/8lF9d.jpg)
Why is the emitter grounded? Why can't it be directly and only connected to the negative terminal of Vcc?
|
2019/11/26
|
[
"https://electronics.stackexchange.com/questions/469068",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/236991/"
] |
>
> Also, what is the use of defining a voltage reference point?
>
>
>
All voltages are relative, a concept which a lot of people have trouble understanding.
It is rather common to say that "at Point A we have X Volts" but actually it is wrong!
Officially you should say "Between point B and point A we have X volts".
As that become tedious it is easier (common) to define a reference point. Then if you say "at Point A we have X Volts" your are actually saying "Between the reference point and point A we have X volts".
The next step often used in a schematic when defining the reference point is to use the ground symbol for that.
|
40,844,416 |
I had developed simple angular 2 application with typescript 2.0 version in visual studio 2015 by using below link.
<https://angular.io/docs/ts/latest/cookbook/visual-studio-2015.html>
Then after, I configured the DEVOPS for that application means when every I check in the code into my team project available in team foundation server using visual studio 2015. it will automatically start build for my application at that time I got exception like "**Unknown Compiler Option lib**" this below figure.
[](https://i.stack.imgur.com/sRvLX.png)
Please tell me how to resolve the above issue.
-Pradeep
|
2016/11/28
|
[
"https://Stackoverflow.com/questions/40844416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5471259/"
] |
I was having this same issue. I opened the .cproj file and changes the line
`<TypeScriptToolsVersion>1.8</TypeScriptToolsVersion>`
to
`<TypeScriptToolsVersion>2.0</TypeScriptToolsVersion>`
and everything worked
|
6,361,287 |
How can I create a class diagram for the whole solution? In the solution, there are some projects and I want to create a class diagramm from all of them.
I use Visual Studio 2010 Professional.
|
2011/06/15
|
[
"https://Stackoverflow.com/questions/6361287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/793077/"
] |
You can create class diagram just for project not for whole solution. You can use sequence diagram and class diagram to manage how everything is related.
|
27,233,610 |
I would change fragment in the viewpager using a button in every fragment. So in the fragment in position 0 i have a button and onClick i'll change in second fragment (position 1) and so on. Actually i'm using this code in the fragment at position 0:
```
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.open_welcome_fragment_layout, container,
false);
final WelcomeViewPager pagerV = new WelcomeViewPager();
Button nextBtnOpen = (Button)view.findViewById(R.id.button_next_open);
nextBtnOpen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((WelcomeViewPager)getActivity()).setCurrentItem(1, true);
}
});
return view;
}
```
position 1:
```
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.firstwelcomefrg, container, false);
final WelcomeViewPager pagerV = new WelcomeViewPager();
Button nextBtn = (Button)view.findViewById(R.id.button_next_one);
nextBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((WelcomeViewPager)getActivity()).setCurrentItem(2, true);
}
});
return view;
}
```
position 2:
```
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.secondwelcomefrg, container,
false);
final WelcomeViewPager pagerV = new WelcomeViewPager();
Button nextBtnTwo = (Button)view.findViewById(R.id.button_next_two);
nextBtnTwo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((WelcomeViewPager)getActivity()).setCurrentItem(3, true);
}
});
return view;
}
```
and in my ViewPager Activity i created this method:
```
public void setCurrentItem (int item, boolean smoothScroll) {
mViewPager.setCurrentItem(item, smoothScroll);
}
```
unfortunatelly not works. I can change from first to second fragment but every fragment returns to second.. Seems that the only one position accepted is the first one. In this case:
```
((WelcomeViewPager)getActivity()).setCurrentItem(1, true);
```
why this behaviour?
|
2014/12/01
|
[
"https://Stackoverflow.com/questions/27233610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1540456/"
] |
If the `Value` is the `class` , then you can simply do this:
```
function changeList() {
var selectedGroup = $("#picker").val();
$('.' + selectedGroup).toggle();
}
```
|
11,060,491 |
Given this code:
```
List<Integer> ints = new ArrayList<Integer>();
// Type mismatch:
// cannot convert from Class<capture#1-of ? extends List> to Class<List<Integer>>
Class<List<Integer>> typeTry1 = ints.getClass();
// Type safety:
// Unchecked cast from Class<capture#2-of ? extends List> to Class<List<Integer>>
Class<List<Integer>> typeTry2 = (Class<List<Integer>>) ints.getClass();
// List is a raw type. References to generic type List<E> should be parameterized
Class<? extends List> typeTry3 = ints.getClass();
```
Is there a way to get the `Class` of a `List<Integer>` without an error or warning? I can suppress the warnings easily enough, but if Java requires me to suppress a warning for this valid code, I am very [disappoint](http://knowyourmeme.com/memes/son-i-am-disappoint).
On the other hand, if warning suppression is the only way, what is the safest to suppress?
|
2012/06/16
|
[
"https://Stackoverflow.com/questions/11060491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/577298/"
] |
This is a real Catch-22 in Java.
The compiler warns you if you don't add a generic type to `List`:
```
// WARN: List is not typed
Class<? extends List> typeTry3 = ints.getClass();
```
That's because, in most cases, it's really best to type your Lists.
However, because of type erasure, there's no way for Java to figure out the generic type of `List` at runtime, and the compiler knows that. Therefore, there is no method on `Class` that will returned a typed object:
```
// ERROR: ints.getClass() doesn't return a Class<List<Integer>>, it returns a Class<List>
Class<? extends List<? extends Integer>> var = ints.getClass();
```
So you *must* cast it to a typed list. However, as you know, since there is no runtime type checking, Java warns you about any casts to a typed variable:
```
// WARN: Casting to typed List
Class<List<Integer>> typeTry2 = (Class<List<Integer>>) ints.getClass();
```
Any attempt to get around this is essentially a means of confusing the compiler, and will inevitably be convoluted.
Your best bet then is to go with Option B:
>
> On the other hand, if warning suppression is the only way, what is the safest to suppress?
>
>
>
The safest way to suppress this warning is to make your `@SuppressWarnings("unchecked")` annotation as localized as possible. Put them above each individual unchecked cast. That way it's absolutely clear who's causing the warning.
|
38,451,291 |
Sir I am trying to send upstream message from my android phone but failed to do so.Don't know where i am wrong.
Here is my code:
```
public class MainActivity extends AppCompatActivity {
Button button;
private AtomicInteger msgId;
FirebaseMessaging fm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseMessaging.getInstance().subscribeToTopic("hello");
FirebaseInstanceId.getInstance().getToken();
msgId = new AtomicInteger();
button = (Button) findViewById(R.id.click);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(),""+msgId,Toast.LENGTH_SHORT).show();
fm = FirebaseMessaging.getInstance();
RemoteMessage message=new RemoteMessage.Builder("<my sender id>@gcm.googleapis.com")
.setMessageId(Integer.toString(msgId.incrementAndGet()))
.addData("my_message", "Hello World")
.addData("my_action", "SAY_HELLO")
.build();
fm.send(message);
}
});
}
}
```
I had implemented onMessageSent() and onSendError() as according to docs but these methods were never called.Here is my messaging service class:
```
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d("msg", "onMessageReceived: " + remoteMessage.getData().get("message"));
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("test")
.setContentText(remoteMessage.getData().get("message"));
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
@Override
public void onMessageSent(String s) {
super.onMessageSent(s);
Log.d("fcm", "onMessageSent: message sent");
Toast.makeText(getApplicationContext(), "message:" + s, Toast.LENGTH_SHORT).show();
}
@Override
public void onSendError(String s, Exception e) {
super.onSendError(s, e);
Log.d("fcm", "onSendError: erroe");
Toast.makeText(getApplicationContext(), "error:" + s, Toast.LENGTH_SHORT).show();
}
}
```
i am trying this from 1 week still don't know where I am wrong.Also there is nothing in logcat.please help.
|
2016/07/19
|
[
"https://Stackoverflow.com/questions/38451291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6603490/"
] |
You have to set TTL at your message, For Example
```
RemoteMessage message=new RemoteMessage.Builder("<my sender id>@gcm.googleapis.com")
.setMessageId(Integer.toString(msgId.incrementAndGet()))
.addData("my_message", "Hello World")
.addData("my_action", "SAY_HELLO")
.setTtl(86400)
.build();
```
>
> setTtl(86400) this line is important ,hope it will helps.
>
>
>
|
22,535,849 |
I have an SQL query that brings back 17 numbers with this format
>
> 06037-11
>
>
>
I need to add a 0 before the dash, so it is:
>
> 060370-11
>
>
>
Is there an easy way to do this? I have seen STUFF() as an option, but I don't understand it.
**Edit**
I am using Teradata
|
2014/03/20
|
[
"https://Stackoverflow.com/questions/22535849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3261877/"
] |
One way in Oracle:
```
with qry as
(select '06037-11' code from dual)
select regexp_replace(code, '-', '0-') from qry;
```
|
66,560,404 |
I'm learning Jetpack Compose and I was trying to make a View Model for my @Composable.
In documentation (<https://developer.android.com/codelabs/jetpack-compose-state#3>) for observing state changes in composable they use `observeAsState` but in my implementation, the method cannot be found. I get instead `Unresolved reference: observeAsState`
ViewModel
```
class MainActivityViewModel : ViewModel() {
val list: LiveData<MutableList<String>> = MutableLiveData(mutableListOf("Ana", "are", "mere"))
fun addString(item: String) {
val list: MutableList<String> = list.value!!
list.add(item)
}
}
```
Composable
[](https://i.stack.imgur.com/N0TyM.png)
I am using Compose 1.0.0-beta01
|
2021/03/10
|
[
"https://Stackoverflow.com/questions/66560404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10805602/"
] |
`observeAsState` is part of the `runtime-livedata` library.
Add the dependency to your module's `build.gradle` file. Replace `$compose_version` with the version of compose which you use, e.g. `1.0.0-beta01`:
```
implementation "androidx.compose.runtime:runtime-livedata:$compose_version"
```
You can find the available versions [here in Google's Maven repository](https://mvnrepository.com/artifact/androidx.compose.runtime/runtime-livedata).
|
37,196,603 |
I have an arrangement with the delivery days of my online store in two different cities:
```
$city1 = array("Monday", "Friday");
$city2 = array("Monday", "Thursday", "Saturday");
```
The store delivers every 2 days, but only on certain days depending on the city.
If today is Thursday and someone buys in city 1, the order will be received in 2 days in this case on Monday (see above array).
If today is Thursday and someone buys in the city 2, the order will be received in 2 days, here on Saturday.
Based on the above, how I can do with PHP to know what day you receive the product?
What should be the logic of programming?
|
2016/05/12
|
[
"https://Stackoverflow.com/questions/37196603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1135144/"
] |
Try this way:
```
SELECT t1.*, t3.NAME
FROM objectTable AS t1
INNER JOIN (
SELECT OBJECT_ID, MIN(PHOTO_ID) AS PHOTO_ID
FROM photo_table
GROUP BY OBJECT_ID
) t2 ON t1.ID = t2.OBJECT_ID
INNER JOIN photo_table AS t3 ON t3.OBJECT_ID = t2.OBJECT_ID AND
t3.PHOTO_ID = t2.PHOTO_ID
```
The trick is to use a derived table that selects the `PHOTO_ID` value per `OBJECT_ID`. This value is used in an additional join to `photo_table`, so as to select the required `NAME` value.
|
433,966 |
I'd like some insight/heuristics on how to tackle a specific kind of situation.
Entity A, B have a parent child relationship with Entity C.
Entity A creation is done thru a `POST /createA API` in Microservice1 and this microservice has APIs to update, edit and delete an instance of A as well.
Entity C create is done thru a `POST /createC API` in Microservice2 and this microservice has APIs to update, edit and delete an instance of C as well.
It is not an option to migrate creation logic of A,B,C into a single component and Microservice1 owns Entity A, while Microservice2 owns Entity C;
Consider the scenario, where a `POST /createA` call is made with incorrect data provided for Entity C.
Do we fail the entire request, or do we create A with No reference to C, with an appropriate HTTP status;
given that we cannot verify if Entity C is valid without making a call to `POST /createC`
|
2021/12/01
|
[
"https://softwareengineering.stackexchange.com/questions/433966",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/332769/"
] |
This might not be the kind of answer you expect. Or anyone reading this might expect, but to me, the question was made to the wrong audience.
Whether `A` without `C` or `A` with a wrong `C` reference is valid or not, we can not say. Only your business experts will know because the relationship between `A` and `C` does respond to a need originated by the business.
Business experts will know if `A` can exist without `C`. If it can exist without, but temporally. If there's a compensative operation to fix wrong references `A.C`, etc.
Once they clear this doubt (*the what to do*), then comes the *how to do it* and that's the kind of question we can help you out with.
|
1,068,494 |
Prove that if $n$ is a positive integer and $n >1$:
$$\binom n2 + \binom {n-1}2$$
is always a perfect square.
I know we need to turn that into a binomial, but I can't follow how.
Please note I'm pretty new to discrete math.
Thanks in advance.
|
2014/12/15
|
[
"https://math.stackexchange.com/questions/1068494",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/179002/"
] |
HINT: $$\binom{n}2=\frac{n!}{2!(n-2)!}=\frac{n(n-1)}2\;.$$ Apply the same idea to $\binom{n-1}2$, add the resulting fractions, and simplify.
Alternatively, if you know that $1+2+\ldots+n=\frac{n(n+1)}2=\binom{n+1}2$, you can observe that
$$\color{green}{\binom{n}2=1+2+\ldots+(n-2)+(n-1)}\;,$$
and
$$\color{brown}{\binom{n-1}2=1+2+\ldots+(n-3)+(n-2)}\;.$$
Now look at the picture below:
$$\begin{array}{ccc}
&1&2&3&\ldots&n-3&n-2&n-1\\
1&\color{green}\bullet&\color{brown}\bullet&\color{brown}\bullet&\ldots&\color{brown}\bullet&\color{brown}\bullet&\color{brown}\bullet\\
2&\color{green}\bullet&\color{green}\bullet&\color{brown}\bullet&\ldots&\color{brown}\bullet&\color{brown}\bullet&\color{brown}\bullet\\
3&\color{green}\bullet&\color{green}\bullet&\color{green}\bullet&\ldots&\color{brown}\bullet&\color{brown}\bullet&\color{brown}\bullet\\
\vdots&\vdots&\vdots&\vdots&\ddots&\vdots&\vdots&\vdots\\
n-3&\color{green}\bullet&\color{green}\bullet&\color{green}\bullet&\ldots&\color{green}\bullet&\color{brown}\bullet&\color{brown}\bullet\\
n-2&\color{green}\bullet&\color{green}\bullet&\color{green}\bullet&\ldots&\color{green}\bullet&\color{green}\bullet&\color{brown}\bullet\\
n-1&\color{green}\bullet&\color{green}\bullet&\color{green}\bullet&\ldots&\color{green}\bullet&\color{green}\bullet&\color{green}\bullet\\
\end{array}$$
|
72,790 |
I want to send "Happy Thanksgiving!" to 35 different people, but I do not want it to be treated as a group message. How can this be accomplished on the iPhone 4S (with or without jailbreak applications, such as biteSMS) with iOS 5.1.1?
The reasons that I would not want it treated as a group message are:
* I do not want the recipients to see the numbers of other recipients
* I do not want the recipients' replies to go to multiple people
* I do not want the recipients' replies to be grouped in a group message, but to instead be part of each individual thread
* depending on the message, I may specifically not want a given recipient to know that other recipients received the same message.
Optimally, the solution would also allow pictures to be attached and would automatically send iMessages instead of text messages to iOS users - but those parts are less important than being able to send plain text messages.
|
2012/11/26
|
[
"https://apple.stackexchange.com/questions/72790",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/15282/"
] |
The option you're looking for is located at `Settings > Messages > Group Messaging`. Turning this off will send all messages individually to their recipients.
Note: Disabling MMS Messaging will remove the Group Messaging toggle from the list.
Note: Some cellular service providers do not support Group Messaging, so if you have MMS enabled, and you still don't see Group Messaging, then it's likely that your provider does not support it. From Apple: [If you don't see an option to turn on MMS Messaging or Group Messaging on your iPhone, contact your carrier.](https://support.apple.com/en-us/HT202724)

|
238,225 |
I am trying to install instamojo payment gateway to my magento2 store, as per the instructions givne by instamojo page <https://docs.instamojo.com/page/instamojo-integeration-for-magento-2>
i tried the command using CLI (ssh) at my ubuntu host
```
composer update instamojo/instamojo-magento-2
```
>
> Loading composer repositories with package information
>
>
> Updating dependencies (including require-dev)
>
>
> Killed
>
>
>
I searched Google and found that , it happens because composer runs out of memory, but how could i increase the memory at remote server (I am running the website on live server at Godaddy)
Is there any other way of doing this ??
|
2018/08/13
|
[
"https://magento.stackexchange.com/questions/238225",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/70746/"
] |
Try this with more memory
```
php -d memory_limit=4G /usr/local/bin/composer update
```
OR
```
php -d memory_limit=-1 /usr/local/bin/composer update
```
|
19,223,294 |
I have the impression that CDI is not working with classes that have a `@javax.faces.component.FacesComponent`. Is this true?
Here's my example, that doesn't work. The `MyInjectableClass` is used at other points in the code where injection is not a problem, so it must be about the `@FacesComponent` annotation I think.
The class I want to inject:
```
@Named
@Stateful
public class MyInjectableClass implements Serializable {
private static final long serialVersionUID = 4556482219775071397L;
}
```
The component which uses that class;
```
@FacesComponent(value = "mycomponents.mytag")
public class MyComponent extends UIComponentBase implements Serializable {
private static final long serialVersionUID = -5656806814384095309L;
@Inject
protected MyInjectableClass injectedInstance;
@Override
public void encodeBegin(FacesContext context) throws IOException {
/* injectedInstance is null here */
}
}
```
|
2013/10/07
|
[
"https://Stackoverflow.com/questions/19223294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1863853/"
] |
Unfortunately, even for JSF 2.2 `@FacesComponent`, `@FacesValidator` and `@FacesConverter` are not valid injection targets (read [What's new in JSF 2.2?](http://jdevelopment.nl/jsf-22/) by Arjan Tijms for more details). As Arjan points out:
>
> It’s likely that those will be taken into consideration for JSF 2.3 though.
>
>
>
What can you do for now? Well, you've got basically two choices:
1. Handle [CDI injection via lookup](http://dominikdorn.com/2010/04/cdi-weld-manual-bean-lookup/), or switch to EJB and do the [simpler EJB lookup](http://balusc.blogspot.com/2011/09/communication-in-jsf-20.html#GettingAnEJBInFacesConverterAndFacesValidator);
2. Annotate tour class with `@Named` instead of `@FacesComponent`, `@Inject` the component the way you did and [register your component in faces-config.xml](https://stackoverflow.com/a/8079296/1820286). As the UI component instance is created via JSF Application#createComponent(), not via CDI you will also need a custom Application implementation as well (exactly like OmniFaces has for those converters/validators).
And, by the way, you've got two issues with what you've got this far: (1) what is meant by `@Named @Stateful` when the former is from a CDI world and the latter is from EJB world and (2) are you sure you intend to keep state in a faces component that's basically recreated on every request?
|
20,525,328 |
I have the following code
```
class Multi extends Thread{
public void run(){
for(int i=1;i<=3;i++){
System.out.println(i + ": "+Thread.currentThread().getName());
}
}
public static void main(String args[]){
Multi t1=new Multi();
t1.setName("First Thread");
Multi t2=new Multi();
t2.setName("Second Thread");
Multi t3=new Multi();
t3.setName("Third Thread");
t1.start();
t2.start();
try{
t1.join();
t2.join();
}catch(Exception e){System.out.println(e);}
t3.start();
}
}
```
\*\*
The output varies every time I run :
```
1st time Output
1: Second Thread
2: Second Thread
3: Second Thread
1: First Thread
2: First Thread
3: First Thread
1: Third Thread
2: Third Thread
3: Third Thread
=============================================
2nd time Output
1: First Thread
2: First Thread
3: First Thread
1: Second Thread
2: Second Thread
3: Second Thread
1: Third Thread
2: Third Thread
3: Third Thread
*************************************************
```
Since `t2.join()` is called after `t1.join()` how come 1st output is coming ? Shouldn't `t2` wait for `t1` to execute?
Please help me understand the `join()` method behavior, if possible with more code snippet examples
|
2013/12/11
|
[
"https://Stackoverflow.com/questions/20525328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1617512/"
] |
`t.join()` blocks the *current* thread (the main thread in your example) until the thread `t` has finished executing. It doesn't block any other thread, and doesn't prevent any other thread to run.
Your example starts t1 and t2. So t1 and t2 run in parallel. And the main thread blocks until t1 is completed. Once t1 is completed, it blocks until t2 is completed. t2 might very well has finished executing before t1. In this case, `t2.join()` will return immediately.
|
55,212,061 |
In my dataframe I have a column of TimestampType format of '2019-03-16T16:54:42.968Z' I would like to convert this to a StringType column with a format of '201903161654' instead of a generic timestamp column. This is because I need to partition several directories based on the string formatted timestamp, if I partition on the timestamp column it creates special characters when creating the directory.
Is there any api I can use in spark to convert the Timestamp column to a string type with the format above?
|
2019/03/17
|
[
"https://Stackoverflow.com/questions/55212061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10571660/"
] |
Map class has the [entries](https://api.dartlang.org/stable/2.2.0/dart-core/Map/entries.html) property which returns the map entries as an iterable on which you can use the [map](https://api.dartlang.org/stable/2.2.0/dart-core/Iterable/map.html) function to generate the list of items you need.
```
var addictionList = dataMan.entries.map((MapEntry mapEntry) => mapEntry.value).toList();
```
`mapEntry.key` is the type of `String` and `mapEntry.value` is the type of `AddictionDay`.
|
5,436,563 |
I'm having trouble to change the font for my emacs configuration.
I've tried using set-default-font, and managed to tab to my desired font, however, some elements are still rendered as the old font (ie python's class names and function names)
|
2011/03/25
|
[
"https://Stackoverflow.com/questions/5436563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/676254/"
] |
[set-default-font](http://www.gnu.org/software/emacs/windows/old/faq5.html) is really old, and has been deprecated in Emacs 23 in favor of its new name set-frame-font (which isn't much better). The current Emacs manual [suggests several ways to set the default font](http://www.gnu.org/software/emacs/manual/html_node/emacs/Fonts.html), but I'll assume you've found those already, seeing as you've tried set-default-font...
The elisp code I use is actually different from all the methods suggested there:
```
;; [in .emacs]
;; Use 10-pt Consolas as default font
([set-face-attribute](http://www.gnu.org/software/emacs/elisp/html_node/Attribute-Functions.html) ['default](http://www.gnu.org/software/emacs/manual/html_node/emacs/Standard-Faces.html) nil
[:family "Consolas" :height 100](http://www.gnu.org/software/emacs/elisp/html_node/Face-Attributes.html))
```
set-face-attribute seems to stick better than set-default-font; at least it seems to use Consolas consistently even in things like Python class and function names.
|
28,352,752 |
I'm trying to add an event in google places and the JSON returned has an invalid request in status and this endpoint has been removed in error\_message. This morning it has worked correctly but now it doesn't work anymore.
I tried to use HTTP in the request to see if it returns the request denied but this doesn't do it, it always returns invalid request.
Here is my code:
```
private final String EVENT_URL =
"https://maps.googleapis.com/maps/api/place/event/add/json?";
private JSONObject uploadEvent() {
JSONObject jsonobj = new JSONObject();
StringEntity sEntity = null;
try {
jsonobj.put("duration", duration);
jsonobj.put("reference", reference);
jsonobj.put("summary", description);
if(url.length() > 0){
jsonobj.put("url", url);
}
sEntity = new StringEntity(jsonobj.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppostreq = new HttpPost(getUrlEvent());
httppostreq.setEntity(sEntity);
String responseText;
JSONObject JSON = null;
try {
HttpResponse httpresponse = httpclient.execute(httppostreq);
responseText = EntityUtils.toString(httpresponse.getEntity());
JSON = new JSONObject(responseText);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
private String getUrlEvent(){
//genero la solicitud como la debajo descrita
StringBuilder urlString = new StringBuilder(EVENT_URL);
urlString.append("&sensor=false&key=" + API_KEY);
return urlString.toString();
}
```
Can anyone helps me please?
|
2015/02/05
|
[
"https://Stackoverflow.com/questions/28352752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1990408/"
] |
The answer is, it depends...
1. If you add it as a system dependency it is likely to become path dependent which makes it more difficult to share among other developers. Sure you can also distribute the 3rd party jar relative to your POM via your SCM but the intention of `systemPath` is more for dependencies that are provided by the JDK or the VM. From [the docs](http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html) about `systemPath`:
>
> They are usually used to tell Maven about dependencies which are provided by the JDK or the VM. Thus, system dependencies are especially useful for resolving dependencies on artifacts which are now provided by the JDK, but where available as separate downloads earlier.
>
>
>
2. To install the jar in the local repo is also not friendly for sharing. It requires all developers to "upload" the jar to their local repo before building. You can of course add a script that handles this for you but it is always easy to forget to upload and IMO a better solution is point 3 below. The local install process is [described here](http://maven.apache.org/guides/mini/guide-3rd-party-jars-local.html).
3. If you are working in an organization where the developers share the POM you should upload the 3rd party jar to a local repository manager. That way you can easily work with the 3rd party jar as if using any other maven enabled jar. Check [this link](http://maven.apache.org/repository-management.html) for a comprehensive list on repository managers.
To summarize, if you are sharing the POM with others I would suggest that you upload it to a local repository manager. Otherwise the second option can work for you. As a last option, I would fall back to option number 1.
Also note that this has nothing to do with which version of Maven you are running.
|
29,960 |
Here I am playing on the hardest setting and trying to get the pacifist achievement also. I *just* finished the "Black Hawk Down" scene when you arrive back in Hengsha. After 5 MILLION retries I finally downed all the enemies non-lethally, and got the robot without any "collateral damage" or accidental kills. But...there's one guy who shoots a barrel that he's standing next to right at the beginning of my save.
Here's the question:
Does that guy count against my no kill record? Am I disqualified from the Pacifist achievement because of something the computer did? Would it be "safer" to just reload from an earlier point?
|
2011/09/09
|
[
"https://gaming.stackexchange.com/questions/29960",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/12328/"
] |
Just to clarify, you don't actually have to save Malik to get the Pacifist achievement. So you can just run past all the guards and go into the elevator, without any risk of discounting the achievement.
But to your question, this does count against the pacifist achievement.
|
35,586,735 |
Im trying to assign the value selected on my 'Razor Dropdown List' into my Input Field but im not getting any result from my javascript
This is my Drodown lsit:
```
<input type="text" name="txtInput" value=""/>
<input type="submit" name="test" value="enter"/>
@Html.DropDownList("Fechas", "Todas")
```
This is my Javascript:
```js
$("#Fechas").live("change", function () {
$("#txtInput").val($(this).find("option:selected").attr("value"));
})
```
How can i get the input to get the value of the dropdown list each time a user pics something from my dropdown?
|
2016/02/23
|
[
"https://Stackoverflow.com/questions/35586735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1650011/"
] |
please try this
```
$(function(){
$('select[name="Fechas"]').on("change", function () {
$('input[name="txtInput"]').val($(this).val());
});
});
```
|
43,490,920 |
I have two tables [LogTable] and [LogTable\_Cross].
Below is the schema and script to populate them:
```
--Main Table
CREATE TABLE [dbo].[LogTable]
(
[LogID] [int] NOT NULL
IDENTITY(1, 1) ,
[DateSent] [datetime] NULL,
)
ON [PRIMARY]
GO
ALTER TABLE [dbo].[LogTable] ADD CONSTRAINT [PK_LogTable] PRIMARY KEY CLUSTERED ([LogID]) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_LogTable_DateSent] ON [dbo].[LogTable] ([DateSent] DESC) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_LogTable_DateSent_LogID] ON [dbo].[LogTable] ([DateSent] DESC) INCLUDE ([LogID]) ON [PRIMARY]
GO
--Cross table
CREATE TABLE [dbo].[LogTable_Cross]
(
[LogID] [int] NOT NULL ,
[UserID] [int] NOT NULL
)
ON [PRIMARY]
GO
ALTER TABLE [dbo].[LogTable_Cross] WITH NOCHECK ADD CONSTRAINT [FK_LogTable_Cross_LogTable] FOREIGN KEY ([LogID]) REFERENCES [dbo].[LogTable] ([LogID])
GO
CREATE NONCLUSTERED INDEX [IX_LogTable_Cross_UserID_LogID]
ON [dbo].[LogTable_Cross] ([UserID])
INCLUDE ([LogID])
GO
-- Script to populate them
INSERT INTO [LogTable]
SELECT TOP 100000
DATEADD(day, ( ABS(CHECKSUM(NEWID())) % 65530 ), 0)
FROM sys.sysobjects
CROSS JOIN sys.all_columns
INSERT INTO [LogTable_Cross]
SELECT [LogID] ,
1
FROM [LogTable]
ORDER BY NEWID()
INSERT INTO [LogTable_Cross]
SELECT [LogID] ,
2
FROM [LogTable]
ORDER BY NEWID()
INSERT INTO [LogTable_Cross]
SELECT [LogID] ,
3
FROM [LogTable]
ORDER BY NEWID()
GO
```
I want to select all those logs (from LogTable) which has given userid (user id will be checked from cross table LogTable\_Cross) with datesent desc.
```
SELECT DI.LogID
FROM LogTable DI
INNER JOIN LogTable_Cross DP ON DP.LogID = DI.LogID
WHERE DP.UserID = 1
ORDER BY DateSent DESC
```
After running this query here is my execution plan:
[](https://i.stack.imgur.com/JjX9O.png)
As you can see there is a sort operator coming in role and that should be probably because of following line "ORDER BY DateSent DESC"
My question is that why that Sort operator is coming in the plan even though I have the following index applied on the table
```
GO
CREATE NONCLUSTERED INDEX [IX_LogTable_DateSent] ON [dbo].[LogTable] ([DateSent] DESC) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_LogTable_DateSent_LogID] ON [dbo].[LogTable] ([DateSent] DESC) INCLUDE ([LogID]) ON [PRIMARY]
GO
```
On the other hand if I remove the join and write the query in this way:
```
SELECT DI.LogID
FROM LogTable DI
-- INNER JOIN LogTable_Cross DP ON DP.LogID = DI.LogID
--WHERE DP.UserID = 1
ORDER BY DateSent DESC
```
the plan changes to
[](https://i.stack.imgur.com/qLgRs.png)
i.e Sort operator is removed and the plan is showing that my query is using my non clustered index.
So is that a way to remove "Sort" operator in the plan for my query even if I am using join.
**EDIT**:
I went further and limited the "Max Degree of Parallelism" to 1
[](https://i.stack.imgur.com/xSox1.png)
Ran the following query again:
```
SELECT DI.LogID
FROM LogTable DI
INNER JOIN LogTable_Cross DP ON DP.LogID = DI.LogID
WHERE DP.UserID = 1
ORDER BY DateSent DESC
```
and the plan is still having that Sort operator:
[](https://i.stack.imgur.com/ZEo2O.png)
**Edit 2**
Even if I have the following index as suggested:
```
CREATE NONCLUSTERED INDEX [IX_LogTable_Cross_UserID_LogID_2]
ON [dbo].[LogTable_Cross] ([UserID], [LogID])
```
the plan is still having the Sort operator:
[](https://i.stack.imgur.com/ffKw6.png)
|
2017/04/19
|
[
"https://Stackoverflow.com/questions/43490920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/148657/"
] |
The second query of yours does not contain the UserId condition and therefore it is not an equivalent query. The reason why the first query is not covered by your indexes on LogTable is the fact, that UserId is not present in them (and you need to perform the join as well). Therefore, SQL Server has to join the tables (Hash Join, Merge Join or Nested-Loop join). SQL Server correctly selects the Hash Join, since the intermediate results are large and they are not sorted according to the LogID. If you give them the intermediate result sorted according to the LogID (your second edit) then he uses merge join, however, sort according to the DateSend is stil needed. The only solution without sort is to create an indexed materialized view:
```
CREATE VIEW vLogTable
WITH SCHEMABINDING
AS
SELECT DI.LogID, DI.DateSent, DP.UserID
FROM dbo.LogTable DI
INNER JOIN dbo.LogTable_Cross DP ON DP.LogID = DI.LogID
CREATE UNIQUE CLUSTERED INDEX CIX_vCustomerOrders
ON dbo.vLogTable(UserID, DateSent, LogID);
```
The view has to be used with noexpand hint, so the optimizer can find the CIX\_vCustomerOrders index:
```
SELECT LogID
FROM dbo.vLogTable WITH(NOEXPAND)
WHERE UserID = 1
ORDER BY DateSent DESC
```
This query is equivalent query to your first query. You may check the correctness if you insert the following row:
```
INSERT INTO LogTable VALUES (CURRENT_TIMESTAMP)
```
then my query still returns the correct result (10000 rows), however, your second query returns 10001 rows. You may try to delete or insert some other rows and the view will still be up-to-date and you recieve correct results from my query.
|
51,925,786 |
How do I subtract the `Amount` if the `Id` and `FreeUpOriginId` matches in my query? I could achieve my desired result bu using `foreach` but I was wondering if it can be done in one select query.
```
DateTime DateToday = DateTime.Now;
var availed = (from c in db.Allocations
where c.Status == Status.Availed && c.FiscalYear == DateToday.Year
select c).ToList();
var freeup = (from c in db.Allocations
where c.Status == Status.FreeUp && c.FiscalYear == DateToday.Year
select c).ToList();
foreach (var availedItem in availed)
{
foreach (var freeupItem in freeup)
{
if (availedItem.Id == freeupItem.FreeUpOriginId)
{
availedItem.Amount = availedItem.Amount - freeupItem.Amount;
}
}
}
return new JsonNetResult() { Data = availed };
```
|
2018/08/20
|
[
"https://Stackoverflow.com/questions/51925786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6701210/"
] |
Better if you use a whereIn function
```
Bidders::where(['project_id'=>$id,'active'=>1])
->whereIn('status', [1,2])
->first();
```
i think the array in the `orWhere` is create as a list of or clauses not as a and clause so you will have `or project_id = $id or active = 1 or status = 2`
if the above is true then you should do the following
```
->orWhere(function($query) {
return $query->where([
'project_id' => $id,
'status' => 2,
'active' => 1
]);
});
```
|
12,812,570 |
I understand that both `tornado` and `gevent` are asynchronous python frameworks.
While reading the [bottle documentation](http://bottlepy.org/docs/stable/async.html#the-limits-of-synchronous-wsgi) I found that gevent actually is NOT asynchronous, and you can create thousands to pseudo-threads that work synchronously.
Seondly, in gevent, you can not terminate the request handler early and you need to return the full response, while in tornado you can. (correct me if I'm wrong here)
Can some one describe in detail how these systems work internally, and in what ways they are different. Also, how does WSGI play with the asynchronous nature of these systems? Do these frameworks conform to WSGI, if yes, how?
|
2012/10/10
|
[
"https://Stackoverflow.com/questions/12812570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1206051/"
] |
The error message 'java.lang.NoSuchMethodError: org.hibernate.cfg.Environment.verifyProperties" means you do have a different version of class `org.hibernate.cfg.Environment`
Your error log says you are using mule. Mule comes with its own hibernate jar. Please check the lib directory of mule to confirm that you don't have a conflicting hibernate jars.
|
70,225,205 |
Code:
#eg. point = (1,2) and eqn = (a,b,c) where the equation is ay+bx+c=0
```
def reflect( point, eqn ):
#tuples to list
new_p = list(point)
new_eqn = list(eqn)
#sub values
p = new_p[0]
q = new_p[1]
a = new_eqn[0]
b = new_eqn[1]
c = new_eqn[2]
#formula where p'=((a^2−b^2)−2b(aq+c))/a^2+b^2
p_new = round((p*(a**2−b**2)−2*b*(a*q+c))/(a**2+b**2),1)
q_new = round((q*(b**2−a**2)−2*a*(b*p+c))/(a**2+b**2),1)
return p_new,q_new
```
error:
```
p_new = round((p*(a**2−b**2)−2*b*(a*q+c))/(a**2+b**2),1)
^
SyntaxError: invalid character in identifier
```
Q: Why is the character invalid? When I plug this into pycharm, I also get errors that my #sub values are not being used.
|
2021/12/04
|
[
"https://Stackoverflow.com/questions/70225205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17587379/"
] |
The "minus" symbol in your code isn't one, it is [Symbole Unicode «−» (U+2212)](https://www.compart.com/fr/unicode/U+2212)
```
>> ord("−") # yours
8722
>> ord("-") # the real one
45
```
Fix that and it'll work
|
247,613 |
We often say "**She's in a baseball cap and red shoes**".
Similarly, can we say "**She is in a red bracelet, a silver necklace, sun glasses and golden earrings**"?
This is a picture of a keychain and a key
[](https://i.stack.imgur.com/Cju30.jpg)
Do we say "**to put the key in or on the keychain**" and "**to put the keychain in or on the key**"?
|
2020/05/16
|
[
"https://ell.stackexchange.com/questions/247613",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/22478/"
] |
She's in (or she's wearing) clothes (including shoes and hats ... and sunglasses!) but she's wearing jewellery (not 'she's in' a necklace, bracelet or nose piercing).
'To put a dog on a chain' and 'to put a chain on a dog' are equivalent. The same applies to key chains (or key rings) and keys.
'To put something *in* a chain' is usually to make something figuratively or literally a link in a chain (and not to add something to the end of the chain).
To put lots of things in a chain is to make a chain in which each of your things forms a link. "He put the daisies in a chain to make a floral crown."
|
37,123,747 |
Hello I got question regarding setting a background-image whenever I hover on an element of my submmenu. I have the following HTML:
```
<div class="navbar navbar-default main-nav">
<div class="container">
<div class="navbar-header" tabindex="-1">
<button type="button" class="navbar-toggle collapsed">
</button>
</div>
<div class="collapse navbar-collapse" tabindex="-1">
<div class="nav navbar-nav" tabindex="-1">
<div class="menuitem_wrapper" tabindex="-1">
<a class="home_button not_active" href="#"></a>
<div class="dropdown-menu" tabindex="-1">
<a href="#">My data</a>
</div>
</div>
<div class="menuitem_wrapper" tabindex="-1">
<a href="#">Menu 1</a>
<div class="dropdown-menu" tabindex="-1">
<a href="#">Submenu1</a>
<a href="#">Submenu2</a>
</div>
</div>
<div class="menuitem_wrapper" tabindex="-1">
<a class="active" href="#">Menu 2</a>
<div class="dropdown-menu" tabindex="-1">
<a href="#">submenu1</a>
<a href="#">submenu2</a>
</div>
</div>
<a href="#">FAQ</a>
<a href="#">Contact</a>
<a href="#">Logout</a></div>
</div>
</div>
</div>
```
I know this is not the proper way to generate a menu with submenu items but despite this, how could I get my grey home button (which becomes visible after hovering on the home button) to stay visible whenever I hover on the "**my data"** button? Is this possible with pure CSS?
I have a demo here: [JSFIDDLE](https://jsfiddle.net/13Lea4tk/)
|
2016/05/09
|
[
"https://Stackoverflow.com/questions/37123747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1976975/"
] |
Change this:
```
.not_active:hover {
background-image: url(https://jira.transvar.org/secure/attachmentzip/unzip/14790/12882%5B1%5D/Home_Icon_for_IGB_pack/home_icon_grey_128x128_more_space_16x16.pn);
}
```
to this:
```
.not_active:hover, .menuitem_wrapper:hover .not_active {
background-image: url(https://jira.transvar.org/secure/attachmentzip/unzip/14790/12882%5B1%5D/Home_Icon_for_IGB_pack/home_icon_grey_128x128_more_space_16x16.pn);
}
```
I just added *.menuitem\_wrapper:hover .not\_active* to the same rule.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.