qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
52,004,676 |
I am trying to pass an ArrayList to a method in Java. But it gives me the error:
```
incompatible types: java.lang.String cannot be converted to java.util.List<java.lang.String>"
```
Here is the code:
```
class hello
{
public static void main()
{
List<String> iname = new ArrayList<>();
iname.add("1");
iname.add("2");
iname.add("3");
hello obj = new hello();
iname = obj.changeName(iname); //<- problem here
}
public String changeName(List<String> iname){
//...
return "some String result";
}
}
```
And it gives me the aforementioned error in this statement at "iname" in parenthesis:
```
iname = obj.changeName(iname);
```
Somebody please help me out.
|
2018/08/24
|
[
"https://Stackoverflow.com/questions/52004676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10269569/"
] |
Your method
```
public String changeName(List<String> iname)
```
has the return type **String** and you are trying to assign that String to a variable of type List when you do
```
iname = obj.changeName(iname);
```
That is not possible.
|
The problem is that you try to store the return of your `changeName` function (a `String`) in the `iname` variable, which can only hold `List<String>`. This should work:
```
String result = obj.changeName(iname);
```
The alternative would be, to change the `changeName` to return `List<String>`, and change the function's implementation accordingly.
|
52,004,676 |
I am trying to pass an ArrayList to a method in Java. But it gives me the error:
```
incompatible types: java.lang.String cannot be converted to java.util.List<java.lang.String>"
```
Here is the code:
```
class hello
{
public static void main()
{
List<String> iname = new ArrayList<>();
iname.add("1");
iname.add("2");
iname.add("3");
hello obj = new hello();
iname = obj.changeName(iname); //<- problem here
}
public String changeName(List<String> iname){
//...
return "some String result";
}
}
```
And it gives me the aforementioned error in this statement at "iname" in parenthesis:
```
iname = obj.changeName(iname);
```
Somebody please help me out.
|
2018/08/24
|
[
"https://Stackoverflow.com/questions/52004676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10269569/"
] |
Your variable `iname` is of type `List<String>` but you are attempting to return type `String` from your method `changeName(...)`.
You need to either update the method to return a type `List<String>`:
`public List<String> changeName(List<String> iname){ ... }`
Or change the variable the method is returned into like:
`String variable = obj.changeName(iname);`
|
The problem is that you try to store the return of your `changeName` function (a `String`) in the `iname` variable, which can only hold `List<String>`. This should work:
```
String result = obj.changeName(iname);
```
The alternative would be, to change the `changeName` to return `List<String>`, and change the function's implementation accordingly.
|
52,004,676 |
I am trying to pass an ArrayList to a method in Java. But it gives me the error:
```
incompatible types: java.lang.String cannot be converted to java.util.List<java.lang.String>"
```
Here is the code:
```
class hello
{
public static void main()
{
List<String> iname = new ArrayList<>();
iname.add("1");
iname.add("2");
iname.add("3");
hello obj = new hello();
iname = obj.changeName(iname); //<- problem here
}
public String changeName(List<String> iname){
//...
return "some String result";
}
}
```
And it gives me the aforementioned error in this statement at "iname" in parenthesis:
```
iname = obj.changeName(iname);
```
Somebody please help me out.
|
2018/08/24
|
[
"https://Stackoverflow.com/questions/52004676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10269569/"
] |
`iname` is `List<String>`, while the return type of method `changeName` is `String`.
If you want to return `List<String>`, you can declare it this way:
```
public List<String> changeName(List<String> iname){
// ... you should return a List<String> in this method
}
```
|
Your method returns String, but you are trying to assign return value to a List variable, so change it to
```
final String someString = obj.changeName(iname);
```
|
52,004,676 |
I am trying to pass an ArrayList to a method in Java. But it gives me the error:
```
incompatible types: java.lang.String cannot be converted to java.util.List<java.lang.String>"
```
Here is the code:
```
class hello
{
public static void main()
{
List<String> iname = new ArrayList<>();
iname.add("1");
iname.add("2");
iname.add("3");
hello obj = new hello();
iname = obj.changeName(iname); //<- problem here
}
public String changeName(List<String> iname){
//...
return "some String result";
}
}
```
And it gives me the aforementioned error in this statement at "iname" in parenthesis:
```
iname = obj.changeName(iname);
```
Somebody please help me out.
|
2018/08/24
|
[
"https://Stackoverflow.com/questions/52004676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10269569/"
] |
Your method returns a simple String which is about to be assigned to a List.
Change changename to `public List<String> changeName(...)` or use a new varible which is of type String and assign the return value.
|
The problem is that you try to store the return of your `changeName` function (a `String`) in the `iname` variable, which can only hold `List<String>`. This should work:
```
String result = obj.changeName(iname);
```
The alternative would be, to change the `changeName` to return `List<String>`, and change the function's implementation accordingly.
|
52,004,676 |
I am trying to pass an ArrayList to a method in Java. But it gives me the error:
```
incompatible types: java.lang.String cannot be converted to java.util.List<java.lang.String>"
```
Here is the code:
```
class hello
{
public static void main()
{
List<String> iname = new ArrayList<>();
iname.add("1");
iname.add("2");
iname.add("3");
hello obj = new hello();
iname = obj.changeName(iname); //<- problem here
}
public String changeName(List<String> iname){
//...
return "some String result";
}
}
```
And it gives me the aforementioned error in this statement at "iname" in parenthesis:
```
iname = obj.changeName(iname);
```
Somebody please help me out.
|
2018/08/24
|
[
"https://Stackoverflow.com/questions/52004676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10269569/"
] |
Your method returns String, but you are trying to assign return value to a List variable, so change it to
```
final String someString = obj.changeName(iname);
```
|
Your method `public String changeName(List<String> iname){}` is returning a String instead of a list of Strings. Try `public List<String> changeName(List<String> iname){}` instead. The method changeName is trying to fit an entire list into a single String. If you left your program as it, then you would have to return a single item from your iname List back into the main method.
|
52,004,676 |
I am trying to pass an ArrayList to a method in Java. But it gives me the error:
```
incompatible types: java.lang.String cannot be converted to java.util.List<java.lang.String>"
```
Here is the code:
```
class hello
{
public static void main()
{
List<String> iname = new ArrayList<>();
iname.add("1");
iname.add("2");
iname.add("3");
hello obj = new hello();
iname = obj.changeName(iname); //<- problem here
}
public String changeName(List<String> iname){
//...
return "some String result";
}
}
```
And it gives me the aforementioned error in this statement at "iname" in parenthesis:
```
iname = obj.changeName(iname);
```
Somebody please help me out.
|
2018/08/24
|
[
"https://Stackoverflow.com/questions/52004676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10269569/"
] |
Your method
```
public String changeName(List<String> iname)
```
has the return type **String** and you are trying to assign that String to a variable of type List when you do
```
iname = obj.changeName(iname);
```
That is not possible.
|
Your method `public String changeName(List<String> iname){}` is returning a String instead of a list of Strings. Try `public List<String> changeName(List<String> iname){}` instead. The method changeName is trying to fit an entire list into a single String. If you left your program as it, then you would have to return a single item from your iname List back into the main method.
|
57,661,819 |
i am trying to call every value from the list and appending it to url and generating url every time for the appended value
here is mine code
```
myList = ['10026','10067','10093','10117','10132','10133','10464','10524','10654','10657','10658','10701','10809','10966','11153','11173','11327','11453','11470','11478','11488','11490','12733','12750','12754','12785','13053','13683','13895','14347','14420','14438','14452','14453','14457','14460','14755','16913','17460','17497','17500','17502','18007','18013','18058','18265','18711','18778','18779','18782','18913','19790','20105','20363','20609','20766','20770','21212','21216','21262','21471','21520','21555','21833','21946','21961','22115','22203','22994','23457','23800','24260','24590','25155','25649','25749','26021','26022']
for i in myList:
unspsc_link = f"https://order.besse.com/Orders/Search/ProductSearch?query={i}"
```
It just take only the last value
```
unspsc_link
'https://order.besse.com/Orders/Search/ProductSearch?query=26022'
```
|
2019/08/26
|
[
"https://Stackoverflow.com/questions/57661819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
One of the simple variants is to save transitions in a form of `I want to transition from X to Y while applying this function`. Enums make a good fit to enumerate all possible / valid states in a state machine. We need something to hold on to our state transitions - maybe a `Map<StateType, StateType>` ? But we also need some sort of `State` object and a way to modify it - we need a `Map<StateType, Map<StateType, Transition>>`. See below for some compiling sample code that should get you started. You can expose the `State` object however you like (maybe make it immutable?) and add transitions on the fly.
```
import java.util.EnumMap;
import java.util.Map;
import java.util.function.Function;
class StackOverflowQuestion57661787 {
enum StateType {
PENDING,
ACTIVE,
DONE
}
//Made the name explicit here to ease readability
public interface Transition extends Function<State, State> { }
public static class State {
public StateType type;
//TODO: some real data to manipulate, or make it immutable
public Object data;
}
public static class StateMachine {
private final Map<StateType, Map<StateType, Transition>> transitions =
new EnumMap<>(StateType.class);
private State state;
public StateMachine(State initialState) {
this.state = initialState;
for (StateType value : StateType.values()) {
transitions.put(value, new EnumMap<>(StateType.class));
}
}
public void addTransition(
StateType input,
StateType output,
Transition transition
) {
//TODO: handle collisions? multiple transitions for a given
// output statetype seems like a strange use-case
transitions.get(input).put(output, transition);
}
public void moveTo(StateType toType) {
Transition transition = transitions.get(state.type).get(toType);
if (transition == null) {
//TODO: handle me
throw new RuntimeException();
}
//transition should modify the states "type" too OR
//you implement it here
state = transition.apply(state);
}
public State getState() {
return state;
}
}
}
```
You will have to reach for a more sophisticated / abstracted solution if your `State` objects type is dependent on the current `StateType`.
|
If you are using Spring you can consider Spring Statemachine.
<https://projects.spring.io/spring-statemachine/>
|
57,661,819 |
i am trying to call every value from the list and appending it to url and generating url every time for the appended value
here is mine code
```
myList = ['10026','10067','10093','10117','10132','10133','10464','10524','10654','10657','10658','10701','10809','10966','11153','11173','11327','11453','11470','11478','11488','11490','12733','12750','12754','12785','13053','13683','13895','14347','14420','14438','14452','14453','14457','14460','14755','16913','17460','17497','17500','17502','18007','18013','18058','18265','18711','18778','18779','18782','18913','19790','20105','20363','20609','20766','20770','21212','21216','21262','21471','21520','21555','21833','21946','21961','22115','22203','22994','23457','23800','24260','24590','25155','25649','25749','26021','26022']
for i in myList:
unspsc_link = f"https://order.besse.com/Orders/Search/ProductSearch?query={i}"
```
It just take only the last value
```
unspsc_link
'https://order.besse.com/Orders/Search/ProductSearch?query=26022'
```
|
2019/08/26
|
[
"https://Stackoverflow.com/questions/57661819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
One of the simple variants is to save transitions in a form of `I want to transition from X to Y while applying this function`. Enums make a good fit to enumerate all possible / valid states in a state machine. We need something to hold on to our state transitions - maybe a `Map<StateType, StateType>` ? But we also need some sort of `State` object and a way to modify it - we need a `Map<StateType, Map<StateType, Transition>>`. See below for some compiling sample code that should get you started. You can expose the `State` object however you like (maybe make it immutable?) and add transitions on the fly.
```
import java.util.EnumMap;
import java.util.Map;
import java.util.function.Function;
class StackOverflowQuestion57661787 {
enum StateType {
PENDING,
ACTIVE,
DONE
}
//Made the name explicit here to ease readability
public interface Transition extends Function<State, State> { }
public static class State {
public StateType type;
//TODO: some real data to manipulate, or make it immutable
public Object data;
}
public static class StateMachine {
private final Map<StateType, Map<StateType, Transition>> transitions =
new EnumMap<>(StateType.class);
private State state;
public StateMachine(State initialState) {
this.state = initialState;
for (StateType value : StateType.values()) {
transitions.put(value, new EnumMap<>(StateType.class));
}
}
public void addTransition(
StateType input,
StateType output,
Transition transition
) {
//TODO: handle collisions? multiple transitions for a given
// output statetype seems like a strange use-case
transitions.get(input).put(output, transition);
}
public void moveTo(StateType toType) {
Transition transition = transitions.get(state.type).get(toType);
if (transition == null) {
//TODO: handle me
throw new RuntimeException();
}
//transition should modify the states "type" too OR
//you implement it here
state = transition.apply(state);
}
public State getState() {
return state;
}
}
}
```
You will have to reach for a more sophisticated / abstracted solution if your `State` objects type is dependent on the current `StateType`.
|
I have a personal design that I have used extensively that I call the 'pump'. Your state machine class has a function called 'pump' which evaluates the state and updates accordingly. Each state evaluation might require some input from an external source (controllers), like the user or an AI. These objects are required when initializing your state machine and are typically abstract implementations. You then add event callbacks that applications can override to catch events. One advantage to this approach the 'pump' method can be executed from a single or multi-thread system.
Once your machine is built you can unit test easily by simply calling pump forever and providing controllers that return random values. This would effectively be a 'monkey' test to make sure your machine can handle any combination of inputs without crashing.
Then in your application you need only provide the proper controllers based on the situation.
Below is a very rough state machine to control a hypothetical dice game. I omitted most details leaving the meat of the approach. Notice that one implementation of Player.rollDice could be a blocking method that waits for the user to hit a button to advance the game. In this scheme all of the logic to control the game is contained in the machine and can be tested independently of any UI.
```
interface Player {
boolean rollDice();
}
class Game {
int state;
Player [] players;
int currentPlayer;
int dice;
void pump() {
switch (state) {
case ROLL_DICE:
if (players[currentPlayer].rollDice()) {
dice = Math.rand() % 6 + 1;
onDiceRolled(dice);
state = TAKE_TURN;
}
break;
case TAKE_TURN:
...
break;
}
}
// base method does nothing. Users can override to handle major state transitions.
protected void onDiceRolled(int dice) {}
}
```
|
57,661,819 |
i am trying to call every value from the list and appending it to url and generating url every time for the appended value
here is mine code
```
myList = ['10026','10067','10093','10117','10132','10133','10464','10524','10654','10657','10658','10701','10809','10966','11153','11173','11327','11453','11470','11478','11488','11490','12733','12750','12754','12785','13053','13683','13895','14347','14420','14438','14452','14453','14457','14460','14755','16913','17460','17497','17500','17502','18007','18013','18058','18265','18711','18778','18779','18782','18913','19790','20105','20363','20609','20766','20770','21212','21216','21262','21471','21520','21555','21833','21946','21961','22115','22203','22994','23457','23800','24260','24590','25155','25649','25749','26021','26022']
for i in myList:
unspsc_link = f"https://order.besse.com/Orders/Search/ProductSearch?query={i}"
```
It just take only the last value
```
unspsc_link
'https://order.besse.com/Orders/Search/ProductSearch?query=26022'
```
|
2019/08/26
|
[
"https://Stackoverflow.com/questions/57661819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
One of the simple variants is to save transitions in a form of `I want to transition from X to Y while applying this function`. Enums make a good fit to enumerate all possible / valid states in a state machine. We need something to hold on to our state transitions - maybe a `Map<StateType, StateType>` ? But we also need some sort of `State` object and a way to modify it - we need a `Map<StateType, Map<StateType, Transition>>`. See below for some compiling sample code that should get you started. You can expose the `State` object however you like (maybe make it immutable?) and add transitions on the fly.
```
import java.util.EnumMap;
import java.util.Map;
import java.util.function.Function;
class StackOverflowQuestion57661787 {
enum StateType {
PENDING,
ACTIVE,
DONE
}
//Made the name explicit here to ease readability
public interface Transition extends Function<State, State> { }
public static class State {
public StateType type;
//TODO: some real data to manipulate, or make it immutable
public Object data;
}
public static class StateMachine {
private final Map<StateType, Map<StateType, Transition>> transitions =
new EnumMap<>(StateType.class);
private State state;
public StateMachine(State initialState) {
this.state = initialState;
for (StateType value : StateType.values()) {
transitions.put(value, new EnumMap<>(StateType.class));
}
}
public void addTransition(
StateType input,
StateType output,
Transition transition
) {
//TODO: handle collisions? multiple transitions for a given
// output statetype seems like a strange use-case
transitions.get(input).put(output, transition);
}
public void moveTo(StateType toType) {
Transition transition = transitions.get(state.type).get(toType);
if (transition == null) {
//TODO: handle me
throw new RuntimeException();
}
//transition should modify the states "type" too OR
//you implement it here
state = transition.apply(state);
}
public State getState() {
return state;
}
}
}
```
You will have to reach for a more sophisticated / abstracted solution if your `State` objects type is dependent on the current `StateType`.
|
I would also advice you to check two frameworks before you implement your own State Machine. State Machine theory is really complex to develop all by yourself, specially not too much mentioned concepts like Sub / Nested State Machines are a must for complex / successful State Machine designs.
One is mentioned above Spring State Machine and second is the [Akka Finite State Machine](https://doc.akka.io/docs/akka/current/typed/fsm.html).
My personal experience Spring State Machine is great for modelling things like a lifecycle of an application with states like, STARTING, INITIALISING, RUNNING, MAINTENANCE, ERROR, SHUTDOWN, etc.... but it is not that great for modelling things like Shopping Charts, Reservation, Credit Approval Processes, etc... while it has too big memory footprint to model millions of instances.
In the other hand, Akka FSM has a real small footprint and I personally implemented systems containing millions of instances of the State Machine and it has another tool that completely missing in Spring State Machine. In modern IT one thing is inevitable, change, no workflow / process that you model, will not stay same over the time, so you need mechanism to integrate these changes to your long running workflows / processes (what I mean with that, what happens if you have process that started before your latest software release and persisted with old model, now you have a new release and the model is changed, you have to read persisted process and continue with the new model). Akka a built in solution for this problem [Event / Schema Evolution](https://doc.akka.io/docs/akka/current/persistence-schema-evolution.html).
If you need examples about how the implementations of Spring State Machine you can check the following [Blog](https://mehmetsalgar.wordpress.com/2016/01/20/xtext-domain-specific-language-and-spring-state-machine/) of me, for Akka FSM examples you can check the following examples [Blog1](https://mehmetsalgar.wordpress.com/2022/05/17/model-driven-akka-finite-state-machine-fsm/), [Blog2](https://mehmetsalgar.wordpress.com/2022/04/18/a-model-driven-event-sourced-cloud-ready-application-with-akka-finite-state-machine-using-kafka-cassandra-and-elasticsearch/).
I hope this would help.
|
57,661,819 |
i am trying to call every value from the list and appending it to url and generating url every time for the appended value
here is mine code
```
myList = ['10026','10067','10093','10117','10132','10133','10464','10524','10654','10657','10658','10701','10809','10966','11153','11173','11327','11453','11470','11478','11488','11490','12733','12750','12754','12785','13053','13683','13895','14347','14420','14438','14452','14453','14457','14460','14755','16913','17460','17497','17500','17502','18007','18013','18058','18265','18711','18778','18779','18782','18913','19790','20105','20363','20609','20766','20770','21212','21216','21262','21471','21520','21555','21833','21946','21961','22115','22203','22994','23457','23800','24260','24590','25155','25649','25749','26021','26022']
for i in myList:
unspsc_link = f"https://order.besse.com/Orders/Search/ProductSearch?query={i}"
```
It just take only the last value
```
unspsc_link
'https://order.besse.com/Orders/Search/ProductSearch?query=26022'
```
|
2019/08/26
|
[
"https://Stackoverflow.com/questions/57661819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
If you are using Spring you can consider Spring Statemachine.
<https://projects.spring.io/spring-statemachine/>
|
I have a personal design that I have used extensively that I call the 'pump'. Your state machine class has a function called 'pump' which evaluates the state and updates accordingly. Each state evaluation might require some input from an external source (controllers), like the user or an AI. These objects are required when initializing your state machine and are typically abstract implementations. You then add event callbacks that applications can override to catch events. One advantage to this approach the 'pump' method can be executed from a single or multi-thread system.
Once your machine is built you can unit test easily by simply calling pump forever and providing controllers that return random values. This would effectively be a 'monkey' test to make sure your machine can handle any combination of inputs without crashing.
Then in your application you need only provide the proper controllers based on the situation.
Below is a very rough state machine to control a hypothetical dice game. I omitted most details leaving the meat of the approach. Notice that one implementation of Player.rollDice could be a blocking method that waits for the user to hit a button to advance the game. In this scheme all of the logic to control the game is contained in the machine and can be tested independently of any UI.
```
interface Player {
boolean rollDice();
}
class Game {
int state;
Player [] players;
int currentPlayer;
int dice;
void pump() {
switch (state) {
case ROLL_DICE:
if (players[currentPlayer].rollDice()) {
dice = Math.rand() % 6 + 1;
onDiceRolled(dice);
state = TAKE_TURN;
}
break;
case TAKE_TURN:
...
break;
}
}
// base method does nothing. Users can override to handle major state transitions.
protected void onDiceRolled(int dice) {}
}
```
|
57,661,819 |
i am trying to call every value from the list and appending it to url and generating url every time for the appended value
here is mine code
```
myList = ['10026','10067','10093','10117','10132','10133','10464','10524','10654','10657','10658','10701','10809','10966','11153','11173','11327','11453','11470','11478','11488','11490','12733','12750','12754','12785','13053','13683','13895','14347','14420','14438','14452','14453','14457','14460','14755','16913','17460','17497','17500','17502','18007','18013','18058','18265','18711','18778','18779','18782','18913','19790','20105','20363','20609','20766','20770','21212','21216','21262','21471','21520','21555','21833','21946','21961','22115','22203','22994','23457','23800','24260','24590','25155','25649','25749','26021','26022']
for i in myList:
unspsc_link = f"https://order.besse.com/Orders/Search/ProductSearch?query={i}"
```
It just take only the last value
```
unspsc_link
'https://order.besse.com/Orders/Search/ProductSearch?query=26022'
```
|
2019/08/26
|
[
"https://Stackoverflow.com/questions/57661819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
If you are using Spring you can consider Spring Statemachine.
<https://projects.spring.io/spring-statemachine/>
|
I would also advice you to check two frameworks before you implement your own State Machine. State Machine theory is really complex to develop all by yourself, specially not too much mentioned concepts like Sub / Nested State Machines are a must for complex / successful State Machine designs.
One is mentioned above Spring State Machine and second is the [Akka Finite State Machine](https://doc.akka.io/docs/akka/current/typed/fsm.html).
My personal experience Spring State Machine is great for modelling things like a lifecycle of an application with states like, STARTING, INITIALISING, RUNNING, MAINTENANCE, ERROR, SHUTDOWN, etc.... but it is not that great for modelling things like Shopping Charts, Reservation, Credit Approval Processes, etc... while it has too big memory footprint to model millions of instances.
In the other hand, Akka FSM has a real small footprint and I personally implemented systems containing millions of instances of the State Machine and it has another tool that completely missing in Spring State Machine. In modern IT one thing is inevitable, change, no workflow / process that you model, will not stay same over the time, so you need mechanism to integrate these changes to your long running workflows / processes (what I mean with that, what happens if you have process that started before your latest software release and persisted with old model, now you have a new release and the model is changed, you have to read persisted process and continue with the new model). Akka a built in solution for this problem [Event / Schema Evolution](https://doc.akka.io/docs/akka/current/persistence-schema-evolution.html).
If you need examples about how the implementations of Spring State Machine you can check the following [Blog](https://mehmetsalgar.wordpress.com/2016/01/20/xtext-domain-specific-language-and-spring-state-machine/) of me, for Akka FSM examples you can check the following examples [Blog1](https://mehmetsalgar.wordpress.com/2022/05/17/model-driven-akka-finite-state-machine-fsm/), [Blog2](https://mehmetsalgar.wordpress.com/2022/04/18/a-model-driven-event-sourced-cloud-ready-application-with-akka-finite-state-machine-using-kafka-cassandra-and-elasticsearch/).
I hope this would help.
|
71,563,517 |
I am using the staggered grid view package. How do I make the images within my staggered grid view clickable? I have tried adding in the GestureDetector function but I do not know where exactly I should input it into the code.
here is my code
```
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
class ExploreGridView extends StatelessWidget {
const ExploreGridView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) => StaggeredGridView.countBuilder(
staggeredTileBuilder: (index) => StaggeredTile.fit(2),
crossAxisCount: 4,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
itemCount: 12,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, index) => buildImageCard(index),
);
Widget buildImageCard(int index) => Card(
margin: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
child: Container(
decoration: BoxDecoration(
color: Colors.grey[850],
borderRadius: BorderRadius.only(
topLeft: Radius.circular(12),
topRight: Radius.circular(12),
bottomLeft: Radius.circular(12),
bottomRight: Radius.circular(12)),
boxShadow: [
BoxShadow(
color: Colors.black,
offset: Offset(5.0, 5.0),
blurRadius: 15.0,
spreadRadius: 1.0),
],
),
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: Image.network(_NFTImgurls[index]),
),
),
);
}
List<String> _NFTImgurls = [
'https://res.cloudinary.com/nifty-gateway/video/upload/v1607376477/beepleopenedition/BEEPLE_2020COLLECTION_INTO-THE-ETHER_wv3eyt.png',
'https://res.cloudinary.com/nifty-gateway/video/upload/v1613576449/A/MadDogJones/MDJ_-_Escalation_C2_iskzf4.png',
'https://res.cloudinary.com/nifty-gateway/video/upload/v1610827318/A/Billelis/%CE%9A%CE%91%CE%98%CE%91%CE%A1%CE%A3%CE%99%CE%A3_udzhmj.png',
'https://res.cloudinary.com/nifty-gateway/video/upload/v1610463118/A/DeadmauMadDog/MDJxDeadmau5_Dead_ramen_md6abq.png',
'https://res.cloudinary.com/nifty-gateway/video/upload/v1614741616/Ashley/AndreasWannerstedt3/the_smooth_saint_-_Andreas_Wannerstedt_jetmhb.png',
'https://res.cloudinary.com/nifty-gateway/video/upload/v1614650252/A/SteveAoki/character_X_-_Carly_Bernstein_rgtnih.png',
'https://res.cloudinary.com/nifty-gateway/video/upload/v1605799567/MadDogJones/MDJ_-_Ideas_r_the_currency_e1o1r2.png',
'https://res.cloudinary.com/nifty-gateway/video/upload/v1629082199/Andrea/NessGraphics/NessGraphics_L0G1ST1CS_Final_cg81g5.png',
'https://res.cloudinary.com/nifty-gateway/video/upload/v1607532674/beepleopenedition/BEEPLE_2020COLLECTION_BULL-RUN_bqjzfj.png',
'https://res.cloudinary.com/nifty-gateway/video/upload/v1614741607/Ashley/AndreasWannerstedt3/the_open_hand_-_Andreas_Wannerstedt_au1bjs.png',
'https://res.cloudinary.com/nifty-gateway/video/upload/v1613507277/A/MadDogJones/Why_would_I_care__I_m_just_a_cat_1_tvtdr3.png',
'https://res.cloudinary.com/nifty-gateway/video/upload/v1618196543/Pak/ACube.png',
];
```
|
2022/03/21
|
[
"https://Stackoverflow.com/questions/71563517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15244204/"
] |
The code works in bash, you just need to run it in the right shell, you can do the following:
```
bash ./script.sh g
```
Also type `ps -p $$` (not `echo $SHELL`) to see what shell you are currently in:
Examples:
```
# ps -p $$
PID TTY TIME CMD
25583 pts/0 00:00:00 sh
# exit
# ps -p $$
PID TTY TIME CMD
22538 pts/0 00:00:00 bash
```
* $SHELL is to tell you what the current user has but you can change on the fly so that is why the other command is more useful.
* Borne shell (sh) does not play as nicely with arrays. You have to use eval.
* change your default shell to bash. Ref: <https://www.tecmint.com/change-a-users-default-shell-in-linux/>
|
I just reach my goal with this !
```
#!/bin/bash
inputsArr=("ab" "67" "7b7" "g" "67777" "07x7g7" "77777" "7777" "")
for input in ${inputsArr[@]}; do [[ "$input" =~ $1 ]]; echo "$?" ; done
```
I would like to say thanks you to every person that give me some tips on this basic BASH script problem. Without you I would certainly not reach my goal by my own way and it is beautiful to see this cooperation in action.
|
12,983,028 |
Suppose I have a snippet like the following which returns the contents of Context.Cache["someComplexObject"]:
```
public class Something {
private static SortedDictionary<Guid, Object> ComplexObjectCache
{
get
{
if (Context.Cache["someComplexObject"] == null)
{
FillCache();
}
return (SortedDictionary<Guid, Object>)Context.Cache["someComplexObject"];
}
set
{
Int32 seconds = (new Random()).Next(120, 180);
Context.Cache.Add(
"someComplexObject",
value,
null,
DateTime.Now.AddSeconds(seconds),
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.NotRemovable,
null
);
}
}
}
```
And in a user control, suppose I have this:
```
Object o = Something.ComplexObjectCache[someGuid];
/*
do some other stuff ...
*/
DoSomethingWith(o);
```
On very rare occasional, I've seen exceptions which would lead me to believe that **o** is no longer in memory when **DoSomethingWith(o)** is hit. I'm 97% sure there's are no other parallel processes occurring, other than whatever the cache is doing. I'm seeing other weird phenomena that would lead me to believe the cache key is either empty or incomplete.
Can/Will the cache really remove an object from memory, even if there's still a pointer to it elsewhere? If so, how do I combat that?
UPDATE
------
After further digging, I found that we had a **related** cache item (an index) that's causing issues when it expires prior to the "main" cache item. I've redone the caching code for this entity to store these two structures *together* in an Object array. This seems to have solved the problem.
None of you had enough information to solve the problem. So, I'll review the answers and give the checkmark to whichever answer seems to have most accurately addressed the question *as given*.
|
2012/10/19
|
[
"https://Stackoverflow.com/questions/12983028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/779572/"
] |
The cache will never remove anything from memory.
It's the garbage collector that removes object from memory, and that can happen only when there are no more references to the object. So, the objects will not be removed from memory, even if they are dropped from the cache, as long as you have a reference to it.
(The cache can drop references to objects mid request. As several threads can handle requests at the same time, something can happen in a different thread that makes the cache drop items. The cache can't wait until all threads are idle to drop items, then it might never be able to do that, and you would run out of memory.)
|
Cache is free to remove objects whenever it feels so. I.e. it can detect memory pressure and drop items as soon as you add them.
You really should not be using Cache to pass objects around. Cache is cache - store objects to speed things up in future, but use other means to pass objects during single request. Also note that Cache is shared unlike something like [Items](http://msdn.microsoft.com/en-us/library/system.web.httpcontext.items.aspx).
|
12,983,028 |
Suppose I have a snippet like the following which returns the contents of Context.Cache["someComplexObject"]:
```
public class Something {
private static SortedDictionary<Guid, Object> ComplexObjectCache
{
get
{
if (Context.Cache["someComplexObject"] == null)
{
FillCache();
}
return (SortedDictionary<Guid, Object>)Context.Cache["someComplexObject"];
}
set
{
Int32 seconds = (new Random()).Next(120, 180);
Context.Cache.Add(
"someComplexObject",
value,
null,
DateTime.Now.AddSeconds(seconds),
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.NotRemovable,
null
);
}
}
}
```
And in a user control, suppose I have this:
```
Object o = Something.ComplexObjectCache[someGuid];
/*
do some other stuff ...
*/
DoSomethingWith(o);
```
On very rare occasional, I've seen exceptions which would lead me to believe that **o** is no longer in memory when **DoSomethingWith(o)** is hit. I'm 97% sure there's are no other parallel processes occurring, other than whatever the cache is doing. I'm seeing other weird phenomena that would lead me to believe the cache key is either empty or incomplete.
Can/Will the cache really remove an object from memory, even if there's still a pointer to it elsewhere? If so, how do I combat that?
UPDATE
------
After further digging, I found that we had a **related** cache item (an index) that's causing issues when it expires prior to the "main" cache item. I've redone the caching code for this entity to store these two structures *together* in an Object array. This seems to have solved the problem.
None of you had enough information to solve the problem. So, I'll review the answers and give the checkmark to whichever answer seems to have most accurately addressed the question *as given*.
|
2012/10/19
|
[
"https://Stackoverflow.com/questions/12983028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/779572/"
] |
Yes it will. If the web server is pressed for memory even code like this will fail to print "foo".
```
Context.Cache.Add(
"someComplexObject",
"foo",
null,
DateTime.Now.AddSeconds(seconds),
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.NotRemovable,
null
);
Response.Write(Cache["someComplexObject").ToString());
```
You need to do something smart, like
```
string val = "foo";
Context.Cache.Add(
"someComplexObject",
val,
null,
DateTime.Now.AddSeconds(seconds),
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.NotRemovable,
null
);
Response.Write(val.ToString());
```
Also, you need to lock any time you read or write to the cache. You can use a ReaderWriterLock (or similar) for this. This is to avoid reads when the cache is being written (and writes when the cache is being read).
I've implemented a couple of caches for the [SixPack library](http://code.google.com/p/sixpack-library), which you may find interesting, for example see this [CacheController](http://code.google.com/p/sixpack-library/source/browse/branches/dotnet2.0/src/SixPack/ComponentModel/CacheController.cs) class.
As a side note, that class is a tad more complex than you need because it's part of a system to allow you to cache like so:
```
[Cached]
public class MyTime : ContextBoundObject
{
[CachedMethod(1)]
public DateTime Get()
{
Console.WriteLine("Get invoked.");
return DateTime.Now;
}
public DateTime GetNoCache()
{
Console.WriteLine("GetNoCache invoked.");
return DateTime.Now;
}
}
```
[Full Example](http://code.google.com/p/sixpack-library/wiki/Caching)
[NuGet package](http://nuget.org/packages/SixPack)
|
Cache is free to remove objects whenever it feels so. I.e. it can detect memory pressure and drop items as soon as you add them.
You really should not be using Cache to pass objects around. Cache is cache - store objects to speed things up in future, but use other means to pass objects during single request. Also note that Cache is shared unlike something like [Items](http://msdn.microsoft.com/en-us/library/system.web.httpcontext.items.aspx).
|
12,983,028 |
Suppose I have a snippet like the following which returns the contents of Context.Cache["someComplexObject"]:
```
public class Something {
private static SortedDictionary<Guid, Object> ComplexObjectCache
{
get
{
if (Context.Cache["someComplexObject"] == null)
{
FillCache();
}
return (SortedDictionary<Guid, Object>)Context.Cache["someComplexObject"];
}
set
{
Int32 seconds = (new Random()).Next(120, 180);
Context.Cache.Add(
"someComplexObject",
value,
null,
DateTime.Now.AddSeconds(seconds),
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.NotRemovable,
null
);
}
}
}
```
And in a user control, suppose I have this:
```
Object o = Something.ComplexObjectCache[someGuid];
/*
do some other stuff ...
*/
DoSomethingWith(o);
```
On very rare occasional, I've seen exceptions which would lead me to believe that **o** is no longer in memory when **DoSomethingWith(o)** is hit. I'm 97% sure there's are no other parallel processes occurring, other than whatever the cache is doing. I'm seeing other weird phenomena that would lead me to believe the cache key is either empty or incomplete.
Can/Will the cache really remove an object from memory, even if there's still a pointer to it elsewhere? If so, how do I combat that?
UPDATE
------
After further digging, I found that we had a **related** cache item (an index) that's causing issues when it expires prior to the "main" cache item. I've redone the caching code for this entity to store these two structures *together* in an Object array. This seems to have solved the problem.
None of you had enough information to solve the problem. So, I'll review the answers and give the checkmark to whichever answer seems to have most accurately addressed the question *as given*.
|
2012/10/19
|
[
"https://Stackoverflow.com/questions/12983028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/779572/"
] |
The cache will never remove anything from memory.
It's the garbage collector that removes object from memory, and that can happen only when there are no more references to the object. So, the objects will not be removed from memory, even if they are dropped from the cache, as long as you have a reference to it.
(The cache can drop references to objects mid request. As several threads can handle requests at the same time, something can happen in a different thread that makes the cache drop items. The cache can't wait until all threads are idle to drop items, then it might never be able to do that, and you would run out of memory.)
|
Yes, your FillCache method is populating the cache, but there is time between that and when you retrieve the contents of the cache. In this time your cache can be invalidated. Try returning from your FillCache method so you always have a solid reference:
```
private SortedDictionary<Guid, Object> ComplexObjectCache()
{
if (Context.Cache["someComplexObject"] == null)
{
var cacheItems = FillCache();
return cacheItems;
}
return (SortedDictionary<Guid, Object>)Context.Cache["someComplexObject"];
}
```
|
12,983,028 |
Suppose I have a snippet like the following which returns the contents of Context.Cache["someComplexObject"]:
```
public class Something {
private static SortedDictionary<Guid, Object> ComplexObjectCache
{
get
{
if (Context.Cache["someComplexObject"] == null)
{
FillCache();
}
return (SortedDictionary<Guid, Object>)Context.Cache["someComplexObject"];
}
set
{
Int32 seconds = (new Random()).Next(120, 180);
Context.Cache.Add(
"someComplexObject",
value,
null,
DateTime.Now.AddSeconds(seconds),
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.NotRemovable,
null
);
}
}
}
```
And in a user control, suppose I have this:
```
Object o = Something.ComplexObjectCache[someGuid];
/*
do some other stuff ...
*/
DoSomethingWith(o);
```
On very rare occasional, I've seen exceptions which would lead me to believe that **o** is no longer in memory when **DoSomethingWith(o)** is hit. I'm 97% sure there's are no other parallel processes occurring, other than whatever the cache is doing. I'm seeing other weird phenomena that would lead me to believe the cache key is either empty or incomplete.
Can/Will the cache really remove an object from memory, even if there's still a pointer to it elsewhere? If so, how do I combat that?
UPDATE
------
After further digging, I found that we had a **related** cache item (an index) that's causing issues when it expires prior to the "main" cache item. I've redone the caching code for this entity to store these two structures *together* in an Object array. This seems to have solved the problem.
None of you had enough information to solve the problem. So, I'll review the answers and give the checkmark to whichever answer seems to have most accurately addressed the question *as given*.
|
2012/10/19
|
[
"https://Stackoverflow.com/questions/12983028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/779572/"
] |
Yes it will. If the web server is pressed for memory even code like this will fail to print "foo".
```
Context.Cache.Add(
"someComplexObject",
"foo",
null,
DateTime.Now.AddSeconds(seconds),
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.NotRemovable,
null
);
Response.Write(Cache["someComplexObject").ToString());
```
You need to do something smart, like
```
string val = "foo";
Context.Cache.Add(
"someComplexObject",
val,
null,
DateTime.Now.AddSeconds(seconds),
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.NotRemovable,
null
);
Response.Write(val.ToString());
```
Also, you need to lock any time you read or write to the cache. You can use a ReaderWriterLock (or similar) for this. This is to avoid reads when the cache is being written (and writes when the cache is being read).
I've implemented a couple of caches for the [SixPack library](http://code.google.com/p/sixpack-library), which you may find interesting, for example see this [CacheController](http://code.google.com/p/sixpack-library/source/browse/branches/dotnet2.0/src/SixPack/ComponentModel/CacheController.cs) class.
As a side note, that class is a tad more complex than you need because it's part of a system to allow you to cache like so:
```
[Cached]
public class MyTime : ContextBoundObject
{
[CachedMethod(1)]
public DateTime Get()
{
Console.WriteLine("Get invoked.");
return DateTime.Now;
}
public DateTime GetNoCache()
{
Console.WriteLine("GetNoCache invoked.");
return DateTime.Now;
}
}
```
[Full Example](http://code.google.com/p/sixpack-library/wiki/Caching)
[NuGet package](http://nuget.org/packages/SixPack)
|
Yes, your FillCache method is populating the cache, but there is time between that and when you retrieve the contents of the cache. In this time your cache can be invalidated. Try returning from your FillCache method so you always have a solid reference:
```
private SortedDictionary<Guid, Object> ComplexObjectCache()
{
if (Context.Cache["someComplexObject"] == null)
{
var cacheItems = FillCache();
return cacheItems;
}
return (SortedDictionary<Guid, Object>)Context.Cache["someComplexObject"];
}
```
|
12,983,028 |
Suppose I have a snippet like the following which returns the contents of Context.Cache["someComplexObject"]:
```
public class Something {
private static SortedDictionary<Guid, Object> ComplexObjectCache
{
get
{
if (Context.Cache["someComplexObject"] == null)
{
FillCache();
}
return (SortedDictionary<Guid, Object>)Context.Cache["someComplexObject"];
}
set
{
Int32 seconds = (new Random()).Next(120, 180);
Context.Cache.Add(
"someComplexObject",
value,
null,
DateTime.Now.AddSeconds(seconds),
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.NotRemovable,
null
);
}
}
}
```
And in a user control, suppose I have this:
```
Object o = Something.ComplexObjectCache[someGuid];
/*
do some other stuff ...
*/
DoSomethingWith(o);
```
On very rare occasional, I've seen exceptions which would lead me to believe that **o** is no longer in memory when **DoSomethingWith(o)** is hit. I'm 97% sure there's are no other parallel processes occurring, other than whatever the cache is doing. I'm seeing other weird phenomena that would lead me to believe the cache key is either empty or incomplete.
Can/Will the cache really remove an object from memory, even if there's still a pointer to it elsewhere? If so, how do I combat that?
UPDATE
------
After further digging, I found that we had a **related** cache item (an index) that's causing issues when it expires prior to the "main" cache item. I've redone the caching code for this entity to store these two structures *together* in an Object array. This seems to have solved the problem.
None of you had enough information to solve the problem. So, I'll review the answers and give the checkmark to whichever answer seems to have most accurately addressed the question *as given*.
|
2012/10/19
|
[
"https://Stackoverflow.com/questions/12983028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/779572/"
] |
The cache will never remove anything from memory.
It's the garbage collector that removes object from memory, and that can happen only when there are no more references to the object. So, the objects will not be removed from memory, even if they are dropped from the cache, as long as you have a reference to it.
(The cache can drop references to objects mid request. As several threads can handle requests at the same time, something can happen in a different thread that makes the cache drop items. The cache can't wait until all threads are idle to drop items, then it might never be able to do that, and you would run out of memory.)
|
Yes it will. If the web server is pressed for memory even code like this will fail to print "foo".
```
Context.Cache.Add(
"someComplexObject",
"foo",
null,
DateTime.Now.AddSeconds(seconds),
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.NotRemovable,
null
);
Response.Write(Cache["someComplexObject").ToString());
```
You need to do something smart, like
```
string val = "foo";
Context.Cache.Add(
"someComplexObject",
val,
null,
DateTime.Now.AddSeconds(seconds),
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.NotRemovable,
null
);
Response.Write(val.ToString());
```
Also, you need to lock any time you read or write to the cache. You can use a ReaderWriterLock (or similar) for this. This is to avoid reads when the cache is being written (and writes when the cache is being read).
I've implemented a couple of caches for the [SixPack library](http://code.google.com/p/sixpack-library), which you may find interesting, for example see this [CacheController](http://code.google.com/p/sixpack-library/source/browse/branches/dotnet2.0/src/SixPack/ComponentModel/CacheController.cs) class.
As a side note, that class is a tad more complex than you need because it's part of a system to allow you to cache like so:
```
[Cached]
public class MyTime : ContextBoundObject
{
[CachedMethod(1)]
public DateTime Get()
{
Console.WriteLine("Get invoked.");
return DateTime.Now;
}
public DateTime GetNoCache()
{
Console.WriteLine("GetNoCache invoked.");
return DateTime.Now;
}
}
```
[Full Example](http://code.google.com/p/sixpack-library/wiki/Caching)
[NuGet package](http://nuget.org/packages/SixPack)
|
13,721,250 |
I am creating a program that has a double array list of a deck of cards. There are two "hands" that will be dealt from this ONE deck. 5 unique cards must be dealt to "comHand" which is a double array which stores the 5 cards. the first [] stores which iteration of the cards being dealt (1st card, 2nd card, etc) and the second [] stores the suit of the card in [0] and the number of the card in [1].
I simplified my code to make sure I get 3 unique draws. There is only one suit and 3 possible numbers to choose from. My code works fine above the /// (the two numbers are always unique). However the code below doesn't yield a unique number sometimes. Can I get some help discerning why this is?
```
int comHand [][] = new int [5][2];
card1 = (int) (Math.random()*1);
card2 = (int) (Math.random()*3);
comHand[0][0] = card1;
comHand[0][1] = card2;
card1 = (int) (Math.random()*1);
card2 = (int) (Math.random()*3);
while (card1 == comHand[0][0] && card2 == comHand[0][1]){
card1 = (int) (Math.random()*1);
card2 = (int) (Math.random()*3);}
comHand[1][0] = card1;
comHand[1][1] = card2;
///
card1 = (int) (Math.random()*1);
card2 = (int) (Math.random()*3);
while (card1 == comHand[0][0] && card2 == comHand[0][1]){
card1 = (int) (Math.random()*1);
card2 = (int) (Math.random()*3);}
while (card1 == comHand[1][0] && card2 == comHand[1][1]){
card1 = (int) (Math.random()*1);
card2 = (int) (Math.random()*3);}
comHand[2][0] = card1;
comHand[2][1] = card2;
```
|
2012/12/05
|
[
"https://Stackoverflow.com/questions/13721250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1371110/"
] |
```
int comHand [][] = new int [5][2];
ArrayList<Integer> cards = new ArrayList<Integer>();
int totalCards = 52; //Cards in a pack
for(int x = 1; x <= totalCards; x++)
{
cards.add(x);
}
//Repeat for 5 cards
for(int y = 0; y < 5; y++)
{
int selectCard = (int)(Math.random()*cards.size()-1);
comHand[y][0] = cards.get(selectCard) % 13; //13 cards per suit
comHand[y][1] = cards.get(selectCard) / 13;
cards.remove(selectCard);
}
```
Hopefully this is what you were after.
|
You cannot be sure by Using a random in getting a unique in consecutive draws.
Maintain an array, storing the draws of one transaction, and if you get any draw which is present in the array, continue generating a new Random number
|
13,721,250 |
I am creating a program that has a double array list of a deck of cards. There are two "hands" that will be dealt from this ONE deck. 5 unique cards must be dealt to "comHand" which is a double array which stores the 5 cards. the first [] stores which iteration of the cards being dealt (1st card, 2nd card, etc) and the second [] stores the suit of the card in [0] and the number of the card in [1].
I simplified my code to make sure I get 3 unique draws. There is only one suit and 3 possible numbers to choose from. My code works fine above the /// (the two numbers are always unique). However the code below doesn't yield a unique number sometimes. Can I get some help discerning why this is?
```
int comHand [][] = new int [5][2];
card1 = (int) (Math.random()*1);
card2 = (int) (Math.random()*3);
comHand[0][0] = card1;
comHand[0][1] = card2;
card1 = (int) (Math.random()*1);
card2 = (int) (Math.random()*3);
while (card1 == comHand[0][0] && card2 == comHand[0][1]){
card1 = (int) (Math.random()*1);
card2 = (int) (Math.random()*3);}
comHand[1][0] = card1;
comHand[1][1] = card2;
///
card1 = (int) (Math.random()*1);
card2 = (int) (Math.random()*3);
while (card1 == comHand[0][0] && card2 == comHand[0][1]){
card1 = (int) (Math.random()*1);
card2 = (int) (Math.random()*3);}
while (card1 == comHand[1][0] && card2 == comHand[1][1]){
card1 = (int) (Math.random()*1);
card2 = (int) (Math.random()*3);}
comHand[2][0] = card1;
comHand[2][1] = card2;
```
|
2012/12/05
|
[
"https://Stackoverflow.com/questions/13721250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1371110/"
] |
Your while loops seem to have a wrong condition. Try || instead of &&:
```
while (card1 == comHand[0][0] || card2 == comHand[0][1]) {
card1 = (int) (Math.random()*1);
card2 = (int) (Math.random()*3);
}
```
I'd try another approach since "repeat Math.random() until everything works" is not a good algorithm. It's hard to predict how many steps the algorithm will need to finish (and whether it will always finish).
Use objects for cards instead of int arrays. Pick the cards from a collection using Math.random (or Random) and remove the selected card from that collection. That way it won't get selected again. Or build a deck, shuffle it and just pop top cards from the deck until done. That's very easy to implement.
|
You cannot be sure by Using a random in getting a unique in consecutive draws.
Maintain an array, storing the draws of one transaction, and if you get any draw which is present in the array, continue generating a new Random number
|
94,425 |
I am using ubuntu Empathy IM client for my Gmail account chatting .Can any one tell me how to clear the previos conversations in the Empathy IM client.I tried right click and clear.But it is clearing temporarily but not permanent.Is there any way to clear that?
|
2010/01/10
|
[
"https://superuser.com/questions/94425",
"https://superuser.com",
"https://superuser.com/users/12572/"
] |
The GUI method of clearing previous messages for an account in empathy consists of right clicking a buddy in the contact list, selecting "previous conversations", and subsequently selecting "Edit"->"Clear" in the popup window. Then, select the account you'd like to clear the logs on and confirm deletion of your logs.
|
Logs for empathy are stored in `/home/<username>/.local/share/Empathy/`
Hope this helps :)
|
185,359 |
My category structure is as follows:
```
- Top Category
---- Sub Category 1
------- Sub Sub Category 1.1
------- Sub Sub Category 1.2
------- Sub Sub Category 1.3
---- Sub Category 2
------- Sub Sub Category 2.1
------- Sub Sub Category 2.2
------- Sub Sub Category 2.3
```
I'm on a post under 1.2 so it would be:
```
Top Category -> Sub Category 1 -> Sub Sub Category 1.2 -> Current Post
```
NB: In the post ONLY "Sub Category 1" and "Sub Sub Category 1.2" are selected as categories ("Top Category" is not checked).
Now, how do I get get the slug of the Top Category ("top-category"), navigating backward?
Thanks!
|
2015/04/25
|
[
"https://wordpress.stackexchange.com/questions/185359",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/56525/"
] |
[`get_ancestors()`](http://codex.wordpress.org/Function_Reference/get_ancestors) returns an array containing the parents of any given object.
This example has two categories. The parent with the id of 447 and the child with a id of 448 and returns the a category hierarchy (with IDs):
```
get_ancestors( 448, 'category' );
```
returns:
```
Array
(
[0] => 447
)
```
[get\_ancestors Codex Page](http://codex.wordpress.org/Function_Reference/get_ancestors)
----------------------------------------------------------------------------------------
|
[get\_ancestors()](https://developer.wordpress.org/reference/functions/get_ancestors/)
Is the correct way to get all the parent categories of a specific category in the hierarchical order, so to get the highest level parent you could extract the last item of the array returned like this:
```
// getting all the ancestors of the categories
$ancestor_cat_ids = get_ancestors( $queried_cat_id, 'category');
// getting the last item of the array of ids returned by the get_ancestors() function
$highest_ancestor = $ancestor_cat_ids[count($ancestor_cat_ids) - 1];
```
|
35,063,889 |
```
compile 'com.google.android.gms:play-services:8.3.0'
compile 'com.android.support:support-v4:22.2.1'
compile 'com.android.support:design:22.2.1'
```
to
```
compile 'com.google.android.gms:play-services:8.4.0'
compile 'com.android.support:support-v4:23.1.0'
compile 'com.android.support:design:23.1.0'
```
Time to time, android studio will automatically change the values to the latest version which is extremely annoying and breaks my application. Is there a way to prevent this from happening?
Did a google search and stackoverflow searched but nothing came up.
|
2016/01/28
|
[
"https://Stackoverflow.com/questions/35063889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469890/"
] |
Instead of:
```
compile 'com.google.android.gms:play-services:8.3.0'
compile 'com.android.support:support-v4:22.2.1'
compile 'com.android.support:design:22.2.1'
```
try:
```
playVersion = '8.3.0'
supportVersion = 'support-v4:22.2.1'
designVersion = '22.2.1'
compile "com.google.android.gms:play-services:$playVersion"
compile "com.android.support:$supportVersion"
compile "com.android.support:design:$designVersion"
```
**Remember** to replace the `'`s with `"`s.
|
**Android Studio doesn't update the dependencies if you specify the version**
Example:
```
compile 'com.google.android.gms:play-services:8.3.0'
compile 'com.android.support:support-v4:22.2.1'
compile 'com.android.support:design:22.2.1'
```
In this case AS will tell you when there is a newer version **without updating them.**
If you the `+` in your dependencies **gradle updates with the latest version** according to the `build.gradle`.
For example:
```
compile 'com.android.support:support-v4:22.2.+'
compile 'com.android.support:support-v4:22.+'
compile 'com.android.support:support-v4:+'
```
It is a good practice to avoid it.
|
35,063,889 |
```
compile 'com.google.android.gms:play-services:8.3.0'
compile 'com.android.support:support-v4:22.2.1'
compile 'com.android.support:design:22.2.1'
```
to
```
compile 'com.google.android.gms:play-services:8.4.0'
compile 'com.android.support:support-v4:23.1.0'
compile 'com.android.support:design:23.1.0'
```
Time to time, android studio will automatically change the values to the latest version which is extremely annoying and breaks my application. Is there a way to prevent this from happening?
Did a google search and stackoverflow searched but nothing came up.
|
2016/01/28
|
[
"https://Stackoverflow.com/questions/35063889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469890/"
] |
Instead of:
```
compile 'com.google.android.gms:play-services:8.3.0'
compile 'com.android.support:support-v4:22.2.1'
compile 'com.android.support:design:22.2.1'
```
try:
```
playVersion = '8.3.0'
supportVersion = 'support-v4:22.2.1'
designVersion = '22.2.1'
compile "com.google.android.gms:play-services:$playVersion"
compile "com.android.support:$supportVersion"
compile "com.android.support:design:$designVersion"
```
**Remember** to replace the `'`s with `"`s.
|
I just ran into this with another developer who had checked out my project, and then started getting build errors shortly thereafter. When I looked, my support library versions had appeared to have been updated as well.
Turns out this was happening after they had added a new Activity via the Android Studio add an activity wizard. This was automatically updating the build.gradle file to use the latest support library versions, and also adding the 'com.android.support:design:23.2.0' library as well which I wasn't even using.
I'm wondering if something similar is happening to you, as you are indicating it seems to be periodically happening.
|
35,063,889 |
```
compile 'com.google.android.gms:play-services:8.3.0'
compile 'com.android.support:support-v4:22.2.1'
compile 'com.android.support:design:22.2.1'
```
to
```
compile 'com.google.android.gms:play-services:8.4.0'
compile 'com.android.support:support-v4:23.1.0'
compile 'com.android.support:design:23.1.0'
```
Time to time, android studio will automatically change the values to the latest version which is extremely annoying and breaks my application. Is there a way to prevent this from happening?
Did a google search and stackoverflow searched but nothing came up.
|
2016/01/28
|
[
"https://Stackoverflow.com/questions/35063889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469890/"
] |
**Android Studio doesn't update the dependencies if you specify the version**
Example:
```
compile 'com.google.android.gms:play-services:8.3.0'
compile 'com.android.support:support-v4:22.2.1'
compile 'com.android.support:design:22.2.1'
```
In this case AS will tell you when there is a newer version **without updating them.**
If you the `+` in your dependencies **gradle updates with the latest version** according to the `build.gradle`.
For example:
```
compile 'com.android.support:support-v4:22.2.+'
compile 'com.android.support:support-v4:22.+'
compile 'com.android.support:support-v4:+'
```
It is a good practice to avoid it.
|
I just ran into this with another developer who had checked out my project, and then started getting build errors shortly thereafter. When I looked, my support library versions had appeared to have been updated as well.
Turns out this was happening after they had added a new Activity via the Android Studio add an activity wizard. This was automatically updating the build.gradle file to use the latest support library versions, and also adding the 'com.android.support:design:23.2.0' library as well which I wasn't even using.
I'm wondering if something similar is happening to you, as you are indicating it seems to be periodically happening.
|
31,836,420 |
I have two tables, with the following info:
```
Table1 Table2
-- --
ID#1 Item#1
ID#2 Item#1
Item#2
```
If an ID# has more than one item, it compares the dates in the created\_date column of Table2 and pick the Item# with the latest created\_date.
Can anyone help me on this?
|
2015/08/05
|
[
"https://Stackoverflow.com/questions/31836420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2744968/"
] |
This question is a bit old, but I still want to point out that adding interactivity to ggmaps output is definitely possible, since it is a ggplot2 object. Shiny has inherent interactive tool functions that record coordinates on the ggplot2 object (click, dblclick, hover, and brush). With a bit of work, these recorded coordinates could be used to recenter the map, zoom in on a location, zoom out, etc.
At the end of the day, it won't be as interactive as maps like Google and leaflet, but the ggmap/ggplot2 package(s) allow for more layer options in my opinion.
If you have any interest in making a ggmap interactive, feel free to message me. (Don't want to type up an example that no one will look at).
|
In the example gallery for shiny is a [superzip](http://shiny.rstudio.com/gallery/superzip-example.html) example that includes an interactive map. The shiny source code is available that you could work from.
I don't think that it uses ggmap though.
The [basic plot interaction demo](http://shiny.rstudio.com/gallery/plot-interaction-basic.html) on the same gallary page, does show an example using ggplot2 graphics and shows how you can identify click location, selection information, etc. You could use that information to create many of the same tools that you are looking for (add the symbols in the corner and when someone clicks on the graph, figure which symbol is closest to the click and update the graph accordingly).
|
31,836,420 |
I have two tables, with the following info:
```
Table1 Table2
-- --
ID#1 Item#1
ID#2 Item#1
Item#2
```
If an ID# has more than one item, it compares the dates in the created\_date column of Table2 and pick the Item# with the latest created\_date.
Can anyone help me on this?
|
2015/08/05
|
[
"https://Stackoverflow.com/questions/31836420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2744968/"
] |
With my `googleway` package you can now plot an interactive Google Map
```
library(shiny)
library(googleway)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(),
mainPanel(
google_mapOutput(outputId = "myMap")
)
)
)
server <- function(input, output){
# mapKey <- 'your_api_key'
output$myMap <- renderGoogle_map({
google_map(key = mapKey)
})
}
shinyApp(ui, server)
```
[](https://i.stack.imgur.com/oKSeq.png)
|
In the example gallery for shiny is a [superzip](http://shiny.rstudio.com/gallery/superzip-example.html) example that includes an interactive map. The shiny source code is available that you could work from.
I don't think that it uses ggmap though.
The [basic plot interaction demo](http://shiny.rstudio.com/gallery/plot-interaction-basic.html) on the same gallary page, does show an example using ggplot2 graphics and shows how you can identify click location, selection information, etc. You could use that information to create many of the same tools that you are looking for (add the symbols in the corner and when someone clicks on the graph, figure which symbol is closest to the click and update the graph accordingly).
|
21,648,761 |
I am new to J2EE development and its frameworks, so I'm leads to create a J2EE application usign Myeclipse,glassfish ans mysql as SGBD ... I need to create a project EJB3 session I have to use Hibernate3 ORM .. My concern is that I've worked with hibernate but in a web project type and not EJB and I really do not know how my project should be like .. I just need to understand the structure of my EJB project because normally we have 2 basic classes: EJBService and EJBserviceRemote .. EJBService, containing all my methods that I would need to call from my client (a web project for exemple) and EJBServiceRemote which contains the signature of each method .. so where do I rank the DAO classes generated by Hibernate ORM and how to call them?? shoukd I copy their code in EJBService and then declare in EJBServiceRemote to be able to call them by my client??
SOS I'm really disturbed
|
2014/02/08
|
[
"https://Stackoverflow.com/questions/21648761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3287621/"
] |
Add a line break tag, or a `br` tag:
```
document.getElementById("homepagetabs").innerHTML+="<li onclick='window.open(\""+fauxTab[x][1]+"\",\""+fauxTab[x][2]+"\")'>
"+fauxTab[x][0]+"</li><br>"
// ^This
```
so your code would look like:
```
var fauxTab = new Array();
fauxTab[0] = new Array("History","http://%LIVESCORINGHOST%/%YEAR%/home/%LEAGUEID%?MODULE=MESSAGE3","_top");
fauxTab[1] = new Array("Scoreboard","http://%LIVESCORINGHOST%/%YEAR%/home/%LEAGUEID%?MODULE=MESSAGE7","_top");
fauxTab[2] = new Array("Forum","http://forums.thehuddle.com/index.php?/forum/156-the-empire/","_blank");
try {for (var x=0;x<fauxTab.length;x++) document.getElementById("homepagetabs").innerHTML+="<li onclick='window.open(\""+fauxTab[x][1]+"\",\""+fauxTab[x][2]+"\")'>"+fauxTab[x][0]+"</li><br>"} catch(er) {}
```
or you could use a Javascript String newline character (`\n`, Opera9 and IE8 on windows will convert it into `\r\n`):
```
document.getElementById("homepagetabs").innerHTML+="<li onclick='window.open(\""+fauxTab[x][1]+"\",\""+fauxTab[x][2]+"\")'>
"+fauxTab[x][0]+"</li>\n"
// ^This
```
so your code would look like:
```
var fauxTab = new Array();
fauxTab[0] = new Array("History","http://%LIVESCORINGHOST%/%YEAR%/home/%LEAGUEID%?MODULE=MESSAGE3","_top");
fauxTab[1] = new Array("Scoreboard","http://%LIVESCORINGHOST%/%YEAR%/home/%LEAGUEID%?MODULE=MESSAGE7","_top");
fauxTab[2] = new Array("Forum","http://forums.thehuddle.com/index.php?/forum/156-the-empire/","_blank");
try {for (var x=0;x<fauxTab.length;x++) document.getElementById("homepagetabs").innerHTML+="<li onclick='window.open(\""+fauxTab[x][1]+"\",\""+fauxTab[x][2]+"\")'>"+fauxTab[x][0]+"</li>\n"} catch(er) {}
```
|
just add a brakeline `<br>`:
```
</li><br>"} catch(er) {}
```
|
21,648,761 |
I am new to J2EE development and its frameworks, so I'm leads to create a J2EE application usign Myeclipse,glassfish ans mysql as SGBD ... I need to create a project EJB3 session I have to use Hibernate3 ORM .. My concern is that I've worked with hibernate but in a web project type and not EJB and I really do not know how my project should be like .. I just need to understand the structure of my EJB project because normally we have 2 basic classes: EJBService and EJBserviceRemote .. EJBService, containing all my methods that I would need to call from my client (a web project for exemple) and EJBServiceRemote which contains the signature of each method .. so where do I rank the DAO classes generated by Hibernate ORM and how to call them?? shoukd I copy their code in EJBService and then declare in EJBServiceRemote to be able to call them by my client??
SOS I'm really disturbed
|
2014/02/08
|
[
"https://Stackoverflow.com/questions/21648761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3287621/"
] |
Add a line break tag, or a `br` tag:
```
document.getElementById("homepagetabs").innerHTML+="<li onclick='window.open(\""+fauxTab[x][1]+"\",\""+fauxTab[x][2]+"\")'>
"+fauxTab[x][0]+"</li><br>"
// ^This
```
so your code would look like:
```
var fauxTab = new Array();
fauxTab[0] = new Array("History","http://%LIVESCORINGHOST%/%YEAR%/home/%LEAGUEID%?MODULE=MESSAGE3","_top");
fauxTab[1] = new Array("Scoreboard","http://%LIVESCORINGHOST%/%YEAR%/home/%LEAGUEID%?MODULE=MESSAGE7","_top");
fauxTab[2] = new Array("Forum","http://forums.thehuddle.com/index.php?/forum/156-the-empire/","_blank");
try {for (var x=0;x<fauxTab.length;x++) document.getElementById("homepagetabs").innerHTML+="<li onclick='window.open(\""+fauxTab[x][1]+"\",\""+fauxTab[x][2]+"\")'>"+fauxTab[x][0]+"</li><br>"} catch(er) {}
```
or you could use a Javascript String newline character (`\n`, Opera9 and IE8 on windows will convert it into `\r\n`):
```
document.getElementById("homepagetabs").innerHTML+="<li onclick='window.open(\""+fauxTab[x][1]+"\",\""+fauxTab[x][2]+"\")'>
"+fauxTab[x][0]+"</li>\n"
// ^This
```
so your code would look like:
```
var fauxTab = new Array();
fauxTab[0] = new Array("History","http://%LIVESCORINGHOST%/%YEAR%/home/%LEAGUEID%?MODULE=MESSAGE3","_top");
fauxTab[1] = new Array("Scoreboard","http://%LIVESCORINGHOST%/%YEAR%/home/%LEAGUEID%?MODULE=MESSAGE7","_top");
fauxTab[2] = new Array("Forum","http://forums.thehuddle.com/index.php?/forum/156-the-empire/","_blank");
try {for (var x=0;x<fauxTab.length;x++) document.getElementById("homepagetabs").innerHTML+="<li onclick='window.open(\""+fauxTab[x][1]+"\",\""+fauxTab[x][2]+"\")'>"+fauxTab[x][0]+"</li>\n"} catch(er) {}
```
|
You should use the newline character \n
`+="<li onclick='window.open(\""+fauxTab[x][1]+"\",\""+fauxTab[x][2]+"\")'>"+fauxTab[x][0]+"</li>\n"`
|
34,979,414 |
I would like to blit hdc to an other hdc, and this hdc will be blit into hdc containing "BeginPaint". But a problem appears, nothing have been drawn.
this is the code, thanks,
```c
HDC hdcMem3 = CreateCompatibleDC(NULL);
SelectObject(hdcMem3, Picture);
BITMAP bitmap;
GetObject(Picture, sizeof(bitmap), &bitmap);
HDC hdcMem2 = CreateCompatibleDC(NULL);
BitBlt(hdcMem2, 0, 0, bitmap.bmWidth, bitmap.bmHeight, hdcMem3, 0, 0, SRCCOPY);
DeleteDC(hdcMem3);
BitBlt(hdcMem, 0, 0, bitmap.bmWidth, bitmap.bmHeight, hdcMem2, 0, 0, SRCCOPY);
DeleteDC(hdcMem2);
```
|
2016/01/24
|
[
"https://Stackoverflow.com/questions/34979414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5833737/"
] |
This is a problem with `gson` and has nothing to do with `SharedPreferences`, since they will not modify the String you are saving.
The error lies within `gson` serializing and deserializing `Integer`. You can see one question about this [here](https://stackoverflow.com/questions/15507997/how-to-prevent-gson-from-expressing-integers-as-floats).
|
```
for (Registo registosItem : registosItems) {
for (int i = 0; i < registosItem.getCommitedViolations().size(); i++) {
String str = String.valueOf(registosItem.getCommitedViolations().get(i));
int valueAsInt= Integer.parseInt(str);
registosItem.getCommitedViolations().set(i, valueAsInt);
}
}
```
This should fix your issue regarding the doubles, why don't you parse the string directly?
|
53,681,648 |
I need to insert a code that contain double curly braces (Its a Shopify liquid object)
That code i need to insert looks like this { collection.products\_count }}, The purpose of that code is that when you insert it on specific object it return something depend on the code used so it can return the product price.. order discount etc..
Now the problem is that Google Tag manger uses the same double curly braces format for its variables so if insert that above shopify code into it hopefully GTM plant it into the store page it just return an error that this variable is not exist because GTM think its a GTM variable and cant recognise it as a Shopify Liquid Object.
Is there any solution or workaround for that issue?
Thanks
|
2018/12/08
|
[
"https://Stackoverflow.com/questions/53681648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8622795/"
] |
You need to understand the way the Shopify platform works. When you create any Liquid tags and add them to your theme, Shopify renders those first. That means when your theme has code like {{ collection.products\_count }} Shopify evaluates that and turns it into a number. That number is then available for your use. What that means is that you are not actually sending curly braces to Google. Google only gets a call and can accept data **AFTER** your Liquid is rendered, not before. So you simply need to structure your data for Google in the Google fashion, not with respect to Liquid.
|
This is an old post but came across it as I had to use double curly braces for a third-party project and had the same issue of GTM not accepting custom JS code containing double braces. I got around this by concatenating strings and will provide my solution here in the hope of helping others.
Instead of the following that was not accepted by GTM:
```
message: {
consent: 'I accept the {{ link:https://example.com/privacy privacy policy }}'
}
```
I used the following code:
```
message: {
consent: 'I accept the {' + '{ link:https://example.com/privacy privacy policy }' + '}'
}
```
This will only help if the double curly braces are in a string, but might help in some instances.
|
17,777,287 |
Reading about `std::unique_ptr` at <http://en.cppreference.com/w/cpp/memory/unique_ptr>, my naive impression is that a smart enough compiler could replace correct uses of `unique_ptr` with bare pointers and just put in a `delete` when the `unique_ptr`s get destroyed. Is this actually the case? If so, do any of the mainstream optimizing compilers actually do this? If not, would it be possible to write something with some/all of `unique_ptr`s compile-time safety benefits that could be optimized to have no runtime cost (in space or time)?
Note to those (properly) worried about premature optimization: The answer here won't stop me from using `std::unique_ptr`, I'm just curious if it's a really awesome tool or just an awesome one.
**EDIT 2013/07/21 20:07 EST:**
OK, so I tested with the following program (please let me know if there's something wrong with this):
```
#include <climits>
#include <chrono>
#include <memory>
#include <iostream>
static const size_t iterations = 100;
int main (int argc, char ** argv) {
std::chrono::steady_clock::rep smart[iterations];
std::chrono::steady_clock::rep dumb[iterations];
volatile int contents;
for (size_t i = 0; i < iterations; i++) {
auto start = std::chrono::steady_clock::now();
{
std::unique_ptr<int> smart_ptr(new int(5));
for (unsigned int j = 0; j < UINT_MAX; j++)
contents = *smart_ptr;
}
auto middle = std::chrono::steady_clock::now();
{
int *dumb_ptr = new int(10);
try {
for (unsigned int j = 0; j < UINT_MAX; j++)
contents = *dumb_ptr;
delete dumb_ptr;
} catch (...) {
delete dumb_ptr;
throw;
}
}
auto end = std::chrono::steady_clock::now();
smart[i] = (middle - start).count();
dumb[i] = (end - middle).count();
}
std::chrono::steady_clock::rep smartAvg;
std::chrono::steady_clock::rep dumbAvg;
for (size_t i = 0; i < iterations; i++) {
smartAvg += smart[i];
dumbAvg += dumb[i];
}
smartAvg /= iterations;
dumbAvg /= iterations;
std::cerr << "Smart: " << smartAvg << " Dumb: " << dumbAvg << std::endl;
return contents;
}
```
Compiling with g++ 4.7.3 using `g++ --std=c++11 -O3 test.cc` gave `Smart: 1130859 Dumb: 1130005`, which means the smart pointer is within 0.076% of the dumb pointer, which is almost surely noise.
|
2013/07/21
|
[
"https://Stackoverflow.com/questions/17777287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636917/"
] |
It would certainly be my expectation from any reasonably competent compiler, since it is just a wrapper around a simple pointer and a destructor that calls `delete`, so the machne code generated by the compiler for:
```
x *p = new X;
... do stuff with p.
delete p;
```
and
```
unique_ptr<X> p(new X);
... do stuff with p;
```
will be exactly the same code.
|
Strictly speaking, the answer is no.
Recall that `unique_ptr` is a template parametrized *not* only on the type of pointer but also on the type of the deleter. Its declaration is:
```
template <class T, class D = default_delete<T>> class unique_ptr;
```
In addition `unique_ptr<T, D>` contains not only a `T*` but also a `D`. The code below (which compiles on MSVC 2010 and GCC 4.8.1) illustrates the point:
```
#include <memory>
template <typename T>
struct deleter {
char filler;
void operator()(T* ptr) {}
};
int main() {
static_assert(sizeof(int*) != sizeof(std::unique_ptr<int, deleter<int>>), "");
return 0;
}
```
When you move a `unique_ptr<T, D>` the cost is not only that of copying the `T*` from source to target (as it would be with a raw pointer) since it must also copy/move a `D`.
It's true that smart implementations can detect if `D` is empty and has a copy/move constructor that doesn't do anything (this is the case of `default_delete<T>`) and, in such case, avoid the overhead of copying a `D`. In addition, it can save memory by not adding any extra byte for `D`.
`unique_ptr`'s destructor must check whether the `T*` is null or not before calling the deleter. For `defalt_delete<T>` I believe, the optimizer might eliminate this test since it's OK to delete a null pointer.
However, there is one extra thing that `std::unique_ptr<T, D>`'s move constructor must do and `T*`'s doesn't. Since the ownership is passed from source to target, the source must be set to null. Similar arguments hold for assignments of `unique_ptr`.
Having said that, for the `default_delete<T>`, the overhead is so small that I believe will be very difficult to be detected by measurements.
|
66,625,887 |
I have my collection like this :
```
{
{
"productType":"Bike",
"company":"yamaha",
"model":"y1"
},
{
"productType":"Bike",
"company":"bajaj",
"model":"b1"
},
{
"productType":"Bike",
"company":"yamaha",
"model":"y1"
},
{
"productType":"Car",
"company":"Maruti",
"model":"m1"
},
{
"productType":"Bike",
"company":"yamaha",
"model":"y2"
},
{
"productType":"Car",
"company":"Suzuki",
"model":"s1"
}
}
```
I want this data :
```
[ "Bike":{
"Yamaha":{
"y1":2,
"y2":1
},
"Bajaj":{
"b1":1
}
},
"Car":{
"Maruti":{
"m1":1
},
"Suzuki":{
"s1":1
}
]
```
I tried to use `$replaceRoot` but could not do it with that (Key should be the `productType` then `company` then the `model` with `count` of that model as the value). How to do this ? In which case specifically we should use $replaceRoot ?
Edit : since the whole answer was inside a json object, I removed that.
|
2021/03/14
|
[
"https://Stackoverflow.com/questions/66625887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8777941/"
] |
* `$group` by `productType`, `company`, and `model`, and count the total
* `$group` by `productType` and `company`, construct array using `model` and `count` of models in key-value format
* `$group` by `productType`, construct array of company using `company` and `model` object that is converted from array using `$arrayToObject`
* `$group` by null, construct array of `product` using `product` and `company` object that is converted from array using `$arrayToObject`
* `$replaceRoot` to replace converted `product` array to object using `$arrayToObject`
```
db.collection.aggregate([
{
$group: {
_id: {
productType: "$productType",
company: "$company",
model: "$model"
},
count: { $sum: 1 }
}
},
{
$group: {
_id: {
productType: "$_id.productType",
company: "$_id.company"
},
model: {
$push: {
k: "$_id.model",
v: "$count"
}
}
}
},
{
$group: {
_id: "$_id.productType",
company: {
$push: {
k: "$_id.company",
v: { $arrayToObject: "$model" }
}
}
}
},
{
$group: {
_id: null,
product: {
$push: {
k: "$_id",
v: { $arrayToObject: "$company" }
}
}
}
},
{ $replaceRoot: { newRoot: { $arrayToObject: "$product" } } }
])
```
[Playground](https://mongoplayground.net/p/8__hXTjL2hf)
|
**SOLUTION #1**: Result as separate documents.
```js
db.products.aggregate([
{
$group: {
_id: {
company: "$company",
model: "$model"
},
productType: { $first: "$productType" },
count: { $sum: 1 }
}
},
{
$group: {
_id: "$_id.company",
productType: { $first: "$productType" },
v: {
$push: {
k: "$_id.model",
v: "$count"
}
}
}
},
{
$group: {
_id: "$productType",
k: { $first: "$productType" },
v: {
$push: {
k: "$_id",
v: { $arrayToObject: "$v" }
}
}
}
},
{
$replaceWith: {
array: [
{
k: "$k",
v: { $arrayToObject: "$v" }
}
]
}
},
{
$replaceRoot: {
newRoot: { $arrayToObject: "$array" }
}
}
]);
```
Output: Result as separate documents.
```js
/* 1 */
{
"Bike" : {
"yamaha" : {
"y1" : 2,
"y2" : 1
},
"bajaj" : {
"b1" : 1
}
}
},
/* 2 */
{
"Car" : {
"Maruti" : {
"m1" : 1
},
"Suzuki" : {
"s1" : 1
}
}
}
```
**SOLUTION #2**: Result as single document.
```js
db.products.aggregate([
{
$group: {
_id: {
company: "$company",
model: "$model"
},
productType: { $first: "$productType" },
count: { $sum: 1 }
}
},
{
$group: {
_id: "$_id.company",
productType: { $first: "$productType" },
v: {
$push: {
k: "$_id.model",
v: "$count"
}
}
}
},
{
$group: {
_id: "$productType",
k: { $first: "$productType" },
v: {
$push: {
k: "$_id",
v: { $arrayToObject: "$v" }
}
}
}
},
{
$group: {
_id: null,
array: {
$push: {
k: "$k",
v: { $arrayToObject: "$v" }
}
}
}
},
{
$replaceRoot: {
newRoot: { $arrayToObject: "$array" }
}
}
]);
```
Output: Result as single document.
```js
{
"Bike" : {
"bajaj" : {
"b1" : 1
},
"yamaha" : {
"y1" : 2,
"y2" : 1
}
},
"Car" : {
"Maruti" : {
"m1" : 1
},
"Suzuki" : {
"s1" : 1
}
}
}
```
|
66,918,701 |
I have two objects are contained by an array for each. The following code works. However, I am feeling this code I wrote is a bit odd. I am seeking a better or more standard way to improve below code. Thanks
```js
const a = [
{
apple: '1',
banana: '2',
},
];
const b = [
{
apples: '1',
bananas: '2',
},
];
const json1 = JSON.parse(JSON.stringify(...a));
const json2 = JSON.parse(JSON.stringify(...b));
console.log({ ...{a: json1}, ...{b: json2}})
```
the output needs to be
```
{
"a": {
"apple": "1",
"banana": "2"
},
"b": {
"apples": "1",
"bananas": "2"
}
}
```
Edit: Sorry I forgot to mention previously, I don't want `a[0]` `b[0]`
|
2021/04/02
|
[
"https://Stackoverflow.com/questions/66918701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1166137/"
] |
You could get an object for each array and assign to the wanted properties.
```js
const
a = [{ apple: '1', banana: '2' }],
b = [{ apples: '1', bananas: '2' }],
result = { a: Object.assign({}, ...a), b: Object.assign({}, ...b) };
console.log(result);
```
|
You can achieve the same result with
```js
const a = [{
apple: '1',
banana: '2',
}];
const b = [{
apples: '1',
bananas: '2',
}];
console.log({ a: a[0], b: b[0] })
```
|
66,918,701 |
I have two objects are contained by an array for each. The following code works. However, I am feeling this code I wrote is a bit odd. I am seeking a better or more standard way to improve below code. Thanks
```js
const a = [
{
apple: '1',
banana: '2',
},
];
const b = [
{
apples: '1',
bananas: '2',
},
];
const json1 = JSON.parse(JSON.stringify(...a));
const json2 = JSON.parse(JSON.stringify(...b));
console.log({ ...{a: json1}, ...{b: json2}})
```
the output needs to be
```
{
"a": {
"apple": "1",
"banana": "2"
},
"b": {
"apples": "1",
"bananas": "2"
}
}
```
Edit: Sorry I forgot to mention previously, I don't want `a[0]` `b[0]`
|
2021/04/02
|
[
"https://Stackoverflow.com/questions/66918701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1166137/"
] |
You could get an object for each array and assign to the wanted properties.
```js
const
a = [{ apple: '1', banana: '2' }],
b = [{ apples: '1', bananas: '2' }],
result = { a: Object.assign({}, ...a), b: Object.assign({}, ...b) };
console.log(result);
```
|
If your current code is giving you the result you want, then you can just do this:
```
const result = {a, b};
```
Live Example:
```js
const a = [
{
apple: '1',
banana: '2',
},
];
const b = [
{
apples: '1',
bananas: '2',
},
];
const result = {a, b};
console.log(result);
```
If you want to make copies of the objects, you can do this:
```
const result = {
a: a.map(o => ({...o})),
b: b.map(o => ({...o})),
};
```
Live Example:
```js
const a = [
{
apple: '1',
banana: '2',
},
];
const b = [
{
apples: '1',
bananas: '2',
},
];
const result = {
a: a.map(o => ({...o})),
b: b.map(o => ({...o})),
};
console.log(result);
```
Or for a more generic deep copy operation, see [this question's answers](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript).
|
9,033,181 |
I tried a lot of the solutions in stackoverflow but I'm not able to find a valid one. I have a core data model with two entities: Client and Destination. Both are wrapped by `NSManagedObject`subclasses.
Client has some properties and a one-to-many relationship called destinations.
Destination has a property called default\_dest that is wrapped by a `NSNumber` and an inverse relationship called client.
I have a `UITableViewController` where I'm using the following `fetchedController` property. The request works well. I'm able to retrieve clients stored in SQLite.
```m
if (fetchedResultsController)
return fetchedResultsController;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Client" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setFetchBatchSize:20];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"code" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
fetchedResultsController.delegate = self;
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
return fetchedResultsController;
```
I would make another step. I would now filter the destinations retrieved from the previous request (that are contained in destinations `NSSet`) for each client. In particular, the destination can be added only if its default\_dest value is 1.
To fix this specification I tried to add an `NSPredicate` like the following:
```m
NSPredicate* predicate = [NSpredicate predicateWithFormat:@"ANY destinations.default_dest == %@", [NSNumber numberWithInt:1]];
```
Then I set it in fetchRequest as:
```m
[fetchRequest setPredicate:predicate];
```
Each time I run the request, it returns a "to-many-relationship fault destinations...". What does it mean?
I've read [iphone-core-data-relationship-fault](https://stackoverflow.com/questions/3123950/iphone-core-data-relationship-fault) but I don't understand what does it mean.
So, my questions are: Is it possible to reach a similar goal? If yes, do you have any suggestions?
**Notes**
Obviously I could iterate over destinations set but I don't know if could be an expensive iteration and how many records there are.
|
2012/01/27
|
[
"https://Stackoverflow.com/questions/9033181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231684/"
] |
For those interested in.
You need to say to your fetch request to prefetch relationships using
```m
- (void)setRelationshipKeyPathsForPrefetching:(NSArray *)keys
```
For example:
```m
[fetchRequest setRelationshipKeyPathsForPrefetching:[NSArray arrayWithObjects: @"destinations", nil]];
```
In this manner Core Data prefetch the relationships you have specified and doesn't fire fault.
In addition you can limit the number of results for your fetch request by limiting it using:
```m
- (void)setFetchLimit:(NSUInteger)limit
```
Hope it helps.
|
Here is a different way to retrieve specific values in fetch. Maybe this can help (look up link name in document):
[Fetching Specific Values](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdFetching.html#//apple_ref/doc/uid/TP40002484-SW1)
|
65,991,141 |
I have a WPF project with a view model and some nested UI elements. Here is the (relevant section of) XAML:
```
<UserControl> // DataContext is MyVM (set programmatically)
<TreeView ItemsSource="{Binding Trees}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Subtrees}">
<StackPanel>
<ListView ItemsSource="{Binding Contents}"
SelectedValue="{Binding SelectedContent}" // won't work: Tree has no such property
SelectionMode="Single"/>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</UserControl>
```
Here the code for the ViewModel class:
```
public class MyVM : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
public IEnumerable<Tree> Trees { get; set; }
private object _selectedContent;
public string SelectedContent
{
get => _selectedContent;
set
{
_selectedContent = value;
OnPropertyChanged();
}
}
}
```
Here the code for class `Tree`:
```
public class Tree
{
public IEnumerable<Tree> Subtrees { get; set; }
public IEnumerable<string> Contents { get; set; }
}
```
I want to allow only one selection globally for all `ListViews`. Just like [here](https://stackoverflow.com/a/28009661/5333340), I want to bind all `ListViews` to the property `SelectedContent` in the view model `MyVM`.
The problem is that the data context of the `ListView` is a `Tree`, and not the `MyVM` from the top user control. (It should be `Tree`, since we want to show the `Contents`.) I know I can bind downwards using `SelectedValuePath`, but how do I go up instead in order to bind `SelectedValue` to the `MyVM` property `SelectedContent`?
I tried `SelectedValue="{Binding RelativeSource={RelativeSource AncestorType ={x:Type UserControl}}, Path=SelectedContent}"`, but it did not work.
|
2021/02/01
|
[
"https://Stackoverflow.com/questions/65991141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5333340/"
] |
I think this is a Scope-Problem.
Each Ajax-Event triggers a Request and on each Request you will get a new Bean-Instance.
Change the Scope of your UserManager to ViewScoped.
|
I think the issue is basically one level of indirection too much. Instead of `value="#{userManager.addUser.USERNAME}"`, it's much better to use two levels only, such as `value="#{userManager.username}"`.
So one approach is the replicate all the fields of the entity as fields in the bean. Then in the action method of the "save" commandButton (`action="#{userManager.insertUSER()}"`), create the Entity object ("USER"), copy all the individual fields from the bean into entity and persist the entity. If you're editing an entity, of course, you'll need to do the reverse in the @PostConstruct method, or at the point the entity is retrieved.
A cleaner approach is to use CDI functionality. In your backing bean (UserManager) include a producer for the entity, such as:
```
@Named
@Produces
@ViewScoped
private USER userEntityBean = new USER();
```
[No need to have getters/setters.] In your .xhtml page you can refer to `value="#{userEntityBean.USERNAME}"`. In the "save" method, just persist the entity.
Somewhat off topic, it is highly unusual to have Java class names and field names all in upper case, even for entities (which are, after all, just POJOs).
|
65,991,141 |
I have a WPF project with a view model and some nested UI elements. Here is the (relevant section of) XAML:
```
<UserControl> // DataContext is MyVM (set programmatically)
<TreeView ItemsSource="{Binding Trees}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Subtrees}">
<StackPanel>
<ListView ItemsSource="{Binding Contents}"
SelectedValue="{Binding SelectedContent}" // won't work: Tree has no such property
SelectionMode="Single"/>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</UserControl>
```
Here the code for the ViewModel class:
```
public class MyVM : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
public IEnumerable<Tree> Trees { get; set; }
private object _selectedContent;
public string SelectedContent
{
get => _selectedContent;
set
{
_selectedContent = value;
OnPropertyChanged();
}
}
}
```
Here the code for class `Tree`:
```
public class Tree
{
public IEnumerable<Tree> Subtrees { get; set; }
public IEnumerable<string> Contents { get; set; }
}
```
I want to allow only one selection globally for all `ListViews`. Just like [here](https://stackoverflow.com/a/28009661/5333340), I want to bind all `ListViews` to the property `SelectedContent` in the view model `MyVM`.
The problem is that the data context of the `ListView` is a `Tree`, and not the `MyVM` from the top user control. (It should be `Tree`, since we want to show the `Contents`.) I know I can bind downwards using `SelectedValuePath`, but how do I go up instead in order to bind `SelectedValue` to the `MyVM` property `SelectedContent`?
I tried `SelectedValue="{Binding RelativeSource={RelativeSource AncestorType ={x:Type UserControl}}, Path=SelectedContent}"`, but it did not work.
|
2021/02/01
|
[
"https://Stackoverflow.com/questions/65991141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5333340/"
] |
I think this is a Scope-Problem.
Each Ajax-Event triggers a Request and on each Request you will get a new Bean-Instance.
Change the Scope of your UserManager to ViewScoped.
|
The problem was solved by adding the primary key to the object before building the preparedstatement. Even if the object was filled befor with every information needed it looses the information after setting/ changing any attribute.
|
34,279,289 |
What I'm trying to do:
* a class that has several (say 10) instance variables of dictionary type (mutable `var`).
* a method that (depending on arguments, etc.) picks a dictionary an updates it.
In ObjC, this is fairly easily accomplished using `NSMutableDictionary`. In Swift, this is more tricky, since the dictionary gets copied on into the local variable.
I think the best way to explain what I'm trying to achieve is via a code sample:
```
class MyClass {
/// There are several dictionaries as instance variables
var dict1: [String : String] = [ : ]
var dict2: [String : String] = [ : ]
// ...
/// This method should change a value in one of the dictionaries,
/// depending on the argument.
func changeDictAtIndex(index: Int) {
var dict: [String : String]
if index == 0 {
dict = dict1
}else{
dict = dict2
}
dict["OK"] = "KO"
// This won't work since Swift copies the dictionary into
// the local variable, which gets destroyed at the end of
// the scope...
}
}
let obj = MyClass()
obj.changeDictAtIndex(0)
obj.dict1 // Still empty.
```
**Question:** Is there a **native** way to do this (native meaning **without** using `NSMutableDictionary`)?
P.S.: I'm aware of the `inout` attribute, but that works AFAIK only with function arguments, which doesn't really solve anything...
EDIT:
I'm currently solving this via closure:
```
var dictSetter: (key: String, value: String) -> Void
if index == 0 {
dictSetter = { self.dict1[$0] = $1 }
}else{
dictSetter = { self.dict2[$0] = $1 }
}
dictSetter(key: "OK", value: "KO")
```
|
2015/12/15
|
[
"https://Stackoverflow.com/questions/34279289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1800936/"
] |
As you may already aware, you can use `inout` to solve the problem
```
func updateDict(inout dict: [String : String]) {
dict["OK"] = "KO"
}
func changeDictAtIndex(index: Int) {
if index == 0 {
updateDict(&dict1)
}else{
updateDict(&dict2)
}
}
```
|
***Question: Is there a native way to do this (native meaning without using NSMutableDictionary)?***
I have rewritten your class, note the changes:
* Different syntax for empty dictionary
* ChangeDictAtIndex function now takes in a dictionary you want to replace.
* The instance variables are being set to the passed in dict.
I would look at the Apple's [The Swift Programming Language (Swift 2.1)](https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID309) section on the basics and collection types.
```
class MyClass {
// There are several dictionaries as instance variables
var dict1 = [String : String]()
var dict2 = [String : String]()
func changeDictAtIndex(index: Int, dict: [String : String]) {
if index == 0 {
dict1 = dict
} else {
dict2 = dict
}
}
}
```
Usage:
```
let obj = MyClass()
obj.changeDictAtIndex(0, dict: ["MyKey" : "MyValue"])
print(obj.dict1)
```
|
117,562 |
please, I have tried to design like this picture
[](https://i.stack.imgur.com/vcID3.png)
I use CS6 but in my design spaces exit between layers ( squares ) like this
[](https://i.stack.imgur.com/an6go.png)
so please what are my mistakes? and how can I remove spaces between layres ( squares)?
and many thanks in advance
|
2018/11/28
|
[
"https://graphicdesign.stackexchange.com/questions/117562",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/129989/"
] |
It would drive me crazy if I had to alter each corner manually. So... I'd use a more global method....
* Expand Strokes (Object > Expand / Copy *only* outer compound rectangle for later use)
* Merge shapes (Pathfinder Panel > Merge)
* Apply Effect (Effect > Stylize > Round Corners)
* Expand Effect (Object > Expand Appearance)
* Fix Outer 4 corners (Paste rectangle, Pathfinder > Unite)
[](https://i.stack.imgur.com/GRKD6.png)
The last 2 steps merely square off the outer 4 corners again. You could do that manually by removing the curves and aligning anchors if desired.
|
* Select all
* Menu **Object** -> **Expand**
* **Shape Builder Tool**
[](https://i.stack.imgur.com/knvvO.png)
* Choose a fill color and click the holes
[](https://i.stack.imgur.com/W4try.gif)
|
117,562 |
please, I have tried to design like this picture
[](https://i.stack.imgur.com/vcID3.png)
I use CS6 but in my design spaces exit between layers ( squares ) like this
[](https://i.stack.imgur.com/an6go.png)
so please what are my mistakes? and how can I remove spaces between layres ( squares)?
and many thanks in advance
|
2018/11/28
|
[
"https://graphicdesign.stackexchange.com/questions/117562",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/129989/"
] |
It would drive me crazy if I had to alter each corner manually. So... I'd use a more global method....
* Expand Strokes (Object > Expand / Copy *only* outer compound rectangle for later use)
* Merge shapes (Pathfinder Panel > Merge)
* Apply Effect (Effect > Stylize > Round Corners)
* Expand Effect (Object > Expand Appearance)
* Fix Outer 4 corners (Paste rectangle, Pathfinder > Unite)
[](https://i.stack.imgur.com/GRKD6.png)
The last 2 steps merely square off the outer 4 corners again. You could do that manually by removing the curves and aligning anchors if desired.
|
Take Danielillo's excellent answer, then use Pathfinder to union all the black elements together. Once you've done this select all the corners using the direct selection tool, and then use the rounded corner tool to give the fillets you prefer or need for the given manufacturing method.
[](https://i.stack.imgur.com/Kbic3.png)
|
40,519,026 |
Okay guys, I am trying to use JavaScript to validate a form, and then display a "Thank you" message after its all been validated with correct information. I've got it working to validate the first name, email address, and a radio selection, however I can't seem to get it to validate the state selection, or display the thank you message, but I've also used my browser's(Firefox) Dev Console to dig for syntax errors. None are displayed. Any help?
A small snip of the code is below, and a jsfiddle link to the whole code, plus the HTML is below that.
```
function validForm() { // reference point
/* first name, email, comments and phone */
var fname = document.form1.fname;
var email = document.form1.email;
var comments = document.form1.comments;
var phone1 = document.form1.phone1;
var phone2 = document.form1.phone2;
var phone3 = document.form1.phone3;
/* collecting the error spans for later use */
var fnErr = document.getElementById('fnErr');
var lnErr = document.getElementById('lnErr');
var emErr = document.getElementById('emErr');
var phErr = document.getElementById('phErr');
var cmErr = document.getElementById('cmErr');
var state = document.getElementById('stErr');
if(fname.value=="") {
fnErr.innerHTML = "We need your name, please.";
fname.focus();
return false;
} else {
fnErr.innerHTML = "";
}
if(email.value=="") {
emErr.innerHTML = "We need your email, please.";
email.focus();
return false;
} else {
emErr.innerHTML = "";
}
if(state.value=="none") {
fnErr.innerHTML = "Please select your state.";
state.focus();
return false;
} else {
fnErr.innerHTML = "";
}
/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i;
if(isNaN(phone1.value) || isNaN(phone2.value) ||
isNaN(phone3.value)) {
phErr.innerHTML = "If you include a phone number it should be numbers only.";
phone1.select();
return false;
} else {
phErr.innerHTML = "";
}
var notices = document.form1.notices;
var selected;
for(var i=0;i<notices.length;i++) {
if(notices[i].checked) {
selected = notices[i].value;
}
}
/* set up a message for a advert recipient */
var msg = "Thank you, <b>"+fname.value
+"!</b> Your message has been received and one of our representatives will reply to <a href='"
+email.value+"'>"+email.value+"</a> within a day or two. Relax, and enjoy the rest of the site!";
if(selected != undefined) {
document.getElementById('notePref').innerHTML = "";
if (selected == "yes") { // here's where we test the contents of "selected"
document.getElementById('fnlMsg').innerHTML = msg;
} else {
document.getElementById('fnlMsg').innerHTML = "<strong>"+fname.value+"</strong>, thank you for your feedback!";
}
var contactForm = document.getElementById('registerForm').setAttribute('class','hide');
var loseSep = document.getElementsByClassName('spec');
loseSep[0].setAttribute('class', 'hide');
} else {
document.getElementById('notePref').innerHTML = "Please make a selection:";
}
} // reference point
```
<https://jsfiddle.net/xp5e099y/2/>
|
2016/11/10
|
[
"https://Stackoverflow.com/questions/40519026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5552540/"
] |
Your code only gets the value and increases it, does not assign the value to the input field. Add this line after the increment statement:
```
document.getElementById("rows_count").value = rows_count;
```
Also it's `parseInt()` with lowercase `p` not `ParseInt()`.
```js
function add_more_row() {
var inputRow = document.getElementById("rows_count"),
rows_count = parseInt(inputRow.value);
rows_count += 1;
inputRow.value = rows_count;
}
```
```html
<input type="text" value="0" id="rows_count" />
<input onclick="add_more_row();" type="button" value="add row" />
```
|
It is because you declare the variable inside the function.
So, the variable does not increase.
```
var rows_count=ParseInt(document.getElementById("rows_count").value);
function add_more_row()
{
rows_count += 1;
}
```
|
40,519,026 |
Okay guys, I am trying to use JavaScript to validate a form, and then display a "Thank you" message after its all been validated with correct information. I've got it working to validate the first name, email address, and a radio selection, however I can't seem to get it to validate the state selection, or display the thank you message, but I've also used my browser's(Firefox) Dev Console to dig for syntax errors. None are displayed. Any help?
A small snip of the code is below, and a jsfiddle link to the whole code, plus the HTML is below that.
```
function validForm() { // reference point
/* first name, email, comments and phone */
var fname = document.form1.fname;
var email = document.form1.email;
var comments = document.form1.comments;
var phone1 = document.form1.phone1;
var phone2 = document.form1.phone2;
var phone3 = document.form1.phone3;
/* collecting the error spans for later use */
var fnErr = document.getElementById('fnErr');
var lnErr = document.getElementById('lnErr');
var emErr = document.getElementById('emErr');
var phErr = document.getElementById('phErr');
var cmErr = document.getElementById('cmErr');
var state = document.getElementById('stErr');
if(fname.value=="") {
fnErr.innerHTML = "We need your name, please.";
fname.focus();
return false;
} else {
fnErr.innerHTML = "";
}
if(email.value=="") {
emErr.innerHTML = "We need your email, please.";
email.focus();
return false;
} else {
emErr.innerHTML = "";
}
if(state.value=="none") {
fnErr.innerHTML = "Please select your state.";
state.focus();
return false;
} else {
fnErr.innerHTML = "";
}
/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i;
if(isNaN(phone1.value) || isNaN(phone2.value) ||
isNaN(phone3.value)) {
phErr.innerHTML = "If you include a phone number it should be numbers only.";
phone1.select();
return false;
} else {
phErr.innerHTML = "";
}
var notices = document.form1.notices;
var selected;
for(var i=0;i<notices.length;i++) {
if(notices[i].checked) {
selected = notices[i].value;
}
}
/* set up a message for a advert recipient */
var msg = "Thank you, <b>"+fname.value
+"!</b> Your message has been received and one of our representatives will reply to <a href='"
+email.value+"'>"+email.value+"</a> within a day or two. Relax, and enjoy the rest of the site!";
if(selected != undefined) {
document.getElementById('notePref').innerHTML = "";
if (selected == "yes") { // here's where we test the contents of "selected"
document.getElementById('fnlMsg').innerHTML = msg;
} else {
document.getElementById('fnlMsg').innerHTML = "<strong>"+fname.value+"</strong>, thank you for your feedback!";
}
var contactForm = document.getElementById('registerForm').setAttribute('class','hide');
var loseSep = document.getElementsByClassName('spec');
loseSep[0].setAttribute('class', 'hide');
} else {
document.getElementById('notePref').innerHTML = "Please make a selection:";
}
} // reference point
```
<https://jsfiddle.net/xp5e099y/2/>
|
2016/11/10
|
[
"https://Stackoverflow.com/questions/40519026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5552540/"
] |
```js
function add_more_row() {
var rows_count = parseInt(document.getElementById("rows_count").value);
rows_count += 1;
document.getElementById("rows_count").value= rows_count;
}
```
```html
<input type="text" value="0" id="rows_count" />
<input onclick="add_more_row();" type="button" value="add row" />
```
|
It is because you declare the variable inside the function.
So, the variable does not increase.
```
var rows_count=ParseInt(document.getElementById("rows_count").value);
function add_more_row()
{
rows_count += 1;
}
```
|
40,519,026 |
Okay guys, I am trying to use JavaScript to validate a form, and then display a "Thank you" message after its all been validated with correct information. I've got it working to validate the first name, email address, and a radio selection, however I can't seem to get it to validate the state selection, or display the thank you message, but I've also used my browser's(Firefox) Dev Console to dig for syntax errors. None are displayed. Any help?
A small snip of the code is below, and a jsfiddle link to the whole code, plus the HTML is below that.
```
function validForm() { // reference point
/* first name, email, comments and phone */
var fname = document.form1.fname;
var email = document.form1.email;
var comments = document.form1.comments;
var phone1 = document.form1.phone1;
var phone2 = document.form1.phone2;
var phone3 = document.form1.phone3;
/* collecting the error spans for later use */
var fnErr = document.getElementById('fnErr');
var lnErr = document.getElementById('lnErr');
var emErr = document.getElementById('emErr');
var phErr = document.getElementById('phErr');
var cmErr = document.getElementById('cmErr');
var state = document.getElementById('stErr');
if(fname.value=="") {
fnErr.innerHTML = "We need your name, please.";
fname.focus();
return false;
} else {
fnErr.innerHTML = "";
}
if(email.value=="") {
emErr.innerHTML = "We need your email, please.";
email.focus();
return false;
} else {
emErr.innerHTML = "";
}
if(state.value=="none") {
fnErr.innerHTML = "Please select your state.";
state.focus();
return false;
} else {
fnErr.innerHTML = "";
}
/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i;
if(isNaN(phone1.value) || isNaN(phone2.value) ||
isNaN(phone3.value)) {
phErr.innerHTML = "If you include a phone number it should be numbers only.";
phone1.select();
return false;
} else {
phErr.innerHTML = "";
}
var notices = document.form1.notices;
var selected;
for(var i=0;i<notices.length;i++) {
if(notices[i].checked) {
selected = notices[i].value;
}
}
/* set up a message for a advert recipient */
var msg = "Thank you, <b>"+fname.value
+"!</b> Your message has been received and one of our representatives will reply to <a href='"
+email.value+"'>"+email.value+"</a> within a day or two. Relax, and enjoy the rest of the site!";
if(selected != undefined) {
document.getElementById('notePref').innerHTML = "";
if (selected == "yes") { // here's where we test the contents of "selected"
document.getElementById('fnlMsg').innerHTML = msg;
} else {
document.getElementById('fnlMsg').innerHTML = "<strong>"+fname.value+"</strong>, thank you for your feedback!";
}
var contactForm = document.getElementById('registerForm').setAttribute('class','hide');
var loseSep = document.getElementsByClassName('spec');
loseSep[0].setAttribute('class', 'hide');
} else {
document.getElementById('notePref').innerHTML = "Please make a selection:";
}
} // reference point
```
<https://jsfiddle.net/xp5e099y/2/>
|
2016/11/10
|
[
"https://Stackoverflow.com/questions/40519026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5552540/"
] |
Your code only gets the value and increases it, does not assign the value to the input field. Add this line after the increment statement:
```
document.getElementById("rows_count").value = rows_count;
```
Also it's `parseInt()` with lowercase `p` not `ParseInt()`.
```js
function add_more_row() {
var inputRow = document.getElementById("rows_count"),
rows_count = parseInt(inputRow.value);
rows_count += 1;
inputRow.value = rows_count;
}
```
```html
<input type="text" value="0" id="rows_count" />
<input onclick="add_more_row();" type="button" value="add row" />
```
|
```js
function add_more_row() {
var rows_count = parseInt(document.getElementById("rows_count").value);
rows_count += 1;
document.getElementById("rows_count").value= rows_count;
}
```
```html
<input type="text" value="0" id="rows_count" />
<input onclick="add_more_row();" type="button" value="add row" />
```
|
55,112 |
>
> Der Nebel wird so dicht, dass ich das Haus kaum noch sehe.
>
>
>
What is the antonym of "dicht" in the sense/meaning used above?
Also what about these two below?
"thick atmosphere"
"thick substance"
What is the antonym of thick here? If we want it in German of course...
|
2019/11/06
|
[
"https://german.stackexchange.com/questions/55112",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/11275/"
] |
I would use [*dünn*](https://www.dwds.de/wb/d%C3%BCnn) as an antonym of *dicht* (or *dick*) in the sense desired:
>
> * Der Nebel ist heute *dünner* als gestern.
> * In der *dünnen* Atmosphäre kann man kaum noch atmen.
> * Die Mischung ist noch viel zu *dünn*.
>
>
>
As mentioned elsewhere, *lichter Nebel* is also appropriate, especially, when *dichter Nebel* was ment to have the connotation *blickdicht* (being opaque), like in your example sentence
>
> Der Nebel wird so *(**blick**)dicht*, dass ich das Haus kaum noch sehe.
>
>
>
This, however, does not invalidate the existence of the phrase *dünner Nebel*. It occurs where the property opacity is not as important as the property denseness, for example, in the definition of [*Nebelschleier*](https://www.dwds.de/wb/Nebelschleier) in the DWDS.
|
This depends indeed heavily on context. In this case (fog = Nebel) you would usually say *leichter Nebel* (light fog).
*Dünner Nebel* (thin fog) would also be possible, but rather unusual.
"Dicht" is also used in the meaning of (air/water-)tight (nothing can leak out), in this case the antonym would simply be *undicht*.
Finally(?) "dicht" can also mean "close" in the context when speaking about traffic and (not) coming to close to the car in front of you ("Fahr nicht zu dicht auf"). The opposite here would be expressed as "halte Abstand" (keep distance) or "bleib weiter weg" (stay farther away).
|
55,112 |
>
> Der Nebel wird so dicht, dass ich das Haus kaum noch sehe.
>
>
>
What is the antonym of "dicht" in the sense/meaning used above?
Also what about these two below?
"thick atmosphere"
"thick substance"
What is the antonym of thick here? If we want it in German of course...
|
2019/11/06
|
[
"https://german.stackexchange.com/questions/55112",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/11275/"
] |
I would use [*dünn*](https://www.dwds.de/wb/d%C3%BCnn) as an antonym of *dicht* (or *dick*) in the sense desired:
>
> * Der Nebel ist heute *dünner* als gestern.
> * In der *dünnen* Atmosphäre kann man kaum noch atmen.
> * Die Mischung ist noch viel zu *dünn*.
>
>
>
As mentioned elsewhere, *lichter Nebel* is also appropriate, especially, when *dichter Nebel* was ment to have the connotation *blickdicht* (being opaque), like in your example sentence
>
> Der Nebel wird so *(**blick**)dicht*, dass ich das Haus kaum noch sehe.
>
>
>
This, however, does not invalidate the existence of the phrase *dünner Nebel*. It occurs where the property opacity is not as important as the property denseness, for example, in the definition of [*Nebelschleier*](https://www.dwds.de/wb/Nebelschleier) in the DWDS.
|
Slightly old-fashioned would be:
>
> lichter Nebel
>
>
>
I don't know which meaning of [*licht*](https://www.dwds.de/wb/licht) this usage is based on: *bright* or *sparse*.
>
> ein lichter Morgen (*bright*)
>
>
> ein lichter Wald, lichtes Haar (*sparse*)
>
>
>
|
21,817,799 |
Im using Fullpage.js and trying to make it work with wordpress, and its going forward. However, I'm trying to figure out how to be able to scroll trough a slide with content higher then the active slide. The plugin comes with a scroll overflow function, but that vill make a scrollbar that scrolls trough your content, and keeps going to the next slide.
Ideally a constant scrollbar that stops at the current slide would be the best option for me, but i dont know if this is possible.
Been fiddling with this for a while, so if anyone has any ideas how to solve this i would be thankful. My site:
<http://www.svenssonsbild.se/Fullscreen/>
Edit: Realize that what i want should be able to achieve by setting scrolloverflow: true in the plugins setting. Just didnt realize it didnt work for me.
So, if anyone hav any ideas why it wont work for me then it would be great. I suspect it have something with having the scripts hardcoded in the header and not enqueued, which i havent been able to figure out how to, since the supercontainer the script creates duplicates.
anyhow, any pointers will be very appriciated.
|
2014/02/16
|
[
"https://Stackoverflow.com/questions/21817799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2059370/"
] |
I struggled with this myself, then went to read through the documentation again. Here what it states:
>
> * scrollOverflow: (default false) defines whether or not to create a
> scroll for the section in case its content is bigger than the height
> of it. In case of setting it to true, it requieres the vendor plugin
> **jquery.slimscroll.min and it should be loaded before** the fullPaje.js
> plugin. For example:
>
>
>
```
<script type="text/javascript" src="vendors/jquery.slimscroll.min.js"></script>
<script type="text/javascript" src="jquery.fullPage.js"></script>
```
Not loading SlimScroll.js was the issue here.
Then set your $.fn.fullpage({ }) config accordingly.
```
$('#fullpage').fullpage({
scrollOverflow: true
});
```
|
Just to add a little info that mighht help out others, I've been using both plugins (fullpage.js and slimscroll.js) but found issues with slimscroll when using it on mobile devices (momentum and lag issues).
It is possible to set scrollOverflow to false and add this next bit to the afterSlideLoad function to get native scrolling if content is too long:
$('.slide .active').css('overflow-y','auto');
|
11,096,042 |
I have 3 tables:
**Customers**
```
ID_CUSTOMER
NAME
```
**Products**
```
ID_PRODUCT
PRODUCTNAME
PRICE
```
**Orders**
```
ID_ORDER
CUSTOMER_ID
PRODUCT_ID
QUANTITY
```
How to select all customers who ordered for $10k or more?
|
2012/06/19
|
[
"https://Stackoverflow.com/questions/11096042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1192466/"
] |
If you'd look at the return value of schedule, either in your IDE or in the [documentation](http://doc.akka.io/api/akka/2.0.2/#akka.actor.Scheduler) you'd see that it returns a Cancellable, so you can cancel the previous and schedule a new one.
Hope that helps!
Cheers,
√
|
Several steps you need to do:
1 You need to have a global key-value variable. Here I use ConcurrentHashMap, because normal HashMap is not safe in multi-threaded environment.
```
var schedulerIDs = new ConcurrentHashMap[String, Cancellable]().asScala
```
2 Every time you create a scheduler, you need to store it to key-value variable. You need to design your key, here I use the scheduler's create time and the user who creates this scheduler as key (Just because it is unique and it is easy for me to restore it back.). And its value is its cancelable variable. (Remember you can't read its content, because it is just cancelable type. )
```
val schedulerID = system.scheduler.schedule(initialDelay, interval, myActor, subMessage)
val schedulerKey = startTime + userName
val filterOption = schedulerIDs.get(schedulerKey)
filterOption match {
case None =>
schedulerIDs += schedulerKey -> schedulerID
case _ =>
}
```
3 When you want to modify one scheduler, you need to fetch its info from key-value variable to get its cancelable variable. And then using this cancelable variable to cancel this scheduler first and remove this scheduler from this key-value variable.
```
def removeScheduler(createTime: String, userName: String) {
val schedulerKey = createTime + userName
val filterOption = schedulerIDs.get(schedulerKey)
filterOption match {
case None =>
case Some(value) =>
value.cancel()
schedulerIDs.remove(schedulerKey)
}
}
```
4 Final step is to create a new scheduler going to step2 and going back to Step1 to store it.
This solution uses global variable to store scheduler info. The benefit of it is fast, but the disadvantage is that when the server is down, all of these info would be gone. Because global variable will be gone when the server is down.
So normally I will store schedulers info into DB in Step1 together to restore everything back according to its scheduler info(like, init time, interval, etc). Exactly like create new schedulers. But users or front-end will not notice it.
|
21,045,300 |
I have a class that I want to construct, by deserializing it from a network stream.
```
public Anfrage(byte[] dis)
{
XmlSerializer deser = new XmlSerializer(typeof(Anfrage));
Stream str = new MemoryStream();
str.Write(dis, 0, dis.Length);
this = (Anfrage)deser.Deserialize(str);
}
```
The intention is that I just want to pass the byte[] and have a proper object, rather than using a method in another class.
Now, I know that I obviously cannot do **this =**.
I've read [this question](https://stackoverflow.com/questions/1001694/using-this-in-c-sharp-constructors) and currently am reading the article mentioned in it, but I am not sure wether I'm understanding it correctly.
Is my intention clear enough?
Is there a way to do what I want to get done here?
Thank you all.
|
2014/01/10
|
[
"https://Stackoverflow.com/questions/21045300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3164870/"
] |
You cannot overwrite an object within the class itself by assigning to `this`.
You can for example create a method that *returns* a new instance:
```
public static Anfrage Create(byte[] dis)
{
XmlSerializer deser = new XmlSerializer(typeof(Anfrage));
Stream str = new MemoryStream();
str.Write(dis, 0, dis.Length);
return (Anfrage)deser.Deserialize(str);
}
```
Then you can instantiate one like this:
```
var anfrage = Anfrage.Create(bytes);
```
|
Usually with this problem is dealt with a static non-constructor function returning the Object.
```
public static Anfrage Create(byte[] dis)
{
XmlSerializer deser = new XmlSerializer(typeof(Anfrage));
Stream str = new MemoryStream();
str.Write(dis, 0, dis.Length);
return (Anfrage)deser.Deserialize(str);
}
```
if you want to have a new object and edit it, make the constructor private instead of public and acces it with you static construction function
|
46,903,118 |
I'm streaming a content of my app to my RTMP server and using RPBroadcastSampleHandler.
One of the methods is
```
override func processSampleBuffer(_ sampleBuffer: CMSampleBuffer, with sampleBufferType: RPSampleBufferType) {
switch sampleBufferType {
case .video:
streamer.appendSampleBuffer(sampleBuffer, withType: .video)
captureOutput(sampleBuffer)
case .audioApp:
streamer.appendSampleBuffer(sampleBuffer, withType: .audio)
captureAudioOutput(sampleBuffer)
case .audioMic:
()
}
}
```
And the captureOutput method is
```
self.lastSampleTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
// Append the sampleBuffer into videoWriterInput
if self.isRecordingVideo {
if self.videoWriterInput!.isReadyForMoreMediaData {
if self.videoWriter!.status == AVAssetWriterStatus.writing {
let whetherAppendSampleBuffer = self.videoWriterInput!.append(sampleBuffer)
print(">>>>>>>>>>>>>The time::: \(self.lastSampleTime.value)/\(self.lastSampleTime.timescale)")
if whetherAppendSampleBuffer {
print("DEBUG::: Append sample buffer successfully")
} else {
print("WARN::: Append sample buffer failed")
}
} else {
print("WARN:::The videoWriter status is not writing")
}
} else {
print("WARN:::Cannot append sample buffer into videoWriterInput")
}
}
```
Since this sample buffer contains audio/video data, I figured I can use AVKit to save it locally while streaming. So what I'm doing is creating an asset writer at the start of the stream:
```
let fileManager = FileManager.default
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
self.videoOutputFullFileName = documentsPath.stringByAppendingPathComponent(str: "test_capture_video.mp4")
if self.videoOutputFullFileName == nil {
print("ERROR:The video output file name is nil")
return
}
self.isRecordingVideo = true
if fileManager.fileExists(atPath: self.videoOutputFullFileName!) {
print("WARN:::The file: \(self.videoOutputFullFileName!) exists, will delete the existing file")
do {
try fileManager.removeItem(atPath: self.videoOutputFullFileName!)
} catch let error as NSError {
print("WARN:::Cannot delete existing file: \(self.videoOutputFullFileName!), error: \(error.debugDescription)")
}
} else {
print("DEBUG:::The file \(self.videoOutputFullFileName!) doesn't exist")
}
let screen = UIScreen.main
let screenBounds = info.size
let videoCompressionPropertys = [
AVVideoAverageBitRateKey: screenBounds.width * screenBounds.height * 10.1
]
let videoSettings: [String: Any] = [
AVVideoCodecKey: AVVideoCodecH264,
AVVideoWidthKey: screenBounds.width,
AVVideoHeightKey: screenBounds.height,
AVVideoCompressionPropertiesKey: videoCompressionPropertys
]
self.videoWriterInput = AVAssetWriterInput(mediaType: AVMediaTypeVideo, outputSettings: videoSettings)
guard let videoWriterInput = self.videoWriterInput else {
print("ERROR:::No video writer input")
return
}
videoWriterInput.expectsMediaDataInRealTime = true
// Add the audio input
var acl = AudioChannelLayout()
memset(&acl, 0, MemoryLayout<AudioChannelLayout>.size)
acl.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
let audioOutputSettings: [String: Any] =
[ AVFormatIDKey: kAudioFormatMPEG4AAC,
AVSampleRateKey : 44100,
AVNumberOfChannelsKey : 1,
AVEncoderBitRateKey : 64000,
AVChannelLayoutKey : Data(bytes: &acl, count: MemoryLayout<AudioChannelLayout>.size)]
audioWriterInput = AVAssetWriterInput(mediaType: AVMediaTypeAudio, outputSettings: audioOutputSettings)
guard let audioWriterInput = self.audioWriterInput else {
print("ERROR:::No audio writer input")
return
}
audioWriterInput.expectsMediaDataInRealTime = true
do {
self.videoWriter = try AVAssetWriter(outputURL: URL(fileURLWithPath: self.videoOutputFullFileName!), fileType: AVFileTypeMPEG4)
} catch let error as NSError {
print("ERROR:::::>>>>>>>>>>>>>Cannot init videoWriter, error:\(error.localizedDescription)")
}
guard let videoWriter = self.videoWriter else {
print("ERROR:::No video writer")
return
}
if videoWriter.canAdd(videoWriterInput) {
videoWriter.add(videoWriterInput)
} else {
print("ERROR:::Cannot add videoWriterInput into videoWriter")
}
//Add audio input
if videoWriter.canAdd(audioWriterInput) {
videoWriter.add(audioWriterInput)
} else {
print("ERROR:::Cannot add audioWriterInput into videoWriter")
}
if videoWriter.status != AVAssetWriterStatus.writing {
print("DEBUG::::::::::::::::The videoWriter status is not writing, and will start writing the video.")
let hasStartedWriting = videoWriter.startWriting()
if hasStartedWriting {
videoWriter.startSession(atSourceTime: self.lastSampleTime)
print("DEBUG:::Have started writting on videoWriter, session at source time: \(self.lastSampleTime)")
LOG(videoWriter.status.rawValue)
} else {
print("WARN:::Fail to start writing on videoWriter")
}
} else {
print("WARN:::The videoWriter.status is writing now, so cannot start writing action on videoWriter")
}
```
And then saving and finishing writing at the end of the stream:
```
print("DEBUG::: Starting to process recorder final...")
print("DEBUG::: videoWriter status: \(self.videoWriter!.status.rawValue)")
self.isRecordingVideo = false
guard let videoWriterInput = self.videoWriterInput else {
print("ERROR:::No video writer input")
return
}
guard let videoWriter = self.videoWriter else {
print("ERROR:::No video writer")
return
}
guard let audioWriterInput = self.audioWriterInput else {
print("ERROR:::No audio writer input")
return
}
videoWriterInput.markAsFinished()
audioWriterInput.markAsFinished()
videoWriter.finishWriting {
if videoWriter.status == AVAssetWriterStatus.completed {
print("DEBUG:::The videoWriter status is completed")
let fileManager = FileManager.default
if fileManager.fileExists(atPath: self.videoOutputFullFileName!) {
print("DEBUG:::The file: \(self.videoOutputFullFileName ?? "") has been saved in documents folder, and is ready to be moved to camera roll")
let sharedFileURL = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.jp.awalker.co.Hotter")
guard let documentsPath = sharedFileURL?.path else {
LOG("ERROR:::No shared file URL path")
return
}
let finalFilename = documentsPath.stringByAppendingPathComponent(str: "test_capture_video.mp4")
//Check whether file exists
if fileManager.fileExists(atPath: finalFilename) {
print("WARN:::The file: \(finalFilename) exists, will delete the existing file")
do {
try fileManager.removeItem(atPath: finalFilename)
} catch let error as NSError {
print("WARN:::Cannot delete existing file: \(finalFilename), error: \(error.debugDescription)")
}
} else {
print("DEBUG:::The file \(self.videoOutputFullFileName!) doesn't exist")
}
do {
try fileManager.copyItem(at: URL(fileURLWithPath: self.videoOutputFullFileName!), to: URL(fileURLWithPath: finalFilename))
}
catch let error as NSError {
LOG("ERROR:::\(error.debugDescription)")
}
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: finalFilename))
}) { completed, error in
if completed {
print("Video \(self.videoOutputFullFileName ?? "") has been moved to camera roll")
}
if error != nil {
print ("ERROR:::Cannot move the video \(self.videoOutputFullFileName ?? "") to camera roll, error: \(error!.localizedDescription)")
}
}
} else {
print("ERROR:::The file: \(self.videoOutputFullFileName ?? "") doesn't exist, so can't move this file camera roll")
}
} else {
print("WARN:::The videoWriter status is not completed, stauts: \(videoWriter.status)")
}
}
```
The problem I'm having is the finishWriting completion code is never being reached. The writer stays in "writing" status therefore the video file is not saved.
If I remove the "finishWriting" line and just leave the completion code to run, a file is being saved, but not properly finished and when I'm trying to view it it's unplayable because it's probably missing metadata.
Is there any other way to do this? I don't want to actually start capturing using AVKit to save the recording, because it's taking too much of the CPU and the RPBroadcastSampleHandler's CMSampleBuffer already has the video data, but maybe using AVKit at all is a wrong move here?
What should I change? How do I save the video from that CMSampleBuffer?
|
2017/10/24
|
[
"https://Stackoverflow.com/questions/46903118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3715075/"
] |
From <https://developer.apple.com/documentation/avfoundation/avassetwriter/1390432-finishwritingwithcompletionhandl>
`This method returns immediately and causes its work to be performed asynchronously`
When `broadcastFinished` returns, your extension is killed. The only way I've been able to get this to work is by blocking the method from returning until the video processing is done. I'm not sure if this is the correct way to do it (seems weird), but it works. Something like this:
```
var finishedWriting = false
videoWriter.finishWriting {
NSLog("DEBUG:::The videoWriter finished writing.")
if videoWriter.status == .completed {
NSLog("DEBUG:::The videoWriter status is completed")
let fileManager = FileManager.default
if fileManager.fileExists(atPath: self.videoOutputFullFileName!) {
NSLog("DEBUG:::The file: \(self.videoOutputFullFileName ?? "") has been saved in documents folder, and is ready to be moved to camera roll")
let sharedFileURL = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.xxx.com")
guard let documentsPath = sharedFileURL?.path else {
NSLog("ERROR:::No shared file URL path")
finishedWriting = true
return
}
let finalFilename = documentsPath + "/test_capture_video.mp4"
//Check whether file exists
if fileManager.fileExists(atPath: finalFilename) {
NSLog("WARN:::The file: \(finalFilename) exists, will delete the existing file")
do {
try fileManager.removeItem(atPath: finalFilename)
} catch let error as NSError {
NSLog("WARN:::Cannot delete existing file: \(finalFilename), error: \(error.debugDescription)")
}
} else {
NSLog("DEBUG:::The file \(self.videoOutputFullFileName!) doesn't exist")
}
do {
try fileManager.copyItem(at: URL(fileURLWithPath: self.videoOutputFullFileName!), to: URL(fileURLWithPath: finalFilename))
}
catch let error as NSError {
NSLog("ERROR:::\(error.debugDescription)")
}
PHPhotoLibrary.shared().performChanges({
PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: "xxx")
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: finalFilename))
}) { completed, error in
if completed {
NSLog("Video \(self.videoOutputFullFileName ?? "") has been moved to camera roll")
}
if error != nil {
NSLog("ERROR:::Cannot move the video \(self.videoOutputFullFileName ?? "") to camera roll, error: \(error!.localizedDescription)")
}
finishedWriting = true
}
} else {
NSLog("ERROR:::The file: \(self.videoOutputFullFileName ?? "") doesn't exist, so can't move this file camera roll")
finishedWriting = true
}
} else {
NSLog("WARN:::The videoWriter status is not completed, status: \(videoWriter.status)")
finishedWriting = true
}
}
while finishedWriting == false {
// NSLog("DEBUG:::Waiting to finish writing...")
}
```
I would think you'd have to also call `extensionContext.completeRequest` at some point, but mine's working fine without it *shrug*.
|
You can try this:
```
override func broadcastFinished() {
Log(#function)
...
// Need to give the end CMTime, if not set, the video cannot be used
videoWriter.endSession(atSourceTime: ...)
videoWriter.finishWriting {
// Callback cannot be executed here
}
...
// The program has been executed.
}
```
|
46,903,118 |
I'm streaming a content of my app to my RTMP server and using RPBroadcastSampleHandler.
One of the methods is
```
override func processSampleBuffer(_ sampleBuffer: CMSampleBuffer, with sampleBufferType: RPSampleBufferType) {
switch sampleBufferType {
case .video:
streamer.appendSampleBuffer(sampleBuffer, withType: .video)
captureOutput(sampleBuffer)
case .audioApp:
streamer.appendSampleBuffer(sampleBuffer, withType: .audio)
captureAudioOutput(sampleBuffer)
case .audioMic:
()
}
}
```
And the captureOutput method is
```
self.lastSampleTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
// Append the sampleBuffer into videoWriterInput
if self.isRecordingVideo {
if self.videoWriterInput!.isReadyForMoreMediaData {
if self.videoWriter!.status == AVAssetWriterStatus.writing {
let whetherAppendSampleBuffer = self.videoWriterInput!.append(sampleBuffer)
print(">>>>>>>>>>>>>The time::: \(self.lastSampleTime.value)/\(self.lastSampleTime.timescale)")
if whetherAppendSampleBuffer {
print("DEBUG::: Append sample buffer successfully")
} else {
print("WARN::: Append sample buffer failed")
}
} else {
print("WARN:::The videoWriter status is not writing")
}
} else {
print("WARN:::Cannot append sample buffer into videoWriterInput")
}
}
```
Since this sample buffer contains audio/video data, I figured I can use AVKit to save it locally while streaming. So what I'm doing is creating an asset writer at the start of the stream:
```
let fileManager = FileManager.default
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
self.videoOutputFullFileName = documentsPath.stringByAppendingPathComponent(str: "test_capture_video.mp4")
if self.videoOutputFullFileName == nil {
print("ERROR:The video output file name is nil")
return
}
self.isRecordingVideo = true
if fileManager.fileExists(atPath: self.videoOutputFullFileName!) {
print("WARN:::The file: \(self.videoOutputFullFileName!) exists, will delete the existing file")
do {
try fileManager.removeItem(atPath: self.videoOutputFullFileName!)
} catch let error as NSError {
print("WARN:::Cannot delete existing file: \(self.videoOutputFullFileName!), error: \(error.debugDescription)")
}
} else {
print("DEBUG:::The file \(self.videoOutputFullFileName!) doesn't exist")
}
let screen = UIScreen.main
let screenBounds = info.size
let videoCompressionPropertys = [
AVVideoAverageBitRateKey: screenBounds.width * screenBounds.height * 10.1
]
let videoSettings: [String: Any] = [
AVVideoCodecKey: AVVideoCodecH264,
AVVideoWidthKey: screenBounds.width,
AVVideoHeightKey: screenBounds.height,
AVVideoCompressionPropertiesKey: videoCompressionPropertys
]
self.videoWriterInput = AVAssetWriterInput(mediaType: AVMediaTypeVideo, outputSettings: videoSettings)
guard let videoWriterInput = self.videoWriterInput else {
print("ERROR:::No video writer input")
return
}
videoWriterInput.expectsMediaDataInRealTime = true
// Add the audio input
var acl = AudioChannelLayout()
memset(&acl, 0, MemoryLayout<AudioChannelLayout>.size)
acl.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
let audioOutputSettings: [String: Any] =
[ AVFormatIDKey: kAudioFormatMPEG4AAC,
AVSampleRateKey : 44100,
AVNumberOfChannelsKey : 1,
AVEncoderBitRateKey : 64000,
AVChannelLayoutKey : Data(bytes: &acl, count: MemoryLayout<AudioChannelLayout>.size)]
audioWriterInput = AVAssetWriterInput(mediaType: AVMediaTypeAudio, outputSettings: audioOutputSettings)
guard let audioWriterInput = self.audioWriterInput else {
print("ERROR:::No audio writer input")
return
}
audioWriterInput.expectsMediaDataInRealTime = true
do {
self.videoWriter = try AVAssetWriter(outputURL: URL(fileURLWithPath: self.videoOutputFullFileName!), fileType: AVFileTypeMPEG4)
} catch let error as NSError {
print("ERROR:::::>>>>>>>>>>>>>Cannot init videoWriter, error:\(error.localizedDescription)")
}
guard let videoWriter = self.videoWriter else {
print("ERROR:::No video writer")
return
}
if videoWriter.canAdd(videoWriterInput) {
videoWriter.add(videoWriterInput)
} else {
print("ERROR:::Cannot add videoWriterInput into videoWriter")
}
//Add audio input
if videoWriter.canAdd(audioWriterInput) {
videoWriter.add(audioWriterInput)
} else {
print("ERROR:::Cannot add audioWriterInput into videoWriter")
}
if videoWriter.status != AVAssetWriterStatus.writing {
print("DEBUG::::::::::::::::The videoWriter status is not writing, and will start writing the video.")
let hasStartedWriting = videoWriter.startWriting()
if hasStartedWriting {
videoWriter.startSession(atSourceTime: self.lastSampleTime)
print("DEBUG:::Have started writting on videoWriter, session at source time: \(self.lastSampleTime)")
LOG(videoWriter.status.rawValue)
} else {
print("WARN:::Fail to start writing on videoWriter")
}
} else {
print("WARN:::The videoWriter.status is writing now, so cannot start writing action on videoWriter")
}
```
And then saving and finishing writing at the end of the stream:
```
print("DEBUG::: Starting to process recorder final...")
print("DEBUG::: videoWriter status: \(self.videoWriter!.status.rawValue)")
self.isRecordingVideo = false
guard let videoWriterInput = self.videoWriterInput else {
print("ERROR:::No video writer input")
return
}
guard let videoWriter = self.videoWriter else {
print("ERROR:::No video writer")
return
}
guard let audioWriterInput = self.audioWriterInput else {
print("ERROR:::No audio writer input")
return
}
videoWriterInput.markAsFinished()
audioWriterInput.markAsFinished()
videoWriter.finishWriting {
if videoWriter.status == AVAssetWriterStatus.completed {
print("DEBUG:::The videoWriter status is completed")
let fileManager = FileManager.default
if fileManager.fileExists(atPath: self.videoOutputFullFileName!) {
print("DEBUG:::The file: \(self.videoOutputFullFileName ?? "") has been saved in documents folder, and is ready to be moved to camera roll")
let sharedFileURL = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.jp.awalker.co.Hotter")
guard let documentsPath = sharedFileURL?.path else {
LOG("ERROR:::No shared file URL path")
return
}
let finalFilename = documentsPath.stringByAppendingPathComponent(str: "test_capture_video.mp4")
//Check whether file exists
if fileManager.fileExists(atPath: finalFilename) {
print("WARN:::The file: \(finalFilename) exists, will delete the existing file")
do {
try fileManager.removeItem(atPath: finalFilename)
} catch let error as NSError {
print("WARN:::Cannot delete existing file: \(finalFilename), error: \(error.debugDescription)")
}
} else {
print("DEBUG:::The file \(self.videoOutputFullFileName!) doesn't exist")
}
do {
try fileManager.copyItem(at: URL(fileURLWithPath: self.videoOutputFullFileName!), to: URL(fileURLWithPath: finalFilename))
}
catch let error as NSError {
LOG("ERROR:::\(error.debugDescription)")
}
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: finalFilename))
}) { completed, error in
if completed {
print("Video \(self.videoOutputFullFileName ?? "") has been moved to camera roll")
}
if error != nil {
print ("ERROR:::Cannot move the video \(self.videoOutputFullFileName ?? "") to camera roll, error: \(error!.localizedDescription)")
}
}
} else {
print("ERROR:::The file: \(self.videoOutputFullFileName ?? "") doesn't exist, so can't move this file camera roll")
}
} else {
print("WARN:::The videoWriter status is not completed, stauts: \(videoWriter.status)")
}
}
```
The problem I'm having is the finishWriting completion code is never being reached. The writer stays in "writing" status therefore the video file is not saved.
If I remove the "finishWriting" line and just leave the completion code to run, a file is being saved, but not properly finished and when I'm trying to view it it's unplayable because it's probably missing metadata.
Is there any other way to do this? I don't want to actually start capturing using AVKit to save the recording, because it's taking too much of the CPU and the RPBroadcastSampleHandler's CMSampleBuffer already has the video data, but maybe using AVKit at all is a wrong move here?
What should I change? How do I save the video from that CMSampleBuffer?
|
2017/10/24
|
[
"https://Stackoverflow.com/questions/46903118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3715075/"
] |
@Marty's answer should be accepted because he pointed out the problem and its `DispatchGroup` solution works perfectly.
Since he used a `while` loop and didn't describe how to use `DispatchGroup`s, here's the way I implemented it.
```
override func broadcastFinished() {
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
self.writerInput.markAsFinished()
self.writer.finishWriting {
// Do your work to here to make video available
dispatchGroup.leave()
}
dispatchGroup.wait() // <= blocks the thread here
}
```
|
You can try this:
```
override func broadcastFinished() {
Log(#function)
...
// Need to give the end CMTime, if not set, the video cannot be used
videoWriter.endSession(atSourceTime: ...)
videoWriter.finishWriting {
// Callback cannot be executed here
}
...
// The program has been executed.
}
```
|
79,239 |
I assigned the AE-L, AF-L button to activate focusing on my Nikon D5500, but I can still focus using the shutter button.
I would like to know if it was possible to use the AE-L/AF-L button to set focus only and the shutter button to take photos only.
|
2016/06/13
|
[
"https://photo.stackexchange.com/questions/79239",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/53081/"
] |
According to page 267 of the [*D5500 Reference Manual*](http://download.nikonimglib.com/archive2/ghyQp00UIXvI02ubPLg17JWflV37/D5500RM_(En)02.pdf), using custom setting f2 to set the AE-L/AF-L button to *AF-ON* prevents the shutter release button from focusing.
[](https://i.stack.imgur.com/6l6Tz.png)
|
Did you put the camera in Continuous mode? I understand back button trick will not work if it isn't in Continuous mode.
|
79,239 |
I assigned the AE-L, AF-L button to activate focusing on my Nikon D5500, but I can still focus using the shutter button.
I would like to know if it was possible to use the AE-L/AF-L button to set focus only and the shutter button to take photos only.
|
2016/06/13
|
[
"https://photo.stackexchange.com/questions/79239",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/53081/"
] |
According to page 267 of the [*D5500 Reference Manual*](http://download.nikonimglib.com/archive2/ghyQp00UIXvI02ubPLg17JWflV37/D5500RM_(En)02.pdf), using custom setting f2 to set the AE-L/AF-L button to *AF-ON* prevents the shutter release button from focusing.
[](https://i.stack.imgur.com/6l6Tz.png)
|
I think I know what happens. If you have set ae-l af-l af af-on and press the button to focus it will focus the lens and the focus confirmation dot will light up in the viewfinder.now if you press the shutter button with the lens still in focus( from pressing ae-l af-l) the focus confirmation dot will light up again :it does not mean that pressing the shutter button activated focus, just that focus had been acquired. To test easily try to focus on a object at a different distance with the shutter button first: it will not focus and you will not see the focus confirmation dot in the viewfinder
|
79,239 |
I assigned the AE-L, AF-L button to activate focusing on my Nikon D5500, but I can still focus using the shutter button.
I would like to know if it was possible to use the AE-L/AF-L button to set focus only and the shutter button to take photos only.
|
2016/06/13
|
[
"https://photo.stackexchange.com/questions/79239",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/53081/"
] |
According to page 267 of the [*D5500 Reference Manual*](http://download.nikonimglib.com/archive2/ghyQp00UIXvI02ubPLg17JWflV37/D5500RM_(En)02.pdf), using custom setting f2 to set the AE-L/AF-L button to *AF-ON* prevents the shutter release button from focusing.
[](https://i.stack.imgur.com/6l6Tz.png)
|
Beside AF-ON button you need to release shutter from autofocus. Check [this manual](https://www.oreilly.com/library/view/nikon-d600-for/9781118530818/ch10-sec013.html) how to do it:
>
> The setting in question is found on the Timers/AE Lock submenu of the
> Custom Setting menu and is called Shutter-Release Button AE-L, as
> shown in Figure 10-21. If you set the option to On, your half-press of
> the shutter button locks both focus and exposure. This option affects
> movie recording as well as still photography.
>
>
>
|
79,239 |
I assigned the AE-L, AF-L button to activate focusing on my Nikon D5500, but I can still focus using the shutter button.
I would like to know if it was possible to use the AE-L/AF-L button to set focus only and the shutter button to take photos only.
|
2016/06/13
|
[
"https://photo.stackexchange.com/questions/79239",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/53081/"
] |
According to page 267 of the [*D5500 Reference Manual*](http://download.nikonimglib.com/archive2/ghyQp00UIXvI02ubPLg17JWflV37/D5500RM_(En)02.pdf), using custom setting f2 to set the AE-L/AF-L button to *AF-ON* prevents the shutter release button from focusing.
[](https://i.stack.imgur.com/6l6Tz.png)
|
I had the same problem
you have to disable "AF Activation", It should be at same place where you remap buttons
I know this is an old post but hope it helps anyone who get the same problem in the future
|
55,555,068 |
I have an issue with a table called "movies". I found the date and the movie title are both in the title column. As shown in the picture:

I don't know how to deal with this kind of issues. So, I tried to play with this code to make it similar to MySQL codes but I didn't work anyways.
```
DataFrame(row.str.split(' ',-1).tolist(),columns = ['title','date'])
```
How do I split it in two columns (title, date)?
|
2019/04/07
|
[
"https://Stackoverflow.com/questions/55555068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9676465/"
] |
If you are using MySQL 8+, then we can try using `REGEXP_REPLACE`:
```
SELECT
REGEXP_REPLACE(title, '^(.*)\\s\\(.*$', '$1') AS title,
REGEXP_REPLACE(title, '^.*\\s\\((\\d+)\\)$', '$1') AS date
FROM yourTable;
```
[Demo
----](https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=ddf875c09f4e136f60f9c51ee1231794)
Here is a general regex pattern which can match your title strings:
```
^.*\s\((\d+)\)$
```
Explanation:
```
^ from the start of the string
(.*)\s match and capture anything, up to the last space
\( match a literal opening parenthesis
(\d+) match and capture the year (any number of digits)
\) match a literal closing parenthesis
$ end of string
```
|
I would simply do:
```
select left(title, length(title) - 7) as title,
replace(right(title, 5) ,')', '') as year
```
Regular expressions seem like overkill for this logic.
In Hive, you need to use `substr()` for this:
```
select substr(title, 1, length(title) - 7) as title,
substr(title, length(title) - 5, 4) as year
```
|
55,555,068 |
I have an issue with a table called "movies". I found the date and the movie title are both in the title column. As shown in the picture:

I don't know how to deal with this kind of issues. So, I tried to play with this code to make it similar to MySQL codes but I didn't work anyways.
```
DataFrame(row.str.split(' ',-1).tolist(),columns = ['title','date'])
```
How do I split it in two columns (title, date)?
|
2019/04/07
|
[
"https://Stackoverflow.com/questions/55555068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9676465/"
] |
If you are using MySQL 8+, then we can try using `REGEXP_REPLACE`:
```
SELECT
REGEXP_REPLACE(title, '^(.*)\\s\\(.*$', '$1') AS title,
REGEXP_REPLACE(title, '^.*\\s\\((\\d+)\\)$', '$1') AS date
FROM yourTable;
```
[Demo
----](https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=ddf875c09f4e136f60f9c51ee1231794)
Here is a general regex pattern which can match your title strings:
```
^.*\s\((\d+)\)$
```
Explanation:
```
^ from the start of the string
(.*)\s match and capture anything, up to the last space
\( match a literal opening parenthesis
(\d+) match and capture the year (any number of digits)
\) match a literal closing parenthesis
$ end of string
```
|
After struggling and searching I was able to build this command which works perfectly.
```
select
translate(substr(title,0,length(title) -6) ,'', '') as title,
translate(substr(title, -5) ,')', '') as date
from movies;
```
Thanks for the people who answered too!
|
3,492,676 |
When I click the 'run as Android application' option, it shows the following error:
```
[2010-08-16 16:56:35 - Emulator] invalid command-line parameter: http://hostname:port.
[2010-08-16 16:56:35 - Emulator] Hint: use '@foo' to launch a virtual device named 'foo'.
[2010-08-16 16:56:35 - Emulator] please use -help for more information
```
|
2010/08/16
|
[
"https://Stackoverflow.com/questions/3492676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/421645/"
] |
i did the following and my problem was solved(MY PROBLEM:when i wanted to run an emulator from the AVD manager,i received the following error
"invalid command-line parameter: Files.
Hint: use '@foo' to launch a virtual device named 'foo'.
please use -help for more information")
i think its happens when in the path of android.exe (in the tools folder in android-sdk directory) any space exists (like C:/Program Files(x86)/... between Program and Files)
So what did i do?
-i deleted all virtual devices that have created.
-copied the whole android-sdk folder somewhere else.
-uninstalled and reinstalled SDK in another path without any spaces(like C:/Android/android-sdk)
-i copied the contents of old sdk-android (which was copied before uninstalling) like platform tools and platforms folders to the new path.(you can download platform tools and platform(s) again from the avd manager but this waist time)
it worked for me and i hope it works for you too.
thanks
|
This trick doesn't work in IntelliJ. To solve it I moved the Android SDK to c:\android-sdk-windows.
After that you still have to change the path to Android in IntelliJ of course:
- right click on the module -> open module settings
- go to: platform settings -> SDKs -> Android
Or delete the previous one and create a new one
|
3,492,676 |
When I click the 'run as Android application' option, it shows the following error:
```
[2010-08-16 16:56:35 - Emulator] invalid command-line parameter: http://hostname:port.
[2010-08-16 16:56:35 - Emulator] Hint: use '@foo' to launch a virtual device named 'foo'.
[2010-08-16 16:56:35 - Emulator] please use -help for more information
```
|
2010/08/16
|
[
"https://Stackoverflow.com/questions/3492676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/421645/"
] |
I've been trying to solve this same problem for two days now, and I just found a solution which works for me:
Cut the 'Android' file folder from it's place in the 'Program Files' (or 'Program Files (x86)' if you use Windows 7) folder and paste it directly in the C:\ directory
Your SDK file path should look like this:
C:\Android\android-sdk
Simple as that :D Now the Android debugger shouldn't worry about there being a space in the file path. Let me know if additional clarification is needed
|
Delete your previous Virtual devices. Re create it. launch it.
Once the emulator is running, run your application.
Other wise, go to your run configuration and select the emulator you would like to run.
|
3,492,676 |
When I click the 'run as Android application' option, it shows the following error:
```
[2010-08-16 16:56:35 - Emulator] invalid command-line parameter: http://hostname:port.
[2010-08-16 16:56:35 - Emulator] Hint: use '@foo' to launch a virtual device named 'foo'.
[2010-08-16 16:56:35 - Emulator] please use -help for more information
```
|
2010/08/16
|
[
"https://Stackoverflow.com/questions/3492676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/421645/"
] |
I had this same exact error when I would try to launch the emulator from Eclipse. I had all my Android files in my documents to begin with, not my program files. I moved these files and still had the problem because of my user name having a space in it.
So I took the suggestion of Andrew McGarry and put my Android SDK folder in my C: directory and viola, problem solved...well after I redirected it in Eclipse obviously lol.
Just make sure that nothing in your SDK path has a space in it and you should be fine. You shouldn't have to uninstall or delete anything, and you probably won't have to move any files around either. Remember...no spaces in the entire path. =)
|
I've been trying to solve this same problem,and I just found a solution which works for me:
@First i saw a file named adb\_has\_moved.txt.The contents of the file were
"The adb tool has moved to platform-tools/
If you don't see this directory in your SDK,
launch the SDK and AVD Manager (execute the android tool)
and install "Android SDK Platform-tools"
Please also update your PATH environment variable to
include the platform-tools/ directory, so you can
execute adb from any location.
"
so i copied adb.exe from platform-tools to tools......***BUT THAT DIDN'T WORKED OUT***
Then i tried the next solution that is to create a new device bt that also flopped
removing old virtual devices and creating new one was also not working for me
SO i tried the ***solution below*** and stated by many.i found it from a spanish blog.i dont knw spanish bt i do knw google translate.
It seems the problem is the spaces in the path for example:C:\Program Files\Android\android-sdk
CHANGE THIS TO
C:\PROGRA~1\Android\android-sdk
***It really worked out for me.***
|
3,492,676 |
When I click the 'run as Android application' option, it shows the following error:
```
[2010-08-16 16:56:35 - Emulator] invalid command-line parameter: http://hostname:port.
[2010-08-16 16:56:35 - Emulator] Hint: use '@foo' to launch a virtual device named 'foo'.
[2010-08-16 16:56:35 - Emulator] please use -help for more information
```
|
2010/08/16
|
[
"https://Stackoverflow.com/questions/3492676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/421645/"
] |
Apparently the problem are the spaces in the path, so just from:
`C:\Program Files\Android\android-sdk`
to:
`C:\PROGRA~1\Android\android-sdk`
If you have a 64 bit system
From:
`C:\Program Files (x86)\Android\android-sdk`
to:
`C:\PROGRA~2\Android\android-sdk`
Under Windows->Preferences->Android Change the SDK Location as shown above.
Translated from: <http://satoriwd.com/astath/?p=11>
|
I had this same exact error when I would try to launch the emulator from Eclipse. I had all my Android files in my documents to begin with, not my program files. I moved these files and still had the problem because of my user name having a space in it.
So I took the suggestion of Andrew McGarry and put my Android SDK folder in my C: directory and viola, problem solved...well after I redirected it in Eclipse obviously lol.
Just make sure that nothing in your SDK path has a space in it and you should be fine. You shouldn't have to uninstall or delete anything, and you probably won't have to move any files around either. Remember...no spaces in the entire path. =)
|
3,492,676 |
When I click the 'run as Android application' option, it shows the following error:
```
[2010-08-16 16:56:35 - Emulator] invalid command-line parameter: http://hostname:port.
[2010-08-16 16:56:35 - Emulator] Hint: use '@foo' to launch a virtual device named 'foo'.
[2010-08-16 16:56:35 - Emulator] please use -help for more information
```
|
2010/08/16
|
[
"https://Stackoverflow.com/questions/3492676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/421645/"
] |
i did the following and my problem was solved(MY PROBLEM:when i wanted to run an emulator from the AVD manager,i received the following error
"invalid command-line parameter: Files.
Hint: use '@foo' to launch a virtual device named 'foo'.
please use -help for more information")
i think its happens when in the path of android.exe (in the tools folder in android-sdk directory) any space exists (like C:/Program Files(x86)/... between Program and Files)
So what did i do?
-i deleted all virtual devices that have created.
-copied the whole android-sdk folder somewhere else.
-uninstalled and reinstalled SDK in another path without any spaces(like C:/Android/android-sdk)
-i copied the contents of old sdk-android (which was copied before uninstalling) like platform tools and platforms folders to the new path.(you can download platform tools and platform(s) again from the avd manager but this waist time)
it worked for me and i hope it works for you too.
thanks
|
Delete your previous Virtual devices. Re create it. launch it.
Once the emulator is running, run your application.
Other wise, go to your run configuration and select the emulator you would like to run.
|
3,492,676 |
When I click the 'run as Android application' option, it shows the following error:
```
[2010-08-16 16:56:35 - Emulator] invalid command-line parameter: http://hostname:port.
[2010-08-16 16:56:35 - Emulator] Hint: use '@foo' to launch a virtual device named 'foo'.
[2010-08-16 16:56:35 - Emulator] please use -help for more information
```
|
2010/08/16
|
[
"https://Stackoverflow.com/questions/3492676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/421645/"
] |
Apparently the problem are the spaces in the path, so just from:
`C:\Program Files\Android\android-sdk`
to:
`C:\PROGRA~1\Android\android-sdk`
If you have a 64 bit system
From:
`C:\Program Files (x86)\Android\android-sdk`
to:
`C:\PROGRA~2\Android\android-sdk`
Under Windows->Preferences->Android Change the SDK Location as shown above.
Translated from: <http://satoriwd.com/astath/?p=11>
|
I've been trying to solve this same problem for two days now, and I just found a solution which works for me:
Cut the 'Android' file folder from it's place in the 'Program Files' (or 'Program Files (x86)' if you use Windows 7) folder and paste it directly in the C:\ directory
Your SDK file path should look like this:
C:\Android\android-sdk
Simple as that :D Now the Android debugger shouldn't worry about there being a space in the file path. Let me know if additional clarification is needed
|
3,492,676 |
When I click the 'run as Android application' option, it shows the following error:
```
[2010-08-16 16:56:35 - Emulator] invalid command-line parameter: http://hostname:port.
[2010-08-16 16:56:35 - Emulator] Hint: use '@foo' to launch a virtual device named 'foo'.
[2010-08-16 16:56:35 - Emulator] please use -help for more information
```
|
2010/08/16
|
[
"https://Stackoverflow.com/questions/3492676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/421645/"
] |
I've been trying to solve this same problem,and I just found a solution which works for me:
@First i saw a file named adb\_has\_moved.txt.The contents of the file were
"The adb tool has moved to platform-tools/
If you don't see this directory in your SDK,
launch the SDK and AVD Manager (execute the android tool)
and install "Android SDK Platform-tools"
Please also update your PATH environment variable to
include the platform-tools/ directory, so you can
execute adb from any location.
"
so i copied adb.exe from platform-tools to tools......***BUT THAT DIDN'T WORKED OUT***
Then i tried the next solution that is to create a new device bt that also flopped
removing old virtual devices and creating new one was also not working for me
SO i tried the ***solution below*** and stated by many.i found it from a spanish blog.i dont knw spanish bt i do knw google translate.
It seems the problem is the spaces in the path for example:C:\Program Files\Android\android-sdk
CHANGE THIS TO
C:\PROGRA~1\Android\android-sdk
***It really worked out for me.***
|
Delete your previous Virtual devices. Re create it. launch it.
Once the emulator is running, run your application.
Other wise, go to your run configuration and select the emulator you would like to run.
|
3,492,676 |
When I click the 'run as Android application' option, it shows the following error:
```
[2010-08-16 16:56:35 - Emulator] invalid command-line parameter: http://hostname:port.
[2010-08-16 16:56:35 - Emulator] Hint: use '@foo' to launch a virtual device named 'foo'.
[2010-08-16 16:56:35 - Emulator] please use -help for more information
```
|
2010/08/16
|
[
"https://Stackoverflow.com/questions/3492676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/421645/"
] |
Apparently the problem are the spaces in the path, so just from:
`C:\Program Files\Android\android-sdk`
to:
`C:\PROGRA~1\Android\android-sdk`
If you have a 64 bit system
From:
`C:\Program Files (x86)\Android\android-sdk`
to:
`C:\PROGRA~2\Android\android-sdk`
Under Windows->Preferences->Android Change the SDK Location as shown above.
Translated from: <http://satoriwd.com/astath/?p=11>
|
I've been trying to solve this same problem,and I just found a solution which works for me:
@First i saw a file named adb\_has\_moved.txt.The contents of the file were
"The adb tool has moved to platform-tools/
If you don't see this directory in your SDK,
launch the SDK and AVD Manager (execute the android tool)
and install "Android SDK Platform-tools"
Please also update your PATH environment variable to
include the platform-tools/ directory, so you can
execute adb from any location.
"
so i copied adb.exe from platform-tools to tools......***BUT THAT DIDN'T WORKED OUT***
Then i tried the next solution that is to create a new device bt that also flopped
removing old virtual devices and creating new one was also not working for me
SO i tried the ***solution below*** and stated by many.i found it from a spanish blog.i dont knw spanish bt i do knw google translate.
It seems the problem is the spaces in the path for example:C:\Program Files\Android\android-sdk
CHANGE THIS TO
C:\PROGRA~1\Android\android-sdk
***It really worked out for me.***
|
3,492,676 |
When I click the 'run as Android application' option, it shows the following error:
```
[2010-08-16 16:56:35 - Emulator] invalid command-line parameter: http://hostname:port.
[2010-08-16 16:56:35 - Emulator] Hint: use '@foo' to launch a virtual device named 'foo'.
[2010-08-16 16:56:35 - Emulator] please use -help for more information
```
|
2010/08/16
|
[
"https://Stackoverflow.com/questions/3492676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/421645/"
] |
I was facing the same problem with Android when executing the emulator, and I found a solution right now. Please follow these steps:
1. Uninstall the SDK that you have already installed
2. Create a folder in disc C
3. Name it like Android
4. Open it and create inside it a new folder, for me I named it PROGRA~1
5. Execute the installation of your SDK to be installed in the folder created PROGRA~1
|
I've been trying to solve this same problem,and I just found a solution which works for me:
@First i saw a file named adb\_has\_moved.txt.The contents of the file were
"The adb tool has moved to platform-tools/
If you don't see this directory in your SDK,
launch the SDK and AVD Manager (execute the android tool)
and install "Android SDK Platform-tools"
Please also update your PATH environment variable to
include the platform-tools/ directory, so you can
execute adb from any location.
"
so i copied adb.exe from platform-tools to tools......***BUT THAT DIDN'T WORKED OUT***
Then i tried the next solution that is to create a new device bt that also flopped
removing old virtual devices and creating new one was also not working for me
SO i tried the ***solution below*** and stated by many.i found it from a spanish blog.i dont knw spanish bt i do knw google translate.
It seems the problem is the spaces in the path for example:C:\Program Files\Android\android-sdk
CHANGE THIS TO
C:\PROGRA~1\Android\android-sdk
***It really worked out for me.***
|
3,492,676 |
When I click the 'run as Android application' option, it shows the following error:
```
[2010-08-16 16:56:35 - Emulator] invalid command-line parameter: http://hostname:port.
[2010-08-16 16:56:35 - Emulator] Hint: use '@foo' to launch a virtual device named 'foo'.
[2010-08-16 16:56:35 - Emulator] please use -help for more information
```
|
2010/08/16
|
[
"https://Stackoverflow.com/questions/3492676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/421645/"
] |
Apparently the problem are the spaces in the path, so just from:
`C:\Program Files\Android\android-sdk`
to:
`C:\PROGRA~1\Android\android-sdk`
If you have a 64 bit system
From:
`C:\Program Files (x86)\Android\android-sdk`
to:
`C:\PROGRA~2\Android\android-sdk`
Under Windows->Preferences->Android Change the SDK Location as shown above.
Translated from: <http://satoriwd.com/astath/?p=11>
|
Delete your previous Virtual devices. Re create it. launch it.
Once the emulator is running, run your application.
Other wise, go to your run configuration and select the emulator you would like to run.
|
56,753,215 |
I'm trying to build a dropdown menu using react. But I couldn't get it to get the onchange working.
I tried few methods but still no sucess. Data loads into the dropdown and when I select one, nothing changes.
```
constructor(props) {
super(props);
this.state = {
serviceList: []
};
this.loadData = this.loadData.bind(this);
this.update = this.update.bind(this);
this.delete = this.delete.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e){
this.setState({[e.target.Name]: e.target.value})
}
fillDropdowncus(list){
let result = [];
for (var key in list) {
result.push({ key: list[key]['CusId'] , text: list[key]['CusName'] })
}
return result;
}
<Form.Field>
<label>Select customer</label><br />
<Dropdown selection options={this.fillDropdowncus(this.state.customersList)} onChange={this.handleChange} name="selectCustomer" placeholder='Select Customer' /><br />
</Form.Field>
```
|
2019/06/25
|
[
"https://Stackoverflow.com/questions/56753215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11697150/"
] |
Your `valueChange` should be `handleChange`.
```
<Dropdown selection options={this.fillDropdowncus(this.state.customersList)} onChange={this.handleChange} name="selectCustomer" placeholder='Select Customer' />
```
|
Always try to call the functions in an anonymous function first. Try calling onChange={this.handleChange} in your Dropdown class with onChange={() =>this.handleChange}
|
39,783,188 |
I want to call a JS Script in Ajax response. What it does is pass the `document.getElementById` script to the Ajax responseText.
The current code returns me this error: `Uncaught TypeError: Cannot set property 'innerHTML' of null`
This is done with Visual Studio Cordova..
Ajax:
```
$("#loginBtn").click(function() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.write(this.responseText);
}
}
xmlhttp.open("POST", "http://www.sampleee.esy.es/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + username + "&" + "password=" + password);
});
```
PHP:
```
if($count == 1){
echo "document.getElementById('alertBox').innerHTML = 'Login Success!';
document.getElementById('alertBox').className = 'alert alert-success';
document.getElementById('alertBox').style.display = 'block';
setTimeout(function () {
window.location.href = '../html/dashboard.html';
}, 1000);
";
}else{
echo "document.getElementById('alertBox').innerHTML = 'Invalid login details';
document.getElementById('alertBox').className = 'alert alert-danger';
document.getElementById('alertBox').style.display = 'block';
";
}
```
|
2016/09/30
|
[
"https://Stackoverflow.com/questions/39783188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6311169/"
] |
The documentation shows how to install Docker on Amazon Linux instances not ubuntu. The user youre logged in with doesnt matter, just replace the yum commands with the apt-get equivalents or switch to using an Amazon Linux AMI.
|
For **Ubuntu**, you can use:
**$ sudo apt-get update**
you might have been checking the documentation of **RHEL** which needs
$ sudo yum update -y
If you are working behind a **proxy**, Make sure you configure the proxy for Docker.
Hope it helps.. **:)**
|
39,783,188 |
I want to call a JS Script in Ajax response. What it does is pass the `document.getElementById` script to the Ajax responseText.
The current code returns me this error: `Uncaught TypeError: Cannot set property 'innerHTML' of null`
This is done with Visual Studio Cordova..
Ajax:
```
$("#loginBtn").click(function() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.write(this.responseText);
}
}
xmlhttp.open("POST", "http://www.sampleee.esy.es/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + username + "&" + "password=" + password);
});
```
PHP:
```
if($count == 1){
echo "document.getElementById('alertBox').innerHTML = 'Login Success!';
document.getElementById('alertBox').className = 'alert alert-success';
document.getElementById('alertBox').style.display = 'block';
setTimeout(function () {
window.location.href = '../html/dashboard.html';
}, 1000);
";
}else{
echo "document.getElementById('alertBox').innerHTML = 'Invalid login details';
document.getElementById('alertBox').className = 'alert alert-danger';
document.getElementById('alertBox').style.display = 'block';
";
}
```
|
2016/09/30
|
[
"https://Stackoverflow.com/questions/39783188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6311169/"
] |
The documentation shows how to install Docker on Amazon Linux instances not ubuntu. The user youre logged in with doesnt matter, just replace the yum commands with the apt-get equivalents or switch to using an Amazon Linux AMI.
|
Follow below commands on ubuntu ec2 :
1. curl -fsSL <https://download.docker.com/linux/ubuntu/gpg> | sudo apt-key add -;
2. sudo add-apt-repository "deb [arch=amd64] <https://download.docker.com/linux/ubuntu> $(lsb\_release -cs) stable";
3. sudo apt-get update -y;
4. sudo apt-cache policy docker-ce; ( Here select the required one from this step for the next step)
5. sudo apt-get install docker-ce=5:18.09.2~3-0~ubuntu-xenial;
6. sudo service docker start;
|
39,783,188 |
I want to call a JS Script in Ajax response. What it does is pass the `document.getElementById` script to the Ajax responseText.
The current code returns me this error: `Uncaught TypeError: Cannot set property 'innerHTML' of null`
This is done with Visual Studio Cordova..
Ajax:
```
$("#loginBtn").click(function() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.write(this.responseText);
}
}
xmlhttp.open("POST", "http://www.sampleee.esy.es/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + username + "&" + "password=" + password);
});
```
PHP:
```
if($count == 1){
echo "document.getElementById('alertBox').innerHTML = 'Login Success!';
document.getElementById('alertBox').className = 'alert alert-success';
document.getElementById('alertBox').style.display = 'block';
setTimeout(function () {
window.location.href = '../html/dashboard.html';
}, 1000);
";
}else{
echo "document.getElementById('alertBox').innerHTML = 'Invalid login details';
document.getElementById('alertBox').className = 'alert alert-danger';
document.getElementById('alertBox').style.display = 'block';
";
}
```
|
2016/09/30
|
[
"https://Stackoverflow.com/questions/39783188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6311169/"
] |
You use simple curl command to install docker on any Linux machine.
**curl -SsL <https://get.docker.com> | bash**
Above command will automatically solve all the dependencies and install docker.
|
For **Ubuntu**, you can use:
**$ sudo apt-get update**
you might have been checking the documentation of **RHEL** which needs
$ sudo yum update -y
If you are working behind a **proxy**, Make sure you configure the proxy for Docker.
Hope it helps.. **:)**
|
39,783,188 |
I want to call a JS Script in Ajax response. What it does is pass the `document.getElementById` script to the Ajax responseText.
The current code returns me this error: `Uncaught TypeError: Cannot set property 'innerHTML' of null`
This is done with Visual Studio Cordova..
Ajax:
```
$("#loginBtn").click(function() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.write(this.responseText);
}
}
xmlhttp.open("POST", "http://www.sampleee.esy.es/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + username + "&" + "password=" + password);
});
```
PHP:
```
if($count == 1){
echo "document.getElementById('alertBox').innerHTML = 'Login Success!';
document.getElementById('alertBox').className = 'alert alert-success';
document.getElementById('alertBox').style.display = 'block';
setTimeout(function () {
window.location.href = '../html/dashboard.html';
}, 1000);
";
}else{
echo "document.getElementById('alertBox').innerHTML = 'Invalid login details';
document.getElementById('alertBox').className = 'alert alert-danger';
document.getElementById('alertBox').style.display = 'block';
";
}
```
|
2016/09/30
|
[
"https://Stackoverflow.com/questions/39783188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6311169/"
] |
You use simple curl command to install docker on any Linux machine.
**curl -SsL <https://get.docker.com> | bash**
Above command will automatically solve all the dependencies and install docker.
|
Follow below commands on ubuntu ec2 :
1. curl -fsSL <https://download.docker.com/linux/ubuntu/gpg> | sudo apt-key add -;
2. sudo add-apt-repository "deb [arch=amd64] <https://download.docker.com/linux/ubuntu> $(lsb\_release -cs) stable";
3. sudo apt-get update -y;
4. sudo apt-cache policy docker-ce; ( Here select the required one from this step for the next step)
5. sudo apt-get install docker-ce=5:18.09.2~3-0~ubuntu-xenial;
6. sudo service docker start;
|
4,604 |
I was trying to talk about films and (marvel) comics the other day, and stumbled upon "**[evil twin](http://tvtropes.org/pmwiki/pmwiki.php/Main/EvilTwin)**". Sure, I can translate it verbatim, but that usually works badly for such fixed expressions.
And then when I was trying to explain it, I couldn't think of a good word for "**trope**" too. Apparently, neither can [jisho.org](http://jisho.org/). There are a few for [cliche](http://jisho.org/words?eng=cliche), but none of these have example sentences that relate remotely to the meaning I am looking for.
Can anyone help me or send me in the right direction? (A Japanese tvtropes.org perhaps?)
Other Japanese trope names (e.g. つんでれ) are welcome.
|
2012/02/08
|
[
"https://japanese.stackexchange.com/questions/4604",
"https://japanese.stackexchange.com",
"https://japanese.stackexchange.com/users/84/"
] |
The word "trope" didn't originally apply to stock characters/plot elements in the way that it is now used in TV Tropes; this is a relatively new (as in past 50 years) usage of the word. This may be why dictionaries come up short: even some English dictionaries I checked didn't cover this meaning.
There is a Japanese wikipedia page for TV tropes, which uses the word トロープ, but this doesn't seem to be a widely used term and the writer of the article felt the need to explain it rather than just giving simple translation:
>
> 創作物に見られる様々な慣例や趣向
>
>
> Various conventions and ideas seen in works of fiction.
>
>
>
So I don't think you will find a single word to cover this. お決まり (and お定まり?) may work for "cliche" in some situations (お決まりの台詞, お決まりのパターン) although they're not limited to fiction. Wikipedia uses 類型 for categorising some things, e.g. ストーリー類型, but again this appears to be a phrase coined for convenience and not widely used in general discussion.
There are some words that will cover some of the things covered by "trope". One (relatively recently coined and probably more an internet slang term than something for academic discussion) is フラグ. I'll quote from wiki again as I think this covers it:
>
> 伏線(ふくせん)と同義であるものの、フラグは比較的単純で定型化された「お決まりのパターン」の含意があるとされる。
>
>
> Although it has the same meaning as 'foreshadowing', 'flag' implies a relatively simple, fixed, "stereotypical pattern".
>
>
>
There are various types of flag (e.g. "death flag", 死亡フラグ). For more description of this term, check dic.nicovideo.jp/ for フラグ and other terms. This site also probably functions as the closest thing to tvtropes in that although it wasn't created for that purpose, if you look up various manga/anime you will find often find links to character types/phrases/story genres associated with that work.
Another useful word is from 落語 originally and is 落ち (when dealing with manga/anime, normally written オチ). There were various set ways of ending a story. A classic one is まわり落ち (ending by returning to the beginning of the story), and 夢オチ is the Japanese name for the "and then he realised it had all been a dream" ending.
The last one is 定番, often in the form (genre name/series)の定番. These are both 2ch examples:
>
> やめてほしいアニメの定番 ("anime staples you want to stop")
>
>
> RPGの定番モンスターの名前を貼っていくスレ ("thread where we post names of typical RPG monsters")
>
>
>
Not necessarily negative, it can also be used to refer to classic/staple/standard examples of a genre, e.g. 定番のクリスマスソング (typical Christmas songs).
|
Isn't "Doppelgänger" (`ドッペルゲンガー`) commonly used to denote "evil twin"? Well, at least an evil version of someone.
|
4,604 |
I was trying to talk about films and (marvel) comics the other day, and stumbled upon "**[evil twin](http://tvtropes.org/pmwiki/pmwiki.php/Main/EvilTwin)**". Sure, I can translate it verbatim, but that usually works badly for such fixed expressions.
And then when I was trying to explain it, I couldn't think of a good word for "**trope**" too. Apparently, neither can [jisho.org](http://jisho.org/). There are a few for [cliche](http://jisho.org/words?eng=cliche), but none of these have example sentences that relate remotely to the meaning I am looking for.
Can anyone help me or send me in the right direction? (A Japanese tvtropes.org perhaps?)
Other Japanese trope names (e.g. つんでれ) are welcome.
|
2012/02/08
|
[
"https://japanese.stackexchange.com/questions/4604",
"https://japanese.stackexchange.com",
"https://japanese.stackexchange.com/users/84/"
] |
Isn't "Doppelgänger" (`ドッペルゲンガー`) commonly used to denote "evil twin"? Well, at least an evil version of someone.
|
I just found another one, which is exactly what I was looking for:
**べた - hackneyed, cliched [1]**
It's marked as "slang", though, and it might be just a version of べたべた. "Sticky" is quite close in connotation.
[1]http://jisho.org/words?jap=beta&eng=&dict=edict
|
4,604 |
I was trying to talk about films and (marvel) comics the other day, and stumbled upon "**[evil twin](http://tvtropes.org/pmwiki/pmwiki.php/Main/EvilTwin)**". Sure, I can translate it verbatim, but that usually works badly for such fixed expressions.
And then when I was trying to explain it, I couldn't think of a good word for "**trope**" too. Apparently, neither can [jisho.org](http://jisho.org/). There are a few for [cliche](http://jisho.org/words?eng=cliche), but none of these have example sentences that relate remotely to the meaning I am looking for.
Can anyone help me or send me in the right direction? (A Japanese tvtropes.org perhaps?)
Other Japanese trope names (e.g. つんでれ) are welcome.
|
2012/02/08
|
[
"https://japanese.stackexchange.com/questions/4604",
"https://japanese.stackexchange.com",
"https://japanese.stackexchange.com/users/84/"
] |
The word "trope" didn't originally apply to stock characters/plot elements in the way that it is now used in TV Tropes; this is a relatively new (as in past 50 years) usage of the word. This may be why dictionaries come up short: even some English dictionaries I checked didn't cover this meaning.
There is a Japanese wikipedia page for TV tropes, which uses the word トロープ, but this doesn't seem to be a widely used term and the writer of the article felt the need to explain it rather than just giving simple translation:
>
> 創作物に見られる様々な慣例や趣向
>
>
> Various conventions and ideas seen in works of fiction.
>
>
>
So I don't think you will find a single word to cover this. お決まり (and お定まり?) may work for "cliche" in some situations (お決まりの台詞, お決まりのパターン) although they're not limited to fiction. Wikipedia uses 類型 for categorising some things, e.g. ストーリー類型, but again this appears to be a phrase coined for convenience and not widely used in general discussion.
There are some words that will cover some of the things covered by "trope". One (relatively recently coined and probably more an internet slang term than something for academic discussion) is フラグ. I'll quote from wiki again as I think this covers it:
>
> 伏線(ふくせん)と同義であるものの、フラグは比較的単純で定型化された「お決まりのパターン」の含意があるとされる。
>
>
> Although it has the same meaning as 'foreshadowing', 'flag' implies a relatively simple, fixed, "stereotypical pattern".
>
>
>
There are various types of flag (e.g. "death flag", 死亡フラグ). For more description of this term, check dic.nicovideo.jp/ for フラグ and other terms. This site also probably functions as the closest thing to tvtropes in that although it wasn't created for that purpose, if you look up various manga/anime you will find often find links to character types/phrases/story genres associated with that work.
Another useful word is from 落語 originally and is 落ち (when dealing with manga/anime, normally written オチ). There were various set ways of ending a story. A classic one is まわり落ち (ending by returning to the beginning of the story), and 夢オチ is the Japanese name for the "and then he realised it had all been a dream" ending.
The last one is 定番, often in the form (genre name/series)の定番. These are both 2ch examples:
>
> やめてほしいアニメの定番 ("anime staples you want to stop")
>
>
> RPGの定番モンスターの名前を貼っていくスレ ("thread where we post names of typical RPG monsters")
>
>
>
Not necessarily negative, it can also be used to refer to classic/staple/standard examples of a genre, e.g. 定番のクリスマスソング (typical Christmas songs).
|
I just found another one, which is exactly what I was looking for:
**べた - hackneyed, cliched [1]**
It's marked as "slang", though, and it might be just a version of べたべた. "Sticky" is quite close in connotation.
[1]http://jisho.org/words?jap=beta&eng=&dict=edict
|
29,131,228 |
I want to have two simple properties: the start date and the end date. I want to put a constraint that the start date must be before the end date. The problem arises when modifying both values - they may (together!) make a new, correct pair, but at the moment of adding them, there is an error. Simple example:
```
start = 5;
end = 10;
new_start = 20;
new_end = 30;
start = new_start; // error!
end = new_end;
```
That is why I introduced the third property. The thing is - the code looks terrible (especially the .Item1, .Item2 thing).
Is there a way to do it in a better way in C#?
```
private DateTime start;
private DateTime end;
public DateTime Start { get { return start; } }
public DateTime End { get { return end; } }
public Tuple<DateTime, DateTime> Dates
{
get
{
return new Tuple<DateTime, DateTime>(Start, End);
}
set
{
if (value.Item1 <= value.Item2)
{
start = value.Item1;
end = value.Item2;
}
else
throw new InvalidDates();
}
}
```
|
2015/03/18
|
[
"https://Stackoverflow.com/questions/29131228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4610370/"
] |
Instead of having two underlying `DateTime`, I would write a class that contains one `DateTime` for the start and one `TimeSpan` for the difference between the start and end. The setter for the start would only change the `DateTime` and the setter for the end would only change the `TimeSpan` (giving an exception if it would make the `TimeSpan` negative).
You see behaviour like this in Google calendar and Outlook's calendar already, as I recall. There changing the start time of an event changes the end time too, but keeps the duration constant.
```
public class TimeWindow
{
private TimeSpan duration;
public DateTime StartTime { get; set; }
public DateTime EndTime
{
get
{
return this.StartTime.Add(this.duration);
}
set
{
// this will throw a ArgumentOutOfRangeException if value is smaller than StartTime
this.duration = value.Subtract(this.StartTime);
}
}
public void SetStartAndEnd(DateTime start, DateTime end)
{
this.StartTime = start;
this.EndTime = end;
}
}
```
|
OO encapsulation isn't always about pretty implementation, it's often about pretty interfaces that provide consistent "black box" behavior. If writing the code that "looks terrible" provides a smooth interface with behavior consistent with the design, then what's the big deal? I think the solution you have is perfectly valid to keep the internals of the class consistent.
|
29,131,228 |
I want to have two simple properties: the start date and the end date. I want to put a constraint that the start date must be before the end date. The problem arises when modifying both values - they may (together!) make a new, correct pair, but at the moment of adding them, there is an error. Simple example:
```
start = 5;
end = 10;
new_start = 20;
new_end = 30;
start = new_start; // error!
end = new_end;
```
That is why I introduced the third property. The thing is - the code looks terrible (especially the .Item1, .Item2 thing).
Is there a way to do it in a better way in C#?
```
private DateTime start;
private DateTime end;
public DateTime Start { get { return start; } }
public DateTime End { get { return end; } }
public Tuple<DateTime, DateTime> Dates
{
get
{
return new Tuple<DateTime, DateTime>(Start, End);
}
set
{
if (value.Item1 <= value.Item2)
{
start = value.Item1;
end = value.Item2;
}
else
throw new InvalidDates();
}
}
```
|
2015/03/18
|
[
"https://Stackoverflow.com/questions/29131228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4610370/"
] |
Well, you might think about whether it would make sense to have a type which represents a start/end combination. A sort of... [`Interval`](http://nodatime.org/1.3.x/api/html/T_NodaTime_Interval.htm). (Yes, this is a not-so-subtle plug for [Noda Time](http://nodatime.org), which makes date/time handling generally better anyway. But you could create your own `Interval` struct for `DateTime` if you wanted...) Then you can have a *single* property to combine the start/end times, in a way which is guaranteed to be valid.
But if you really *want* to keep them as separate properties, I'd go with a simple setter. I wouldn't create a separate exception for this though - just use `ArgumentException`:
```
public void SetDates(DateTime start, DateTime end)
{
if (end < start)
{
throw new ArgumentException("End must be at or after start", "end");
}
this.start = start;
this.end = end;
}
```
|
Use a method to set them together:
```
public void SetDates(DateTime start, DateTime end)
{
if(start >= end)
throw new ArgumentException("start must be before end");
this.start = start;
this.end = end;
}
```
|
29,131,228 |
I want to have two simple properties: the start date and the end date. I want to put a constraint that the start date must be before the end date. The problem arises when modifying both values - they may (together!) make a new, correct pair, but at the moment of adding them, there is an error. Simple example:
```
start = 5;
end = 10;
new_start = 20;
new_end = 30;
start = new_start; // error!
end = new_end;
```
That is why I introduced the third property. The thing is - the code looks terrible (especially the .Item1, .Item2 thing).
Is there a way to do it in a better way in C#?
```
private DateTime start;
private DateTime end;
public DateTime Start { get { return start; } }
public DateTime End { get { return end; } }
public Tuple<DateTime, DateTime> Dates
{
get
{
return new Tuple<DateTime, DateTime>(Start, End);
}
set
{
if (value.Item1 <= value.Item2)
{
start = value.Item1;
end = value.Item2;
}
else
throw new InvalidDates();
}
}
```
|
2015/03/18
|
[
"https://Stackoverflow.com/questions/29131228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4610370/"
] |
Instead of having two underlying `DateTime`, I would write a class that contains one `DateTime` for the start and one `TimeSpan` for the difference between the start and end. The setter for the start would only change the `DateTime` and the setter for the end would only change the `TimeSpan` (giving an exception if it would make the `TimeSpan` negative).
You see behaviour like this in Google calendar and Outlook's calendar already, as I recall. There changing the start time of an event changes the end time too, but keeps the duration constant.
```
public class TimeWindow
{
private TimeSpan duration;
public DateTime StartTime { get; set; }
public DateTime EndTime
{
get
{
return this.StartTime.Add(this.duration);
}
set
{
// this will throw a ArgumentOutOfRangeException if value is smaller than StartTime
this.duration = value.Subtract(this.StartTime);
}
}
public void SetStartAndEnd(DateTime start, DateTime end)
{
this.StartTime = start;
this.EndTime = end;
}
}
```
|
Take the validation checks out of the setters and add a validate method. You can then set them in any order without exception and check the final outcome once you think they are ready by calling validate.
```
private DateTime start;
private DateTime end;
public DateTime Start { get { return start; } }
public DateTime End { get { return end; } }
public void Validate()
{
if (end.Ticks < start.Ticks)
throw new InvalidDates();
}
```
|
29,131,228 |
I want to have two simple properties: the start date and the end date. I want to put a constraint that the start date must be before the end date. The problem arises when modifying both values - they may (together!) make a new, correct pair, but at the moment of adding them, there is an error. Simple example:
```
start = 5;
end = 10;
new_start = 20;
new_end = 30;
start = new_start; // error!
end = new_end;
```
That is why I introduced the third property. The thing is - the code looks terrible (especially the .Item1, .Item2 thing).
Is there a way to do it in a better way in C#?
```
private DateTime start;
private DateTime end;
public DateTime Start { get { return start; } }
public DateTime End { get { return end; } }
public Tuple<DateTime, DateTime> Dates
{
get
{
return new Tuple<DateTime, DateTime>(Start, End);
}
set
{
if (value.Item1 <= value.Item2)
{
start = value.Item1;
end = value.Item2;
}
else
throw new InvalidDates();
}
}
```
|
2015/03/18
|
[
"https://Stackoverflow.com/questions/29131228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4610370/"
] |
OO encapsulation isn't always about pretty implementation, it's often about pretty interfaces that provide consistent "black box" behavior. If writing the code that "looks terrible" provides a smooth interface with behavior consistent with the design, then what's the big deal? I think the solution you have is perfectly valid to keep the internals of the class consistent.
|
Another way which is not listed in answers is to implement `ISupportInitialize` interface. Before modifying dates you call `BeginInit` method and after - `EndInit`. On `EndInit` validate dates.
```
public class SomeClass : ISupportInitialize
{
private bool initializing;
private DateTime start;
private DateTime end;
public DateTime Start
{
get { return start; }
set { CheckInitializing(); start = value; }
}
public DateTime End
{
get { return end; }
set { CheckInitializing(); end = value; }
}
private void CheckInitializing()
{
if (!initializing)
{ throw new InvalidOperationException("Can not execute this operation outside a BeginInit/EndInit block."); }
}
public void BeginInit()
{
if (initializing)
{ throw new InvalidOperationException("Can not have nested BeginInit calls on the same instance."); }
initializing = true;
}
public void EndInit()
{
if (!initializing)
{ throw new InvalidOperationException("Can not call EndInit without a matching BeginInit call."); }
if (start <= end)
{ throw new InvalidDates(); }
initializing = false;
}
}
```
|
29,131,228 |
I want to have two simple properties: the start date and the end date. I want to put a constraint that the start date must be before the end date. The problem arises when modifying both values - they may (together!) make a new, correct pair, but at the moment of adding them, there is an error. Simple example:
```
start = 5;
end = 10;
new_start = 20;
new_end = 30;
start = new_start; // error!
end = new_end;
```
That is why I introduced the third property. The thing is - the code looks terrible (especially the .Item1, .Item2 thing).
Is there a way to do it in a better way in C#?
```
private DateTime start;
private DateTime end;
public DateTime Start { get { return start; } }
public DateTime End { get { return end; } }
public Tuple<DateTime, DateTime> Dates
{
get
{
return new Tuple<DateTime, DateTime>(Start, End);
}
set
{
if (value.Item1 <= value.Item2)
{
start = value.Item1;
end = value.Item2;
}
else
throw new InvalidDates();
}
}
```
|
2015/03/18
|
[
"https://Stackoverflow.com/questions/29131228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4610370/"
] |
Wow. Lots of answers. Well, here's my take.
Create two public properties for the start and end dates, and then add a SetStartAndEndDates method that does the validation. The public properties should have private setters. Since the `SetStartAndEndDates` method throws an error if invalid dates are set, you'll want to create methods allowing you to test potential dates. To illustrate this methodology, I'll create a fictional `CalendarEvent` class:
```
public class CalendarEvent
{
public DateTime StartDate { get; private set; }
public DateTime EndDate { get; private set; }
public SetStartAndEndDates(DateTime start, DateTime end)
{
if (start <= end)
{
StartDate = start;
EndDate = end;
}
else
{
throw new InvalidDates();
}
}
public bool IsValidEndDate(DateTime end)
{
return StartDate <= end;
}
public bool IsValidStartDate(DateTime start)
{
return start <= EndDate;
}
public bool IsValidStartAndEndDate(DateTime start, DateTime end)
{
return start <= end;
}
}
```
And to use it without throwing exceptions:
```
var event = new Event();
var start = DateTime.Now;
var end = start.AddDays(7);
if (event.IsValidStartAndEndDate(start, end))
{
event.SetStartAndEndDates(start, end);
}
```
|
Use a method as a setter:
```
public void SetDates(DateTime startDate, EndDate endDate)
{
if (startDate <= endDate)
{
start = startDate;
end = endDate;
}
else
{
throw new InvalidDates();
}
}
```
|
29,131,228 |
I want to have two simple properties: the start date and the end date. I want to put a constraint that the start date must be before the end date. The problem arises when modifying both values - they may (together!) make a new, correct pair, but at the moment of adding them, there is an error. Simple example:
```
start = 5;
end = 10;
new_start = 20;
new_end = 30;
start = new_start; // error!
end = new_end;
```
That is why I introduced the third property. The thing is - the code looks terrible (especially the .Item1, .Item2 thing).
Is there a way to do it in a better way in C#?
```
private DateTime start;
private DateTime end;
public DateTime Start { get { return start; } }
public DateTime End { get { return end; } }
public Tuple<DateTime, DateTime> Dates
{
get
{
return new Tuple<DateTime, DateTime>(Start, End);
}
set
{
if (value.Item1 <= value.Item2)
{
start = value.Item1;
end = value.Item2;
}
else
throw new InvalidDates();
}
}
```
|
2015/03/18
|
[
"https://Stackoverflow.com/questions/29131228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4610370/"
] |
Wow. Lots of answers. Well, here's my take.
Create two public properties for the start and end dates, and then add a SetStartAndEndDates method that does the validation. The public properties should have private setters. Since the `SetStartAndEndDates` method throws an error if invalid dates are set, you'll want to create methods allowing you to test potential dates. To illustrate this methodology, I'll create a fictional `CalendarEvent` class:
```
public class CalendarEvent
{
public DateTime StartDate { get; private set; }
public DateTime EndDate { get; private set; }
public SetStartAndEndDates(DateTime start, DateTime end)
{
if (start <= end)
{
StartDate = start;
EndDate = end;
}
else
{
throw new InvalidDates();
}
}
public bool IsValidEndDate(DateTime end)
{
return StartDate <= end;
}
public bool IsValidStartDate(DateTime start)
{
return start <= EndDate;
}
public bool IsValidStartAndEndDate(DateTime start, DateTime end)
{
return start <= end;
}
}
```
And to use it without throwing exceptions:
```
var event = new Event();
var start = DateTime.Now;
var end = start.AddDays(7);
if (event.IsValidStartAndEndDate(start, end))
{
event.SetStartAndEndDates(start, end);
}
```
|
Instead of having two underlying `DateTime`, I would write a class that contains one `DateTime` for the start and one `TimeSpan` for the difference between the start and end. The setter for the start would only change the `DateTime` and the setter for the end would only change the `TimeSpan` (giving an exception if it would make the `TimeSpan` negative).
You see behaviour like this in Google calendar and Outlook's calendar already, as I recall. There changing the start time of an event changes the end time too, but keeps the duration constant.
```
public class TimeWindow
{
private TimeSpan duration;
public DateTime StartTime { get; set; }
public DateTime EndTime
{
get
{
return this.StartTime.Add(this.duration);
}
set
{
// this will throw a ArgumentOutOfRangeException if value is smaller than StartTime
this.duration = value.Subtract(this.StartTime);
}
}
public void SetStartAndEnd(DateTime start, DateTime end)
{
this.StartTime = start;
this.EndTime = end;
}
}
```
|
29,131,228 |
I want to have two simple properties: the start date and the end date. I want to put a constraint that the start date must be before the end date. The problem arises when modifying both values - they may (together!) make a new, correct pair, but at the moment of adding them, there is an error. Simple example:
```
start = 5;
end = 10;
new_start = 20;
new_end = 30;
start = new_start; // error!
end = new_end;
```
That is why I introduced the third property. The thing is - the code looks terrible (especially the .Item1, .Item2 thing).
Is there a way to do it in a better way in C#?
```
private DateTime start;
private DateTime end;
public DateTime Start { get { return start; } }
public DateTime End { get { return end; } }
public Tuple<DateTime, DateTime> Dates
{
get
{
return new Tuple<DateTime, DateTime>(Start, End);
}
set
{
if (value.Item1 <= value.Item2)
{
start = value.Item1;
end = value.Item2;
}
else
throw new InvalidDates();
}
}
```
|
2015/03/18
|
[
"https://Stackoverflow.com/questions/29131228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4610370/"
] |
Well, you might think about whether it would make sense to have a type which represents a start/end combination. A sort of... [`Interval`](http://nodatime.org/1.3.x/api/html/T_NodaTime_Interval.htm). (Yes, this is a not-so-subtle plug for [Noda Time](http://nodatime.org), which makes date/time handling generally better anyway. But you could create your own `Interval` struct for `DateTime` if you wanted...) Then you can have a *single* property to combine the start/end times, in a way which is guaranteed to be valid.
But if you really *want* to keep them as separate properties, I'd go with a simple setter. I wouldn't create a separate exception for this though - just use `ArgumentException`:
```
public void SetDates(DateTime start, DateTime end)
{
if (end < start)
{
throw new ArgumentException("End must be at or after start", "end");
}
this.start = start;
this.end = end;
}
```
|
OO encapsulation isn't always about pretty implementation, it's often about pretty interfaces that provide consistent "black box" behavior. If writing the code that "looks terrible" provides a smooth interface with behavior consistent with the design, then what's the big deal? I think the solution you have is perfectly valid to keep the internals of the class consistent.
|
29,131,228 |
I want to have two simple properties: the start date and the end date. I want to put a constraint that the start date must be before the end date. The problem arises when modifying both values - they may (together!) make a new, correct pair, but at the moment of adding them, there is an error. Simple example:
```
start = 5;
end = 10;
new_start = 20;
new_end = 30;
start = new_start; // error!
end = new_end;
```
That is why I introduced the third property. The thing is - the code looks terrible (especially the .Item1, .Item2 thing).
Is there a way to do it in a better way in C#?
```
private DateTime start;
private DateTime end;
public DateTime Start { get { return start; } }
public DateTime End { get { return end; } }
public Tuple<DateTime, DateTime> Dates
{
get
{
return new Tuple<DateTime, DateTime>(Start, End);
}
set
{
if (value.Item1 <= value.Item2)
{
start = value.Item1;
end = value.Item2;
}
else
throw new InvalidDates();
}
}
```
|
2015/03/18
|
[
"https://Stackoverflow.com/questions/29131228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4610370/"
] |
Use a method as a setter:
```
public void SetDates(DateTime startDate, EndDate endDate)
{
if (startDate <= endDate)
{
start = startDate;
end = endDate;
}
else
{
throw new InvalidDates();
}
}
```
|
OO encapsulation isn't always about pretty implementation, it's often about pretty interfaces that provide consistent "black box" behavior. If writing the code that "looks terrible" provides a smooth interface with behavior consistent with the design, then what's the big deal? I think the solution you have is perfectly valid to keep the internals of the class consistent.
|
29,131,228 |
I want to have two simple properties: the start date and the end date. I want to put a constraint that the start date must be before the end date. The problem arises when modifying both values - they may (together!) make a new, correct pair, but at the moment of adding them, there is an error. Simple example:
```
start = 5;
end = 10;
new_start = 20;
new_end = 30;
start = new_start; // error!
end = new_end;
```
That is why I introduced the third property. The thing is - the code looks terrible (especially the .Item1, .Item2 thing).
Is there a way to do it in a better way in C#?
```
private DateTime start;
private DateTime end;
public DateTime Start { get { return start; } }
public DateTime End { get { return end; } }
public Tuple<DateTime, DateTime> Dates
{
get
{
return new Tuple<DateTime, DateTime>(Start, End);
}
set
{
if (value.Item1 <= value.Item2)
{
start = value.Item1;
end = value.Item2;
}
else
throw new InvalidDates();
}
}
```
|
2015/03/18
|
[
"https://Stackoverflow.com/questions/29131228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4610370/"
] |
Use a method to set them together:
```
public void SetDates(DateTime start, DateTime end)
{
if(start >= end)
throw new ArgumentException("start must be before end");
this.start = start;
this.end = end;
}
```
|
OO encapsulation isn't always about pretty implementation, it's often about pretty interfaces that provide consistent "black box" behavior. If writing the code that "looks terrible" provides a smooth interface with behavior consistent with the design, then what's the big deal? I think the solution you have is perfectly valid to keep the internals of the class consistent.
|
29,131,228 |
I want to have two simple properties: the start date and the end date. I want to put a constraint that the start date must be before the end date. The problem arises when modifying both values - they may (together!) make a new, correct pair, but at the moment of adding them, there is an error. Simple example:
```
start = 5;
end = 10;
new_start = 20;
new_end = 30;
start = new_start; // error!
end = new_end;
```
That is why I introduced the third property. The thing is - the code looks terrible (especially the .Item1, .Item2 thing).
Is there a way to do it in a better way in C#?
```
private DateTime start;
private DateTime end;
public DateTime Start { get { return start; } }
public DateTime End { get { return end; } }
public Tuple<DateTime, DateTime> Dates
{
get
{
return new Tuple<DateTime, DateTime>(Start, End);
}
set
{
if (value.Item1 <= value.Item2)
{
start = value.Item1;
end = value.Item2;
}
else
throw new InvalidDates();
}
}
```
|
2015/03/18
|
[
"https://Stackoverflow.com/questions/29131228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4610370/"
] |
Wow. Lots of answers. Well, here's my take.
Create two public properties for the start and end dates, and then add a SetStartAndEndDates method that does the validation. The public properties should have private setters. Since the `SetStartAndEndDates` method throws an error if invalid dates are set, you'll want to create methods allowing you to test potential dates. To illustrate this methodology, I'll create a fictional `CalendarEvent` class:
```
public class CalendarEvent
{
public DateTime StartDate { get; private set; }
public DateTime EndDate { get; private set; }
public SetStartAndEndDates(DateTime start, DateTime end)
{
if (start <= end)
{
StartDate = start;
EndDate = end;
}
else
{
throw new InvalidDates();
}
}
public bool IsValidEndDate(DateTime end)
{
return StartDate <= end;
}
public bool IsValidStartDate(DateTime start)
{
return start <= EndDate;
}
public bool IsValidStartAndEndDate(DateTime start, DateTime end)
{
return start <= end;
}
}
```
And to use it without throwing exceptions:
```
var event = new Event();
var start = DateTime.Now;
var end = start.AddDays(7);
if (event.IsValidStartAndEndDate(start, end))
{
event.SetStartAndEndDates(start, end);
}
```
|
OO encapsulation isn't always about pretty implementation, it's often about pretty interfaces that provide consistent "black box" behavior. If writing the code that "looks terrible" provides a smooth interface with behavior consistent with the design, then what's the big deal? I think the solution you have is perfectly valid to keep the internals of the class consistent.
|
17,165,156 |
I am getting error when trying to import .mm file to another one.
Its build like that :
first class `FailedMenuLayer` is .mm and have in its .h :
```
#import "gameScene.h"
```
second class `gameScene` is .mm, and have in its .h :
```
#import "FailedMenuLayer.h"
FailedMenuLayer *menuGO; //here i get the error: unknown type FailedMenuLayer .
```
why is that ?
|
2013/06/18
|
[
"https://Stackoverflow.com/questions/17165156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/721925/"
] |
It looks like an import cycle.
One way to fix it is to move the "gameScene.h" import to the .mm file. It's actually a good practice to keep the imports in the .h file limited only to what you actually need in the header and keep everything else in the .mm file.
If you need the import in the header try using @class instead of #import;
```
@class gameScene;
```
Don't forget to import gameScene.h in the .mm file also.
|
you are not importing ".mm" file, you are importing it's header.
Check your build phases> compile sources for your .mm file to be listed there. That might be your issue
|
448,132 |
How can I easily and simply schedule a cron job in PHP? Rails has BackgroundRB...
|
2009/01/15
|
[
"https://Stackoverflow.com/questions/448132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Most website control panels (assuming you've got cPanel or something similar running) include a crontab application. If you're on shared hosting ask your host about this.
If you're on a dedicated server and have installed cron then have a look at the [crontab syntax](http://en.wikipedia.org/wiki/Cron#crontab_syntax). These commands go in `crontab`, usually in `/etc` on \*nix.
|
You're conflating a language with a framework. PHP doesn't have a cron scheduling any more than Ruby does. If you're using a PHP framework or cms however, there is likely some utility for cron tasks.
Here is a useful link if you have control over the machine.
[http://troy.jdmz.net/cron/](http://troy.jdmz.net/cron)
If you have shared hosting, there's probably some tool they'd give you for cron jobs; ask them or look in the knowledge base.
|
448,132 |
How can I easily and simply schedule a cron job in PHP? Rails has BackgroundRB...
|
2009/01/15
|
[
"https://Stackoverflow.com/questions/448132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Most website control panels (assuming you've got cPanel or something similar running) include a crontab application. If you're on shared hosting ask your host about this.
If you're on a dedicated server and have installed cron then have a look at the [crontab syntax](http://en.wikipedia.org/wiki/Cron#crontab_syntax). These commands go in `crontab`, usually in `/etc` on \*nix.
|
There is [PHP-Resque](http://github.com/chrisboulton/php-resque), a PHP port of the queue&background process framework written by GitHub guys.
|
448,132 |
How can I easily and simply schedule a cron job in PHP? Rails has BackgroundRB...
|
2009/01/15
|
[
"https://Stackoverflow.com/questions/448132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Most website control panels (assuming you've got cPanel or something similar running) include a crontab application. If you're on shared hosting ask your host about this.
If you're on a dedicated server and have installed cron then have a look at the [crontab syntax](http://en.wikipedia.org/wiki/Cron#crontab_syntax). These commands go in `crontab`, usually in `/etc` on \*nix.
|
I recommend <http://www.phpjobscheduler.co.uk/>
|
448,132 |
How can I easily and simply schedule a cron job in PHP? Rails has BackgroundRB...
|
2009/01/15
|
[
"https://Stackoverflow.com/questions/448132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Here's a semi-PHP solution to add to a crontab:
```
$cmd = 'crontab -l > /tmp/crontab.bak'; // preserve current crontab
$cmd .= ' && echo "*/5 * * * * /foo/bar" >> /tmp/crontab.bak'; // append new command
$cmd .= ' && crontab /tmp/crontab.bak'; // update crontab
$cmd .= ' rm /tmp/crontab.bak'; // delete temp file
exec($cmd); // execute
```
|
You're conflating a language with a framework. PHP doesn't have a cron scheduling any more than Ruby does. If you're using a PHP framework or cms however, there is likely some utility for cron tasks.
Here is a useful link if you have control over the machine.
[http://troy.jdmz.net/cron/](http://troy.jdmz.net/cron)
If you have shared hosting, there's probably some tool they'd give you for cron jobs; ask them or look in the knowledge base.
|
448,132 |
How can I easily and simply schedule a cron job in PHP? Rails has BackgroundRB...
|
2009/01/15
|
[
"https://Stackoverflow.com/questions/448132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
There is [PHP-Resque](http://github.com/chrisboulton/php-resque), a PHP port of the queue&background process framework written by GitHub guys.
|
You're conflating a language with a framework. PHP doesn't have a cron scheduling any more than Ruby does. If you're using a PHP framework or cms however, there is likely some utility for cron tasks.
Here is a useful link if you have control over the machine.
[http://troy.jdmz.net/cron/](http://troy.jdmz.net/cron)
If you have shared hosting, there's probably some tool they'd give you for cron jobs; ask them or look in the knowledge base.
|
448,132 |
How can I easily and simply schedule a cron job in PHP? Rails has BackgroundRB...
|
2009/01/15
|
[
"https://Stackoverflow.com/questions/448132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I recommend <http://www.phpjobscheduler.co.uk/>
|
You're conflating a language with a framework. PHP doesn't have a cron scheduling any more than Ruby does. If you're using a PHP framework or cms however, there is likely some utility for cron tasks.
Here is a useful link if you have control over the machine.
[http://troy.jdmz.net/cron/](http://troy.jdmz.net/cron)
If you have shared hosting, there's probably some tool they'd give you for cron jobs; ask them or look in the knowledge base.
|
448,132 |
How can I easily and simply schedule a cron job in PHP? Rails has BackgroundRB...
|
2009/01/15
|
[
"https://Stackoverflow.com/questions/448132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Here's a semi-PHP solution to add to a crontab:
```
$cmd = 'crontab -l > /tmp/crontab.bak'; // preserve current crontab
$cmd .= ' && echo "*/5 * * * * /foo/bar" >> /tmp/crontab.bak'; // append new command
$cmd .= ' && crontab /tmp/crontab.bak'; // update crontab
$cmd .= ' rm /tmp/crontab.bak'; // delete temp file
exec($cmd); // execute
```
|
There is [PHP-Resque](http://github.com/chrisboulton/php-resque), a PHP port of the queue&background process framework written by GitHub guys.
|
448,132 |
How can I easily and simply schedule a cron job in PHP? Rails has BackgroundRB...
|
2009/01/15
|
[
"https://Stackoverflow.com/questions/448132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Here's a semi-PHP solution to add to a crontab:
```
$cmd = 'crontab -l > /tmp/crontab.bak'; // preserve current crontab
$cmd .= ' && echo "*/5 * * * * /foo/bar" >> /tmp/crontab.bak'; // append new command
$cmd .= ' && crontab /tmp/crontab.bak'; // update crontab
$cmd .= ' rm /tmp/crontab.bak'; // delete temp file
exec($cmd); // execute
```
|
I recommend <http://www.phpjobscheduler.co.uk/>
|
45,866,145 |
We are implementing a number of SDK's for our suite of hardware sensors.
Having successfully got a working C API for one of our sensors, we are now starting the arduous task of testing the SDK to ensure that we haven't introduced any fatal bugs, memory leaks or race conditions.
One of our engineers has reported that when developing the test application (a Qt Widgets application), an issue has occurred when hooking onto a callback which is executed from a separate thread within the DLL.
Here is the callback prototype:
```
#define API_CALL __cdecl
typedef struct {
// msg fields...
DWORD dwSize;
// etc...
} MSG_CONTEXT, *PMSG_CONTEXT;
typedef void (API_CALL *SYS_MSG_CALLBACK)(const PMSG_CONTEXT, LPVOID);
#define API_FUNC __declspec(dllexport)
API_FUNC void SYS_RegisterCallback(SYS_MSG_CALLBACK pHandler, LPVOID pContext);
```
And it is attached in Qt as follows:
```
static void callbackHandler(const PMSG_CONTEXT msg, LPVOID context) {
MainWindow *wnd = (MainWindow *)context;
// *wnd is valid
// Call a function here
}
MainWindow::MainWindow(QWidget *parent) {
SYS_RegisterCallback(callbackHandler, this);
}
```
My question is this: is the callback executed on the thread which creates it or on the thread which executes it? In either case, I guess it need of some kind of synchronization method. Googling has resulted in a plethora of C# examples, which isn't really whats needed.
One thing under consideration is using the `SendMessage` or `PostMessage` functions rather than going down the callback route.
Could anyone offer any suggestions please at to how cross-thread safety could be achieved using callbacks? Or is the message pump route the way to go for a Windows-based SDK?
|
2017/08/24
|
[
"https://Stackoverflow.com/questions/45866145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2321263/"
] |
Unfortunately at this time there's no API for Google Shopping (or for Google Keep, which is fairly similar)
[Is there a Google Keep API?](https://stackoverflow.com/questions/19196238/is-there-a-google-keep-api)
|
(Almost?) All public software products of Google have some sort of API.
Thumb rule: You can access the product via app, website or similar? Then there will be an API.
You can however create a thread over on googles suggestion site and request an api for the shopping list, if no one has done so. :)
|
45,866,145 |
We are implementing a number of SDK's for our suite of hardware sensors.
Having successfully got a working C API for one of our sensors, we are now starting the arduous task of testing the SDK to ensure that we haven't introduced any fatal bugs, memory leaks or race conditions.
One of our engineers has reported that when developing the test application (a Qt Widgets application), an issue has occurred when hooking onto a callback which is executed from a separate thread within the DLL.
Here is the callback prototype:
```
#define API_CALL __cdecl
typedef struct {
// msg fields...
DWORD dwSize;
// etc...
} MSG_CONTEXT, *PMSG_CONTEXT;
typedef void (API_CALL *SYS_MSG_CALLBACK)(const PMSG_CONTEXT, LPVOID);
#define API_FUNC __declspec(dllexport)
API_FUNC void SYS_RegisterCallback(SYS_MSG_CALLBACK pHandler, LPVOID pContext);
```
And it is attached in Qt as follows:
```
static void callbackHandler(const PMSG_CONTEXT msg, LPVOID context) {
MainWindow *wnd = (MainWindow *)context;
// *wnd is valid
// Call a function here
}
MainWindow::MainWindow(QWidget *parent) {
SYS_RegisterCallback(callbackHandler, this);
}
```
My question is this: is the callback executed on the thread which creates it or on the thread which executes it? In either case, I guess it need of some kind of synchronization method. Googling has resulted in a plethora of C# examples, which isn't really whats needed.
One thing under consideration is using the `SendMessage` or `PostMessage` functions rather than going down the callback route.
Could anyone offer any suggestions please at to how cross-thread safety could be achieved using callbacks? Or is the message pump route the way to go for a Windows-based SDK?
|
2017/08/24
|
[
"https://Stackoverflow.com/questions/45866145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2321263/"
] |
Unfortunately at this time there's no API for Google Shopping (or for Google Keep, which is fairly similar)
[Is there a Google Keep API?](https://stackoverflow.com/questions/19196238/is-there-a-google-keep-api)
|
Also looking for the same. Have been browsing around with no results. Wrote them feedback but I doubt that they will do anything as the page seems so empty...
Although I found that Amazon Alexa has all the needed documentation to access shopping lists and todo lists: <https://developer.amazon.com/docs/custom-skills/access-the-alexa-shopping-and-to-do-lists.html>
I think its shamefull for me, just this weekend I already gave up of using Google TTS and started using (Amazon) AWS Polly for the simplicity of installation and use, and now it seems Google has no API for shopping list while Alexa does... I guess its time to sell my Google Home
|
45,866,145 |
We are implementing a number of SDK's for our suite of hardware sensors.
Having successfully got a working C API for one of our sensors, we are now starting the arduous task of testing the SDK to ensure that we haven't introduced any fatal bugs, memory leaks or race conditions.
One of our engineers has reported that when developing the test application (a Qt Widgets application), an issue has occurred when hooking onto a callback which is executed from a separate thread within the DLL.
Here is the callback prototype:
```
#define API_CALL __cdecl
typedef struct {
// msg fields...
DWORD dwSize;
// etc...
} MSG_CONTEXT, *PMSG_CONTEXT;
typedef void (API_CALL *SYS_MSG_CALLBACK)(const PMSG_CONTEXT, LPVOID);
#define API_FUNC __declspec(dllexport)
API_FUNC void SYS_RegisterCallback(SYS_MSG_CALLBACK pHandler, LPVOID pContext);
```
And it is attached in Qt as follows:
```
static void callbackHandler(const PMSG_CONTEXT msg, LPVOID context) {
MainWindow *wnd = (MainWindow *)context;
// *wnd is valid
// Call a function here
}
MainWindow::MainWindow(QWidget *parent) {
SYS_RegisterCallback(callbackHandler, this);
}
```
My question is this: is the callback executed on the thread which creates it or on the thread which executes it? In either case, I guess it need of some kind of synchronization method. Googling has resulted in a plethora of C# examples, which isn't really whats needed.
One thing under consideration is using the `SendMessage` or `PostMessage` functions rather than going down the callback route.
Could anyone offer any suggestions please at to how cross-thread safety could be achieved using callbacks? Or is the message pump route the way to go for a Windows-based SDK?
|
2017/08/24
|
[
"https://Stackoverflow.com/questions/45866145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2321263/"
] |
Unfortunately at this time there's no API for Google Shopping (or for Google Keep, which is fairly similar)
[Is there a Google Keep API?](https://stackoverflow.com/questions/19196238/is-there-a-google-keep-api)
|
You can get the JSON from this endpoint, assuming you're authenticated. You'll have to pass the cookie and maybe a few other headers - not sure. But, it could get the job done...
Sign into your account and go to <https://shoppinglist.google.com>. From there, open up your networking tab in your dev console, check the requests. You'll see one called `lookup`:
`https://shoppinglist.google.com/u/0/_/list/textitem/lookup`
The query params are important for auth. I don't know how auth works here and if you can easily hit it or not, but it's there, the JSON in the request. You'll just need to auth and pass the right query params.
|
45,866,145 |
We are implementing a number of SDK's for our suite of hardware sensors.
Having successfully got a working C API for one of our sensors, we are now starting the arduous task of testing the SDK to ensure that we haven't introduced any fatal bugs, memory leaks or race conditions.
One of our engineers has reported that when developing the test application (a Qt Widgets application), an issue has occurred when hooking onto a callback which is executed from a separate thread within the DLL.
Here is the callback prototype:
```
#define API_CALL __cdecl
typedef struct {
// msg fields...
DWORD dwSize;
// etc...
} MSG_CONTEXT, *PMSG_CONTEXT;
typedef void (API_CALL *SYS_MSG_CALLBACK)(const PMSG_CONTEXT, LPVOID);
#define API_FUNC __declspec(dllexport)
API_FUNC void SYS_RegisterCallback(SYS_MSG_CALLBACK pHandler, LPVOID pContext);
```
And it is attached in Qt as follows:
```
static void callbackHandler(const PMSG_CONTEXT msg, LPVOID context) {
MainWindow *wnd = (MainWindow *)context;
// *wnd is valid
// Call a function here
}
MainWindow::MainWindow(QWidget *parent) {
SYS_RegisterCallback(callbackHandler, this);
}
```
My question is this: is the callback executed on the thread which creates it or on the thread which executes it? In either case, I guess it need of some kind of synchronization method. Googling has resulted in a plethora of C# examples, which isn't really whats needed.
One thing under consideration is using the `SendMessage` or `PostMessage` functions rather than going down the callback route.
Could anyone offer any suggestions please at to how cross-thread safety could be achieved using callbacks? Or is the message pump route the way to go for a Windows-based SDK?
|
2017/08/24
|
[
"https://Stackoverflow.com/questions/45866145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2321263/"
] |
Unfortunately at this time there's no API for Google Shopping (or for Google Keep, which is fairly similar)
[Is there a Google Keep API?](https://stackoverflow.com/questions/19196238/is-there-a-google-keep-api)
|
You can export shopping lists in a CSV format using <https://takeout.google.com>. A download link can be emailed or a file can be dropped in Drive, Dropbox etc. This can be configured to export every two months for 1 year.
The data contains the name of the item, the quantity, if it is checked or not, and any additional notes.
|
45,866,145 |
We are implementing a number of SDK's for our suite of hardware sensors.
Having successfully got a working C API for one of our sensors, we are now starting the arduous task of testing the SDK to ensure that we haven't introduced any fatal bugs, memory leaks or race conditions.
One of our engineers has reported that when developing the test application (a Qt Widgets application), an issue has occurred when hooking onto a callback which is executed from a separate thread within the DLL.
Here is the callback prototype:
```
#define API_CALL __cdecl
typedef struct {
// msg fields...
DWORD dwSize;
// etc...
} MSG_CONTEXT, *PMSG_CONTEXT;
typedef void (API_CALL *SYS_MSG_CALLBACK)(const PMSG_CONTEXT, LPVOID);
#define API_FUNC __declspec(dllexport)
API_FUNC void SYS_RegisterCallback(SYS_MSG_CALLBACK pHandler, LPVOID pContext);
```
And it is attached in Qt as follows:
```
static void callbackHandler(const PMSG_CONTEXT msg, LPVOID context) {
MainWindow *wnd = (MainWindow *)context;
// *wnd is valid
// Call a function here
}
MainWindow::MainWindow(QWidget *parent) {
SYS_RegisterCallback(callbackHandler, this);
}
```
My question is this: is the callback executed on the thread which creates it or on the thread which executes it? In either case, I guess it need of some kind of synchronization method. Googling has resulted in a plethora of C# examples, which isn't really whats needed.
One thing under consideration is using the `SendMessage` or `PostMessage` functions rather than going down the callback route.
Could anyone offer any suggestions please at to how cross-thread safety could be achieved using callbacks? Or is the message pump route the way to go for a Windows-based SDK?
|
2017/08/24
|
[
"https://Stackoverflow.com/questions/45866145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2321263/"
] |
Also looking for the same. Have been browsing around with no results. Wrote them feedback but I doubt that they will do anything as the page seems so empty...
Although I found that Amazon Alexa has all the needed documentation to access shopping lists and todo lists: <https://developer.amazon.com/docs/custom-skills/access-the-alexa-shopping-and-to-do-lists.html>
I think its shamefull for me, just this weekend I already gave up of using Google TTS and started using (Amazon) AWS Polly for the simplicity of installation and use, and now it seems Google has no API for shopping list while Alexa does... I guess its time to sell my Google Home
|
(Almost?) All public software products of Google have some sort of API.
Thumb rule: You can access the product via app, website or similar? Then there will be an API.
You can however create a thread over on googles suggestion site and request an api for the shopping list, if no one has done so. :)
|
45,866,145 |
We are implementing a number of SDK's for our suite of hardware sensors.
Having successfully got a working C API for one of our sensors, we are now starting the arduous task of testing the SDK to ensure that we haven't introduced any fatal bugs, memory leaks or race conditions.
One of our engineers has reported that when developing the test application (a Qt Widgets application), an issue has occurred when hooking onto a callback which is executed from a separate thread within the DLL.
Here is the callback prototype:
```
#define API_CALL __cdecl
typedef struct {
// msg fields...
DWORD dwSize;
// etc...
} MSG_CONTEXT, *PMSG_CONTEXT;
typedef void (API_CALL *SYS_MSG_CALLBACK)(const PMSG_CONTEXT, LPVOID);
#define API_FUNC __declspec(dllexport)
API_FUNC void SYS_RegisterCallback(SYS_MSG_CALLBACK pHandler, LPVOID pContext);
```
And it is attached in Qt as follows:
```
static void callbackHandler(const PMSG_CONTEXT msg, LPVOID context) {
MainWindow *wnd = (MainWindow *)context;
// *wnd is valid
// Call a function here
}
MainWindow::MainWindow(QWidget *parent) {
SYS_RegisterCallback(callbackHandler, this);
}
```
My question is this: is the callback executed on the thread which creates it or on the thread which executes it? In either case, I guess it need of some kind of synchronization method. Googling has resulted in a plethora of C# examples, which isn't really whats needed.
One thing under consideration is using the `SendMessage` or `PostMessage` functions rather than going down the callback route.
Could anyone offer any suggestions please at to how cross-thread safety could be achieved using callbacks? Or is the message pump route the way to go for a Windows-based SDK?
|
2017/08/24
|
[
"https://Stackoverflow.com/questions/45866145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2321263/"
] |
You can get the JSON from this endpoint, assuming you're authenticated. You'll have to pass the cookie and maybe a few other headers - not sure. But, it could get the job done...
Sign into your account and go to <https://shoppinglist.google.com>. From there, open up your networking tab in your dev console, check the requests. You'll see one called `lookup`:
`https://shoppinglist.google.com/u/0/_/list/textitem/lookup`
The query params are important for auth. I don't know how auth works here and if you can easily hit it or not, but it's there, the JSON in the request. You'll just need to auth and pass the right query params.
|
(Almost?) All public software products of Google have some sort of API.
Thumb rule: You can access the product via app, website or similar? Then there will be an API.
You can however create a thread over on googles suggestion site and request an api for the shopping list, if no one has done so. :)
|
45,866,145 |
We are implementing a number of SDK's for our suite of hardware sensors.
Having successfully got a working C API for one of our sensors, we are now starting the arduous task of testing the SDK to ensure that we haven't introduced any fatal bugs, memory leaks or race conditions.
One of our engineers has reported that when developing the test application (a Qt Widgets application), an issue has occurred when hooking onto a callback which is executed from a separate thread within the DLL.
Here is the callback prototype:
```
#define API_CALL __cdecl
typedef struct {
// msg fields...
DWORD dwSize;
// etc...
} MSG_CONTEXT, *PMSG_CONTEXT;
typedef void (API_CALL *SYS_MSG_CALLBACK)(const PMSG_CONTEXT, LPVOID);
#define API_FUNC __declspec(dllexport)
API_FUNC void SYS_RegisterCallback(SYS_MSG_CALLBACK pHandler, LPVOID pContext);
```
And it is attached in Qt as follows:
```
static void callbackHandler(const PMSG_CONTEXT msg, LPVOID context) {
MainWindow *wnd = (MainWindow *)context;
// *wnd is valid
// Call a function here
}
MainWindow::MainWindow(QWidget *parent) {
SYS_RegisterCallback(callbackHandler, this);
}
```
My question is this: is the callback executed on the thread which creates it or on the thread which executes it? In either case, I guess it need of some kind of synchronization method. Googling has resulted in a plethora of C# examples, which isn't really whats needed.
One thing under consideration is using the `SendMessage` or `PostMessage` functions rather than going down the callback route.
Could anyone offer any suggestions please at to how cross-thread safety could be achieved using callbacks? Or is the message pump route the way to go for a Windows-based SDK?
|
2017/08/24
|
[
"https://Stackoverflow.com/questions/45866145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2321263/"
] |
You can export shopping lists in a CSV format using <https://takeout.google.com>. A download link can be emailed or a file can be dropped in Drive, Dropbox etc. This can be configured to export every two months for 1 year.
The data contains the name of the item, the quantity, if it is checked or not, and any additional notes.
|
(Almost?) All public software products of Google have some sort of API.
Thumb rule: You can access the product via app, website or similar? Then there will be an API.
You can however create a thread over on googles suggestion site and request an api for the shopping list, if no one has done so. :)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.