text:
Q: git divergent renaming I'd like to know how you handle a situation like this in Git:

*

*create branch task001 from master

*master: modify foo.c and rename it to bar.c

*task001: modify foo.c and rename it to moo.c

*merge task001 to master

What Git tells me is:
CONFLICT (rename/rename): Rename "foo.c"->"bar.c" in branch "HEAD" rename "foo.c"->"moo.c" in "task001"
Automatic merge failed; fix conflicts and then commit the result.

How should I solve it? I mean, I still want to merge the two files once the name conflict is resolved.
Thanks.

A: I initially understood your question to mean something different from what you have clarified in the comments, but the original answer may be useful, so I'm leaving that as the first part, but adding an alternative below:
1. Just resolving the conflict, so you only have the diverged moo.c and bar.c
Here I'm assuming that the result you want is to have bar.c and moo.c, with their changes from each branch, in the merged version.  I would deal with this by resolving the conflict in the index and committing.  The situation you describe looks like this:
$ git log --pretty=oneline --graph --decorate master task001
* fce127471ab5d1ef55b1d16412a75a7129782517 (task001) Rename to a different file on task001
* 8edbc1357a3c0484dc077f6f7ce43de91d21e794 A small change on the task001 branch
| * d10e9020d147a4bbd3688744823380322bf37718 (HEAD, master) Rename on master to bar.c
| * f952617645456a551df07f219bfdc95e00c8ac9b Added a small change in master
|/
* e8602eef46af744defd4fb4073ecdb6a7afbfd28 Initial version of foo.c

If I then merge task001 into master, it produces the same error that you see:
$ git merge task001
CONFLICT (rename/rename): Rename "foo.c"->"bar.c" in branch "HEAD" rename "foo.c"->"moo.c" in "task001"
Automatic merge failed; fix conflicts and then commit the result.

Then git status will show you a summary of problems:
$ git status
# On branch master
# Unmerged paths:
#   (use "git add/rm <file>..." as appropriate to mark resolution)
#
#   added by us:        bar.c
#   both deleted:       foo.c
#   added by them:      moo.c
#
no changes added to commit (use "git add" and/or "git commit -a")

Now you just need to use git add and git rm to resolve the conflicts:
$ git add bar.c
$ git rm --cached foo.c
foo.c: needs merge
moo.c: needs merge
rm 'foo.c'
$ git add moo.c
$ git status
# On branch master
# Changes to be committed:
#
#   new file:   moo.c
#

(I used --cached for removing foo.c because it's no longer in the working copy, and --cached means the command only looks at the index -- otherwise you get an error about foo.c not existing.)
Then you just commit the results:
$ git commit
[ save the prepopulated commit message ]

And you've resolved the conflicts and have bar.c and moo.c in the merged version.
(I note in passing that git merge -s resolve works for me in the simple example situation describe here, but I hope this is more generally useful.)
2. Merging bar.c and moo.c back into one file
It seems from your comments below that really what you would like is to merge these files back into one again, with the changes to the file in both branches merged.  If you want git's merge strategies to help you with this, the files on each branch must have the same path before merging, so you'll need to rename at least one of them before merging.  Let's suppose you want the merged file to be called quux.c, although you could just as well make it foo.c again, of course.  Then you could do the following steps, which rename the file on each branch before merging:
# Rename the file on master:

$ git checkout master
Already on 'master'
$ git mv bar.c quux.c
$ git commit -m "Rename bar.c to quux.c on branch master"
[master f9b3f49] Rename bar.c to quux.c on branch master
 1 files changed, 0 insertions(+), 0 deletions(-)
 rename bar.c => quux.c (100%)

# Rename the file on task001:

$ git checkout task001
Switched to branch 'task001'
$ git mv moo.c quux.c
$ git commit -m "Rename moo.c to quux.c as well on branch task001"
[task001 c71ad89] Rename moo.c to quux.c as well on branch task001
 1 files changed, 0 insertions(+), 0 deletions(-)
 rename moo.c => quux.c (100%)

# Switch back to master, and merge in task001:

$ git checkout master
Switched to branch 'master'
$ git merge task001

If the changes didn't conflict, then at this point that merge should Just Work.  In the example I tried they did conflict, so I needed to edit the file, git add the file and commit the result:
Renaming foo.c->quux.c
Auto-merging quux.c
CONFLICT (content): merge conflict in quux.c
Automatic merge failed; fix conflicts and then commit the result.
$ emacs -nw quux.c
$ git add quux.c
$ git commit
[master 8baa7cb] Merge branch 'task001'
$ ls
quux.c

A: Simple way to fix this First abort the current merge
git merge --abort

Now, decide which version of the file you want to use and use a merge strategy (with the flag -s)
You are on the branch master. If you want to keep the name you set in master then use this command
git merge -s ours task

If you want to use the version from task
git merge -s theirs task


text:
Q: Draw downloaded icon chrome extension I use this example for setting extension icon from url.
                                var img = new Image,
                                canvas = document.createElement("canvas"),
                                ctx = canvas.getContext("2d"),
                                src = settings['address'] + "/2.png"; // insert image url here

                                img.crossOrigin = "Anonymous";

                                img.onload = function() {
                                    canvas.width = img.width;
                                    canvas.height = img.height;
                                    ctx.drawImage( img, 0, 0 );
                                    chrome.browserAction.setIcon({"imageData" : ctx.getImageData(0,0,19,19)});

                                };

                                img.src = 'https://lh3.googleusercontent.com/krl72AYWGWgmhSCcdlHm-IgwkOBfdq6qVFIJtHxhfoSlMcrIgKdVhK-l-o800kv0m7uO=w300';

But in the end I get a stupidly transparent icon, not even an icon but a void. There is no mistake.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create new element using number input I'm using ionic and I'm trying to make a function where I can use a number input from another page as variable to create new elements. So input number is on page A and I want to use that number to create new elements on page B. Anyone who can help me? Thanks!

A: We do something similar in our app. We send individuals through a questionnaire which is several slides inside of a component page. We have a class backing the overall questionnaire component page and store the value from the first page into a variable in that class. We then reference that variable in later slides to customize the experience.
Following along that same idea, you could use a Service/Provider (ionic generate provider MyModel). Then use that service to store values that can be referenced across various pages by injecting the provider into your page/component constructors like so:
@Component({
  ...
})
export class MyApp {

  constructor(
    public model: MyModelProvider) {
  }
}

https://forum.ionicframework.com/t/how-can-ionic-share-data-between-pages-or-componenets-with-ng-or-something-related-ionic2/59515/5

A: You can use NavController and NavParams to send and get data on another page.
https://ionicframework.com/docs/api/navigation/NavController/
https://ionicframework.com/docs/api/navigation/NavParams/
import { NavController, NavParams} from 'ionic-angular';

constructor(public navParams: NavParams, public navCtrl: NavController) {}

In your page A you send your variable, like this when you change the page
this.navCtrl.setRoot(RouteOfPageB,{
  variableName: variableData
});

In page B you get your data
this.navParams.get('variableName');

I hope that answers your question.


text:
Q: How to set a field as protected in yaml? There is a way to define an entity properties to protected in the yaml format ?

A: Things you write in doctrine yaml mapping files are metadatas. This config help you to determine how your entity object will behave with doctrine.
Properties of this object are handled by php, and cannot be configured by yaml configuration.
However, if you realy need this, you could build a cached entity generator component that will create php object in the cache and register them to doctrine. This is quite complex so I let you decide if you need it or not.


text:
Q: Quit vs Run statements in SAS In SAS, what is the difference between 'quit' and 'run'? statements? I cannot figure out when to use 'quit' and when to use 'run'? For example, why is proc datasets using quit but proc contents using run

A: This dates back to where SAS used to be a mainframe program (and still can be!).
RUN; is a command for SAS to run the submitted statements.  Back in the older mainframe days, statements would've been submitted to SAS one at a time (or in batches, but the core concept here is that each line is separate from SAS's point of view).  SAS accepts statements without doing anything until it hits a RUN; or something else that would create a step boundary (another DATA or PROC line, usually).  In a data step, or a non-interactive proc (proc means, for example - a proc that can only do one set of instructions, and then exits), run tells it to do (whatever) and then return to a blank slate.
QUIT; is used in interactive programming environments.  IML, SQL, many of the regression and modelling PROCs, FORMAT, TEMPLATE, DATASETS, etc. - all can be used interactively, meaning, more than one set of instructions can be sent to them.
In these interactive cases, you want SAS to go ahead and run some of the instructions, but still keep that PROC's environment open - your next statement would be in the same PROC, for example.  Some of those run immediately - PROC SQL is a good example of this - while some (particularly the modelling PROCs) RUN; does something (tells it to run the model so far) but it won't exit the proc until QUIT; is encountered (or another step boundary that requires it to exit, i.e. a data/proc statement).  These are called "run groups", and "run group processing" is the term you'll see associated with that.
You will find that some people put run; quit; at every point that run; or quit; might be appropriate; that doesn't hurt anything, though it isn't really 'right', either.  And there are some cases where it's needed to do that!
One example:
/* first run group*/
proc gplot data=sales;
   title1 "Sales Summary";
   plot sales*model_a;
run;

      /* second run group */
   plot sales*model_b;
run;
quit;

(from run-group processing )


text:
Q: Plotting Complex Sets in a Research Paper I am meant to "sketch" the set $|z - 1 + i| \leq 3$ for my Complex Analysis homework. I am able to draw this set by hand, so my question isn't about that! Rather, I would like to know how a professional mathematician would generate such an image if he or she were submitting the image as part of a journal article. What program/software/code would he or she use?...all I need is a direction to head in!
(For context: I get extra credit in the class for submitting my homework typed out in Latex. And for this question, I'm sure I could just leave a blank space and hand draw the diagram. I also found this answer, which is kind of a hacker way to generate such diagrams. But my aspiration is to become a mathematician, and so I wanna know how a real mathematician would make such a diagram! Thanks in advance!)

A: Another tool that can be incorporated into LaTeX documents: Asymptote. It's a programming language, so there's a learning curve there. On the plus side, it comes standard with TeX distributions, and the usual editors can easily be configured to run Asymptote code in the same .tex file as everything else.
Drawing circles is in the base capabilities of Asymptote even before importing any of the standard libraries.


text:
Q: Disable a frame before dispose if("Back".equals(e.getActionCommand()))
{
    escape.setVisible(false);
    paused = false;
    running = !running;
    Graphics g = start.getGraphics();
    g.dispose();
    Component glassPane = start.getGlassPane();
    glassPane.setVisible(!glassPane.isVisible());
    Main.main(null);
    Main.running = true;
    start.dispose();
}

This is my code for disabling my jframe, loading a new one, and disposing it. Whenever I do this, when I return to the frame I get strange graphical errors.

How do I close the frame completly?

A: *

*create private/public(depends of your code design) variable for JFrame instance

*then you can't bothering with dispose of visible JFrame and then re_create a new one

*create class or local instace that returns JPanel with game content

*call JFrame#getContentPane#removeAll()

*call JFrame#getContentPane#add(new GamePanel())

*maybe there are easiest ways how to reset whatever (depends of your code design) to the start_up statuses


text:
Q: Webpack-hot-middleware with Koa 2.0 Is there a way to integrate webpack-hot-middleware and webpack-dev-server with Koa? I am having hard time find working example which is not up to date fork of webpack-hot-middleware code.

A: You can use koa-webpack-hot-middleware and wrap it with koa-convert

A: koa-webpack has been released and integrates both for Koa 2.0.

A: You can use koa2-connect to make connect/express middleware compatible with koa2.
https://www.npmjs.com/package/koa2-connect


text:
Q: Can you package and launch an adobe AIR application from within a native Android application? I work for a company that has a an adobe AIR game/application for Android.   We are now developing a native application for android.  We would like to reuse the game component of the AIR application and launch the AIR game from within the native application. Basically the AIR game will be one of many games in an arcade in the native application.
My question is, is this even possible?  If so what would be the best way to accomplish this.  Also is it possible for the packaged AIR application to communicate back to the native framework?  I am familiar with Native extensions but those typically wrap native or 3rd party functionality to be used with actionscript in the AIR application.  If anyone has any advice or ideas it would be much appreciated.  Thank you.

A: I don't know if this is possible, but if you don't mind it being two sepparate applications, they can launch each other using Intents.
http://developer.android.com/reference/android/content/Intent.html
What is comes down to is firing an intent wich the other application listens to(This is also why you can select multiple apps to open up some filetypes; they all listen to the same intent). Also if you look closely you can see that the default application code in Eclipse(at least) listens to the Launch(or something like that) intent.


text:
Q: Password Match with Angular.js I try to create a form with validation. I am very new at angular.js. I copied some code from samples but I couldn't make it work.
Here is my html and script:

Validation Example

    <form name="myForm" novalidate>

Username:

        <input type="text" name="user" ng-model="user" required>

            Username is required.

Email:

        <input type="email" name="email" ng-model="email" required>

            Email is required.
            Invalid email address.

         Password
        <input type="password" name="password" ng-model="password" placeholder="New Password"/>
        Confirm Password
        <input type="password" name="confirmPassword" placeholder="Confirm Password" ng-model="confirmPassword" pw-check="password"/>
         Passwords don't match.

        <input type="submit" ng-disabled="myForm.user.$dirty && myForm.user.$invalid || myForm.email.$dirty && myForm.email.$invalid">

    </form>

Can anyone tell me what is wrong with this ?

A: From what I know about this directive, @dcodesmith's solution is mostly correct. Try this one:
<input type="password" name="confirmPassword" placeholder="Confirm Password" ng-model="confirmPassword" pw-check="password"/>

UPDATE. Sorry for previous snippet. Check this out. This works:
<input type="password" name="password" ng-model="password" placeholder="New Password"  pw-check="confirmPassword"/>

<input type="password" name="confirmPassword" placeholder="Confirm Password" ng-model="confirmPassword"/>

JS
link: function (scope, elem, attrs, ctrl) {
  scope.$watch(attrs.pwCheck, function (password) {
    var isValid = ctrl.$viewValue === password;
    ctrl.$setValidity('pwmatch', isValid);
  });
}

JSBin: http://jsbin.com/rakivadibi/1/edit?html,js,output


text:
Q: Getting a segmentation fault but cannot see error? Here is a simple program that is a function which checks for the character 'a' within a string, then returns the character if found, and NULL if it is not found. I am not really sure if it is the function or the call of the function itself, here is the code.
#include <stdio.h>
char *find_char(char *str, char character);
int main(){
char *str;

printf("str\n");
scanf("%s", str);

printf("%c",*find_char(str,'a'));

return 0;
}

char *find_char(char *str, char character){

    char *pstr = str;

    while(*pstr!='\0' && *pstr!=character){
        pstr++;}

    if (*pstr!=character)
        return NULL;

        else
            return pstr;
    }

A: Your problem basically lies in these two lines, the first and third code line of your main function:
char *str;        // Create pointer, pointing to ***arbitrary*** memory.
scanf("%s", str); // Write to that memory, undefined behaviour.

You need to create backing storage for the pointer so you have somewhere valid to write your input to.
A better idea would be to use a rock-solid input routine rather than relying on often-dodgy practices like writing to invalid memory, or allowing uncontrolled input into limited-size buffers. One such beast can be found here.


text:
Q: Plugging in d3-force-3d calculations into a 3-D graph renderer I am a threejs noob and my use case requires me to render force directed graphs in 3D. I am using d3-force-3d to calculate all the forces that are on the nodes of the graph. However, I've failed to find any library that takes those calculations into account and creates a 3 dimensional graph for the same.
I could find only one library that makes force directed graphs in 3D, which is 3d-force-graph, but it does not allow you to edit forces, which I need to.
Is there a library that directly plugs in d3 calculations and renders a 3D-graph?

A: As of v1.15.0, 3d-force-graph allows for manipulation of the d3 forces and decay parameters, using the methods d3Force(), d3AlphaDecay() and d3VelocityDecay().
Here's an example with custom force configuration that adds collision detection to free moving nodes:
https://vasturiano.github.io/3d-force-graph/example/collision-detection/
Code from example:
https://github.com/vasturiano/3d-force-graph/tree/master/example/collision-detection


text:
Q: If an object falls - regarding air resistance - does the Potential or Kinetic energy get converted into thermal energy as it is falling? I read a paragraph on the transfer of potential energy to kinetic energy and heat from this website:

Even if air resistance slows down the ball, the potential energy is
  the same (Mb x g x H). But if air resistance is in the way, not all of
  the potential energy can be converted to kinetic energy. Some of the
  energy has to be used to push the air molecules out of the way. When
  that happens, the energy of the air molecules is increased. The air is
  actually "heated" up by the falling ball.

This text indirectly mentions that the Potential Energy gets converted into heat. However my common sense (for lack of a better term) makes me think that the Potential Energy gets converted into Kinetic Energy which in turn gets converted into Thermal energy. Would someone be able to enlighten me on this please?
Also, as a side question, it isn't called Heat Energy right? A lot of websites seem to be saying that, but heat is just the transfer of Thermal Energy...

A: The friction with the air indeed slows down the falling ball. The friction is minimal if the ball stays in place (i.e. there may be only some friction due to air currents.) But if the ball moves the friction is bigger because as the ball moves, it pushes away the air molecules to make room. The friction opposes the ball movement. So, indeed, the heating takes from the kinetic energy through friction, not from the potential energy. The meaning of the text, as I understand, it that, bottom line, the kinetic energy acquired by the ball during its fall is not equal to the total potential energy $M_b gH$.

A: Heat energy and thermal energy are pretty much the same thing. My science teacher taught me, that because potential energy is related to height, it would be the kinetic energy that is converted into thermal energy.

A: As the ball moves it is in interaction with the local gravitational field, and with the air. The interaction with the air includes both viscosity, and also an adjustment of the regular flow of the air (moving the flow lines), and, related to this, turbulence behind the ball. The ball accelerates at each moment in proportion to the resultant of all these forces. As it moves through any given change in height its gravitational potential energy changes by precisely the associated amount, $m g (h_f - h_i)$. Its kinetic energy does not increase by this amount, however, since the ball is doing work on the air. This work gives kinetic energy to the air molecules, some of it in a regular form (so not heat) and some of it in an irregular form, which can be called heat or thermal energy (both terms are ok; but if you want to be strict then you use the word heat for the energy in transit from one    system to another, and internal energy for the energy when it arrives in some other system, in this example the air).
The regular part of the air's motion eventually dies way, and then one may say that all the energy acquired by the air is just as if it had absorbed that amount of heat. The ball itself will also acquire some heat and consequently warm up. (And there will then be another process of heat transfer between air and ball).
If an author says that some of the gravitational potential energy has been converted into heat, then they are referring to the overall result; it is a perfectly correct summary, but it is also correct to say that the conversion takes places via the movement of the ball. So your intuition that the ball first picks up kinetic energy, and then this energy is partly passed on to the air, is sound, as long as you realise that the whole process is continuous.

A: Note that during a fall of a ball, the air friction is negligible, and we call it a free fall, only $\vec{P}$ is applied, the work of this force is given by : $W(\vec{P})=mgl$.
In this case, the air slows the ball falling, so there absolutely is two forces, the weight and the air contact, let it be  $\vec{f}$, its work will be : $W(\vec{f})=\vec{f}.\vec{l}$
The speed of this ball isn't constant so the $\sum W \neq 0 \Leftrightarrow \Delta E_k\neq0$ and the variation of potential energy $\Delta E_p=-W(\vec{P})$
Back into the free fall; $\Delta E_k=\sum W \Leftrightarrow \frac{1}{2}mv_f^2-\frac{1}{2}mv_i^2=W(\vec{P})$
$\frac{1}{2}mv_f^2-\frac{1}{2}mv_i^2=-mg(z_f-z_i)$
$\frac{1}{2}mv_f^2+mgz_f=\frac{1}{2}mv_i^2+mgz_i$
Adding the Constant of the potential energy, we get:
$\frac{1}{2}mv_f^2+mgz_f+C=\frac{1}{2}mv_i^2+mgz_i+C$
Note that : $E_p=mgz+C$ we will have :
$E_{k_f}+E_{p_f}=E_{k_i}+E_{p_i} \Leftrightarrow E_{m_f}=E_{m_i} \Leftrightarrow \Delta E_m=0$
Therefore during a free fall the mechanical energy (Kinetic and potential) is conserved, but what about this case ?
I mentioned that the ball's speed isn't constant and there's a negative friction force (The work is negative because of the angle note that $W(\vec{f})=f.l.cos(\pi)=-f.l$), obviously the mechanical energy isn't conserved and that's why:
$$\Delta E_k= \sum W$$
In this case there's two forces, thus there's two works
$$\frac{1}{2}mv_f^2-\frac{1}{2}mv_i^2=W(\vec{P})+W(\vec{f})$$
We're doing the same thing here, but there's a new factor which is $W(\vec{f})$, We'll have :
$$ \Delta E_m=W(\vec{f})$$
Now how this friction is transformed to a heat ?
Well to answer this question, you'll need the first law of thermodynamics $$\Delta U=Q+W$$
but I see that it's obvious without any mathematical proof, by the way $\Delta E_m=-Q$ so we can conclude that $W(\vec{f})=-Q$, so the friction is transformed to a heat (thermal energy) the sign minus is conventional. and you can conclude that when there's any friction force (external force) its work is converted into a thermal energy.

A: In classical mechanics, Kinetic Energy,  $\frac{m\vec v^2}{2}$, depends only on the velocity while Potential Energy, $mgz$, depends only on position. Since friction force$^2$ acts to oppose the velocity, $-k\vec v,^1$ your intuition is correct: potential energy first changes to kinetic energy and then to heat (as friction).
$^1$A spinning ball or an oddly shaped object might cause "friction" to act in a sightly direction but it still depends on velocity. When the friction force depends on position, as when a bowling ball leaves the oiled part of the lane, it makes the friction coefficient, $k$, dependent on position, $k(\vec x)$, but it still reduces the kinetic energy of the object.
$^2$Friction makes a system non-energy-conservative, so we mostly use the force picture (or the equations of motion) for friction problems.


text:
Q: Context based object initialization python Thank you for your time. Hope everything is going well  with you during this strange times.
I'm working on a class that represents a list of operations. These operations receive arguments (some optional, some mandatory) and output some values. All arguments are keyword arguments and each operation outputs a dictionary with the results.
Consider that Operation1 takes no arguments and outputs a result called 'arg1'.
Consider that Operation2 takes a mandatory argument called 'arg1' and outputs 'arg2'.
Operations throw errors if a mandatory argument is missing.
o = Operation2() # raises error because arg1 is not given

In my class List, operation outputs are fed as inputs to the next operation meaning that the following wouldn't raise any errors:
l = List([Operation1(), Operation2()])

How can i achieve this? Since validation occurs in in the operation init an error will be thrown. I pretend to init the object differently depending if it is inside a List or outside.
I know how to achieve this using class methods and flags but that would change the simple and consistent syntax i displayed above. That's not an option for this project. I have full control about the rest of the implementation of List and all Operations.
Thanks again for taking the time to help me, stay safe!


text:
Q: Replace String by List that contains the String I have a Dataframe that has the structure:
(List[String], String)
An example of two row could be: ([a,b,c], d) and ([d, e], a)
I want to transform these rows then to ([a,b,c], [d,e]) and ([d, e], [a, b, c])
The column names of the dataframe are "src" and "dst".
How can I approach this problem?
What I've tried:
val result = df.map(f => {
  if(df.exists(x => x._1.contains(f._2))) {
    (f._1, df.filter(x => x._1.contains(f._2)).head._1)
  } else {
    (f._1, List(f._2))
  }
}).toDF("src", "dst")

However, this solution gives me the following error:

java.lang.IllegalStateException: unread block data
          at java.io.ObjectInputStream$BlockDataInputStream.setBlockDataMode(ObjectInputStream.java:2740)
          at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1567)
          at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2245)
          at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2169)
          at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2027)
          at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
          at java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
          at org.apache.spark.serializer.JavaDeserializationStream.readObject(JavaSerializer.scala:75)
          at org.apache.spark.serializer.JavaSerializerInstance.deserialize(JavaSerializer.scala:114)
          at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:85)
          at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:53)
          at org.apache.spark.scheduler.Task.run(Task.scala:108)
          at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:335)
          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
          at java.lang.Thread.run(Thread.java:748)

There must be a more efficient way?

A: As far as I have understood from your question and comments above, following can be your solution
Given input dataframe as
+---------+---+
|src      |dst|
+---------+---+
|[a, b, c]|d  |
|[d, e]   |a  |
+---------+---+

You can use join and udf function as
import org.apache.spark.sql.functions._
val joinExpr = udf((col1: mutable.WrappedArray[String], col2: String) =>  col1.contains(col2))

df.as("t1").join(df.as("t2"), joinExpr($"t1.src", $"t2.dst")).select($"t1.src".as("src"), $"t2.src".as("dst")).show(false)

to get the final output as
+---------+---------+
|src      |dst      |
+---------+---------+
|[a, b, c]|[d, e]   |
|[d, e]   |[a, b, c]|
+---------+---------+

Hope the answer is helpful


text:
Q: React-native manifest merger failed Suddenly when i compile my project in android phone i get this error with the merge of manifest

Execution failed for task ':app:processDebugManifest'.
  Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91
          is also present at [androidx.core:core:1.0.0] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
          Suggestion: add 'tools:replace="android:appComponentFactory"' to  element at AndroidManifest.xml:7:5-117 to override.

I try to add in my gradle.properties
android.enableJetifier=true
android.useAndroidX=true

and i get other error

Execution failed for task ':react-native-firebase:compileDebugJavaWithJavac'.
   Compilation failed; see the compiler error output for details

My manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.wizdeoapptalent">

<uses-permission android:name="android.permission.INTERNET" />

<application
  android:name=".MainApplication"
  android:label="@string/app_name"
  android:icon="@mipmap/ic_launcher"
  android:roundIcon="@mipmap/ic_launcher_round"
  android:allowBackup="false"
  android:theme="@style/AppTheme">
  <activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
    android:windowSoftInputMode="adjustResize">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
  </activity>
  <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
  <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
      <intent-filter>
          <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
  </service>
  <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
</application>

My build.gradle
    // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
        googlePlayServicesAuthVersion = "15.0.1"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.1'
        classpath 'com.google.gms:google-services:4.2.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        mavenLocal()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
    }
}

My app/build.gradle
apply plugin: "com.android.application"

import com.android.build.OutputFile

def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.wizdeoapptalent"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
    }
    signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    implementation project(':react-native-i18n')
    implementation project(':react-native-device-info')
    implementation project(':react-native-vector-icons')
    implementation project(':react-native-google-signin')
    implementation project(':react-native-gesture-handler')
    implementation project(':react-native-firebase')
    implementation project(':react-native-device-info')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation "com.google.android.gms:play-services-base:16.1.0"
    implementation "com.google.firebase:firebase-core:16.0.8"
    implementation "com.google.firebase:firebase-messaging:17.5.0"
    implementation 'me.leolin:ShortcutBadger:1.1.21@aar'

}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}
apply plugin: 'com.google.gms.google-services'

I don't understand why i get these errors suddenly
UPDATE
I solved this issue with this response after trying all solution provided in comments.
Thanks you for all

A: Updating react-native-device-info to v2.1.3 will fix the issue

A: see this answer for not upgrading to androidX should prevent it from happening on react native 0.59.X
Manifest merger failed after import a module


text:
Q: Why are some websites' HTML and JavaScript so unreadable? I was trying to figure out what was going on in Facebook's login page and viewed the source in my browser. Some of the code is so unreadable it almost looks like somebody was just typing randomly:
<script>
function envFlush(a){
    function b(c){for(var d in a)c[d]=a[d];}
    if(window.requireLazy){window.requireLazy(['Env'],b);}
    else{window.Env=window.Env||{};b(window.Env);}
}
envFlush({
    "ajaxpipe_token":"AXjTsqcPXwT0nKMR",
    "lhsh":"8AQEln95N",
    "khsh":"0`sj`e`rm`s-0fdu^gshdoer-0gc^eurf-3gc^eurf;
    1;
    enbtldou;
    fduDmdldourCxO`ld-2YLMIuuqSdptdru;qsnunuxqd;
    rdoe-0unjdojnx-0unjdojnx0-0gdubi^rdbsduOdv-0`sj`e`r-0q`xm`r-0StoRbs`qhof"
});
</script>

Why is the HTML and JavaScript of most major websites so horrible and hard to read?

A: Most of the JavaScript code you will find online, especially on big websites like Facebook, is minified, compressed and sometimes even obfuscated.
Minification of JavaScript is mostly done because of performance reasons. All unnecessary whitespace (+ line breaks) and unnecessary elements like comments will be deleted to make the code as lightweight as possible. This results in faster loading times, reduces the server load and improves so the user experience.
Obfuscation is a way to render code unreadable, without destroying it's functionality. It is mostly done to protect the code and to make stealing it more difficult.
There are tools online (most of them called "beautifier" or "prettifier"), that can revert said minimization.

A: why not?
Web sites are not designed for human reading.  They are designed often for performance (minimum number of characters make less to transmit - including stripping all white-space) and often they are DELIBERATELY trying to make it hard to read, as a way of protecting their intellectual property.  There are actually tools out there designed to take "beautiful" code and deliberately make it ugly - for exactly this reason!


text:
Q: How to save a Tensorflow dataset to csv? I find a lot of documents/forums telling how to convert a csv to a Tensorflow dataset, but not a single one saying how to convert a dataset to a csv. I have csv with two columns now (filename, weight - more columns maybe be added later). I read that into tensorflow and create a dataset. At the end of the script the 2nd column is modified and I need to save these columns to a csv. I need them in csv (not checkpoint) because I may need to do stuff with it on Matlab.
I tried to call the dataset map function and tried to save to csv inside map function. But it doesn't work as expected.
#reading csv to dataset

def map_func1(line):
    FIELD_DEFAULTS = [[""], [0.0]]
    sample,weight = tf.decode_csv(line, FIELD_DEFAULTS)
    return sample,weight

ds = tf.data.TextLineDataset('sample_weights.csv')
ds_1 = ds.map(map_func1)

# then the dataset is modified to ds_2 then, not including code- it's just another map func

# trying to save to csv -

def map_func3(writer,x):
    x0,x1 = x
    writer.writerow([x0,x1])
    return x

with open('sample_weights_mod.csv','w') as file:
    writer = csv.writer(file)
    ds_3 = ds_2.map(lambda *x: map_func3(writer,x))

This doesn't work as expected just writes the tensor shape to csv Tensor("arg0:0", shape=(), dtype=string)  Tensor("arg1:0", shape=(), dtype=float32)
This solution is probably a bad one. I really need to get a neat way to do this

A: Though not a good way of doing for now I did it as below
type(movies) ## movies variable is of type tensorflow.python.data.ops.dataset_ops.MapDataset
z=[]
for example in movies:
  z.append(example.numpy().decode("utf-8"))

mv={'movie_title':z}
pd.DataFrame(mv).to_csv('movie.csv')


text:
Q: Potential floating point issue with cosine acceleration curve I am using a cosine curve to apply a force on an object between the range [0, pi]. By my calculations, that should give me a sine curve for the velocity which, at t=pi/2 should have a velocity of 1.0f
However, for the simplest of examples, I get a top speed of 0.753.
Now if this is a floating point issue, that is fine, but that is a very significant error so I am having trouble accepting that it is (and if it is, why is there such a huge error computing these values).
Some code:
// the function that gives the force to apply (totalTime = pi, maxForce = 1.0 in this example)
return ((Mathf.Cos(time * (Mathf.PI / totalTime)) * maxForce));

// the engine stores this value and in the next fixed update applies it to the rigidbody
// the mass is 1 so isn't affecting the result
engine.ApplyAccelerateForce(applyingForce * ship.rigidbody2D.mass);

Update
There is no gravity being applied to the object, no other objects in the world for it to interact with and no drag. I'm also using a RigidBody2D so the object is only moving on the plane.
Update 2
Ok have tried a super simple example and I get the result I am expecting so there must be something in my code. Will update once I have isolated what is different.
For the record, super simple code:
float forceThisFrame;
float startTime;

// Use this for initialization
void Start () {
    forceThisFrame = 0.0f;
    startTime = Time.fixedTime;
}

// Update is called once per frame
void Update () {
    float time = Time.fixedTime - startTime;

    if(time <= Mathf.PI)
    {

        forceThisFrame = Mathf.Cos (time);

        if(time >= (Mathf.PI /2.0f)- 0.01f && time <= (Mathf.PI /2.0f) + 0.01f)
        {
            print ("Speed: " + rigidbody2D.velocity);
        }
    }
    else
    {
        forceThisFrame = 0.0f;
    }
}

void FixedUpdate()
{
    rigidbody2D.AddForce(forceThisFrame * Vector2.up);
}

Update 3
I have changed my original code to match the above example as near as I can (remaining differences listed below) and I still get the discrepancy.
Here are my results of velocity against time. Neither of them make sense to me, with a constant force of 1N, that should result in a linear velocity function v(t) = t but that isn't quite what is produced by either example.
Remaining differences:

*

*The code that is "calculating" the force (now just returning 1) is being run via a non-unity DLL, though the code itself resides within a Unity DLL (can explain more but can't believe this is relevant!)

*The behaviour that is applying the force to the rigid body is a separate behaviour.

*One is moving a cube in an empty enviroment, the other is moving a Model3D and there is a plane nearby - tried a cube with same code in broken project, same problem

Other than that, I can't see any difference and I certainly can't see why any of those things would affect it. They both apply a force of 1 on an object every fixed update.

A: For the cosine case this isn't a floating point issue, per se, it's an integration issue.
[In your 'fixed' acceleration case there are clearly also minor floating point issues].
Obviously acceleration is proportional to force (F = ma) but you can't just simply add the acceleration to get the velocity, especially if the time interval between frames is not constant.
Simplifying things by assuming that the inter-frame acceleration is constant, and therefore following v = u + at (or alternately ∂v = a.∂t) you need to scale the effect of the acceleration in proportion to the time elapsed since the last frame.  It follows that the smaller ∂t is, the more accurate your integration.

A: This was a multi-part problem that started with me not fully understanding Update vs. FixedUpdate in Unity, see this question on GameDev.SE for more info on that part.
My "fix" from that was advancing a timer that went with the fixed update so as to not apply the force wrong. The problem, as demonstrated by Eric Postpischil was because the FixedUpdate, despite its name, is not called every 0.02s but instead at most every 0.02s. The fix for this was, in my update to apply some scaling to the force to apply to accomodate for missed fixed updates. My code ended up looking something like:
Called From Update
float oldTime = time;
time = Time.fixedTime - startTime;
float variableFixedDeltaTime = time - oldTime;
float fixedRatio = variableFixedDeltaTime / Time.fixedDeltaTime;

if(time <= totalTime)
{
    applyingForce = forceFunction.GetValue(time) * fixedRatio;

    Vector2 currentVelocity = ship.rigidbody2D.velocity;
    Vector2 direction = new Vector2(ship.transform.right.x, ship.transform.right.y);
    float velocityAlongDir = Vector2.Dot(currentVelocity, direction);
    float velocityPrediction = velocityAlongDir + (applyingForce * lDeltaTime);

    if(time > 0.0f && // we are not interested if we are just starting
       ((velocityPrediction < 0.0f  && velocityAlongDir > 0.0f ) ||
       (velocityPrediction > 0.0f  && velocityAlongDir < 0.0f ) ))
    {
        float ratio = Mathf.Abs((velocityAlongDir / (applyingForce * lDeltaTime)));
        applyingForce = applyingForce * ratio;

        // We have reversed the direction so we must have arrived
        Deactivate();
    }

    engine.ApplyAccelerateForce(applyingForce);
}

Where ApplyAccelerateForce does:
public void ApplyAccelerateForce(float requestedForce)
{
    forceToApply += requestedForce;
}

Called from FixedUpdate
rigidbody2D.AddForce(forceToApply * new Vector2(transform.right.x, transform.right.y));
forceToApply = 0.0f;


text:
Q: How to join 3 table in mysql with rule? First, I have 3 table.
Table 1 data:
tid | type_1 | address_1 | contact_1
----+--------+-----------+-----------+
1   | 4      | No.2123   | 01234567
4   | 4      | No.4567   | 00011234

Table 2 data:
tid | type_2 | address_2 | contact_2
----+--------+-----------+-----------+
2   | 3      | No.8888   | 7654321

Table 3 data:
tid | subject | desc
----+---------+-------------+
1   | Test 1  | Desc 1
2   | Test 2  | Desc 2
3   | Test 3  | Desc 3
4   | Test 4  | Desc 4

I would like to combine like this:
tid | subject | type_1 | type_2 | address_1 | address_2 | contact_1 | contact_2 | desc
----+---------+--------+--------+-----------+-----------+-----------+-----------+------
1   | Test 1  | 4      |        | No.2123   |           |01234567   |           | Desc1
2   | Test 2  |        | 3      |           |No.8888    |           |7654321    | Desc2
4   | Test 4  | 4      |        | No.4567   |           |00011234   |           | Desc4

if table 1 got "tid" 1, then table 2 never got the same tid.
Ignore if tid no found in table 1 and table 2
Thanks!
My code before is:
$query = mysql_query("SELECT table1.*, table2.*, table3.subject, table3.desc, FROM table1 ON table1.tid = table3.tid LEFT JOIN table2 ON table2.tid = table3.tid LEFT JOIN table3 ON table1.tid AND table2.tid = table3.tid");

A: SELECT
        table1.tid,
        table3.subject,
        table1.type_1,
        NULL AS type_2,
        table1.address_1,
        NULL AS address_2,
        table1.contact_1,
        NULL AS contact_2,
        table3.`desc`

FROM table1
INNER JOIN table3 ON table1.tid=table3.tid
UNION ALL
SELECT
        table2.tid,
        table3.subject,
        NULL AS type_1,
        table2.type_2,
        NULL AS address_1,
        table2.address_2,
        NULL AS contact_1,
        table2.contact_2,
        table3.`desc`

FROM table2
INNER JOIN table3 ON table2.tid=table3.tid

A: The JOIN clause you have written is not in correct format. You should use it like this:
`table1 JOIN table2 ON` your conditions to join the table.

You can get more about JOIN from here.
So you can try this:
SELECT table3.tid AS tid,
  t3.subject AS subject,
  t1.type_1 AS type_1,
  t2.type_2 AS type_2,
  t1.address_1 AS address_1,
  t2.address_2 AS address_2,
  t1.contact_1 AS contact_1,
  t2.contact_2 AS contact_2,
  t3.desc AS description
FROM table3 t3
  INNER JOIN table1 t1 ON t3.tid = t1.tid
  INNER JOIN table2 t2 ON t3.tid = t2.tid

A: DROP TABLE IF EXISTS table1;
CREATE TABLE table1
(tid INT NOT NULL
,type_1 INT NOT NULL
,address_1 VARCHAR(12) NOT NULL
,contact_1 VARCHAR(12) NOT NULL
);

INSERT INTO table1 VALUES
(1   ,4      ,'No.2123','01234567'),
(4   ,4      ,'No.4567','00011234');

DROP TABLE IF EXISTS table2;
CREATE TABLE table2
(tid INT NOT NULL
,type_2 INT NOT NULL
,address_2 VARCHAR(12) NOT NULL
,contact_2 VARCHAR(12) NOT NULL
);

INSERT INTO table2 VALUES
(2   ,3      ,'No.8888','7654321');

DROP TABLE IF EXISTS table3;
CREATE TABLE table3
(tid INT NOT NULL
,subject VARCHAR(12) NOT NULL
,description VARCHAR(12) NOT NULL
);

INSERT INTO table3 VALUES
(1   ,'Test 1','Desc 1'),
(2   ,'Test 2','Desc 2'),
(3   ,'Test 3','Desc 3'),
(4   ,'Test 4','Desc 4');

SELECT x.*
     , y.subject
     , y.description
  FROM
     ( SELECT tid
            , type_1
            , NULL type_2
            , address_1
            , contact_1
            , NULL address_2
            , NULL contact_2
         FROM table1
        UNION
       SELECT tid
            , NULL
            , type_2
            , NULL
            , NULL
            , address_2
            , contact_2
         FROM table2
    ) x
 JOIN table3 y
   ON y.tid = x.tid;

+-----+--------+--------+-----------+-----------+-----------+-----------+---------+-------------+
| tid | type_1 | type_2 | address_1 | contact_1 | address_2 | contact_2 | subject | description |
+-----+--------+--------+-----------+-----------+-----------+-----------+---------+-------------+
|   1 |      4 |   NULL | No.2123   | 01234567  | NULL      | NULL      | Test 1  | Desc 1      |
|   2 |   NULL |      3 | NULL      | NULL      | No.8888   | 7654321   | Test 2  | Desc 2      |
|   4 |      4 |   NULL | No.4567   | 00011234  | NULL      | NULL      | Test 4  | Desc 4      |
+-----+--------+--------+-----------+-----------+-----------+-----------+---------+-------------+
3 rows in set (0.00 sec)


text:
Q: wp_schedule_event action not running It seems like all the answers on here for this question end up being a syntax error, however I'm not seeing it here.
I'm trying to setup a daily job here that will run through all my 'vacation' posts, if the _simple_start_date (unix timestamp) is the same date as today, then run some functions to update the usermeta.  The three functions I call are defined earlier in my plugin and I know work since as I am using them multiple other places to do the exact same thing I'm doing here.  Only difference is that this is a scheduled event.
Since I have set this up, it has not ran once.
I am using define( 'DISABLE_WP_CRON', true ); for use with some other plugins I have that are running daily tasks.  However from what I've read, that should not cause an issue with this.
Any help is of course greatly appreciated. thanks
add_action( 'wp', 'pto_setup_schedule' );
/**
 * On an early action hook, check if the hook is scheduled - if not, schedule it.
 */
function pto_setup_schedule() {
    if ( ! wp_next_scheduled( 'pto_daily_event' ) ) {
        wp_schedule_event( time(), 'daily', 'pto_daily_event');
    }
}

add_action( 'pto_daily_event', 'check_pto_request_date' );
/**
 * On the scheduled action hook, run a function.
 */
function check_pto_request_date() {

    $loop = new WP_Query( array( 'post_type' => 'vacation') );
    while ( $loop->have_posts() ) : $loop->the_post();

    $request_start_time = (get_post_meta( $post->ID, '_simple_start_date',true) );

    if  (date('Ymd') == date('Ymd', $request_start_time)){

        $current_user = $post->post_author;
        $request_date = get_post_meta( $post->ID, '_simple_start_date',true );
        $request_year = date("Y",$request_date);
        $time_year= date("Y");
        $request_time = get_post_meta($post->ID, '_simple_total_hours', true);
        $request_type = get_post_meta($post->ID, '_simple_vacation_type', true);

        update_days_requested((-1 * $request_time), $request_type, $current_user);
        update_days_left((-1 * $request_time), $request_type, $current_user);
        update_days_used($request_time, $request_type, $current_user);

    }
    endwhile;

}

A: I think your problem may be in the use of $post->ID. In your code $post is an undefined variable. As you are inside a loop, try get_the_ID() instead of $post->ID:
$post_ID = get_the_ID();

$request_start_time = get_post_meta( $post_ID, '_simple_start_date', true );

if  (date('Ymd') == date('Ymd', $request_start_time)){

    $current_user = $post->post_author;
    $request_date = get_post_meta( $post_ID, '_simple_start_date',true );
    $request_year = date("Y",$request_date);
    $time_year= date("Y");
    $request_time = get_post_meta($post_ID, '_simple_total_hours', true);
    $request_type = get_post_meta($post_ID, '_simple_vacation_type', true);

    update_days_requested((-1 * $request_time), $request_type, $current_user);
    update_days_left((-1 * $request_time), $request_type, $current_user);
    update_days_used($request_time, $request_type, $current_user);

}


text:
Q: How to generate gRPC services and reuse existed DTOs in java with gradle? Is it possible to describe some services in .proto files which use the existed DTOs & generate the service classes with gradle?
I'm developing client SDK for some server. The current communication layer based on gRPC but I don't want to expose the implementation details (those ugly gRPC messages classes) to the end user. So the public API represented with POJOs.
The existed solution make some conversions between two types of DTOs with custom converters. And this is quite annoying - copy tones of properties just to beautify the public API. So I'm looking a way to reuse the POJO on gRPC layer. Is it possible?

A: Protobuf really needs those messages in order to be told what to serialize. So while there are some ways to serialize your own message types (like MethodDescriptor.Marshaller), if you want to use Protobuf you'll need to copy between the different types of objects.


text:
Q: SEO crawler DDOSing sites I have a customer that runs 36 websites (many thousands of pages) on a round robin with sticky affinity load-balanced set of IIS servers - the infra is entirely AWS based (r3.2xl - 8 VCPU, 60.5 GiB RAM)
To get straight to the point, the site is configured to 'cache on access' using standard in-memory caching with ASP.NET 4.6 and static assets through Cloudfront.  The site on a 'cold start' makes both SQL Server queries for content, and separate elasticsearch queries at runtime to determine hreflang alternate language tags - this basically queries which versions of the URL are available in different languages for SEO reasons.  This query has been optimised to be a lookup on a single index from a cross-index wildcard query.  As mentioned, the entire result is cached for 24h once all this has executed.
Under normal use conditions the site works perfectly.  As there are 36 sites running on a single box, the private set space gets allocated up to the max (99%) of physical RAM over time, as more and more content gets cached in memory.  I can end up with App Pools in excess of 1.5GiB which isn't ideal.  After this point, presumably the .NET LRU cache eviction algorithm is working overtime.
The problem I have, after some post-mortem review of the IIS logd, the customer is using an SEO bot tool, SEMrush, which essentially triggers a denial of service attack against the sites (thundering herd?) because of simultaneous requests for the 'long tail' of pages which are never viewed by a user and hence aren't stored in the cache.
The net result is a server brought to its knees, App Pool CPU usage all over the place, and an Elasticsearch queue length > 1000, huge ES heap growth, rejection rate - and eventually a crash.
The solutions I've thought about but haven't implemented:

*

*Cloudfront all the sites - use a warm up script (although I don't think this will actually help as it's a cold start problem when all the pages expire, unless I could have a MOST recently used cache invalidation mechanism which invalidated pages on number of requests - say > 100, and left everything else persistent)

*AWS Shield/WAF to provide some sort of rate limiting

*Remove the runtime ES lookup all together and move to an eventually-consistent model which computes the hreflang lookup table elsewhere on a separate process.  Hpwever, the ES instances, whilst on a v1.3.1 version which is old, is a 3-node cluster which has a lot of CPU power and each node set to a 16GiB min/max heap so should be able to take that level of throughput?
Or all 3!
Has anyone come across this problem before and what was your solution? it must be fairly common especially for large sites which are hammered by SEO / DQM web crawlers?


text:
Q: Migrate Exchange 2010 to Exchange 2016, but do it gradually We have a small-organization, on-premises Exchange 2010 setup running on Server 2008 R2. Our goal is to migrate to Exchange 2016 running on Server 2016 (I guess -- I would prefer Server 2019, but apparently that is not supported for Exchange 2016.)
We do not have a test domain set up, which is probably part of the problem, but which is probably not going to be fixed.
I have been reading through the Exchange Assistant , Microsoft documentation) and answers here (eg Migrate from Exchange 2010 to Exchange 2016). I am getting a grasp of the basics, but I am confused about how to install Exchange 2016 without it taking over functionality from Exchange 2010 right away.
I would like to install Exchange 2016 in my environment, but have all my users continue to use Exchange 2010 for their Outlook and OWA setups. Then I would like to change configuration to start using Exchange 2016 functionality later. But from what I have read about coexistence, it appears that Exchange 2016 becomes the default connection point immediately (eg, as described in this coexistence document ).
My questions:

*

*Is it the case that Exchange 2016 will begin serving my existing clients as soon as I install it?

*If so, is there a way to stop this? Part of this looks like changing the Service Connection Point published in Active Directory using the Set-ClientAccessService cmdlet, as documented in step 6 here. It looks as if I also have to unset (or refrain from setting) DNS entries for autodiscover. Is there more?

*Related to the above: are there ways to revert whatever changes Exchange 2016 will make so that I can use Exchange 2010 exclusively again?

*At what installation/migration step do I lose the ability to back out of the migration and go back to Exchange 2010? Is it as soon as I successfully install the product? Earlier? Later? I was reading that doing the schema updates prohibits me from installing a new Exchange 2013 server (but I still think I can install an Exchange 2010 one).
Thanks for any insight you can offer, and apologies if these are dumb questions.

A: If you set up a separate Exchange 2016 environment next to your existing Exchange 2010 one, at first nothing at all should happen. The reference in point 6 you mention seems to be a precaution to ensure it stays that way initially.
When you're confident enough that you have a working configuration on the Exchange 2016 environment and that it can interact with the Exchange 2010 server(s), you may configure your DNS records - one service at a time - to point at the new machines.
All this time, if anything goes wrong, simply point the DNS records back to your old server.
During this transition period, the new Exchange version will proxy requests back to the older environment when necessary - for example when delivering mail.
Then you will migrate mailboxes to the new server(s), and finally - after you've confirmed that everything relevant is still working - clean up your environment to rid it of references to the old mail servers, and remove them.

A: Agree with Mikael H, If you only install exchange 2016, it will not affect the existing exchange 2010.
You say go back to exchange 2010, yes, you can, If all mailboxes are on exchange 2010 and there are no mailboxes on 2016. If there is a mailbox on exchange 2016, and all urls point to exchange 2010, the mailbox on exchange 2016 will no longer be available.


text:
Q: jQuery parsing XML finding specific elements I'm making a "TV guide" which gets data from an xml file. Here's what I have so far:
$(document).ready(function(){
$.ajax({
    type: "GET",
    url: "programmes.xml",
    dataType: "xml",
    error: function (xhr, status, error) {
        console.log(status, error);
    },
    success: function(xml) {

        var programmeOne = $(xml).find('programme').first();
        $(xml).find('[programme[id="ch1pg1"]').text();
        $('.p1').text(programmeOne.find('title').text());

    }

});

And here's the XML:
<channel id="bbc1" source="Sky" date="20/12/2014">
<programme id="ch1pg1">
  <desc>The latest news, sport, business and weather from the BBC's Breakfast team.</desc>
  <title>Breakfast</title>
  <start>0900</start>
  <end>1100</end>
</programme>
<programme id="ch1pg2">
  <desc>James Martin presents the weekly cooking show. [HD] [S]</desc>
  <title> Kitchen</title>
  <start>1100</start>
  <end>1200</end>
</programme>
<programme id="ch1pg3">
  <desc>descriptions [HD] [S]</desc>
  <title>second  Kitchen</title>
  <start>1200</start>
  <end>1300</end>
</programme>

When I remove
$(xml).find('[programme[id="ch1pg1"]').text();

The code works, but all programme 1's from each channel use the same title from ch1pg1.
How can I make the function only use the "title" element from the parent element "programme" which has an id of "ch1pg1"?

A: Firstly when searching by id you can use the # selector to make things both quicker and shorter.
Your second line of code does not work because you are returning a string, and then attempting to use jQuery methods on it, which will not work. Instead return the jQuery object and use that. Try this:
success: function(xml) {
    var $programmeOne = $(xml).find('#ch1pg1');
    $('.p1').text($programmeOne.find('title').text());
}

Example fiddle


text:
Q: Direct sum of the spinors and EM field tensor EM field tensor refer to the direct sum of $(1, 0), (0, 1)$ spinor representation of the Lorentz group. How to show it?
Each of these spinor representations corresponds to the symmetrical spinor tensor rank 2. So first I got the relation between an arbitrary antisymmetrical tensor $M_{\mu \nu}$ and spinor tensor $h_{ab \dot {a}\dot {b}}$:
$$
M_{\mu \nu} \to h_{ab \dot {a}\dot {b}} = \epsilon_{a b}h_{(\dot {a}\dot {b})} + \epsilon_{\dot {a} \dot {b}}h_{(ab)},
$$
where $ h_{(ab)}, h_{(\dot {a}\dot {b})}$ are symmetrical spinor tensors, but I don't understand how to identity $h_{ab \dot {a}\dot {b}}$ with $(1, 0) + (0, 1)$.
Maybe I need to build the transformation law of $h_{ab \dot {a}\dot {b}}$, then the transformation law of "bispinor" $(1, 0) + (0, 1)$, and then to see, that they are identically?


text:
Q: Sort [key => value] array by another array of keys with same index I have an array of indexes that I want to sort my other array:
$order = [7, 2, 1, 4];

$array = [
   1 => "O",
   2 => "T"
   4 => "F"
   7 => "S"
]

How can I order the $array based on $order array, so that the output is..
$array = [
   7 => "S",
   2 => "T"
   1 => "O",
   4 => "F"
]

As far as I read, something other than for loop is much preferred

A: You could make use of uksort and array_search:
uksort($array, static function (int $key1, int $key2) use ($order): int {
    return array_search($key1, $order, true) <=> array_search($key2, $order, true);
});

The idea is to sort the array by the positions of its items' keys within the $order array:

*

*uksort is a sorting function that allows sorting based on array keys (here 1, 2, 4 and 7),

*array_search($key1, $order, true) gives you $key1's position within $order,

*array_search($key2, $order, true) gives you $key2's position within $order,

*<=> (known as the spaceship operator) compares these values, so that the sorting puts lower values (aka lower positions within $order) first.

Demo
Note: performance could be bad if your array is big, as array_search will be run several times on the same keys. If that's an issue, what you can do is grab all keys' positions within $order first, then sort based on them.


text:
Q: surface sdk scatterview I'm using bluetooth surface published in http://code.msdn.microsoft.com/Surface-Bluetooth-Connect-dbe7e0e8 I add the kinect in this wpf application. But i need multitouch function to zoom in and zoom out the scatterviewitem picture. So can anyone give me idea about how can i achieve multitouch in this application.
And i also try using kinect gesture to zoomin the scatterview, but it still have a problem how to select the scatterviewitem in scatterview and zoom it.
I'm add all kinect function in MainWindow class, so how can i achieve all scatterviewitems in scatterview, and zoom I select one.
I'm using Win7, not touch screen.


text:
Q: How would you TDD or unit test a class/method that shutsdown an NT Service like "telnet"? New to unit testing and TDD and I write alot more OS utilities than say traditional LOBs.  So, I understand how you might mock or stub a database or a file, but how about things like:

*

*Authentication against Active Directory

*Stopping an NT service

*Authorization against an AD Group

*etc...

A: You cannot test whether a service was actually stopped using unit test. That's what other tests (e.g. integration tests) are for. Often it is worth testing though, whether you system under test (SUT) is actually making the right calls to stop the service.
In that case could wrap these concrete APIs into an interface (façade) specifically tailored towards the needs of your consumers. And then mock that interface and assert that the appropiate members have been called with the right arguments by your consumers that you are testing.
Example (c#, NUnit, FakeItEasy):
// implementation of this interface basically wraps the concrete service APIs of the OS
public interface IServiceController
{
   public void Start(string serviceName);
   public void Stop(string serviceName);
}

// consumer that wants to stop a specific service and that is your SUT
public class SomeConsumer
{
    // ctor takes dependency on a service controller
    SomeConsumer(IServiceController controller)
    {
       // ...
    }

    public void DoSomethingThatRequiresAServiceStop()
    {
       // ...
    }
}

[TestFixture]
public class SomeConsumerTests
{
    [Test]
    public void DoSomethingThatRequiresAServiceStop_StopsServiceXYZ()
    {
          // arrange
          IServiceController mockServiceConntroler = A.Fake<IServiceController>();
          SomeConsumer sut = new SomeConsumer(mockServiceController);

         // act
         sut.DoSomethingThatRequiresAServiceStop();

         // assert
         A.CallTo(() => mockServiceConntroler.Stop("XYZ")).MustHaveHappend();
    }
}

As Matt already pointed out in some environments that are tools that allow you to replace concrete implementations without you having to introduce abstractions (here: IServiceController). I tend to avoid these as much as possible because they often are not only a bit tedious to use but also seem to enforce bad design choice (e.g. depending on concrete implementations instead of abstractions). I see tools like Microsoft Moles or TypeMock Isolator more as tools that help you work with legacy code bases that already have a ton of bad design choices that you cannot get rid of (right away).

A: With some code it may not be possible to unit test with stubs or mocks directly in a loosely coupled way* as the code you are depending on itself may not be loosely coupled. You may need to end up writing an integration test instead.
If this is the case, it may be better to write a wrapper class (i.e. use the adapter or facade pattern) over the non-unit-testable code driven by integration tests. This way you can still stub/mock your wrapper class elsewhere in the code using unit tests when you need to, say, start/stop a windows service. Your wrapper class also is test-driven, but just with integration tests instead.
*If on .NET some tools out there may allow you to still write unit tests and inject some sort of fake object, such as Microsoft Moles (soon to be named Fakes) or TypeMock Isolator in these cases, but the tests would be slower and take more code to write. While I've used Moles, I personally would rather wrap the hard-to-test code instead of using these tools.


text:
Q: XYZ from pointcloud I am utilizing the ros node for the ensenso camera. From this I want to read the pointcloud data, which is published on the /point_cloud topic with the message type PointCloud2, and convert this to data that can be used to assert a destination for a robot.
I have tried using
sensor_msgs.point_cloud2.read_points(pointCloud,
                                    field_names=pointCloud.data,
                                    skip_nans=True)

which does infact return three values, from the script point_cloud2.py I understand that these are infact the x, y and z coordinates. The issue is that these are floats with values below 1.
I also tried reading the data in pointCloud.data directly but this resulted in raw unsorted data that I will not be able to apply.
    def point_cloud_callback(self, pc_msg):
        rospy.logdebug("Get a point cloud")
        if self._msg_lock.acquire(False):
            self._last_point_cloud_msg = pc_msg
            self._msg_lock.release()

    def print_pc(self):
        pointCloud = self._last_point_cloud_msg

        for point in sensor_msgs.point_cloud2.read_points(pointCloud,
                            field_names=pointCloud.data,
                            skip_nans=True):
            pt_x = point[0]
            pt_y = point[1]
            pt_z = point[2]
            print pt_x, pt_y, pt_z

def main():
    rospy.init_node("simple_pc_subscriber")
    node = pc_subscriber()
    rate = rospy.Rate(1)
    while not rospy.is_shutdown():
        node.print_pc()
        rate.sleep()

if __name__ == '__main__':
    main()

The results that I am getting are floats with values between 0 and 1. I am expecting to get coordinates based on the pixels they coincide with. Resolution of the camera is 1280 * 1080, which i expect as the x and y values, and for every pixel a depth value representing the Z coordinate that can be used to ascertain the position of an object.

A: I hope you're doing well.
You should map your data to the resolution you want. You can do it like this:
x = int(X1280)
y = int(Y1080)
where X and Y are the output of this:
    sensor_msgs.point_cloud2.read_points(pointCloud,
                                field_names=pointCloud.data,
                                skip_nans=True)

The Z shows the intensity in [0, 1]. You can also multiply it by 255.


text:
Q: Problemas com Fragments: Activity has been destroyed Meu navigation drawer está correto, mas quando você clica num item do drawer, e ele vai dar um replace nos fragments, a aplicação pára, e no logcat aparece mensagem de erro dizendo que

Activity has been destroyed

Código:
class DrawerItemClickListener extends FragmentActivity implements         ListView.OnItemClickListener {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    selectItem(position);
}

private void selectItem(int position) {

    Fragment fragment = null;

    switch(position)
    {
    case 0:
        fragment = new DadosCadastraisDilmaFragment();
        break;
    case 1:
        fragment = new DadosCadastraisAecioFragment();
        break;
    ...
            default:
            break;
    }

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.content_frame, fragment).commit();
}
}

public class MainActivity extends ActionBarActivity{

private String [] listaCandidatos;
private DrawerLayout drawerLayout;
private ListView drawerList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // inicializar a lista do drawer
    listaCandidatos = getResources().getStringArray(R.array.lista_candidatos);
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerList = (ListView) findViewById(R.id.left_drawer);

    // Set the adapter for the list view
    drawerList.setAdapter(new ArrayAdapter<String>(this,
            R.layout.drawer_list_item,R.id.drawerListItemTextView, listaCandidatos));
    // Set the list's click listener
    drawerList.setOnItemClickListener(new DrawerItemClickListener());
}

A: O problema é que o  DrawerItemClickListener herda de FragmentActivity. E está fazendo reposições de Fragment em uma Activity (DrawerItemClickListener) usando o FragmentManager, que não foi criada pelo ActivityManager (parte do framework Android).
A mensagem:

Activity has been destroyed

É causada porque essa Activity não foi iniciada. Então para ele está destruída.
Remova essa herança e faça com que o DrawerItemClickListener seja declarado não estático dentro da MainActivity.
Mais ou menos assim:
public class MainActivity extends ActionBarActivity {

    // Restante do codigo

    public class DrawerItemClickListener implements ListView.OnItemClickListener {

        // Restante do seu código

    }
}


text:
Q: Getting incorrect width when drawing a UITableViewCell with variable height An address cell needs a variable height.
In viewWillAppear I draw a test cell to capture the label height in an ivar.
In the delegate method, tableView:heightForRowAtIndexPath, I use the ivar to set the height for the actual address cell.
The code:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];

UITableViewCell *testCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:@"addressCell"] autorelease];

testCell.textLabel.text = @"Address";
testCell.detailTextLabel.text = [selectedPatient valueForKey:@"address"];
testCell.selectionStyle = UITableViewCellSelectionStyleNone;
testCell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
testCell.frame = CGRectMake(0,0,100,30);
[testCell addSubview:testCell.detailTextLabel];
[testCell sizeToFit];

CGSize maxSize;

// HERE is where the problem occurs
// maxSize.width is 35 when it should be 200
maxSize.width = testCell.detailTextLabel.frame.size.width;
//

maxSize.height = 500;

UIFont *font = testCell.detailTextLabel.font;

CGSize testSize = [[selectedPatient valueForKey:@"address"] sizeWithFont:font constrainedToSize:maxSize lineBreakMode:UILineBreakModeWordWrap];

addressLabelHeight = testSize.height;

[testCell removeFromSuperview];
}

Getting the width of the test cell is the problem.  When NSLog'ing cellForRowAtIndexPath: it shows the width to be 200, but my testCell's width is only 35.  This causes the height to be too big, showing a cell with way too much white space.
I fixed the problem by just setting maxSize.width = 200 but I was curious what I was doing wrong to get the detailLabel's width dynamically?

A: maxSize.width is going to be the width of the text. What's the text you get from @"address"? I'm betting it's about 35 points wide.
BTW, why are you doing this:
// This is legal, but a strange size
testCell.frame = CGRectMake(0,0,100,30);

// This is redundant I believe
[testCell addSubview:testCell.detailTextLabel];

// Does this help you at all?
[testCell sizeToFit];

You can't really trust the width of the cell until tableView:willDisplayCell:atIndexPath:. That's where you want to do any final layout. For your purposes, you should probably choose how wide you want the address to be (200 points if you like), and then force it to be that width rather than asking it how big it is.


text: Q: Why and when does D3 resolve links in a force diagram I have found that in a force diagram when I look at my data after a bit that some of the links, which have a source and target id instead have the full data of the node inside of them. Why is that and when does this step happen?


text:
Q: What is the preferable memory layout of Algebraic Data Types? Algebraic Data Types (ADTs) are types consisting of unit, product and sum types with possible recursion.
Consider a simple ADT in Haskell:
data Tree = Empty
          | Leaf Int
          | Node Tree Tree

Or a different example in Rust:
enum Message {
    Quit,
    ChangeColor(i32, i32, i32),
    Move { x: i32, y: i32 },
    Write(String),
}

How does Haskell (garbage collected) and Rust (not garbage collected) actually represent these in memory, and how should they be represented?
I'm primarily interested in the non garbage collected case which is simpler, but the solution must be workable both for the heap and stack if non-garbage collected, like for Rust.
Representations in LLVM, or C/C++ are what I'm interested in.
Using the second example, I can think of two options:
Option 1, using unions:
enum MCtor { CQ, CCC, CM, CW  };

struct Message {
    enum MCtor ctor;
    union {
        void*; /* Quit */
        struct { int r; int g; int b; } /* ChangeColor */
        struct { int x; int y; } /* Move */
        struct { char* str; } /* Write */
    };
};

Option 2, using separate allocation, void* and (bit)casts:
enum MCtor { CQ, CCC, CM, CW  };

typedef struct { int r; int g; int b; } ChangeColor;
typedef struct { int x; int y; } Move;
typedef struct { char* str; } Write;

struct Message {
    enum MCtor ctor;
    void* data;
};

Pattern matching is then simply a matter of switch on msg -> ctor.
Which one is preferable, especially considering recursive types?
Off the top of my head, I guess that the locality of the first one is better and that it avoids loads, while it might use more memory... So the second option has a better memory footprint but worse performance...?

A: Here are some resources for explaining how GHC implements data structures:

*

*Johan Tibell's talk at ZuriHac 2015 (video) (slides) (talk starts at slide 42)

*GHC Commentary: The Layout of Heap Objects


text:
Q: How to convert columns into Rows I have a table data where the data will be shown like this :
DatePeriod  Good    Fair    Poor    NotCategorised  NotTested   GoodPercentage  FairPercentage  PoorPercentage  NotCategorisedPercentage    NotTestedPercentage
Feb-13  4   0   0   0   60  6.25    0   0   0   93.75

And for this one I have written query using UNPIVOT.
Select DatePeriod,Legend FROM
(
select DatePeriod,Good,Fair,Poor,NotCategorised,NotTested,GoodPercentage,
FairPercentage,poorPercentage,NotCategorisedPercentage,NotTestedPercentage  from #cte

)P
UNPIVOT(Legend FOR  #CTE IN (Good,Fair,Poor,NotCategorised,NotTested))AS UNPVT;

I am not getting the required output
my result set need to be like this :
year    Legend  percent count
Dec-12  Good    13.89   35
Dec-12  Fair    0   0
Dec-12  Poor    0   0
Dec-12  NC  0   0
Dec-12  NoData  86.11   217

Suggest me the best way.

A: You did not specify what version of SQL Server you are using but using UNPIVOT for your data might be more difficult since you want to unpivot the columns in sets.  It might be easier to use CROSS APPLY to get the result:
select dateperiod,
  Legend,
  [Percent],
  [Count]
from yourtable t
cross apply
(
  select 'Good', Good, GoodPercentage union all
  select 'Fair', Fair, FairPercentage union all
  select 'Poor', Poor, PoorPercentage union all
  select 'NotCategorised', NotCategorised, NotCategorisedPercentage union all
  select 'NotTested', NotTested, NotTestedPercentage
) c (Legend, [Percent], [Count]);

See SQL Fiddle with Demo. If you are using a version of SQL Server that supports the VALUES clause then you could alter the above to the following:
select dateperiod,
  Legend,
  [Percent],
  [Count]
from yourtable t
cross apply
(
  values
    ('Good', Good, GoodPercentage),
    ('Fair', Fair, FairPercentage),
    ('Poor', Poor, PoorPercentage),
    ('NotCategorised', NotCategorised, NotCategorisedPercentage),
    ('NotTested', NotTested, NotTestedPercentage)
) c (Legend, [Percent], [Count]);

See SQL Fiddle with Demo. These give a result:
| DATEPERIOD |         LEGEND | PERCENT | COUNT |
|     Feb-13 |           Good |       4 |  6.25 |
|     Feb-13 |           Fair |       0 |     0 |
|     Feb-13 |           Poor |       0 |     0 |
|     Feb-13 | NotCategorised |       0 |     0 |
|     Feb-13 |      NotTested |      60 | 93.75 |

A: You can unpivot twice.
Select
    DatePeriod,
    Legend,
    amount,
    pc
FROM
(
select DatePeriod,
Good,Fair,Poor,NotCategorised,NotTested,GoodPercentage,
FairPercentage,poorPercentage,NotCategorisedPercentage,NotTestedPercentage
from yourtable
)P
UNPIVOT(Amount FOR  Legend IN (Good,Fair,Poor,NotCategorised,NotTested))AS UNPVT
unpivot(pc for var in (GoodPercentage, FairPercentage, PoorPercentage, NotCategorisedPercentage,NotTestedPercentage)) u2
where REPLACE(var,'Percentage','')=Legend

Or, if as it seems your data contains redundant information, do the percentage calculation
Select
    DatePeriod,
    Legend,
    amount,
    100.0*Amount/nullif(SUM(Amount) over (partition by dateperiod),0)

FROM
(
select DatePeriod,
Good,Fair,Poor,NotCategorised,NotTested,GoodPercentage,
FairPercentage,poorPercentage,NotCategorisedPercentage,NotTestedPercentage  from @t

)P
UNPIVOT(Amount FOR  Legend IN (Good,Fair,Poor,NotCategorised,NotTested))AS UNPVT


text:
Q: How to do Path filter for Release pipeline in Azure Devops I am doing one DevOps exercise, where I am maintaining the Code for different projects within an Azure DevOps Repo (one folder for one Project).Need to create single Release Pipeline for all.
I am trying to create a release pipeline, where I am using Artifact source as DevOps repo (because I am directly deploying ARM template, which do not require to be build). Now, I need to trigger release for change in that particular ARM folder (i.e. if change is done to Project 2).It should not be triggered, if I am doing change in Project1.
How can I achieve it?
It is feasible with Build Pipeline, becuase there we can add Path filter for respective folder. I did and that is working as expected, i.e. if I change in Project 1, only corresponding Build 1 will be triggered.
I am using classis editor for Azure DevOps release pipeline. And I do not see any option for Path filter while enabling CD trigger.

A: There is no such out of the box solution and you need to handle it manually to detect changes in like here
$files=$(git diff HEAD HEAD~ --name-only)
$temp=$files -split ' '
$count=$temp.Length
echo "Total changed $count files"
For ($i=0; $i -lt $temp.Length; $i++)
{
  $name=$temp[$i]
  echo "this is $name file"
  if ($name -like "SubFolderA/*")
    {
      Write-Host "##vso[task.setvariable variable=MicroserviceAUpdated]True"
    }
}

then you can use this variable in custom condition on specific deployment task.


text:
Q: Render ninja form inside markup I want to render a ninja form via markup (in a php file):

hello

  <ninja-form>           <---- ?

What do i put in there to render a particular ninja form?

A: <?php Ninja_Forms()->display(123) ?>


text:
Q: Perl - Dropping delimited text files into one Excel file with tabs Returning to Perl after some time off, I have been looking for a way to drop some tab delimited text files into an array and then into an Excel file; basically an Excel tab generated for each text file in a directory.  Generally the text files are a similar format.
The code below which has been cobbled from examples generally produces what I am after. However the output ignores any tabs and prints all text (per row) in one string. I am struggling with how to implement the tab delimiter into the code.  I know I will need to split the text files as they are pushed into the array.  I had been playing around with hashes, but I think I am looking too far into the problem, and it's likely to be an obvious answer that I am missing.
use warnings;
use strict;
use Cwd qw(abs_path);
use Spreadsheet::WriteExcel;

die "Log path ARG required " unless defined $ARGV[0];

my $path = abs_path( $ARGV[0] );

my $workbook = Spreadsheet::WriteExcel->new("resultsbook.xls");

chdir $path or die "no such directory: $!";
if ( -d $path ) {    ## test if $path given is a directory
    opendir my $dir, $path or die "can't open the directory: $!";
    while ( defined( my $file = readdir($dir) ) ) {
        chomp $file;
        next if $file eq '.' or $file eq '..';

        (my $sheetname = $file) =~s/\.\w+?//;
        my $wrksheet = $workbook->add_worksheet($sheetname);
        $wrksheet->write_col( 0, 0, [ @{ readfile($file) } ] );
    }
}

sub readfile {
    my $textfilecontent = [];
    open my $fh, '<', shift() or die "can't open file:$!";
    while (<$fh>) {
        chomp;
        push @{$textfilecontent}, $_, $/;
    }
    return $textfilecontent;
}

A: You need to split the lines with tab (or whatever delimiter) before pushing them into the @textfilecontent variable. There are a couple of other minor corrections in here:
use warnings;
use strict;
use Cwd qw(abs_path);
use Spreadsheet::WriteExcel;

die "Log path ARG required " unless defined $ARGV[0];

my $path = abs_path( $ARGV[0] );

my $workbook = Spreadsheet::WriteExcel->new("resultsbook.xls");

chdir $path or die "no such directory: $!";
if ( -d $path ) {    ## test if $path given is a directory
    opendir my $dir, $path or die "can't open the directory: $!";
    while ( defined( my $file = readdir($dir) ) ) {
        chomp $file;
        next if $file eq '.' or $file eq '..';

        (my $sheetname = $file) =~s/\.\w+//;
        my $wrksheet = $workbook->add_worksheet($sheetname);
        $wrksheet->write_col( 0, 0, readfile($file));
    }
}

sub readfile {
    my @textfilecontent = ();
    open my $fh, '<', shift() or die "can't open file:$!";
    while (<$fh>) {
      chomp;
      push @textfilecontent, [split(/\t/)];
    }
    return \@textfilecontent;
}


text:
Q: Why isn't my jQuery functioning So I am trying to use some jQuery on a site I am building, but nothing seems to get it working.
Here is how I have the files linked in my html:
<head>
    <title>Eddy: Designer</title>
    <link rel="stylesheet" type="text/css" href="main.css"/>
    <script language="javascript" type="text/javascript" src="jquery.js"></script>
    <script src="script.js"></script>
</head>

Then in my javascript document "script.js" I have this code:
$(document).ready(function () {
"use strict";
$('#branding').click(function () {
    $('.branding').removeClass('.hidden');
    $('.ui').addClass('.hidden');
    $('.logos').addClass('.hidden');
    $('.print').addClass('.hideen');
});
$('#ui').click(function () {
    $('.branding').addClass('.hidden');
    $('.ui').removeClass('.hidden');
    $('.logos').addClass('.hidden');
    $('.print').addClass('.hideen');
});
$('#logos').click(function () {
    $('.branding').addClass('.hidden');
    $('.ui').addClass('.hidden');
    $('.logos').removeClass('.hidden');
    $('.print').addClass('.hideen');
});
$('#print').click(function () {
    $('.branding').addClass('.hidden');
    $('.ui').addClass('.hidden');
    $('.logos').addClass('.hidden');
    $('.print').removeClass('.hideen');
}); });

My code editing software says that my $(document).ready is using a '$' before it is defined... I have no idea what that means or if that is what is causing me these issues.
The idea is, when I addClass '.hidden' it will make every image that ISN'T the category that the button is labeled go to 50% opacity. This would in a sense "highlight" all the items that are "branding" or what have you.
I have been looking at tutorials about using jQuery, and I can't find what is going wrong. Please help. I am stressing myself out over this.
I tried linking the jQuery like this:
        <link rel="stylesheet" type="text/css" href="main.css"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="script.js"></script>

This did not fix my problem. Is my jQuery code written incorrectly and that's why it isn't functioning? It seems like I am loading the jQuery properly, but it still doesn't work.

A: First you have dots in removeClass and addClass method. You need to pass only class names not .classname, only classname. And as other sad you should check your folder structure and try loading jQuery from some CDN.
In your CSS you have #branding and in HTML and JS it's a class. And you are adding classes the wrong way you in HTML. Multiple classes are separated by spaces in class attribute like:
class="one two"
not like class="one" class="two"
Try this fiddle , it's working xD, I have just commented opacity and use outline: solid 2px red;. So you could better see changes when clicked.


text:
Q: How is REQUEST object for a user in Django Views diffrentiated from one to another? I'm not sure if what I'm doing is right or wrong. But this functionality brought me across a very esoteric event happening inside Django Views.
So the code:
from django.contrib.messages import get_messages
from django.contrib import messages
#Other required modules.

@require_GET
def get_form(request):
    #code to get a form.
    storage = get_messages(request)
    for message in storage:
        message = message
    if message:
        context['message'] = message
    html = render(request , 'some_html.html' , context)
    return HttpResponse(html)

@require_POST
def submit_form(request):
    #Initialize a bounded form.
    if form.is_valid():
        form.save()
        messages.add_message(request, messages.INFO, success_message)
    else:
        messages.add_message(request, messages.INFO, error_message)
        # ABOVE LINE IS WHERE THE ISSUE OCCURS
        return redirect('reverse_url_mapping_to_get_form')
        # Above line is redirecting to "get_form" function(The function preceding this one).

ISSUE : Now the strange thing I encountered occurred when I made a typo in return redirect('reverse_url_mapping_to_get_form')(The last line of the code mentioned.).
Obviously I encountered Django's error page, saying that there is "NoReverseMatch". But when I reloaded the form(normal refreshing through the browser, on the "url" mapping to get_form(request)), I found that the error message which I added in the line messages.add_message(request, messages.INFO, error_message) was being brought to the html(some_html.html). Even thought the error occurred and I never redirected to the url successfully.
Now I understand that messages.add_message() somewhat piggybacks on the request, BUT, shouldn't it have been destroyed in the case when error occurred. The case where the redirect wasn't successfully executed.
Why did the message was still inside the request object when the reload occur?
Shouldn't it have been destroyed(because it was a completely independent GET request; I initiated it from my browser by reloading)?
Thanks in advance.

A: You've completely misunderstood how the messages framework works. It does not store the messages in the request; they are stored in the session.


text:
Q: Prevent sort result of union in entity framework In SQL server union, result is sorted based on primary key column. I want to prevent this behavior in entity framework.
In this post, @praveen has explained how to do this in pure sql. But I want to do this in entity framework.
My code:
public virtual ActionResult Search(string keyword)
{
    var products = _db.Products
        .Where(x => x.IsActive)
        .AsQueryable();

    var productExactlyTitle = products.Where(x => x.Title == keyword);
    var productStartTitle = products.Where(x => x.Title.StartsWith(keyword));
    var productContainsTitle = products.Where(x => x.Title.Contains(keyword)
                                                   || x.Title.Contains(keyword)
                                                   || x.SubTitle.Contains(keyword)
                                                   || x.OtherName.Contains(keyword));

    var productList = productExactlyTitle.Union(productStartTitle)
        .Union(productContainsTitle)
        .Take(10)
        .AsEnumerable()
        .Select(x => new ProductItemViewModel()
        {
            Id = x.Id,
            Title = x.Title,
            Price = x.Price.ToPrice(),
            Image = x.Images.FirstOrDefault(y => y.IsCoverPhoto)?.ImageUrl
        });

        // some code ...
}

I want to show records with below order:
First: records of productExactlyTitle
Second: records of productStartTitle
Third: records of productContainsTitle
But result is sorted with Id column! and I don't want this.
Is there a way for do this?

A: In SQL all queries without an order by explicitly set is considered unordered. (and EF queries a translated into SQL). So if you want a specific order after your union just specify it.
var result = q1.Union(q2).OrderBy(x => x.?);

For your specific case:
var p1 = productExactlyTitle.Select(x => new { Item = x, Order = 1 });
var p2 = productStartTitle.Select(x => new { Item = x, Order = 2 });
var p3 = productContainsTitle.Select(x => new { Item = x, Order = 3 });
var productList = p1.Union(p2)
                    .Union(p3)
                    .OrderBy(x => x.Order)
                    .Select(x => x.Item)
                    .Take(10);


text:
Q: Принципы ООП. Интерфейс Пишу класс для работы с матрицами. Указатель и кол-во строк и столбцов сокрыто, это понятно. Пришла в голову мысль, что можно для доступа к элементу матрицы возвращать ссылку (m[i][j]), а если пользователь запросит несуществующий элемент, вернуть затычку и сгенерировать исключение. Но у меня сомнения по поводу того, насколько нормальна такая практика? У кого есть опыт работы с ООП, хочется услышать ваше мнение.
Для наглядности, по моей задумке можно будет делать так mtrx.get(i,j) = value.

A: Возвращать нужно уметь две ссылки, константную и неконстантную. И да, это правильная практика.
Константая ссылка нужна для того, чтобы вашу матрицу можно было всю делать константой, без нее - не скомпилируется.
Учтите, что стандартная библиотека C++ в операции [] не проверяет индексы у контейнеров-массивов, и для снижения WTF/seс будет лучше этому правилу следовать - иначе ваш класс матриц будет лютой черепахой, и вызывать у читателя кода справедливое негодование ("какого черта индекс швыряет исключения?!").
Если вы пишете с надеждой написать что-то быстрое (догнать и перегнать MKL!), то исключения вам придется вырубить совсем, опциями компилятора.


text:
Q: Vale a pena colocar duas chaves estrangeiras numa tabela? tendo as tabelas:

*

*Empresas

*Clientes

*

*empresa_id: chave estrangeira

*Vendas

*

*cliente_id: chave estrangeira

sendo que as relações são:

*

*Empresas e Clientes => 1:N

*Clientes e Vendas => 1:N

Considerando que irei precisar listar todas as vendas da empresa, vale a pena criar uma segunda chave estrangeira na tabela vendas para que eu possa fazer:
SELECT * FROM `vendas` WHERE `empresa_id` = 'x'

A: Pela descrição deve usar sim, mas não é certo. Precisa da performance? Uma coisa que eu vejo muito em relatórios é não precisar, mas depende do caso. Quanto mais índices coloca mais lento fica para atualizar as tabelas e isso pode ser crítico em certos ambientes.
É perfeitamente possível fazer sem ter a chave estrangeira, mas fazer um JOIN sem ela pode tornar tudo muito mais lento.
É uma questão de medição. Você faz e mede e vê se compensa ou não para a sua necessidade.
Veja:

*

*Quais as vantagens e desvantagens do uso de índices em base de dados?

*Índices desnecessários no banco são um problema?

*Índices em consultas no MySQL

A: Tendo em conta que já existe uma chave estrangeira empresa_id na tabela Clientes e uma venda pressupõe sempre um cliente (através do campo cliente_id, suponho que seja NOT NULL), não será necessário criar uma chave estrangeira para a empresa na tabela Vendas. Aliás, duplicação de informação (assim como de código) nunca é boa prática.
Como já foi referido, a consulta SQL para filtrar por empresa é simples:
SELECT      *
FROM        Vendas      V
INNER JOIN  Clientes    C ON V.cliente_id = C.id
WHERE       C.empresa_id = 'X'


text:
Q: Rails Nested / Multi-level AREL Query I have 3 models:
Tiersets
  has_many Tiers

Tiers
  belongs_to Tierset
  has_and_belongs_to_many Features

Feature
  has_and_belongs_to_many Tiers

In Feature, I have a String column named Feature_Code that contains one of the following strings: "F_VIZ", "F_DATA", "F_SCORE".
I'm trying to construct a query to find, within a known Tierset, all the Feature objects with code F_VIZ in all Tier objects for that Tierset.
I've tried a bunch of combinations of :includes in AREL queries, but I'm clearly getting mixed up with how the tables are joined. Any help is much appreciated.

A: The SQL you want is
select * from features, features_tiers, tiers where features_tiers.id = features.id and features_tiers.tier_id = tiers.id and features.code = 'F_VIZ' AND tierset_id = ?;

so we'll translate this directly to ActiveRecord:
Feature.joins(:tiers).where(:code => 'F_VIZ', 'tiers.tierset_id' => 1)

Which is a bit cleaner, since AR 'knows' about the implicit join table between features and tiers based on how your associations are set up.