text:
Q: Why does this call the copy constructor, not the move constructor? I have a class, PlayerInputComponent:
.h:
class PlayerInputComponent
{
public:
    PlayerInputComponent(PlayerMoveComponent& parentMoveComponent_, std::unique_ptr<IRawInputConverter> inputConverter_);
    PlayerInputComponent(PlayerInputComponent&& moveFrom);
    void update();

private:
    std::unique_ptr<IRawInputConverter> inputConverter;
    PlayerMoveComponent& parentMoveComponent;
};
}

.cpp:
PlayerInputComponent::PlayerInputComponent(PlayerMoveComponent& parentMoveComponent_, std::unique_ptr<IRawInputConverter> inputConverter_) :
    parentMoveComponent(parentMoveComponent_),
    inputConverter(std::move(inputConverter_))
{
}

PlayerInputComponent::PlayerInputComponent(PlayerInputComponent&& moveFrom) :
    parentMoveComponent(moveFrom.parentMoveComponent),
    inputConverter(moveFrom.inputConverter.release())
{
}

and a class, PlayerMoveComponent, that contains a PlayerInputComponent member and initializes it using a std::unique_ptr passed as a parameter. Its constructor:
PlayerMoveComponent::PlayerMoveComponent(/* other parameters */ std::unique_ptr<IRawInputConverter> inputConverter) :
    //other initializations
    inputComponent(PlayerInputComponent(*this, std::move(inputConverter)))
{
}

I defined my own move constructor for the PlayerInputComponent class since my understanding is that a default move constructor won't be constructed for a class which contains a reference member. In this case though I know that the reference will remain in scope for duration of the PlayerInputComponent object's lifetime.
Since I'm initializing the PlayerMoveComponent's inputComponent variable from a temporary, I believe one of the following two things is supposed to happen:

*

*PlayerInputComponent's move constructor is used to initialize the playerInputComponent member variable.

*The move is elided by the compiler.

However, Visual Studio 2012 spits this out:
error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'
1>          with
1>          [
1>              _Ty=SDLGame::IRawInputConverter
1>          ]
1>          c:\program files\microsoft visual studio 11.0\vc\include\memory(1447) : see declaration of 'std::unique_ptr<_Ty>::unique_ptr'
1>          with
1>          [
1>              _Ty=SDLGame::IRawInputConverter
1>          ]
1>          This diagnostic occurred in the compiler generated function 'PlayerInputComponent::PlayerInputComponent(const PlayerInputComponent &)'

Why is the copy constructor being called here? Making the PlayerInputComponent class's parentMoveComponent member a regular ParentMoveComponent instance, rather than a reference, gets rid of the error, but I don't understand why - I've tested and verified that move constructing objects with reference members works so long as you provide your own move constructor, so what's the deal?

A: If you initialize a new Object using =, the copy constructor will be triggered by default.
To trigger the move constructor, you need to alter the behavior of operator=
You can find an example here
Hope I helped you.

A: I'm sorry in advance if this doesn't really answer your question, I just want to react on the apparent complexity of your problem. If I may, wouldn't this be a thousand times simpler:
/********************     **********     ********************/

class C {};
class B;

class A
{
public:

    A(): _b(nullptr), _c(nullptr) {}
    A( B *b, C *c ): _b(b), _c(c) {}
    A( A&& a ): _b(a._b), _c(a._c) {}

private:

    C *_c;
    B *_b;
};

class B
{
public:

    B( /* other parameters */ C *c ): _a( A(this,c) ) {}

private:

    A _a;
};

    /********************     **********     ********************/

int main()
{
    C c;
    B b(&c);
}

and yet achieve the same thing? I have nothing against using the new features in c++11, like std::unique_ptr, but IMHO, ensuring that a pointer can never be dereferenced from two places should not be a matter of run-time checking (except maybe in very rare cases), but a matter of design.. shouldn't it?


text:
Q: How to split a String and keep the delimiter '=' I have a string like this
String s = "p=YSp%hZ5=YunnYDUuGxVxAeLCZuVvSfoutO8=";
String[] array = s.split("=");

This array will give me an an output like this: p, YSp%hZ5, YunnYDUuGxVxAeLCZuVvSfoutO8
Desired would be to have those elements but keep the = sign like: p=, YSp%hZ5=, YunnYDUuGxVxAeLCZuVvSfoutO8=
I need to split it by = sing and keep the '=' sign somehow. Does anyone knows some pattern which will help me with it.

A: You can use this pattern...

 s = "p=YSp%hZ5=YunnYDUuGxVxAeLCZuVvSfoutO8=";
array = s.split(/(?<=\=)/);
console.log(array);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I move files from an ESXi datastore onto a VM? I uploaded two 15GB .WIM images onto my ESXi 6.0.0 datastore. I have a VM that I would like to image using those .WIM files from within a WinPE environment but can't access the files from within the VM (which does seem logical -- it would be a a security risk to allow access to the root drive from a VM). In any case, it's what I want to do. So I'm looking for workarounds.
I found an open source VMFS driver but it uses Java and WinPE doesn't have Java (https://code.google.com/p/vmfs/).
I thought of maybe mounting the .WIM files as a "ISO" (which doesn't quite work). vSphere will mount the file just fine, but if you try to navigate to the CD drive it complains that there is no filesystem (which is correct). I thought of maybe using DD to try a raw copy from the "mounted" WIM? It just seems like there should be a better way (and I'm not sure if DD will work in this case).
I want to try to avoid having to upload a 30GB ISO image of the two WIMs because it will take a day or two.

A: If you enable ssh on the esxi server then you can scp the files off into an attached vmdk either using winpe or another suitable bootdisc.


text:
Q: Loading a default script everytime Powershell ISE is launched In PowerShell ISE, I would like a default script (Template) to open every time I open Powershell ISE.
Is there a way this could be achieved?
Thanks

A: Put it in your PowerShell ISE Profile.
To locate your personal ISE profile on the current machine, check the value of:
$profile.CurrentUserCurrentHost

To locate the default personal ISE profile on the current machine, check the value of:
$profile.AllUsersCurrentHost


text:
Q: Properties of the adjacency matrix Here is a seemingly easy exercise from Bondy and Murty's book on graph theory:
For a simple graph $G$, show that the diagonal entries of $A^2$ are the degrees of the vertices of G.
Here, $A$ represents the adjacency matrix of the graph $G$. Although I have managed to come up with a proof that seems to be correct, I am dissatisfied because I do not know how to formulate it more rigorously . The verification that I came up with proceeds as follows:
First note that all entries of $A$ are either $0$ or $1$.  Clearly, the diagonal entry $(i,i)$ of $A^2$ is given by:
($i$th row of $A$) $\cdot$ ($i$th column of $A$)
$=$ ($i$th row of $A$) $\cdot$ ($i$th row of $A$)
The previous line follows because $A$ is symmetric, i.e. $A=A^T$. Here, we have the dot product between two vectors.
Observe that all entries are either $0$ or $1$, and that the dot product of the $i$th row of $A$ with itself is equal to the sum of the squares of the entries in the row vector. Thus, we simply have that  the dot product of the $i$th row of $A$ with itself is clearly equal to the sum of all the entries in the $i$th row of $A$, that is, the $i$th diagonal entry of $A^2$ is the degree of vertex $i$ in $G$.
However, is there a way to formulate this argument in a more mathematically concise manner?

A: Note that the $ij$ entry of $A^k$ counts the number of paths of length $k$ from $v_i$ to $v_j$
Thus if you have a vertex $v_i$ with degree k, that means you have $k$ paths of length $2$ from $v_i$ to itself, so  $$ (A^2)_{ii} = k $$

A: In response to the answer provided, I have managed to come up with an inductive proof for  a crucial claim provided in the answer (Specifically, prove that the $(i,j)$th entry of $A^k$ is the number of length $k$ walks from vertex $v_i$ to $v_j$). I am posting my proof here for reference purposes, as well as to request for help in checking the validity of the proof. Any suggestions on how to refine/improve this proof are most welcome. @Mohammad Riazi-Kermani can you help me take a look at it?
Proof)
Let $P_k$ be the proposition that the $(i,j)$th entry of $A^k$ is the number of walks of length $k$ from vertex $v_i$ to $v_j$. Clearly, $k=1$ is true due to the way that adjacency matrices are defined. Now, suppose the proposition is true for some $1,2, \cdots m-1,  m \in \mathbb{Z^+} $. Let $d_{ij}$ represent the $(i,j)$th entry of $A(G)^{m-1}$. By the induction hypothesis,  $d_{ij}$ is precisely the number of length $m-1$ walks between $v_i$ and $v_j$.
Now, by definition of matrix multiplication, $A(G)^m=A(G)^{m-1}A(G)$. Hence, the $(i,j)$th entry of $A(G)^m$, which we denote as $A(G)_{ij}^{m}$, is such that $A(G)_{ij}^{m}=(A(G)^{m-1}A(G))_{ij}$=$d_{i1}a_{1j} \ + d_{i2}a_{2j} \ + \cdots + d_{in}a_{nj}.$
Note that $d_{ir}a_{rj}$ gives us the number of walks of length exactly $m$ from vertices $v_i$ and $v_j$ that passes through $v_r$, $r \in [1,2, \cdots n]$. This is because $d_{ir}$ represents the number of walks of length $m-1$ between $v_i$ and $v_r$, while $a_{ij}$ represents the number of walks of length $1$ between $v_r$ and $v_j$. The conclusion then follows from the Multiplication Principle.
Finally, summing across all possible values of $r$ gives us the total number of walks of length $k$ from $v_i$ to $v_j$ and passing through $v_r$, i.e. $P_{m}$ is true.
Since $P_1$ is true and $P_m$ is true $\Rightarrow$ $P_{m+1}$ is true $\forall$ $m \in \mathbb{Z^+}$, by the Principle of Mathematical Induction, $P_k$ is true $\forall$ $k \in \mathbb{Z^+}$, i.e the $ij$th entry of $A^k$ will be the number of walks of length $k$ from $v_i$ to $v_j$. $\blacksquare$


text:
Q: C Program - Prime numbers It is to determine whether a number is prime or not.
Executed using Codeblocks 13.12.
Compiler GNU GCC 4.7.0
#include <stdio.h>

main()
{
    int input,check,count;

    printf("Enter the number: ");
    scanf("&d",&check);

    count=0;
    for(check=1;check<=1;check++)
    {
        if((input%check)==0)
        {
            count++;
        }
    }
    if(count==2)
    {
        printf("The number %d is prime",check);
    }
    else
    {
        printf("The number %d is not prime",check);
    }
}

Please note that there is no error or warning.
But the compiler assumes a number "2" even after giving someother input and it says 2 is not prime!!

A: scanf("&d",&check);

should be
//     v-- percent, not ampersand
scanf("%d",&check);

Or (probably)
scanf("%d", &input);

...since it would make a lot more sense to read into the input variable. Later in the program, then,
printf("The number %d is prime", check);

should be
printf("The number %d is prime\n", input);

because you're checking input, not check. The same two lines below that. Finally, the loop condition in
for(check=1;check<=1;check++)

makes no sense. The loop would run exactly once, and you don't want to test if input is divisible by 1. It would make sense with
                 // v-- check factors until input
for(check=1;check<=input;check++)

This is not the most efficient check here, but it's something to get you started.
Side note: the prototype
main()

is compliant only with C89. From C99 onwards, the old K&R method of function declaration is no longer included, and the proper equivalent prototype for main is
int main(void)

So while you're fixing things, you should put that there.

A: Some issues are:

*

*Variable input is not defined which contains garbage value.

*for(check=1;check<=1;check++) This seems incorrect, loops only once for all cases.

*Read values using scanf by passing format specifier as %d instead of &d.

A: Well I assume it always comes down to someone doing the code for the asker anyway.
#include <stdio.h>
#include <conio.h>

int main() // note "int" before "main()"
{
    int input, check, count;
    printf("Enter the number: ");
    scanf("%d", &input); //I believe this is what you meant instead of storing the inputted value in "check"

    count = 0;
    check = 2; //Check should equal "2" because anything divided by one will have no remainder

    while((count != 1) && (check <= 50)) //If you want to stop trying to divide when the number you're dividing by is above 50, change this line. I stopped at 50 just as a random number, but I'm sure there's a more logical one to use. ------ "while(count != 1)" stops the loop when the number is successfully divided.

    {
        if (check == input) break; // stop checking when the number we're trying to divide is equal to the number to divide by.

        if((input%check) == 0)
        {
            count++;
        }

        check++; //increment the number we're checking by
    }

    if(count == 1)
    {
        printf("The number %d is not prime\n", input); // output the number the user tried to input
    }

    else
    {
        printf("The number %d is prime\n", input);
    }

    getch();
    return 1;
}

I beg of you to read the comments and understand them instead of just copying the code, as I've seen done so many times.
Edit: My mistake for originally including a c++ function. It's in C now.


text:
Q: How to know the Duration of audio song before streaming? I am making an application for Stream audio song. In Custom media player, i have to show the total duration of that audio file.
If a audio song will be SDCard , i can know its duration using
MediaPlayer player;

public double duration() {
        return player.getDuration();
    }

But in my case audio file is on the server, so i have to stream it.
What is the best approach?

A: This might help you: Example of Streaming mp3 with android media player class .
The respective data is probably available, once prepare() is called for the file to be streamed.

A: I think this will give you the length of the file to be streamed. After the declaring the MediaPlayer mp object
 mp.start();
 totalDur=mp.getDuration();//will give you the duration in milliseconds.

For further reference please go through the following link: http://developer.android.com/reference/android/media/MediaPlayer.html#getDuration%28%29

A: with below code you can get duration without using any library
player = new MediaPlayer();
player.setDataSource(YOUR_URL);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.prepareAsync();

        player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                seekBar.setMax(mediaPlayer.getDuration());
                player.start();
            }
        });


text:
Q: Kubernetes crd failed to be created using go-client interface I created a Kubernetes CRD following the example at https://github.com/kubernetes/sample-controller.
My controller works fine, and I can listen on the create/update/delete events of my CRD.  Until I tried to create an object using go-client interface.
This is my CRD.
type MyEndpoint struct {
    metav1.TypeMeta   `json:",inline"`

    // Standard object's metadata.
    // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
    // +optional
    metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
}

I can create the CRD definition and create object using kubectl without any problems. But I got failure when I use following code to create the object.
myepDeploy := &crdv1.MyEndpoint{
    TypeMeta: metav1.TypeMeta{
        Kind:       "MyEndpoint",
        APIVersion: "mydom.k8s.io/v1",
    },
    ObjectMeta: metav1.ObjectMeta{
        Name: podName,
        Labels: map[string]string{
            "serviceName": serviceName,
            "nodeIP": nodeName,
            "port": "5000"
        },
    },
}
epClient := myclientset.MycontrollerV1().MyEndpoints("default")
epClient.Create(myepDeploy)

But I got following error:
object *v1.MyEndpoint does not implement the protobuf marshalling interface and cannot be encoded to a protobuf message

I take a look at other standard types, I don't see if they implemented such interface.  I searched on google, but not getting any luck.
Any ideas? Please help.  BTW, I am running on minikube.

A: For most common types and for simple types marshalling works out of the box. In case of more complex structure, you may need to implement marshalling interface manually.
You may try to comment part of the MyEndpoint structure to find out what exactly caused the problem.

A: This error is occurred when your client epClient trying to marshal the MyEndpoint object to protobuf. This is because of your rest client config. Try setting Content Type is "application/json".
If you are using below code to generate config, then change the content type.
cfg, err := clientcmd.BuildConfigFromFlags(masterURL, kubeconfig)
if err != nil {
    glog.Fatalf("Error building kubeconfig: %s", err.Error())
}

cfg.ContentType = "application/json"

kubeClient, err := kubernetes.NewForConfig(cfg)
if err != nil {
    glog.Fatalf("Error building kubernetes clientset: %s", err.Error())
}


text:
Q: Airflow Scheduler not picking up DAG Runs I'm setting up airflow such that webserver runs on one machine and scheduler runs on another. Both share the same MySQL metastore database. Both instances come up without any errors in the logs but the scheduler is not picking up any DAG Runs that are created by manually triggering the DAGs via the Web UI.
The dag_run table in MysQL shows few entries, all in running state:
mysql> select * from dag_run;
+----+--------------------------------+----------------------------+---------+------------------------------------+------------------+----------------+----------+----------------------------+
| id | dag_id                         | execution_date             | state   | run_id                             | external_trigger | conf   | end_date | start_date                 |
+----+--------------------------------+----------------------------+---------+------------------------------------+------------------+----------------+----------+----------------------------+
|  1 | example_bash_operator          | 2017-12-14 11:33:08.479040 | running | manual__2017-12-14T11:33:08.479040 |                1 | ��       }�.    | NULL     | 2017-12-14 11:33:09.000000 |
|  2 | example_bash_operator          | 2017-12-14 11:38:27.888317 | running | manual__2017-12-14T11:38:27.888317 |                1 | ��       }�.    | NULL     | 2017-12-14 11:38:27.000000 |
|  3 | example_branch_dop_operator_v3 | 2017-12-14 13:47:05.170752 | running | manual__2017-12-14T13:47:05.170752 |                1 | ��       }�.    | NULL     | 2017-12-14 13:47:05.000000 |
|  4 | example_branch_dop_operator_v3 | 2017-12-15 04:26:07.208501 | running | manual__2017-12-15T04:26:07.208501 |                1 | ��       }�.    | NULL     | 2017-12-15 04:26:07.000000 |
|  5 | example_branch_dop_operator_v3 | 2017-12-15 06:12:10.965543 | running | manual__2017-12-15T06:12:10.965543 |                1 | ��       }�.    | NULL     | 2017-12-15 06:12:11.000000 |
|  6 | example_branch_dop_operator_v3 | 2017-12-15 06:28:43.282447 | running | manual__2017-12-15T06:28:43.282447 |                1 | ��       }�.    | NULL     | 2017-12-15 06:28:43.000000 |
+----+--------------------------------+----------------------------+---------+------------------------------------+------------------+----------------+----------+----------------------------+
6 rows in set (0.21 sec)

But the Scheduler that's started up on another machine and connected to the same MySQL DB is just not interested in talking to this DB and actually running these DAG runs and converting them to Task Instances.
Not sure what I'm missing in the setup here. So few questions:

*

*When and how is the DAGS folder located at $AIRFLOW_HOME/dags populated? I think its when the webserver is started. But then if I just start the scheduler on another machine, how will the DAGS folder on that machine be filled up?

*Currently, I'm doing airflow initdb only on the machine hosting the webserver and not on scheduler. Hope that is correct.

Can I enable debug logs for Scheduler to get more logs that could indicate what's missing? From the current logs it looks like it just looks in the DAGS folder on local system and finds no DAGS there ( not even example ones ) inspite of the config to load examples set as True.
Don't think it matters but I'm currently using a LocalExecutor
Any help is appreciated.
Edit: I know that I need to sync up DAGS folder across machines as the airflow docs suggest but not sure if this is the reason why Scheduler is not picking up the tasks in the above case.

A: Ok, I got the answer - It looks like the Scheduler does not query the DB until there are any DAGS in the local DAG Folder. The code in job.py looks like
ti_query = (
        session
        .query(TI)
        .filter(TI.dag_id.in_(simple_dag_bag.dag_ids))
        .outerjoin(DR,
            and_(DR.dag_id == TI.dag_id,
                 DR.execution_date == TI.execution_date))
        .filter(or_(DR.run_id == None,
                not_(DR.run_id.like(BackfillJob.ID_PREFIX + '%'))))
        .outerjoin(DM, DM.dag_id==TI.dag_id)
        .filter(or_(DM.dag_id == None,
                not_(DM.is_paused)))
    )

I added a simple DAG in my local DAG folder on the machine hosting Scheduler and it started picking up other DAG instances as well.
We raised an issue for this - https://issues.apache.org/jira/browse/AIRFLOW-1934


text:
Q: Authenticating with openstack.net API cloud files using London account When I use:
            CloudIdentity identity =
            new CloudIdentity()
            {
                Username = "files.user",
                APIKey = "pswd",
            };
            var _storage = new CloudFilesProvider(identity);

Authentication fails. I figured that the problem is that I have a LON account and the default authentication target is US cloud instance. On openstack.net wiki, I saw the below example.
IIdentityProvider identityProvider = new CloudIdentityProvider();
var userAccess = identityProvider.Authenticate(new RackspaceCloudIdentity{
                                                    Username = "MyUserName",
                                                    Password = "MyPassword",
                                                    CloudInstance =CloudInstance.UK});

In the latest version of the library, RackspaceCloudIdentity has Domain parameter instead of CloudInstance. I guess the example is out dated.
How do I use the Domain parameter? Or is there a better way to authenticate with LON cloud instance?

A: Rackspace uses global authentication now, so the only difference between the US and UK accounts is the credentials you pass in. If authentication is failing then one of the following is the likely issue:

*

*Your username and/or API key for the CloudIdentity instance are not correct.

*The identity service experienced an outage of some sort at the particular moment you tried to authenticate.

*Authentication is succeeding, but another error occurred which you have attributed to failed authentication (you didn't provide any exception details so I can't rule this out).

A: I have been seeing the same error. I believe that it is something to do with child accounts created via the UI. They do not have a DefaultRegion correctly set (it is null).
The only way around this is to use the parent account, or alternatively to manually set the region on every API call.


text: Q: How to tell programmatically if IBM java (version 8) is running in FIPS mode IBM Java 8 on AIX and Linux has changed the com.ibm.crypto.fips.provider.SelfTest class access from public to package.  I have code that was using this class to tell if JVM is running in FIPS mode.  How do we do this now that the class is no longer public.  I need to know if the FIPS self test passed.


text:
Q: I want to solve this query with c program Can someone guide me how to put this properly in an if-else statement.
Consider the following if statement, where doesSignificantWork, makesBreakthrough, and nobelPrizeCandidate are all boolean variables:
if (doesSignificantWork) {
    if (makesBreakthrough)
        nobelPrizeCandidate = true;
    else
        nobelPrizeCandidate = false;
}
else if (!doesSignificantWork)
    nobelPrizeCandidate = false;

First, write a simpler if statement that is equivalent to this one. Then write a single assignment statement that does the same thing.

A: if (doesSignificantWork) {
    if (makesBreakthrough)
        nobelPrizeCandidate = true;
    else
        nobelPrizeCandidate = false;
}
else if (!doesSignificantWork)
    nobelPrizeCandidate = false

Is equivalent to
nobelPrizeCandidate = (doesSignificantWork && makesBreakthrough);

A: You can make a truth table. The first step is to identify inputs, and write down all combinations of their values.
Input   Output
d   m   n
0   0   ?
0   1   ?
1   0   ?
1   1   ?

Then fill the correct output values
Input   Output
d   m   n
0   0   0
0   1   0
1   0   0
1   1   1

You should now see that the output function corresponds to logical AND (&&).

A: A simpler if statement is:
if (doesSignificantWork && makesBreakthrough)
  nobelPrizeCandidate = true;
else
  nobelPrizeCandidate = false;

@Blaze's answer gives you the simplest one-liner. An alternative is
nobelPrizeCandidate = (doesSignificantWork && makesBreakthrough) ? true : false;


text:
Q: What's the difference between "BB regression algorithms used in R-CNN variants" vs "BB in YOLO" localization techniques? Question:

What's the difference between the bounding box(BB) produced by "BB regression algorithms in region-based object detectors" vs "bounding box in single shot detectors"? and can they be used interchangeably if not why?

While understanding variants of R-CNN and Yolo algorithms for object detection, I came across two major techniques to perform object detection i.e Region-based(R-CNN) and niche-sliding window based(YOLO).
Both use different variants(complicated to simple) in both regimes but in the end, they are just localizing objects in the image using Bounding boxes!. I am just trying to focus on the localization(assuming classification is happening!) below since that is more relevant to the question asked & explained my understanding in brief:

*

*Region-based:

*

*Here, we let the Neural network to predict continuous variables(BB coordinates) and refers to that as regression.

*The regression that is defined (which is not linear at all), is just a CNN or other variants(all layers were differentiable),outputs are four values (,,ℎ,), where (,) specify the values of the position of the left corner and (ℎ,) the height and width of the BB.

*In order to train this NN, a smooth L1 loss was used to learn the precise BB by penalizing when the outputs of the NN are very different from the labeled (,,ℎ,) in the training set!

*niche-Sliding window(convolutionally implemented!) based:

*

*first, we divide the image into say 19*19 grid cells.

*the way you assign an object to a grid-cell is by selecting the midpoint of an object and then assigning that object to whichever one grid cell contains the midpoint of the object. So each object, even if the objects span multiple grid cells, that object is assigned only to one of the 19 by 19 grid cells.

*Now, you take the two coordinates of this grid-cell and calculate the precise BB(bx, by, bh, bw) for that object using some method such as

*(bx, by, bh, bw) are relative to the grid cell where x & y are center point and h & w are the height of precise BB i.e the height of the bounding box is specified as a fraction of the overall width of the grid cell and h& w can be >1.

*There multiple ways of calculating precise BB specified in the paper.

Both Algorithms:

*

*outputs precise bounding boxes.!

*works in supervised learning settings, they were using labeled dataset where the labels are bounding boxes stored(manually marked my some annotator using tools like labelimg ) for each image in a JSON/XML file format.
I am trying to understand the two localization techniques on a more abstract level(as well as having an in-depth idea of both techniques!) to get more clarity on:

*

*in what sense they are different?, &

*why 2 were created, I mean what are the failure/success points of 1 on the another?.

*and can they be used interchangeably, if not then why?

please feel free to correct me if I am wrong somewhere, feedback is highly appreciated! Citing to any particular section of a research paper would be more rewarding!

A: The essential differences are that two-stage Faster R-CNN-like are more accurate while single-stage YOLO/SSD-like are faster.
In two-stage architectures, the first stage is usually of region proposal, while the second stage is for classification and more accurate localization. You can think of the first stage as similar to the single-stage architectures, when the difference is that the region proposal only separates "object" from "background", while the single-stage distinguishes between all object classes. More explicitly, in the first stage, also in a sliding window-like fashion, an RPN says whether there's an object present or not, and if there is - to roughly give the region (bounding box) in which it lies. This region is used by the second stage for classification and bounding box regression (for better localization) by first pooling the relevant features from the proposed region, and then going through the Fast R-CNN-like architecture (which does the classificaion+regression).
Regarding your question about interchanging between them - why would you want to do so? Usually you would choose an architecture by your most pressing needs (e.g. latency/power/accuracy), and you wouldn't want to interchange between them unless there's some sophisticated idea which will help you somehow.


text:
Q: SQL Server Index and Statistics Maintenance -- IndexOptimize ola hallengren Script I am using IndexOptimize script by Ola Hallengren and am having problems. I have set this up using the parameters below. I read online you have to specify all parameters in order for this to work which I have done. I have put this stored procedure into a database and am calling it in a job. The job runs successfully but it is not rebuilding or reorganizing the indexes.
Please see my code below can any help.
USE TestDBA
EXEC [OlaH].[usp_IndexOptimize]

@Databases = 'USER_DATABASES',
@FragmentationLow  = NULL,
@FragmentationMedium  = 'INDEX_REORGANIZE,INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE',
@FragmentationHigh  = 'INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE',
@FragmentationLevel1  = 5,
@FragmentationLevel2  = 30,
@PageCountLevel  = 0,
@SortInTempdb = 'Y',
@MaxDOP = NULL,
@FillFactor = NULL,
@PadIndex = NULL,
@LOBCompaction  = 'Y',
@UpdateStatistics = 'ALL',
@OnlyModifiedStatistics = 'Y',
@StatisticsSample = NULL,
@StatisticsResample = 'N',
@PartitionLevel = 'Y',
@MSShippedObjects = 'Y',
@Indexes = NULL,
@TimeLimit = 360,
@Delay = NULL,
@WaitAtLowPriorityMaxDuration = 5,
@WaitAtLowPriorityAbortAfterWait  = 'SELF',
@LockTimeout = NULL,
@LogToTable = 'N',
@Execute = 'Y'

A: You issue is likely  the fact that you have @TimeLimit = 360 which is the seconds after which no commands are executed. That's not a long time for this job. This likely is preventing the script from finishing gathering the fragmentation statistics, and thus never makes it to the reindex, reorganize, rebuild steps. 6 minutes is pretty small window for a decent size database. Set this to something more realistic, like 3600, which is 1 hour.
Aside from that, the fragmentation level could be a second culprit.
@FragmentationLevel1  = 5,
@FragmentationLevel2  = 30,

This means if the fragmentation is between 5% and 30%, then it will perform the actions in @FragmentationMedium. If it's greater than 30% then it will perform what you have listed in @FragmentationHigh.  If your indexes aren't fragmented at least 5%, nothing is going to happen since you have @FragmentationLow = NULL.
You can check this with sys.dm_db_index_physical_stats
SELECT OBJECT_NAME(ips.OBJECT_ID)
 ,i.NAME
 ,ips.index_id
 ,index_type_desc
 ,avg_fragmentation_in_percent
 ,avg_page_space_used_in_percent
 ,page_count
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'SAMPLED') ips
INNER JOIN sys.indexes i ON (ips.object_id = i.object_id)
 AND (ips.index_id = i.index_id)
ORDER BY avg_fragmentation_in_percent DESC

Benjamin brought up a good point. After 5 minutes of waiting for low priority locks, the script would abort the online index rebuild operation since you have @WaitAtLowPriorityAbortAfterWait = 'SELF'. This shouldn't affect every table in your database though. However, if you specifically fragmented an index by adding a bunch of data or playing with the fill factor, and this is the only index that meets your threshold and a lock is holding onto it, it could result in this behavior.


text:
Q: The conditions that partial derivatives commute State the conditions that partial derivatives commute, namely, $D_1D_2f = D_2D_1f$.
I understand how to prove that these partial derivatives are equal but I don't understand what commute means. Please help.

A: Commute just means that the order of derivatives that we take does not matter. One could take the partials with respect to $x$ and then the partial with respect to $y$ or instead the partial to $y$ and then $x$. The final answer is independent of the order in which we take our derivatives.

A: Technically, you can think of $D_1$ and $D_2$ as operations on the function $f$. For the operations $D_1$ and $D_2$ to commute we need that after applying $D_1 D_2$ to $f$ we get $D_2 D_1 f$ or
$$ D_1 D_2 f(x_1, x_2)  = D_2 D_1 f(x_1, x_2) \Leftrightarrow D_1 D_2 f - D_2 D_1 f(x_1, x_2) = 0 \Leftrightarrow (D_1 D_2 - D_2 D_1)f(x_1, x_2) = 0. $$
Yes that last bit means that $D_1 D_2 - D_2 D_1$ is also an operation on $f(x_1, x_2)$ and it will be the zeroing operation.
As an exercise you may want to try to rewrite the above tautology in terms of a simple function, say $\exp\{ - (x^2 + y^2) \}.$
We can think of more general operations like, say multiplying $f(x_1,x_2)$ by $x_1$, call this operation $M_1$. That is, $$ M_1 f(x_1, x_2) = x_1 f(x_1, x_2)$$ a new function. Then we see that (this is an exercise) $M_1 D_2 f = D_2 M_1 f$ but $M_1 D_1 f \neq D_1 M_1 f$. In fact $$( M_1 D_1 - D_1 M_1) f = 1 $$ the constant function.
I know this is extra information but I just wanted to point out that this formalism is not arbitrary. It turns out that the certain operations (like differentiation and multiplication by a variable) have a nice algebraic structure and that commutativity is usually not part of it. However, the commutator substructure can be built by considering the bits left over: the operations $$ AB - BA$$ as above. The properties of this substructure are important to  many branches of engineering and physics. The example above (with a small but imaginative modification) can be used to describe the uncertainty of position and momentum observations according to the laws of quantum mechanics.


text:
Q: Where is scss file I use PhpStorm. In new file list I don't have scss file - how to get it?

A: Use Stylesheet entry -- it's a special "combo" entry for all bundled CSS-related languages. Once invoked you will see a dialog where you can choose what language to use (and it will be remembered for next invocation as well).
Same story for PHP ("PHP Class" entry) and HTML ("HTML File" entry).
P.S.
Note, that any custom (user created) File Templates will be listed in that popup menu as usual -- as individual entries.

A: You can also add/edit File Templates in PhpStorm:
https://confluence.jetbrains.com/display/PhpStorm/File+Templates+in+PhpStorm


text:
Q: Intervals on x axis I want to change the size of the of the intervals between numbers.
The x axis obviously goes from 10 to 26. But I want every whole number to be displayed: 10, 11, 12, 13 etc...
I also want bins to have a width of .5 so that I can have a bin from 10.5 to 11 or 24 to 24.5 etc...because otherwise, python outputs the histogram with the bins random and undetermined.
Here's what I have:
import random
import numpy
from matplotlib import pyplot
import numpy as np

data = np.genfromtxt('result.csv',delimiter=',',skip_header=1, dtype=float)

magg=[row[5] for row in data]
magr=[row[6] for row in data]

bins = numpy.linspace(10, 26)

pyplot.hist(magg, bins, alpha=0.5, color='g', label='mag of g')
pyplot.hist(magr, bins, alpha=0.5, color='r', label='mag of r')
pyplot.legend(loc='upper left')
pyplot.show()

A: Use an axes locator, in particular, MultipleLocator. Building of your example, it becomes this:
import matplotlib.pyplot as plt
import numpy as np

x = np.random.random_integers(low=10, high=27, size=37)

bins = np.linspace(10, 26)

fig, ax = plt.subplots()
hist = ax.hist(x, bins, alpha=0.5, color='g', label='mag of g')
ax.xaxis.set_major_locator(plt.MultipleLocator(1))


text:
Q: SoapUI: When I do an update followed by a select in a JDBC Request, I do not see the select result In a JDBC Request I have:
select 1 "col"

This works fine, on the right in het GUI I see the result.
But when I first do an update, and then the select:
update  tempdb..c
set m=2*m
where n=1
select 1 "col"

then I see that there is 1 update done, but I do not see the select result anymore. Why is that?


text:
Q: Jqgrid Navgrid doesn't work Im trying to add navgrid to a working jqgrid but it doesn't show. The documentation could be better imo.
$("#" + id + "Table").jqGrid({
        datatype: "local",
        data: data,
        colNames: colNames,
        colModel: colModel,
        pager: '#' + id + 'Table',
        autowidth: true,
        scroll: false,
        forceFit: true,
        shrinkToFit: true,  //Width of columns should be expressed in integers which add to 100
        rowNum: <xsl:value-of select="$totalLength"/>,
        rowTotal: <xsl:value-of select="$totalLength"/>,
        sortname: defaultSortColumn,
        sortorder: defaultSortOrder,
        url: "fs/servlet/CS"
      });
      $("#" + id + "Table").jqGrid('navGrid',"#" + id + "Pager",{edit:true,add:true,del:true});

A: You are setting your pager to be the same element as the grid:
It should be different
Ex
Html

And then your pager would be setup via
pager: $('#pagerId'),


text:
Q: Winforms Designer: Modify (and keep) properties in sub objects For a WinForms control, I'd like to move certain settings into a sub object. One of them is a custom class containing all UI Strings, the other a OpenFileDialog:
class MyControl: Control
{
  // ...
  private OpenFileDialog m_dlgOpen = new OpenFileDialog();
  public OpenFileDialog DialogOpen
  {
     get { return m_dlgOpen; }
  }
}

This adds the sub object to the designer, and allows to edit its properties (e.g. title, default extension, filter). However, the changes are nto added to the InitalizeComponent method, so they are lost.
Is it possible to make this properties "persist" in the InitializeComponent method?

A: Tell the designer to serialize the object itself:
  [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
  public OpenFileDialog DialogOpen {
    get { return m_dlgOpen; }
  }


text:
Q: VECM with first differences? Is it ok to take first differences of data which is non stationary in levels but stationary in first differences (and cointegrated), and input these differenced variables into the VECM? Or does this constitute over differencing given th VECM differences the data as well?

A: When the variables are integrated of order one, I(1), and cointegrated, VECM is specified with variables in differences on the left hand side of the equation:
$$
\Delta y_t=\Pi y_{t-1}+\Gamma_1\Delta y_{t-1}+...+\Gamma_{p-1}\Delta y_{t-(p-1)}+\varepsilon_t.
$$
The right-hand-side variables are all differenced except for the error correction term which is a linear combination (or several of them) of $y_{t-1}$ in levels.
If you specify a VECM of the form
$$
\Delta^2 y_t=\Pi\Delta y_{t-1}+\Gamma_1\Delta^2 y_{t-1}+...+\Gamma_{p-1}\Delta^2 y_{t-(p-1)}+u_t
$$
instead, you have overdifferencing your series, and that is a problem.
Could you be getting "better" results from the latter model in terms of impulse response function? That is not impossible. Models are but approximations to reality. Assumptions for making these models and the coefficient estimators work may be violated to a smaller or larger degree. Perhaps the behavior of variables you are modelling is indeed better described by the overdifferenced model than the regular/"proper" one.
However, there is also a question of how you know what is "better". Perhaps the IRFs you obtain from the overdifferenced model are more like what you expected beforehand, but that does not mean they are closer to the truth than those from the regular VECM.
In any case, when choosing the overdifferenced model you would need to come up with a justification for that, while choosing the regular VECM is already justified by the theory around cointegrated processes (Granger's representation theorem etc.).


text:
Q: How to calculate quarterly averages from daily data with VBA? I have daily data from 01.01.1990. to 31.12.2012. I need to calculate quarterly averages from the daily data with a VBA function. Is there an efficient way to do this?
Any help is appreciated!

A: Put your data in a pivot table. Put your Date values in the Rows and put your numeric values in the Values. Right click on the date data and select Group...

To make sure you are taking the average right click on your numeric data and select Value Field Settings

You'll get something that looks like this


text:
Q: Highcharts Graph not recreating on same Android activity I am using Android Highcharts Graph Library in my project.
https://github.com/highcharts/highcharts-android
I have Four Buttons Day, Hour, Minute, Week as below image.

When Activity starts first time it works fine, Graph is also showing correctly all things are working fine but when again API is hitting again on same activity response I am getting correctly but graph is not recreating.
I checked with LOG  inside callGraphView() Log prints Correctly but no change detected in graph.
I also checked it without API but same thing happens again. In Web/iOS its working fine.
Below is the URL of This Graph :
https://www.highcharts.com/android/demo/line-basic
Below is my Code :
private void JsonRequestOrderVelocity(String dmhw) {
    utils.showDialog();

    String url = Constants.ORDER_VELOCITY_API+"stemSku=com-1&type="+dmhw+"&warehouse_id="+whareHouse;
    Log.e("URL", "" + url);

    JsonObjectRequest request = new JsonObjectRequest(url, null,
            response -> {
                Log.e("onResponse",""+response);
                try {
                    Gson gson = new Gson();
                    Type listType = new TypeToken<OrderVelocityPojo>() {}.getType();
                    orderVelocityPojo = gson.fromJson(response.toString(), listType);

                    if(dmhw.equalsIgnoreCase("day")){
                        callGraphView("Daily");
                    }else if(dmhw.equalsIgnoreCase("hour")){
                        callGraphView("Hourly");
                    }else if(dmhw.equalsIgnoreCase("minute")){
                        callGraphView("Minute-wise");
                    }else{
                        callGraphView("Weekly");
                    }
                        ...................
}

Graph call Method :
 private void callGraphView(String timeType) {
    Log.e("TIMETYPE",""+timeType);
    chartView.setWillNotDraw(false);
    HIOptions options = new HIOptions();

    HIChart chart = new HIChart();
    chart.type = "line";
    options.chart = chart;

    HITitle title = new HITitle();
    title.text = "("+getIntent().getStringExtra("WHARE_HOUSE_NAME")+") "+timeType+" Sales Trend";
    options.title = title;

    HISubtitle subtitle = new HISubtitle();
    subtitle.text = "Source: thesolarfoundation.com";
    options.subtitle = subtitle;

    HIYAxis yaxis = new HIYAxis();
    yaxis.title = new HITitle();
    yaxis.title.text = "Quantity Sold";
    options.yAxis = new ArrayList<>(Collections.singletonList(yaxis));

    HIXAxis xaxis = new HIXAxis();
    xaxis.categories=orderVelocityPojo.getRange();
    options.xAxis = new ArrayList<>(Collections.singletonList(xaxis));

    HILegend legend = new HILegend();
    legend.layout = "vertical";
    legend.align = "right";
    legend.verticalAlign = "middle";
    options.legend = legend;

    HIPlotOptions plotoptions = new HIPlotOptions();
    plotoptions.series = new HISeries();
    plotoptions.series.label = new HILabel();
    plotoptions.series.label.connectorAllowed = false;;
    plotoptions.series.pointStart = 2010;

    HILine line1 = new HILine();
    line1.name = "Actual Sales("+orderVelocityPojo.getFromDate()+" to "+orderVelocityPojo.getToDate()+")";
    line1.data = count;

    HILine line2 = new HILine();
    line2.name = "Inventory Projected";
    line2.visible=false;
    line2.data = null;

    HILine line3 = new HILine();
    line3.name = "Previous Day Sales("+orderVelocityPojo.getPreviousIntervalFromDateDay()+" to "+orderVelocityPojo.getPreviousIntervalToDateDay()+")";
    line3.visible=false;
    line3.data = previousCountDay;

    HILine line4 = new HILine();
    line4.name = "Previous Week Sales("+orderVelocityPojo.getPreviousIntervalFromDateWeek()+" to "+orderVelocityPojo.getPreviousIntervalToDateWeek()+")";
    line4.visible=false;
    line4.data = previousCountWeek;

    HILine line5 = new HILine();
    line5.name = "Previous Month Sales("+orderVelocityPojo.getPreviousIntervalFromDateMonth()+" to "+orderVelocityPojo.getPreviousIntervalToDateMonth()+")";
    line5.visible=false;
    line5.data = previousCountMonth;

    HILine line6 = new HILine();
    line6.name = "Previous 3 Month Sales("+orderVelocityPojo.getPreviousIntervalFromDate3Month()+" to "+orderVelocityPojo.getPreviousIntervalToDate3Month()+")";
    line6.visible=false;
    line6.data = previousCount3_Month;

    HILine line7 = new HILine();
    line7.name = "Previous 6 Month Sales("+orderVelocityPojo.getPreviousIntervalFromDate6Month()+" to "+orderVelocityPojo.getPreviousIntervalToDate6Month()+")";
    line7.visible=false;
    line7.data = previousCount6_Month;

    HILine line8 = new HILine();
    line8.name = "Previous Years Sales("+orderVelocityPojo.getPreviousIntervalFromDateYear()+" to "+orderVelocityPojo.getPreviousIntervalToDateYear()+")";
    line8.visible=false;
    line8.data = previousCountYear;

    HILine line9 = new HILine();
    line9.name = "MDay 2016 Week Sales("+orderVelocityPojo.getPreviousIntervalFromMothersDay()+" to"+orderVelocityPojo.getPreviousIntervalToMothersDay()+")";
    line9.visible=false;
    line9.data = previousCountMothersDay;

    HILine line10 = new HILine();
    line10.name = "MDay 2016(-1) Week Sales("+orderVelocityPojo.getPreviousIntervalFromMothersDayMinusOne()+" to "+orderVelocityPojo.getPreviousIntervalToMothersDay()+")";
    line10.visible=false;
    line10.data = previousCountMothersDayMinusOne;

    HILine line11 = new HILine();
    line11.name = "MDay 2017 Week Sales("+orderVelocityPojo.getPreviousIntervalFromMothersDay2017()+" to "+orderVelocityPojo.getPreviousIntervalToMothersDay2017()+")";
    line11.visible=false;
    line11.data = previousCountMothersDay2017;

    HILine line12 = new HILine();
    line12.name = "MDay 2017 (-1)Week Sales("+orderVelocityPojo.getPreviousIntervalFromMothersDay2017MinusOne()+" to "+orderVelocityPojo.getPreviousIntervalToMothersDay2017MinusOne()+")";
    line12.visible=false;
    line12.data = previousCountMothersDay2017MinusOne;

    HILine line13 = new HILine();
    line13.name = "VDay 2017 Week Sales("+orderVelocityPojo.getPreviousIntervalFromValentinesDay()+" to "+orderVelocityPojo.getPreviousIntervalToValentinesDay()+")";
    line13.visible=false;
    line13.data = previousCountValentinesDay;

    HILine line14 = new HILine();
    line14.name = "VDay 2017 (-1) Week Sales("+orderVelocityPojo.getPreviousIntervalFromValentinesDayMinusOne()+" to "+orderVelocityPojo.getPreviousIntervalToValentinesDayMinusOne();
    line14.visible=false;
    line14.data = previousCountValentinesDayMinusOne;

    HILine line15 = new HILine();
    line15.name = "Inventory Received";
    line15.visible=false;
    line15.data = null;

    HIResponsive responsive = new HIResponsive();

    HIRules rules1 = new HIRules();
    rules1.condition = new HICondition();
    rules1.condition.maxWidth = 500;
    HashMap<String, HashMap> chartLegend = new HashMap<>();
    HashMap<String, String> legendOptions = new HashMap<>();
    legendOptions.put("layout", "horizontal");
    legendOptions.put("align", "center");
    legendOptions.put("verticalAlign", "bottom");
    chartLegend.put("legend", legendOptions);
    rules1.chartOptions = chartLegend;
    responsive.rules = new ArrayList<>(Collections.singletonList(rules1));
    options.responsive = responsive;
    options.series = new ArrayList<HISeries>(Arrays.asList(line1,line2,line3,line4,line5,line6,line7,line8,line9,line10,line11,line12,line13,line14,line15));
    chartView.options = options;
}

A: First Solution :
We can use HIChartView object like this: chartView.reload() after each request.
full Code :
 dayButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                manager.updateChart(chartView, c, "area", "DataSteps.json", "day");
                chartView.reload();
            }
        });
        weekButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                manager.updateChart(chartView, c, "area", "DataSteps.json", "week");
                chartView.reload();
            }
        });
        monthButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                manager.updateChart(chartView, c, "area", "DataSteps.json", "month");
                chartView.reload();
            }
        });
        yearButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                manager.updateChart(chartView, c, "area", "DataSteps.json", "year");
                chartView.reload();
            }
        });

Second Solution :
I solved this issue by myself, I created one fragment inside Activity for graph, also I'm hitting API inside fragment with highcharts-graphView.
So when i  taps on any of them Day,Hour,Minute,Week button it creates fragment every time and graph showing.
Here is the code :
 @Override
public void onClick(View view) {
    if(view.getId()==R.id.btndayOV){

        OrderVelocityFragment fragment = new OrderVelocityFragment().newInstance(whareHouse,whareHouseName,"day");
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content_frame_home, fragment)
                .commit();

        day.setTextColor(Color.WHITE);
        day.setBackgroundResource(R.color.orderVelocity);
        hour.setBackgroundResource(R.color.orderVelocityLight);
        minute.setBackgroundResource(R.color.orderVelocityLight);
        week.setBackgroundResource(R.color.orderVelocityLight);
    }
    else if(view.getId()==R.id.btnHourOV){

        OrderVelocityFragment fragment = new OrderVelocityFragment().newInstance(whareHouse,whareHouseName,"hour");
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content_frame_home, fragment)
                .commit();

        hour.setTextColor(Color.WHITE);
        day.setBackgroundResource(R.color.orderVelocityLight);
        hour.setBackgroundResource(R.color.orderVelocity);
        minute.setBackgroundResource(R.color.orderVelocityLight);
        week.setBackgroundResource(R.color.orderVelocityLight);
    }
    else if(view.getId()==R.id.btnMinuteOV){

        OrderVelocityFragment fragment = new OrderVelocityFragment().newInstance(whareHouse,whareHouseName,"minute");
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content_frame_home, fragment)
                .commit();

        minute.setTextColor(Color.WHITE);
        day.setBackgroundResource(R.color.orderVelocityLight);
        hour.setBackgroundResource(R.color.orderVelocityLight);
        minute.setBackgroundResource(R.color.orderVelocity);
        week.setBackgroundResource(R.color.orderVelocityLight);
    }
    else if(view.getId()==R.id.btnWeekOV){

        OrderVelocityFragment fragment = new OrderVelocityFragment().newInstance(whareHouse,whareHouseName,"week");
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content_frame_home, fragment)
                .commit();

        week.setTextColor(Color.WHITE);
        day.setBackgroundResource(R.color.orderVelocityLight);
        hour.setBackgroundResource(R.color.orderVelocityLight);
        minute.setBackgroundResource(R.color.orderVelocityLight);
        week.setBackgroundResource(R.color.orderVelocity);
    }
}


text:
Q: Корректные модальные окна для мобилок Подскажите плагин модального окна для мобильных устройств на js, который:

*

*Легко кастомизируеются css свойства

*Документ не прокручивается при прокрутке внутри модального окна

*При открытии модального окна, основной документ не прокручивается к началу.

Или как реализовать сие чудо.
Пробую стандартными способами, но ios возникает проблема с прокруткой, скроллится документ. Если сделать для body {position: fixed;} то при появлении окна происходит прокрутка к началу документа


text:
Q: Why do projects in the quantlib solution look for the older version of quantlib.lib to link with? I was able to build the Quantlib project. However, for some reason, building CDS and other projects in the QuantLib solution failed for the following error message.

LNK1104   cannot open file 'QuantLib-vc110-mt-gd.lib' CDS

I am using vs2015 and have quantlib built under the name QuantLib-vc140-mt-gd.lib, but somehow the CDS project manages to look for an older QuantLib lib.
I also added the following block of code to auto_link.hpp of quantlib.

#elif (_MSC_VER == 1900)
#  define QL_LIB_TOOLSET "vc140"


text: Q: ROC curve issue for multiple users I have a system that has a classifier and multiple users. To test each user I train a binary classifier for each genuine user and all other users. I find that the score scales seem to be different. This means that some scores are lower than others for different users. This means that EERs and ROC curves for testing on a whole dataset appears worse than for each user, but it's not feasible to show an ROC curve for each user. The image below displays this. The purple lines show the EERs for individual users and will be 0, but the orange line shows the EER for the whole dataset which means that half of the dataset (for these 2 users) is falsely accepted and the other half falsely rejected. Is there a protocol or technique to deal with this? Most studies seem to generate an ROC curve over the whole dataset but isn't this an issue?


text:
Q: How to forward user back in case not pass the auth I need to set auth on few pages and forward user back in case not authorized. For now, it display destination page with error.
Unauthorized
This server could not verify that you are authorized to access the
document requested. Either you supplied the wrong credentials (e.g.,
bad password), or your browser doesn't understand how to supply the
credentials required.

I have 0 knowledges in basic auth and apache conf. I have google deep and didn't find any solution, please advice.
Thank you
SetEnvIf Request_URI ^/en auth=1

AuthName "Please login to access english part"
AuthType Basic
AuthUserFile "/path/to/my/.htpasswd"

# first, allow everybody
Order Allow,Deny
Satisfy any
Allow from all
Require valid-user
# then, deny only if required
Deny from env=auth

A: This is really a limitation of HTTP Basic Authentication.
However, you could customise the 401 response (which I assume is what you are seeing, as opposed to a 403) the server would otherwise send back. You could directly redirect from the custom 401, however, that would result in the client receiving a 3xx response, rather than a 401, which is not as informative and confusing for users. Or, you present a "friendly" message, with a link back to where they came from.
The additional problem is knowing which page to send the user back to. Unless you are storing this information in the session, then you'll need to examine the Referer HTTP request header, which might not be set at all.
For example... at the top of your .htaccess file, define your custom error document for the 401 response:
ErrorDocument 401 /errordocs/e401.php

In /errordocs/e401.php, you would have something like:
<?php
/**
 * 401 Unauthorized - Error Document
 */

// Get the HTTP Referer (if set at all)
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;

// Immediately redirect back to the referring page if known
// But the client then sees a 3xx response, without any error, which could be confusing for users
if (!empty($referer)) {
    header('Location: '.$referer,true,302);
    exit;
}
?>
<!DOCTYPE html>

<title>401 Unauthorized</title>

401 Unauthorized

Sorry, you do not have permission to view that resource.

<?php if (empty($referer)): ?>
    Go back to the home page
<?php else: ?>
    <a href="<?=$referer?>">Go back to <?=$referer?>
<?php endif; ?>

To "automate" this, you could perhaps implement a meta refresh (or JS "redirect") back to the referring page (if set) after so many seconds.


text:
Q: How to set my application to full screen mode? I want to set my application to a full screen mode, but still want to be able to drag the collapsed menu from the top (the one that you drag when you receive notification, and you can activate Bluetooth, WI-FI, GPS from it)..
I've tried to set:
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"

For each activity, but with this - I can't drag and show the top menu.
The device I'm using is Galaxy S2.

A: Change it to this:
android:theme="@android:style/Theme.Black.NoTitleBar"

A: Try this code in your activity class. Paste this before setContentView(R.layout.main) method
            requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);


text:
Q: Best Dialog windows for ASP.Net Web forms What are the best Dialog windows available for ASP.Net Web forms application ? I am using the Modal Dialog right now because at the moment the Web app is focusing only IE. But soon we are going to test for others browsers as well.
It would be great if someone can list out me the best available solution for Dialog windows with proc and cons.
Following is the code that I am using to open up the model dialog in IE.
function showDialog(id) {
            var url = "MyPage.aspx?mode=view&nt=C" + "&id=" + id;
            returnValue = myModule.showModalDialog(url);
            if (returnValue) {
                // Call relevant js method
            }
        }

// My generic modal dialog function
myModule.showModalDialog = function (url, arguments, features)

{
    if (features == undefined) {
        features = "resizable:yes;status:no;dialogHide:true;help:no;scroll:auto;center:no";
    }
    return window.showModalDialog(url, arguments, features);
}

I tried to open up the same modal dialog in non-IE browser (chrome) and dialogs are open up as a different tabs or not opening altogether sometimes. I need to solve this issue with best suitable dialog windows.
Thanks

A: Try to use some framework like Bootstrap which solves many compatibility problems, simplify development and provides you with modal dialogs you need. You can start from here: http://www.w3schools.com/bootstrap/bootstrap_modal.asp


text:
Q: jQuery Mobile: Difference Between  and  Many of the examples on jQuery Mobile use ... for buttons instead of <button>...</button> for buttons that are NOT hyperlinks.  Is there is good reason for this? Will you find differences in behavior or performance on certain platforms when using one over the other?
Thank you.


text:
Q: How to delegate within a crontab to use another file as a crontab? aka Crontab in SVN/CVS? Maybe theres another solution to this. I built a web app that requires 5-10 crons to keep it maintained and various intervals.
I want to check-in the crontab into version control, so that it can be easily deployed
to other servers.
I would like to be able to put a line in the /etc/crontab file
that would tell it to look into /myapp/app.crontab file and treat all the lines
in that file as crontab entries... ie:
0 1 * * *    root   /bin/sh /do/something.sh

Why not just checkin /etc/crontab?
Because when deploying from server to server, some servers may have different
entries in their crontabs that i dont want to interfere with.
Any ideas?
What are other people doing for storing a bunch of crontab entries in rev ctrl?
Thanks.

A: Put your crontab file in /etc/cron.d/ - either as a checked out file or a symlink to the checked out file.

A: We take a very different approach to this problem on the project I'm working on.
We have a Perl script called crontab.pl that all servers call in their crontab.  Doing it this way means the crontab never has to change on successive application deployments and the crontab.pl script can happily live in source control with the rest of the application source files.
We can specify different time intervals to this script with a command line parameter.  The crontab looks like this:
*/5 * * * * /usr/local/apache/crontab.pl 5    > /var/log/crontab.log 2>&1 # 5 minute interval
1   * * * * /usr/local/apache/crontab.pl 60   > /var/log/crontab.log 2>&1 # 1 hour interval
1   1 * * * /usr/local/apache/crontab.pl 3600 > /var/log/crontab.log 2>&1 # 1 day interval

Then it is just a matter of reading in that command line time interval and running the tasks needed for the given interval.

A: Just add one (or very few) entries to crontab, and have that entry be a revision-controlled script that calls others:
0 * * * * /path/to/app/hourly.sh
0 0 * * * /path/to/app/daily.sh
0 1 * * 5 /path/to/app/weekly.sh
hourly.sh would then call everything that needs to be done hour, daily.sh would then call everything that needs to be done daily, etc.
I have found when managing large numbers of cron jobs for a single application that it is best not to have the jobs all hanging loose in the crontab, because that encourages you to overlook dependencies between them, i.e., one task that runs at 14 minutes past the hour depends on a task that runs at 12 minutes past the hour succeeding, but every so often that task takes 2.1 minutes to complete, and the other script fails, giving you a Heisenbug.
Another approach is to write your own daemon to manage these tasks.

A: The way I do this is put my crontab file in source control, and then in my deploy script, I replace the crontab file with what is being deployed.
You can do that like this:
crontab filename
Or for a specific user (must have superuser access for this):
crontab -u my_web_user filename
One big caveat with this is that it assumes there's only one crontab entry per user and that it's stored in SCM. If someone else edits the crontab on the server, those edits will be lost on the next deploy. So be aware of that.


text:
Q: Mapping multiple database tables to one object in SQLAlchemy I'm using SQLAlchemy and MySQL to create an ORM.
I automapped my database tables with this:
Base = automap_base()
Base.prepare(engine, reflect=True)
tScenario = Base.classes.table_scenario
tSchedule = Base.classes.table_schedule
tScheduleRestriction = Base.classes.table_schedule_restriction

Scenarios have schedules, which have restrictions.
Then at some point I create this object:
schedule = (session
   .query(tSchedule)
   .join(tScheduleRestriction)
   .filter(and_(
      tSchedule.scenario_id==47,
      tSchedule.period=='saturday')
      )
   .all()
)

I can access all the table_schedule columns and set them normally, like this:
schedule[1].parameter01 = 19

But if I want to access a column from the joined table (table_schedule_restriction), it's buried in that thing:
schedule[1].table_schedule_restriction_collection[0].parameter01_min = 20

My question is: how can I get all the columns from both tables as direct properties of my schedule object?
I know one way is to declare all the columns from both tables inside the .query, like this pseudocode:
".query(tSchedule.parameter01, tScheduleRestriction.parameter01_min, etc)"
But I think there is a better way.
Thanks for the attention.


text:
Q: CSS two equal columns with dynamic height My question is how do I arrange each element to achieve this output? Note that each item is generated dynamically. Due to framework limitation, flex is not supported.

.col {
  display: block;
  float: left;
}

.w50 {
  width: 50%
}

      Item 1

      Remarks : Bacon ipsum dolor amet buffalo prosciutto doner biltong kevin porchetta, spare ribs meatloaf shankle.

      Item 2

      Remarks : Hello world

      Item 3

      Remarks : Sample

      Item 4

      Remarks : Hello world

A: Being that you can't manually add in parent elements to this page you'll have to float them instead. To get them to stack you apply a clear: both to the first element of the second row (3rd one).
Your last task is to get them to have an equal height. For this you apply an arbitrary margin and padding while your overall parent container col has an overflow of hidden. Credit for this technique in particular goes to this post here

.col {
  overflow: hidden;
}

.w50 {
  width: 50%;
  margin-bottom: -500px;
  padding-bottom: 500px;
  float: left;
}

.w50:nth-of-type(3n) {
  clear: both;
}

      Item 1

      Remarks : Bacon ipsum dolor amet buffalo prosciutto doner biltong kevin porchetta, spare ribs meatloaf shankle.

      Item 2

      Remarks : Hello world

      Item 3

      Remarks : Sample

      Item 4

      Remarks : Hello world


text:
Q: javascript let iframe become parent i have one iframe on my page which has a different domain to that of my site. i know i can't access anything inside the iframe from the parent window, but can i make that iframe take over my entire page - ie redirect the parent to the url of the iframe?
so far i have tried things like
window.location.href = iframe.contentWindow.location.href;

but the browser won't allow that - i guess it isn't smart enough to realise that the = assignment is for the purposes of redirecting and not storage for later inspection.
is there another way of doing this on all modern browsers?

A: How about:
window.location = iframe.src;

A: Why don't you try with the iframe src attributes?
with jquery:
window.location.href = $('#iframeid').attr('src');

or:
window.location.href = document.getElementById('#iframeid').src;


text:
Q: CORS problem with B2C and Azure App Service I have enabled CORS in my ASP.NET/Angular application by using AddCors and EnableCors in controllers. My application is communicating with AD B2C pages. After build I have this error in the console :

Access to XMLHttpRequest at 'https://XXX.b2clogin.com/ (redirected
  from 'https://XXX.azurewebsites.net/User/Info') from origin
  'https://XXX.azurewebsites.net' has been blocked by CORS policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

Startup.cs :
            services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });

Controller :
[EnableCors("CorsPolicy")]
[Authorize]
public class UserEditController : Controller

I have enabled CORS on Azure too by putting : Allowed Origins - * .
UPDATE:
[Route("User/Info")]
[HttpGet]
public async Task<IActionResult> LoggedInUserInfo()
{
    if (User.Identity.IsAuthenticated)
    {
        var user = ((ClaimsIdentity)User.Identity).FindFirst(ClaimTypes.NameIdentifier).Value;
        var viewmodel = await userService.GetUserByObjectId(user);
        return Json(new { loggedIn = "true", user = viewmodel });
    }
    return Json(new { loggedIn = "false" });
}

A: It appears that you're attempting a cross-origin request from the https://xxx.azurewebsites.net/ domain to the https://xxx.b2clogin.com/ domain.
Currently the .b2clogin.com domain doesn't allow any cross-origin requests from any other domain.


text:
Q: Quickbox iOS Content API -- how to tag content I notice that there are you can query object with tags.
But how do I get tags associated with the objects in the first place?

A: By adding tag to Content File you say that users with this tag will be able to retrieve this file with query
[QBContent taggedBlobsWithPagedRequest:pagedRequest delegate:self];

To update user's tags use
QBUUser *user = [QBUUser user];
user.tags = [NSArray arrayWithObjects:@"man", @"travel", nil];
[QBUsers updateUser:user delegate:self];


text:
Q: If a question is in all-uppercase or all-lowercase, our quality filters should automatically reject it Proposal
If a question on an English-language Stack Exchange site does not contain at least one uppercase and one lowercase letter, our quality filter should reject it.
(We can make exceptions for sites which don't use a mixed-case alphabet, such as Japanese Language and Usage.)
Justification
The quality filter currently rejects neither all-uppercase nor all-lowercase posts. I've checked.
The best Stack Exchange users use mixed case. If an asker is too lazy to use their Shift key, their question tends not to be of very good quality.
Don't take my word for it. You can see proof. Sam Saffron helped me write a Stack Exchange Data Explorer query which lets you see with your very own eyes that what I am saying is true.
Single-case askers tend to ask poor-quality questions such as:

*

*"gem 'websocket-rails' and its scalability

*how to set particular value as dropdown default value in edit button click event in php

*Changing copied arabic text font in document richtexteditor
In addition, posts which use only uppercase or only lowercase — even if they aren't riddled with typos or grammatical errors — tend to be hard to read. Capitalization aids readability.
Why is this proposal not a duplicate?
This proposal is not a duplicate of the older proposal "BLOCK QUESTIONS IN ALL CAPS". This is because it also deals with all-lowercase questions.
All-lowercase questions are 50 times more common than all-caps questions.  Stack Overflow gets only about 100 all-uppercase questions per year; see here.  Yet it gets about 5,000 all-lowercase questions per year; see here. (These statistics are for Stack Overflow only; the rest of our network wasn't considered.)
I suspect that the older proposal was declined for two reasons:

*

*All-uppercase questions are rare.

*Therefore, the effort required to block all-uppercase questions is too much.
This proposal is better. For just a bit more effort, the Stack Exchange developers can get a much richer reward.
Conclusion
What do you think of my proposal?
Agree? Disagree? Thoughts?
PS: This idea is modified and adapted from an older idea by Stack Exchange user Gilles. My dear sir Gilles, I thank you.
Note
There's even a chat bot which automatically detects questions with all-caps titles and alerts interested users and moderators.


text:
Q: How to make a GUI application run in ubuntu without a desktop manager? One of my friends recently asked me if it was possible to run a GUI application in ubuntu without installing a desktop environment. He had a machine at work which functions as their server. Therefore, there isn't any DM or DE installed on it. He wanted to run a browser on it without installing a DE which will clutter things up. While one solution is to install a lightweight desktop environment like xfce or lxde, I decided to figure out a solution which will work without any. I will be posting my solution below because I could not find anything that would work online and I feel that this could help others facing this problem. Feel free to make any suggestions or to suggest  alternative solutions.
*My solution works with Firefox but not with Chrome. The details are down below. If someone figures it out please do leave a comment.

A: Install xdm and Firefox using the following command:
sudo apt-get install xdm firefox -y

Make the a .desktop file with the following contents:
[Desktop Entry]
Encoding=UTF-8
Type=XSession
Exec=/usr/bin/firefox
TryExec=/usr/bin/firefox
Name=Firefox
Comment=Testing

I named mine firefox.desktop but you can name it whatever you want.
Paste this file into /usr/share/xsessions using the following command:
sudo mv firefox.desktop /usr/share/xsessions

Finally, start xdm using the following command or restart your computer, and choose firefox as your desktop manager.
sudo service xdm start

In order to quit, press Ctrl+Alt+F1 to enter terminal mode. From here you can shutdown your computer or restart the desktop manager in order to log into a different desktop environment.
*I used xdm because it is lightweight but any other desktop manager such as lightdm, gdm or sddm will work too.
**When I tried this with Google Chrome, I ran into a problem. The window was not covering the entire screen and there was black space around it. If someone figures out how to fix this, please do comment it.


text:
Q: Moving elements between 2 div's with jQuery I am trying to move divs between two containers (#one and #two). I can't seem to figure out how to select a div which is inside another div.
I found a similar topic about targeting class inside a div. It gave me idea of using parent.
jQuery has  a large list of selectors, I assume I could use one of them. But I intuitively think I could use something like #one.draggable or some other kind of specifying path.
Example on JSFiddle
CSS:
div
{
    display:inline;
    background-color:#eee;
}

.draggable
{
    width: 50px;
    height: 50px;
    background-color: lime;
    z-index: 2;
    display: block;
    float: left;
    background-color: #333333;
}

#one
{
    width: 200px;
    height: 200px;
    background-color: #555555;
    z-index: 1;
    float: left;
}

#two
{
    width: 200px;
    height: 200px;
    background-color: #777777;
    z-index: 1;
    float: left;
}

jQuery:
$(document).ready(function() {
    $(".draggable",$(this).parent("one")).click(function () {
        // move from "one" to "two"
        $(this).appendTo("#two");
    });

    $(".draggable",$(this).parent("two")).click(function () {
        // move from "two" to "one"
        $(this).appendTo("#one");
    });
});

HTML:

1

2

3

4

5

6

A: I'll try to stick to what seems to be the core of your question: use $('#one .draggable') (the space is important!) to select all divs with class 'draggable' inside the div with id 'one'.
So your full jQuery code should be:
$(document).ready(function() {
    $('#one .draggable').click(function () {
        // move from "one" to "two"
        $(this).appendTo("#two");
    });

    $('#two .draggable').click(function () {
        // move from "two" to "one"
        $(this).appendTo("#one");
    });
});

UPDATE
As you noticed, with the code above it's not possible to move the same div again after the first move. The solution is as follows:
$(document).ready(function() {
    $('#one .draggable').live('click', function () {
        // move from "one" to "two"
        $(this).appendTo("#two");
    });

    $('#two .draggable').live('click', function () {
        // move from "two" to "one"
        $(this).appendTo("#one");
    });
});


text:
Q: How to assign a keyword to multiple images open in Preview on Mac OS I'm adding keyword metadata to a set of images in Preview.app, MacOS 10.6.6
I can select multiple images and create a keyword using the Keywords window.
But when I save, all but one image is deselected and the keyword info is only applied to that image.
I would prefer not to use iPhoto, so I don't have to

*

*add images to it's database

*create an album or event

Is there a way to do this in Preview or some similarly lightweight way to add keywords to a set of images at once?

A: Preview is not AppleScriptable, and there's no Automator action to do this.

If you have Aperture, there's an Automator action to apply keywords to images.

MacMetaMod is a third party droplet application that can apply keywords to selected files.

MacMetaMod uses ExifTool internally, which can probably be wrapped in a Mac OS X Service. It can be used from Terminal directly though:
exiftool −keywords+=newkeyword test.jpg


text:
Q: How to remove multiple HTML files in batch Ubuntu 16.04 LTS, Gnome version 3.18.2 My desktop filled with multiple html pages (GHex editor output).
binary00000000.html
binary00000001.html
binary00000002.html
...
binary00043310.html

How to remove these HTML files from desktop in batch?


text:
Q: WCF MessageContract complex type property not deserializing I have to implement a service to handle this SOAP message:
<soapenv:Envelope
        xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
        xmlns:serv="http://www.company.com/Service">
    <soapenv:Body>
        <serv:ServiceOperation xmlns="http://www.company.com/Service">
            <serv:operationParam>X</serv:operationParam>
            <serv:operationHeader>
                <serv:headerParamA>12345</serv:headerParamA>
                <serv:headerParamB>ABCD</serv:headerParamB>
                ...

The message contract currently looks like:
[MessageContract(
    WrapperName = nameof(ServiceOperation),
    WrapperNamespace = ServiceNamespace,
    IsWrapped = true)]
public class ServiceOperation
{

    [MessageBodyMember(Name = "operationParam", Namespace = ServiceNamespace)]
    public string OperationParam { get; set; }

    [MessageBodyMember(Name = "operationHeader", Namespace = ServiceNamespace)]
    public OperationHeader OperationHeader { get; set; }

    ...

The string property operationParam is parsed correctly by my service. But whatever I do, I cannot get the "complex type" operationHeader to work.
With the code above, properties on the OperationHeader are always null, regardless of XmlType and XmlElement declarations:
[XmlType]
public class OperationHeader
{
    [XmlElement]
    public string HeaderParamA { get; set; }
}

I've tried variations of the OperationHeader class with no attributes, MessageBodyMember attributes, decorating the XML type as anonymous. Still null on all members of the OperationHeader class.
Something very strange is that if I do this instead:
    [MessageBodyMember(Name = "operationParam", Namespace = ServiceNamespace)]
    public string OperationParam { get; set; }

    [MessageBodyMember(Name = "operationHeader", Namespace = ServiceNamespace)]
    public XmlElement OperationHeader { get; set; }

Then the XML element parsed is not the operationHeader itself, but the first child element from the XML; headerParamA.
Does anyone know what my classes should look like?
I've tried to do it exactly as in this answer, but that only gives null for member properties on the complex type as well.
Or is the XML I'm sent broken somehow?


text:
Q: TSQL, "простой некластеризованный индекс" Есть несколько индексов такого вида:
CREATE INDEX IX_ProductVendor_VendorID ON Purchasing.ProductVendor (VendorID);

На MSDN здесь (в разделе "примеры", первый пример) сказано, что это "простой некластеризованный индекс". Что это значит? Обычный первичный ключ? Может быть, глупый вопрос, но для меня не очевидно, хотелось бы быть уверенным.

A: На Хабре есть аааааабалденная статья на тему индексов. Очень советую.
Если вкратце, то:

*

*Индекс использует дерево для быстрого обращения к данным.

*У кластеризованного индекса в листьях дерева лежат сами строки данных. В силу природы дерева данные хранятся в уже отсортированном виде, поэтому кластеризованный индекс может быть только один.

*У некластеризованного индекса в листьях дерева лежат указатели на
строки данных, т.е. для чтения данных необходима еще одна операция. Т.о. кластеризованных индексов у таблицы может быть несколько.

Что это значит? Обычный первичный ключ?

Понятие первичного ключа в общем-то не связано с индексом. В таблице может быть колонка, являющаяся первичным ключом, но без индекса. Однако на первичные ключи как правило создают кластеризованный индекс. В вашем вопросе VendorID это скорее просто foreign key -- на них обычно создают некластеризованные индексы.


text:
Q: Touch event doesn't work on an ImageView I am trying to add an image button when a touch event occurred on an image. Image is displayed using ImageView. But nothing happens when I touch on the image.
 Codes attached here
Quick.java
 ImageView myImageView = (ImageView)findViewById(R.id.imgView);
   Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.india_map);
   myImageView.setImageBitmap(bitmap);

    myImageView.setOnTouchListener(new OnTouchListener()
 {

     @Override
     public boolean onTouch(View v, MotionEvent event)
     {
         ImageButton  imgbutton=(ImageButton)findViewById(R.id.imageButton1);
         Bitmap image = BitmapFactory.decodeResource(getResources(),R.drawable.image5);
         imgbutton.setImageBitmap(image);
         imgbutton.setVisibility(View.VISIBLE);
                 return false;
     }

});

activity_quick.xml
 <LinearLayout
            android:id="@+id/tab2"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical"
            android:padding="5dp" >

         <ImageView
             android:id="@+id/imgView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:scaleType="fitXY"
            android:contentDescription="@string/desc"
            android:src="@drawable/india_map"/>
          <ImageButton
                android:id="@+id/imageButton1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/image5"
                android:contentDescription="@string/desc"
                android:visibility="invisible" />

                </LinearLayout>

Please help me to solve this problem

A: Use FrameLayout to put a view over the other.
Try the following:
<FrameLayout
            android:id="@+id/tab2"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical"
            android:padding="5dp" >

         <ImageView
             android:id="@+id/imgView"
             android:layout_width="fill_parent"
             android:layout_height="fill_parent"
             android:scaleType="fitXY"
             android:contentDescription="@string/desc"
             android:src="@drawable/india_map"/>

          <ImageButton
             android:id="@+id/imageButton1"
             android:layout_width="fill_parent"
             android:layout_height="fill_parent"
             android:src="@drawable/image5"
             android:contentDescription="@string/desc"
             android:visibility="gone" />

 </FrameLayout>

No need to set the Image bitmap in java code. You've already specified them in xml.

A:  myImageView.setOnTouchListener(new OnTouchListener()
 {

     @Override
     public boolean onTouch(View v, MotionEvent event)
     {
         ImageButton  imgbutton=(ImageButton)findViewById(R.id.imageButton1);
         Bitmap image = BitmapFactory.decodeResource(getResources(),R.drawable.image5);
imgbutton.setImageBitmap(null);
 imgbutton.setImageBitmap(image);
         imgbutton.setVisibility(View.VISIBLE);
                 return false;
     }

});

first of all you have set image bitmap null and then set other bitmap.

A: Set your imageview as clickable. In the xml use android:clickable = "true"

A: Is there any special reason to use TouchListener? (ex> for handling pinch or swipe gesture)
If what you consider is just 'handling click event of image', I think it's better & easy to use OnClickListener instead of OnTouchListener. For example...
    View iv = findViewById(R.id.imgView));
    iv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ImageButton  imgbutton=(ImageButton)findViewById(R.id.imageButton1);
            Bitmap image = BitmapFactory.decodeResource(getResources(),R.drawable.image5);
            imgbutton.setImageBitmap(image);
            imgbutton.setVisibility(View.VISIBLE);
    });

And one other thing you may consider is always it's not good idea to decode a bitmap in a main UI thread, so how about consider use another thread or AsyncTask to handle bitmap.


text:
Q: How do I evaluate a formula in Google Sheets? I'm trying to see where the math is going wrong in a formula, but I can't find a way to see what the formula is doing step by step. In Excel, you can search in the help bar for a tool called 'evaluate formula' which does exactly the job I need but I cannot find a similar formula in Google Sheets
Is there a way to evaluate a formula that is stored in a cell? Immediately appears on a google search however this talks about taking a string in 1 cell and using it as a formula in another cell, which is not what I'm looking for. I think in the 6 years since that post the phrase 'evaluate' has changed in meaning slightly.
=(IFERROR((vlookup($E9,$A$3:$Y$102,21,FALSE)*$J9),0))+(IFERROR((vlookup($F9,$A$3:$Y$102,21,FALSE)*$K9),0))+(IFERROR((vlookup($G9,$A$3:$Y$102,21,FALSE)*$L9),0))+(IFERROR((vlookup($H9,$A$3:$Y$102,21,FALSE)*$M9),0))+(IFERROR((vlookup($I9,$A$3:$Y$102,21,FALSE)*$N9),0))

Easier to read if I put it like this:
 =(IFERROR((vlookup($E9,$A$3:$Y$102,21,FALSE)*$J9),0))+
(IFERROR((vlookup($F9,$A$3:$Y$102,21,FALSE)*$K9),0))+
(IFERROR((vlookup($G9,$A$3:$Y$102,21,FALSE)*$L9),0))+
(IFERROR((vlookup($H9,$A$3:$Y$102,21,FALSE)*$M9),0))+
(IFERROR((vlookup($I9,$A$3:$Y$102,21,FALSE)*$N9),0))

I'd like to see what each vlookup is returning individually. I have over 500 cells with V similar cells so making a cell for each vlookup, then referencing those cells so it's easier to track the results isn't practical.
I expect the output of this cell, C9, to be less than B9 and more than D9 (B9>C9>D9 ect) however I am seeing inconsistent results where sometimes this rule is followed and sometimes it is not in my spreadsheet.

A: well, the most obvious way is to run them separately like:
=IFERROR((VLOOKUP($E9, $A$3:$Y$102, 21, 0)*$J9), 0)

or in an array:
={IFERROR((VLOOKUP($E9, $A$3:$Y$102, 21, 0)*$J9), 0),
  IFERROR((VLOOKUP($F9, $A$3:$Y$102, 21, 0)*$K9), 0),
  IFERROR((VLOOKUP($G9, $A$3:$Y$102, 21, 0)*$L9), 0),
  IFERROR((VLOOKUP($H9, $A$3:$Y$102, 21, 0)*$M9), 0),
  IFERROR((VLOOKUP($I9, $A$3:$Y$102, 21, 0)*$N9), 0)}

or column instead of row:
={IFERROR((VLOOKUP($E9, $A$3:$Y$102, 21, 0)*$J9), 0);
  IFERROR((VLOOKUP($F9, $A$3:$Y$102, 21, 0)*$K9), 0);
  IFERROR((VLOOKUP($G9, $A$3:$Y$102, 21, 0)*$L9), 0);
  IFERROR((VLOOKUP($H9, $A$3:$Y$102, 21, 0)*$M9), 0);
  IFERROR((VLOOKUP($I9, $A$3:$Y$102, 21, 0)*$N9), 0)}

or in one cell perhaps:
=IFERROR((VLOOKUP($E9, $A$3:$Y$102, 21, 0)*$J9), 0)&" "&
 IFERROR((VLOOKUP($F9, $A$3:$Y$102, 21, 0)*$K9), 0)&" "&
 IFERROR((VLOOKUP($G9, $A$3:$Y$102, 21, 0)*$L9), 0)&" "&
 IFERROR((VLOOKUP($H9, $A$3:$Y$102, 21, 0)*$M9), 0)&" "&
 IFERROR((VLOOKUP($I9, $A$3:$Y$102, 21, 0)*$N9), 0)


text:
Q: what advantage are AT-ATs (they're rubbish) In Starwars during the battle of Hoth, the empire made what i believe to be a hilarious strategic miscalculation and sent vehicles with only forward facing firepower (unimpressive firepower at that), are easy targets, and are slow moving, up against the stronger, more agile squadrons of rebel fighters which consequently result in massive imperial AT-AT casualties.
The rebels had previously illustrated a proficiency at fighter based combat and rely upon them heavily. Fighters appear to be the perfect counter to an AT-AT assault.
So why would any general in his sane mind deploy them? granted, i recognise that their firepower was sufficient to breach the rebel defences, would likely impose a significant psychological effect on the enemy, would act as overwatch due to heigh and acted as troop carriers. However they were completely vulnerable to the obvious rebel fighter counter and appear to be totally impractical anyway: They are slow moving, easy targets and possess obvious weak spots around the cockpit and leg joints.
What ever happened to tanks, which would be the far more logical alternative, especially when supported with ground to air/air-air defences, and why would the empire use AT-ATs?

A: AT-AT stands for All Terrain Armored Transport. Its purpose was to transport Storm Troopers in the battle field. It wasn't an alternative of real-world tanks to engage enemies although it had some support weapons in case.
Its superiority against real-world tanks:

*

*Thanks to its humanoid legs, it can cross small cliffs and travel across very rough terrain.

*Its high height could allow to keep watch on enemies better.

*Height also allows it to really fire with laser. Real-world tanks fire projectiles for which height isn't that important, but in case of lasers, height is very important.


text:
Q: AWS SQS not receiving SNS messages I created a SNS topic that publishes all the information coming out of Cloudformation via the cli. However, when I check the queue, it is not receiving any of the SNS messages. I verified the SNS is working by subscribing my email to it, so the issue seems to be in the connection between the queue and the SNS. However, I cannot find any problems with my syntax. I, as far as I know, have followed amazon's documentation precisely.
Bash:
#SNS parameters
SNS_NAME="${NAME}_SNS"
SQS_NAME="${NAME}_SQS"

#Create SNS topic to send cloudformation notifications to
SNS_ARN=`aws sns create-topic --name ${SNS_NAME} | jq -r '.TopicArn'`

#Create SQS to send SNS to (holding SNS messages for lambda -^ up)
SQS_URL=`aws sqs create-queue --queue-name ${SQS_NAME} | jq -r '.QueueUrl'`
SQS_ARN=`aws sqs get-queue-attributes --queue-url ${SQS_URL} --attribute-names QueueArn | jq -r '.Attributes .QueueArn'`

#subscribe the queue to the notifications
aws sns subscribe --topic-arn ${SNS_ARN} --protocol sqs --notification-endpoint ${SQS_ARN}
aws sns subscribe --topic-arn ${SNS_ARN} --protocol email-json --notification-endpoint ${EMAIL}

#Create the stack which kicks everything else off-
aws cloudformation create-stack $REGIONTEXT $ITYPETEXT --capabilities CAPABILITY_IAM --template-url https://${BUCKETNAME}.s3.amazonaws.com/${TEMPLATE} --notification-arns ${SNS_ARN} --stack-name $NAME --parameters ParameterKey=SNSARN,ParameterValue=${SNS_ARN} ParameterKey=Bucket,ParameterValue=${BUCKETNAME} ${PARAMTEXT} ${EXTRAARGS}

A: If the SQS is encryted then the event pushing messages to queue must follow below steps
Several AWS services send events to Amazon SQS queues. To allow these event sources to work with encrypted queues, you must perform the following steps.

*

*Use a customer managed CMK.
To allow the AWS service to have the kms:GenerateDataKey* and
kms:Decrypt permissions, add the following statement to the CMK
policy.
{
   "Version": "2012-10-17",
      "Statement": [{
         "Effect": "Allow",
         "Principal": {
            "Service": "service.amazonaws.com"
         },
         "Action": [
            "kms:GenerateDataKey*",
            "kms:Decrypt"
         ],
         "Resource": "*"
       }]
}

*Create a new SSE queue or configure an existing SSE queue using the
ARN of your CMK.
Provide the ARN of the encrypted queue to the event source.

For sns replace service section with  sns.amazonaws.com

"Principal": {
                "Service": "sns.amazonaws.com"
             }

A: Thank you to Mark B for his answer. It provided the start to getting this working. However, in order to make a policy document work via the CLI there are a few quirks that aren't covered in the docs.

*

*There are all sorts of errors trying to pass json directly to the --attributes flag in aws sqs set-queue-attributes command. For some reason it requires the modifying json to be in a .json document referenced by the cli.

*In the .json file provided to the cli, all of the double quotes inside the "Policy" value (nested json) must be escaped (i.e. { \"Statement\": \"HelloWorld\" }). If this is not followed, it will validation errors. I ended up needing to use the ascii escape characters in order properly format the output (\x5C).

*The json file must be referenced by using file://local-location in the --attributes flag. It throws errors if this is not followed.

See the following elements I used for reference:
load_sqs.sh:
SQS_POLICY=
sqs-policy()
{
#First param is the queue arn, second param is the topic arn
SQS_POLICY=`printf '{ "Policy": "{\x5C\"Version\x5C\":\x5C\"2012-10-17\x5C\",\x5C\"Statement\x5C\":[{\x5C\"Sid\x5C\":\x5C\"CloudformationLambdaSQSPolicy\x5C\",\x5C\"Effect\x5C\":\x5C\"Allow\x5C\",\x5C\"Principal\x5C\":\x5C\"*\x5C\",\x5C\"Action\x5C\":\x5C\"sqs:SendMessage\x5C\",\x5C\"Resource\x5C\":\x5C\"%s\x5C\",\x5C\"Condition\x5C\":{\x5C\"ArnEquals\x5C\":{\x5C\"aws:SourceArn\x5C\":\x5C\"%s\x5C\"}}}]}" }' "$1" "$2"`
`echo $SQS_POLICY > $PWD/sqs-policy.json`
}

#SNS parameters
SNS_NAME="${NAME}_SNS"
SQS_NAME="${NAME}_SQS"

#Create SNS topic to send cloudformation notifications to
SNS_ARN=`aws sns create-topic --name ${SNS_NAME} | jq -r '.TopicArn'`

#Create SQS to send SNS to (holding SNS messages for lambda -^ up)
SQS_URL=`aws sqs create-queue --queue-name ${SQS_NAME} | jq -r '.QueueUrl'`
SQS_ARN=`aws sqs get-queue-attributes --queue-url ${SQS_URL} --attribute-names QueueArn | jq -r '.Attributes .QueueArn'`

#Add necessary SQS <--> SNS permissions
sqs-policy ${SQS_ARN} ${SNS_ARN}
`aws sqs set-queue-attributes --queue-url ${SQS_URL} --attributes file://sqs-policy.json`

#subscribe the queue to the notifications
aws sns subscribe --topic-arn ${SNS_ARN} --protocol sqs --notification-endpoint ${SQS_ARN}

sqs-policy.json:
{ "Policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"CloudformationLambdaSQSPolicy\",\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":\"sqs:SendMessage\",\"Resource\":\"ResourceARN\",\"Condition\":{\"ArnEquals\":{\"aws:SourceArn\":\"SourceARN\"}}}]}" }

A: It doesn't look like you have given the SNS topic permission to publish to the SQS queue. Look at step 2 in this walkthrough. You'll need to add a policy like this to the SQS queue:
{
  "Version":"2012-10-17",
  "Statement":[
    {
      "Sid":"MySQSPolicy001",
      "Effect":"Allow",
      "Principal":"*",
      "Action":"sqs:SendMessage",
      "Resource":"arn:aws:sqs:us-east-1:123456789012:MyQueue",
      "Condition":{
        "ArnEquals":{
          "aws:SourceArn":"arn:aws:sns:us-east-1:123456789012:MyTopic"
        }
      }
    }
  ]
}

Replacing the ARNs with the ones for your topic and queue.

A: In my case SQS wan't receiving messages from SNS because SQS had encryption turned ON. When I turned OFF encryption on SQS it started working!
This AWS documentation explains how to enable SNS compatibility with encrypted SQS queues:
https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html#compatibility-with-aws-services
SNS requires extra permissions to be able to use the KMS key to encrypt messages for the queue.