text:
Q: How do I join two table on a column and group by on another column Lets say I have two franchise of dance schools.
I have two tables. First table tells about students roll no. every
Table 1 =
Roll No.    Center ID   Name    Date
1   A   Anna    10/10/2020
1   A   Anna    11/10/2020
1   B   Anna    12/10/2020
2   A   Bella   12/10/2020
2   B   Bella   13/10/2020
3   A   Catty   10/10/2020

Table 2 =
Roll no.    Center ID   Report
1   A   Did well
1   A   Sick
1   B   Needs more twist
2   A   Practice required
2   B   Did well
3   A   Needs more practice

Result table expected: I want in the result it should pick Center id as A only but Report should be from both the centers
Roll no.    Center ID   Report  Name
1   A   Did well ,Sick ,Needs more twist    Anna
2   A   Practice required,Did well  Bella
3   A   Needs more practice Catty

Could someone pls help.

A: By dplyr,
t1 %>%
  mutate(Report = t2$Report) %>%
  group_by(Roll_No.) %>%
  summarise(Center_ID = "A",
    Report = paste0(Report, collapse = ', '),
    Name = unique(Name)
    )

  Roll_No. Center_ID Report                           Name
     <int> <chr>     <chr>                            <chr>
1        1 A         Did well, Sick, Needs more twist Anna
2        2 A         Practice required, Did well      Bella
3        3 A         Needs more practice              Catty

A: library(tidyverse)

a <- tribble(
  ~Roll, ~Center, ~Name, ~Date,
  1, "A", "Anna", "10/10/2020",
  1, "B", "Anna", "12/10/2020",
  3, "A", "Catty", "10/10/2020"
)

b <- tribble(
  ~Roll, ~Center, ~Report,
  1, "A", "Dis well",
  1, "A", "Sick",
  1, "B", "Needs more twist",
  3, "A", "Needs more practice"
)

a %>%
  left_join(b) %>%
  group_by(Roll, Center) %>%
  summarise(
    Report = c(Report, Name %>% unique()) %>% paste0(collapse = ",")
  )
#> Joining, by = c("Roll", "Center")
#> `summarise()` has grouped output by 'Roll'. You can override using the `.groups` argument.
#> # A tibble: 3 x 3
#> # Groups:   Roll [2]
#>    Roll Center Report
#>   <dbl> <chr>  <chr>
#> 1     1 A      Dis well,Sick,Anna
#> 2     1 B      Needs more twist,Anna
#> 3     3 A      Needs more practice,Catty

Created on 2021-10-05 by the reprex package (v2.0.0)

A: With dplyr package:
library(dplyr)
cbind(df1, Report=df2$Report) %>% group_by(Name) %>%
  summarize(RollNo=first(RollNo), CenterID=first(CenterID), Report=paste(toString(Report), first(Name), collapse='  '))

Output:
  Name  RollNo CenterID Report
  <chr>  <dbl> <chr>    <chr>
1 Anna       1 A        Did well, Sick, Needs more twist Anna
2 Bella      2 A        Practice Required, Did well Bella
3 Cathy      3 A        Needs more practice Cathy

A: update:
With the hint of @Park many thanks!:
Logic:

*

*left_join by RollNo.

*filter, group_by and summarise
library(dplyr)
table1 %>%
  left_join(table2, by=c("RollNo."="Rollno.")) %>%
  filter(CenterID.x== "A") %>%
  group_by(RollNo., CenterID=CenterID.x, Name) %>%
  summarise(Report = paste(unique(Report), collapse = ", "))

output:
  RollNo. CenterID Name  Report
    <dbl> <chr>    <chr> <chr>
1       1 A        Anna  Did well, Sick, Needs more twist
2       2 A        Bella Practice required, Did well
3       3 A        Catty Needs more practice

First answer:
We could try this: It is depending on whether Date should be considered or not, so you may modify the code:

table1 %>%
  left_join(table2, by=c("CenterID", "RollNo."="Rollno.")) %>%
  filter(CenterID == "A") %>%
  group_by(RollNo., CenterID, Name) %>%
  summarise(Report = paste(unique(Report), collapse = ", "))

    RollNo. CenterID Name  Report
    <dbl> <chr>    <chr> <chr>
1       1 A        Anna  Did well, Sick
2       2 A        Bella Practice required
3       3 A        Catty Needs more practice


text:
Q: Passing websocket streaming data to child in reactJS constructor(){
    super();
    this.state = {
        chartData : {}
    };

    let ws = new WebSocket('link');

    ws.onopen = function () {
        console.log('Successfully connected WebSocket!');
    };

    ws.onmessage = function (msg) {
        console.log("Message: " + msg.data);
        try {

            //Parse the message
            let obj = JSON.parse(msg.data);

        }catch(err){
            console.log('Error in onmessage: ' + err);
        }

    };
}
getChartData(){
    this.setState({chartData:[2,3,4,5,6] }) //Want to send obj from onmessage
}

componentWillMount(){
    this.getChartData();

};

render() {
    return (
     <div className="wrap">
       <Chart chartData={this.state.chartData} />
    )
}

This works fine if I have pasted the correct code!
I get the data in Chart component such as:
 constructor(props){
    super(props);
    this.state = {
        chartData:props.chartData
    };
};

My question is, how do I send the obj from the ws.onmessage function because this function receives data every second.

A: You're already keeping the chart data in state and passing it down as a prop. So, simply have your onmessage listener update your component state every time it gets new data.
ws.onmessage = (msg) => {
    console.log("Message: " + msg.data);
    try {

        //Parse the message
        let obj = JSON.parse(msg.data);
        this.setState({chartData: obj});

    }catch(err){
        console.log('Error in onmessage: ' + err);
    }
};

Note that the listener is now an arrow function so that it retains the proper this context.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Alterar o título e as cores da legenda no ggplot2 Como faço para alterar o campo pop e continent. Quero colocar em português (População e Continente). Os dados estão no R através do pacote library(gapminder).
Utilizei o seguinte comando:
library(gapminder)
library(dplyr)
library(ggplot2)
gapminder_2007 <- filter(.data=gapminder,year==2007)
ggplot(data=gapminder_2007,aes(x=gdpPercap,y=lifeExp,color=continent,size=pop)) +
   labs(title="PIB e Expectativa de Vida em 2007", subtitle="",
   y="Expectativa de Vida",x="PIB Per capita", caption="") +
   geom_point() +
   scale_x_log10()

Resultado:

A: Use os argumentos color e size dentro da função labs:
ggplot(data=gapminder_2007,aes(x=gdpPercap,y=lifeExp,color=continent,size=pop)) +
  labs(title="PIB e Expectativa de Vida em 2007", subtitle="",
       y="Expectativa de Vida",x="PIB Per capita", caption="",
       color = "Continente",
       size = "População") +
  geom_point() +
  scale_x_log10()

Ou
ggplot(data=gapminder_2007,aes(x=gdpPercap,y=lifeExp,color=continent,size=pop)) +
  labs(title="PIB e Expectativa de Vida em 2007", subtitle="",
       y="Expectativa de Vida",x="PIB Per capita", caption="") +
  geom_point() +
  scale_x_log10() +
  guides(color=guide_legend(title="Continente")) + # Argumentos para os títulos das legendas
  guides(size=guide_legend(title="População"))

Edição: Escolher as cores dos países:
Para alterar as cores do país você pode usar qualquer opção do scale_color_****

*

*scale refere-se ao nome da função para realizar alterações de
cores; `

*colorrefere-se ao nome do argumento que você colocou noaes` que tu quer alterar;

****** refere-se ao modo que você quer    informar as cores. Você
pode passar os valores da forma manual, brewer, e demais formas (essas são as principais/quais eu uso).

Na opção manual, você deve informar os nomes das cores manualmente:
ggplot(data=gapminder_2007,aes(x=gdpPercap,y=lifeExp,color=continent,size=pop)) +
  labs(title="PIB e Expectativa de Vida em 2007", subtitle="",
       y="Expectativa de Vida",x="PIB Per capita", caption="",
       color = "Continente",
       size = "População") +
  geom_point() +
  scale_x_log10() +
  scale_color_manual(values = c("green", "red", "yellow", "gray11", "blue")) #Informa aqui as cores!

Usando a paleta de cor Spectral de color brewer:

ggplot(data=gapminder_2007,aes(x=gdpPercap,y=lifeExp,color=continent,size=pop)) +
  labs(title="PIB e Expectativa de Vida em 2007", subtitle="",
       y="Expectativa de Vida",x="PIB Per capita", caption="",
       color = "Continente",
       size = "População") +
  geom_point() +
  scale_x_log10() +
  scale_color_brewer(palette = "Spectral")


text:
Q: Counteracting g-force Is it possible to counter-act g-force for a jet-pilot, by him putting on a scuba-diving suit
and filling the cockpit with water? On earth we are constantly pulled down, or accelerated with one g. In this situation, if we put the jet-pilot in a pool, he would neither sink nor float.
If we could increase Earth's gravity to say 9 g's, the pilot in the pool would float even more.
Is this correct? Thanks...

A: If you fill the cockpit with water, the pilot will feel a buoyant force.  Humans have about the same density as water, so ignoring the scuba suit, the pilot will feel a buoyant force about equal to his own weight.
The plane's maneuvers don't change this result much.  By the equivalence principle, when the plane accelerates, the water in the cockpit and the pilot both get heavier.  The buoyancy changes in the same way the pilot's weight does.  If he feels weightless before takeoff, he'll continue feeling weightless during maneuvers.  If he's supported by buoyancy before takeoff, he'll continue to be supported by buoyancy during maneuvers.  (This assumes that the jerk, or time derivative of acceleration, is low enough that the water can remain in hydrostatic equilibrium during the maneuver.)
Although basic buoyancy works the same, there will be a pressure change during accelerations.  If the plane is accelerating up at 9g, he'll feel pressure as if he's under water ten times as deep as he really is dense as the water really is.  As Bruce pointed out, this is a big pressure gradient, and the pilot will still realize that the force beneath him pushing up is stronger than the force above pushing down.  He will essentially feel heavy.
Ignoring compression, changing Earth's gravity won't change whether something sinks or floats.  Something more dense than water sinks.  Something less dense floats.  If we multiply gravity by some constant, an object immersed in water has the net force on it also multiplied by that constant.  So if you have something that floats and has a net force on it of $1N$ upward under normal gravity, if you double the gravity, it will experience a net upward force of $2N$ and have double the acceleration (ignoring drag).

A: Your logic is mostly precise, but it won't counteract g-forces.
(I'll assume the jet flyes straight up, for simplicity, but it doesn't make any difference.)
Like you said, if the pilot was originally in equilibrium inside the water and we accelerate the jet at 9g, the buoyancy would get 10 times as strong (9+1). However, the pilot will still feel a force accelerating him. The only difference is that, instead of being pushed by the jet seat, he will be pushed up by the water itself.
So he will still feel the g-force, only a little differently. Instead of the force being concentrated on the area of contact between him and the seat, it will be distributed through the area of contact between him and the water (approximately half of it, to be more precise). But the net force will be the same.
The final effect will be that he'll float inside the water. The water is accelerating up with the jet, and he'll accelerate up as well (because of all the extra buoyancy).
If he were submersed in a heavier fluid to start with, the effect would be the same, except he would float partially above water.
If he were submersed in a lighter fluid to start with, then he would be able to touch his jet seat, and the upward acceleration would come partially from the seat and partially from the liquid.

A: If you suspended a jellyfish in a bucket of water and accelerated the bucket upwards at say 100g, the jellyfish will remain stationary relative to the water. IE the jellyfish will not experience any acceleration, it is weightless as it normally is. All of the additional forces due to acceleration are imparted on the buckets bottom and sides.
So by this rational the human body should be able to withstand very high g forces when submerged in water, as long as all air cavities were filled with fluid of equal density.

A: I came upon this discussion while musing about the effects of spinoculation on cells in culture (e.g., see http://www.ncbi.nlm.nih.gov/pubmed/21795326).  Forgive me, I'm a virologist and not a physicist, though I did teach 8th grade physical sciences for a while and was often challenged to go far beyond the text and understand things more deeply than the most curious and intelligent student in the class.  It seems with respect to the pilot that both Connor and Eichenlaub may be correct in their own way, depending upon what one means by "feeling."  We tend to "feel" acceleration via our inner ear which, being encased in a bony homeostatic case, is not subjected to the equilibrating pressures of the surrounding water.  On the other hand, the pilot's posterior would feel relatively fine, and he would presumably not suffer blackout from acceleration because (as with a pilot's pressure suit), blood would not be depleted from his brain.  So, assuming the pilot was breathing (necessarily pressurized) air during a long acceleration, would he (she) get the bends when acceleration ceased? Sounds like an "ask NASA" question.  It all might be relevant to spinoculation, in which cells do survive but change.


text:
Q: Bad loops with JSP Trying to traverse 2 arrays and compare if the entities are equal for setting the "selected" propierty
Wanted something like this:

And I got this:

In the code:
items="${listadoPaises}" var="pais" is allCountries (allPaises)
items="${divisa.paises}" var="paisoption" is the countries I want to be checked
<select multiple id="paisesSeleccionados" name="paisesSeleccionados">
    <option value="" disabled>País</option>
        <c:forEach items="${listadoPaises}" var="pais">
            <c:forEach items="${divisa.paises}" var="paisoption">

                <c:choose>
                    <!-- If the id is equal, set the SELECTED property -->
                    <c:when test="${pais.idpais==paisoption.idpais}">

                        <option selected value="${pais.idpais}" data-icon="${pageContext.request.contextPath}/resources/flags/${pais.siglas}.png">
                            ${pais.nombre}
                        </option>
                    </c:when>
                    <!-- Else, not setting the property -->
                    <c:otherwise>

                        <option value="${pais.idpais}" data-icon="${pageContext.request.contextPath}/resources/flags/${pais.siglas}.png">
                            ${pais.nombre}
                        </option>
                    </c:otherwise>
                </c:choose>

            </c:forEach>
        </c:forEach>
</select>

It has to be a little mistake, maybe it´s easy but i´m getting totally crazy.
Thank you guys.

A: I got it. I had to add a new a <% and <%= expression tag with the selected string to fix it. Here the code:
<select multiple id="paisesSeleccionados" name="paisesSeleccionados">
    <option value="" disabled>País</option>

    <c:forEach items="${listadoPaises}" var="pais">
        <% String selected=""; %>
        <c:forEach items="${divisa.paises}" var="paisoption">

            <c:if test="${pais.idpais==paisoption.idpais}">
                <% selected="selected"; %>
            </c:if>

        </c:forEach>
        <option <%= selected %> value="${pais.idpais}" data-icon="${pageContext.request.contextPath}/resources/flags/${pais.siglas}.png">${pais.nombre}</option>
    </c:forEach>

</select>


text:
Q: Deploying flask with sqlite to heroku When I push my app to Heroku it does use the data_base.db and if i try to add a user to the data base I get the error that no data base is found
2021-08-15T13:02:39.226938+00:00 app[web.1]: cursor.execute(statement, parameters)
2021-08-15T13:02:39.226938+00:00 app[web.1]: sqlite3.OperationalError: no such table: users

Does heroku forbid the use of sqlite  or am I doing something wrong
This is config.py
import random
import string

class Config:

    SECRET_KEY = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(60))

    SQLALCHEMY_DATABASE_URI = 'sqlite:///data_base.db'
    SQLALCHEMY_TRACK_MODIFICATIONS = False

class DevelopmentConfig(Config):
    DEBUG = True

class ProductionConfig(Config):
    DEBUG = False

config = {
    'dev' : DevelopmentConfig,
    'prod': ProductionConfig,
    }

A: replace this
SQLALCHEMY_DATABASE_URI = 'sqlite:///data_base.db'

with
uri = os.getenv("DATABASE_URL")
if uri.startswith("postgres://"):
    uri = uri.replace("postgres://", "postgresql://", 1)

SQLALCHEMY_DATABASE_URI = uri or 'sqlite:///data_base.db'

simply tells the app to use postgresql when deployed to heroku
and don't forget to add psycopg2 to the requirements.txt file


text:
Q: SurfaceView onMeasure() did not set the measured dimension by calling setMeasuredDimension() I have a SurfaceView. I just draw on it manually from an other Thread.
It runs nicely. But after 10-20 minutes of running in average I get this exception:
01-14 08:51:25.000    3740-3740/com.myPackage E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.IllegalStateException: onMeasure() did not set the measured dimension by calling setMeasuredDimension()
            at android.view.View.measure(View.java:15200)
            at android.widget.RelativeLayout.measureChild(RelativeLayout.java:602)
            at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:415)
            at android.view.View.measure(View.java:15195)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4823)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at android.view.View.measure(View.java:15195)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4823)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
            at android.view.View.measure(View.java:15195)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4823)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2340)
            at android.view.View.measure(View.java:15195)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1850)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1102)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1275)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4216)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
            at android.view.Choreographer.doCallbacks(Choreographer.java:555)
            at android.view.Choreographer.doFrame(Choreographer.java:525)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4813)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:559)
            at dalvik.system.NativeStart.main(Native Method)

Android Documention says:
Measure the view and its content to determine the measured width and the measured height. This method is invoked by measure(int, int) and should be overriden by subclasses to provide accurate and efficient measurement of their contents.
As I think the original implementation from google is this:
@Override
    protected void More ...onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = getDefaultSize(mRequestedWidth, widthMeasureSpec);
        int height = getDefaultSize(mRequestedHeight, heightMeasureSpec);
        setMeasuredDimension(width, height);
    }

I don't know what I else should I implement here.
I think the size of the surface view never changes.
NOTE:
My SurfaceView is contained in a RelativeLayout.
The exception is called by a child, but it's a view (line 3 in the exception)
Please help me if you know how could I solve this annoying bug.
EDIT:
In Activity's onCreate I set the size of my view (that extended form SurfaceView) from code
Answear to comment:
This is how I set some public fields for the required size:
Parameters.initialize(getResources().getDisplayMetrics().widthPixels,
                getResources().getDisplayMetrics().heightPixels);

The Parameters.initialize:
public static void initialize(int screenWidth, int screenHeight){
    FIELD_WIDTH = screenWidth;
    FIELD_HEIGHT = (int)(0.92f * screenHeight);
}

MyView is written in the xml.
Then I set something on it:
public class MyViewManager {
    protected MyView mMyView;

    public FieldPainterComp(MainActivity activity) {
        super(activity);
        initialize();
    }

    private void initialize(){
        mMyView= (MyView) activity.findViewById(R.id.vMyView);
        mMyView.getLayoutParams().height = Parameters.FIELD_HEIGHT;
        mMyView.getLayoutParams().width = Parameters.FIELD_WIDTH;
    }
}

This whole process happens ones in the beginning.
android:screenOrientation="landscape"

Screen never goes dark. Game is running, and simply the exception is coming.
Should I call measure somewhere?
I don't understand why is it happaning after a long time
Some other exception that must be in connected with this:
01-19 11:53:39.812  29666-31881/com.mypackage V/GAV4﹕ Thread[disconnect check,5,main]: Disconnecting due to inactivity
01-19 11:53:39.812  29666-31881/com.mypackage V/GAV4﹕ Thread[disconnect check,5,main]: Disconnected from service
01-19 11:57:17.732  29666-29666/com.mypackage D/AndroidRuntime﹕ Shutting down VM
01-19 11:57:17.732  29666-29666/com.mypackage W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x420face0)
01-19 11:57:17.812  29666-29666/com.mypackage V/GAV4﹕ Thread[main,5,main]: Tracking Exception: IllegalStateException (@View:measure:16533) {main}
01-19 11:57:17.832  29666-29666/com.mypackage V/GAV4﹕ Thread[main,5,main]: Dispatch call queued. Dispatch will run once initialization is complete.
01-19 12:19:27.982  29666-29670/com.mypackage I/dalvikvm﹕ threadid=3: reacting to signal 3
01-19 12:19:28.262  29666-29670/com.mypackage I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
01-19 12:19:32.452  29666-29666/com.mypackage A/libc﹕ Fatal signal 6 (SIGABRT) at 0x0000025a (code=0), thread 29666 (ames.adaptation)

The GAV -is the Google Analytics stuff.
I launched an other question about the ANR: ANR with 3 threads - using locks

A: setMeasuredDimension()

Must be called inside of your onMeasure() method.  I had a similar problem where the logic wasn't reaching setMeasuredDimension().  I resolved it forcing the call of setMeasuredDimension() no matter what the if/else statements preceded it.

A: You use Fragment and don't write this line at the first
super.onCreate(savedInstanceState);

A: private double aspectRatio = 1.0;
private boolean isCalledRecreate = true;
in onMeasure ::-
double localRatio = aspectRatio;
    if (localRatio == 0.0) {
        super.onMeasure(widthSpec, heightSpec);

    } else {
        int lockedWidth = MeasureSpec.getSize(widthSpec);
        int lockedHeight = MeasureSpec.getSize(heightSpec);

        if (lockedWidth == 0 && lockedHeight == 0) {

            widthSpec = MeasureSpec.makeMeasureSpec((int) (basicWidth), MeasureSpec.AT_MOST);
            heightSpec = MeasureSpec.makeMeasureSpec((int) (basicHeight), MeasureSpec.AT_MOST);

            lockedWidth = MeasureSpec.getSize(widthSpec);
            lockedHeight = MeasureSpec.getSize(heightSpec);

            Log.i(TAG, "onMeasure: onMeasure");

            callForRecreate();
        }

        // Get the padding of the border background.
        int hPadding = getPaddingLeft() + getPaddingRight();
        int vPadding = getPaddingTop() + getPaddingBottom();

        // Resize the preview frame with correct aspect ratio.
        lockedWidth -= hPadding;
        lockedHeight -= vPadding;

        if (lockedHeight > 0 && (lockedWidth > lockedHeight * localRatio)) {
            lockedWidth = (int) (lockedHeight * localRatio + .5);
        } else {
            lockedHeight = (int) (lockedWidth / localRatio + .5);
        }

        // Add the padding of the border.
        lockedWidth += hPadding;
        lockedHeight += vPadding;

        // Ask children to follow the new preview dimension.
        super.onMeasure(MeasureSpec.makeMeasureSpec(lockedWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(lockedHeight, MeasureSpec.EXACTLY));

Note :- callForRecreate() in that you have to create or restart activity

A: Make sure to call
super.onMeasure(widthMeasureSpec,heightMeasureSpec);
//e.g
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec,heightMeasureSpec);
//then your code
}


text:
Q: How to display text in the second and third xml element which have the same name using xslt I would like to know if I can display the names by using the values of the xml part using xslt. If that is not possible then how would I simply display the names using xslt? I would also like to know can xslt change an element name in the xml?
My xml is this
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="myxmltest.xsl type="text/xsl" version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" ?>

<x>
 <y>
  <z value="mike"></z>
  <z value="john"></z>
  <z value="dave"></z>
 </y>
</x>

My xsl is this
<?xml version="1.0"?>

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:strip-space elements="*" />

<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*" />
</xsl:copy>
</xsl:template>

<xsl:template match="z">
<xsl:apply-templates select="z[1]" />mike
</xsl:template>

<xsl:template match="z">
<xsl:apply-templates select="z[2]" />john
</xsl:template>

<xsl:template match="z">
<xsl:apply-templates select="z[3]" />dave
</xsl:template>

</xsl:stylesheet>

Desired result in the xml is:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="myxmltest.xsl type="text/xsl" version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" ?>

<boss>
 <manager>
  <employee value="mike">mike</employee>
  <employee value="john">john</employee>
  <employee value="dave">dave</employee>
 </manager>
</boss>

A: The result you show can be easily accomplished by:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="x">
    <boss>
        <xsl:apply-templates/>
    </boss>
</xsl:template>

<xsl:template match="y">
    <manager>
        <xsl:apply-templates/>
    </manager>
</xsl:template>

<xsl:template match="z">
    <employee value="{@value}">
        <xsl:value-of select="@value"/>
    </employee>
</xsl:template>

</xsl:stylesheet>


text:
Q: ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist ORACLE 10g XE
Dont know what went wrong.
It worked perfectly first time untill i restarted my Machine.

A: It looks like your database didn't start automatically after your machine rebooted, and you're trying to connect as SYS in order to start it. You're currently trying to connect without specifying the SYSDBA role.
$ sqlplus /nolog

SQL*Plus: Release 11.2.0.2.0 Production on Thu Feb 16 16:04:26 2017

Copyright (c) 1982, 2010, Oracle.  All rights reserved.

SQL> connect sys/12345
ERROR:
ORA-01034: ORACLE not available
ORA-27101: shared memory realm does not exist
SVR4 Error: 2: No such file or directory
Process ID: 0
Session ID: 0 Serial number: 0

With the role specified it connects to the idle instance:
SQL> connect sys/12345 as sysdba
Connected to an idle instance.
SQL>

You can then issue the startup command.
You can also connect straight from the command line:
$ sqlplus / as sysdba

SQL*Plus: Release 11.2.0.2.0 Production on Thu Feb 16 16:07:47 2017

Copyright (c) 1982, 2010, Oracle.  All rights reserved.

Connected to an idle instance.

SQL>

The password you supply for SYS can be anything, as it relies on OS authentication anyway. You have to supply the role though. And be logged in to the OS as a user in the right group, of course, and have $ORACLE_HOME and $ORACLE_SID set correctly, etc.

A: In addition to Alex's explanation, in particular the bit about the database not restarting automatically when you restarted your machine:
Navigate to /etc/oratab and edit it as root.
Find the line
orcl:/u01/app/oracle/product/12.1.0/db_1:N

Change the N at the very end to Y.
This will make the database start up whenever you restart your machine, so you won't have this trouble again.

A: Set environment variable ORACLE_HOME and ORACLE_SID should fix.
ORACLE_HOME=\<your path>\oracle\product\10.2.0\server
ORACLE_SID=xe

Obviusly you have to configure database to startup automatically.
To do so you need to set flag Y to youre instance in /etc/oratab
and create appropriate /etc/init.d/dbora

A: As "chkconfig" doesnt work now.
I tried using sysv-rc-conf but the command not found:
then,
i tried apt-get install sysv-rc-conf
but then shows
E: Unable to locate package sysv-rc-conf
{
i was trying to config : " /etc/init.d/dbora " file to let my database to autostart.
}

A: This set of errors can occur when you don't have properly set ORACLE_SID and ORACLE_HOME variables.
Note, the ORACLE_HOME variable is supposed not to end with a slash char. So, even though it seems everything is configured fine, trailing slash in the ORACLE_HOME value will lead to the issue too:
# wrong:
export ORACLE_HOME=/usr/local/oracle/11gR2/

# correct:
export ORACLE_HOME=/usr/local/oracle/11gR2


text:
Q: NodeJS: Sharing Application State Between Modules I am working on a node.js application that is intended to be globally installed using npm. I am using commander in order to expose multiple commands to the command line. i.e. my-app serve and my-app clean. The problem I'm running into is that there is some data that I want all of my JS files in my lib directory to have access to, however from what I can tell, I should be avoiding the global object.
Here is the solution I came up with:
In my lib directory, I have a file named shared-state.js. Its contents:
var initialized = false;

var SHAREDSTATE = module.exports = {
    init: function( stateToShare ) {
        if ( !initialized ) {
            SHAREDSTATE.data = stateToShare;
            initialized = true;
        } else {
            // log warning about calling init > 1 time
        }
        return SHAREDSTATE;
    }
};

As long as I call init during my application's start-up, I can write the following code to get access to the shared data.
var sharedState = require('./shared-state').data;

This is a distilled example to illustrate the pattern I am following. In reality I am taking steps to make the data read-only for any modules that are consuming it, and I am appropriately handling the case where init is called multiple times.
My question is this: Am I crazy for going to these lengths to avoid the global object? Is this an established pattern in node? What is it called? If it is not, how are other people solving a similar issue?


text:
Q: How to allocate memory in user space I need to allocate memory in a program without using Zwallocatevirtualmemory. The code works but I have a memory leak because the memory belongs to the kernel and not to the program. How can I transfer her ownership?
The only solution I see is to save the mdl and attach a callback to close the process. When the program is closed, the driver will release the memory. But here's the problem, if the driver is unloaded before the program closes, there will be a memory leak.
BOOLEAN allock_mem(DWORD PID, DWORD Size)
{
    __try
    {
        NTSTATUS status = STATUS_SUCCESS;
        PEPROCESS process;
        PsLookupProcessByProcessId((HANDLE)PID, &process);

        KAPC_STATE state;
        KeStackAttachProcess(process, &state);

        PVOID mem = ExAllocatePool(NonPagedPool, 409600000);

        PMDL mdl = IoAllocateMdl(mem, 409600000, FALSE, FALSE, NULL);
        if (!mdl)return FALSE;

        MmProbeAndLockPages(mdl, KernelMode, IoReadAccess);
        //MmProbeAndLockProcessPages(mdl, process, KernelMode, IoReadAccess);
        PVOID mapping = MmMapLockedPagesSpecifyCache(mdl, UserMode, MmNonCached, NULL, FALSE, NormalPagePriority);
        MmProtectMdlSystemAddress(mdl, PAGE_READWRITE);

        //MmUnmapLockedPages(mapping, mdl);
        MmUnlockPages(mdl);
        DbgPrintEx(0, 0, "MmUnlockPages\n");
        IoFreeMdl(mdl);
        DbgPrintEx(0, 0, "IoFreeMdl\n");
        KeUnstackDetachProcess(&state);
        DbgPrintEx(0, 0, "KeUnstackDetachProcess\n");
    }
    __except (1)
    {
        DbgPrintEx(0, 0, "__except\n");
    }

    return TRUE;
}


text:
Q: Retrieve order of draggable list I'm a complete newby to html, javascript and to d3, so I apologize if my question is completely obvious.
I have a html list

item 1

item 2

item 3

item 4

and what I want is to be able to sort the list (by dragging the items for example) and then print the list current order in an html span field, for example

["item 3","item 4","item 2","item 1"]

This information will drive my datasource sort in a D3 graph after. I know that it should be really simple but ...
What I was trying was to use the js "Sortable" script of rubaxa found here . With this script I was able to drag and "sort" the list, but I just don't know how to retrieve the list order.
Any other suggestion about how to do the drag and sort list and how to retrieve the order are welcome. Please have in mind that I'm a total newby. Thanks

A: You probably want to do some housekeeping using for example data-attributes to store ids.

actual content

actual content

actual content

actual content

Let's now define a function to calc the order:
function getOrderOfData(listId){

    //get the list
    var list = document.getElementById(listId);

    //and iterate the children in order. Get the myId property and add (in order)
    //to array.
    var orderArray = [];
    var childs = list.children;
    for(var i=0; i< childs.length; i++){
      var child = childs[i];
      orderArray.push(child.dataset.myId);
    }

    return orderArray;

    //NOTE: the native map probably doesn't work on list.children
    //since children is not a proper array.
    // Instead using lodash as suggested, e.g. _.map(list.children, ...)
    //will do things without having to worry about it.
    //
    //OLD CODE
    //alternative which is nicer / more terse:
    // return list.children.map(function(child){
    //  return child.dataset.myId;
    // });

    // //and using ES6
    // return list.children.map((child) => child.dataset.myId);
}

Now whenever you need it call getOrderOfData("simpleList") and use the result. (untested)


text:
Q: System.Web.UI.ScriptManager' is defined in an assembly that is not referenced. But it is in the assembly? I just added Ajax to my website and i'm using toolkitscript manager, when i go to build it it produces the error.

The type 'System.Web.UI.ScriptManager' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

here is my entire web.config, I already see System>web>extensions referenced, what else could be the issue?
<system.web>
    <pages>
        <controls>
            <add tagPrefix="cc1" namespace="AjaxControlToolkit" assembly="AjaxControlToolkit"/>
        </controls>
    </pages>
    <assemblies>
        <add assembly="System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="System.Web.UI, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Web.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Web.ApplicationServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.ServiceModel.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Data.Services.Client, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Data.Services.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies></compilation>
</system.web>

This is how it is in my aspx.
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</cc1:ToolkitScriptManager>`

EDIT
Here is the solution:
<compilation debug="true" targetFramework="4.0">
It was missing targetFramework = "4.0"

A: For all those who, like me, still have this problem after reading the solution, I can well highlight that it is essential to add the reference System.Web.Extensions (As mentioned in the question ).
<add assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

A: Add: targetFramework="4.0" to the compilation tag.
<compilation debug="true" **targetFramework="4.0"**>

A: We just deleted the files with the warnings/errors and were planning on loading them back in but when deleted we republished with no errors and no issues so we never put them back in.  Just a suggestion but try it.


text:
Q: Matching CRC32 from STM32F0 and zlib I'm working on a communication link between a computer running Linux and a STM32F0. I want to use some kind of error detection for my packets and since the STM32F0 has CRC32 hw and I have zlib with CRC32 on Linux I thought it would be a good idea to use CRC32 for my project. The problem is that I won't get the same CRC value for the same data on the different platforms.
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <zlib.h>

int
main(void)
{
  uint8_t byte0 = 0x00;
  uint32_t crc0 = crc32(0L, Z_NULL, 0);
  crc0 = crc32(crc0, &byte0, 1);
  printf("CRC32 value of %" PRIu8 " is: %08" PRIx32 "\n", byte0, crc0);
}

outputs CRC32 value of 0 is: d202ef8d which matches the result on several online calculators.
It seems though that whatever settings I use on the STM32 I can't get the same CRC.
I have found a flowchart on how the CRC hw calculates its value in an application note from ST but I can't figure out how it's done in zlib.
Does anyone know if they are compatible?
[edit 1] They both uses the same init value and polynomial.
[edit 2] The STM32 code is relatively uninteresging since it's using the hw.
...
/* Default values are used for init value and polynomial, see edit 1 */
CRC->CR |= CRC_CR_RESET;
CRC->DR = (uint8_t)0x00;
uint32_t crc = CRC->DR;
...

A: The CRC32 implementation on STM32Fx seems to be not the standard CRC32 implementation you find on many online CRC calculators and the one used in zip.
STM32 implements CRC32-MPEG2 which uses big endian and no final flip mask compared to the zip CRC32 which uses little endian and a final flip mask.
I found this online calculator which supports CRC32-MPEG2.
If you are more interested on other CRC algorithms and their implementation, look at this link.
PS: The HAL driver from STM supports input in byte, half word and word formats and they seem to work fine for STM32F0x in v1.3.1

A: From the documentation, it appears that your STM32 code is not just uninteresting — it is rather incomplete.  From the documentation, in order to use the CRC hardware you need to:

*

*Enable the CRC peripheral clock via the RCC peripheral.

*Set the CRC Data Register to the initial CRC value by configuring the Initial CRC value register (CRC_INIT).(a)

*Set the I/O reverse bit order through the REV_IN[1:0] and REV_OUT bits respectively in CRC Control register (CRC_CR).(a)

*Set the polynomial size and coefficients through the POLYSIZE[1:0] bits in CRC
Control register (CRC_CR) and CRC Polynomial register (CRC_POL) respectively.(b)

*Reset the CRC peripheral through the Reset bit in CRC Control register (CRC_CR).

*Set the data to the CRC Data register.

*Read the content of the CRC Data register.

*Disable the CRC peripheral clock.

Note in particular steps 2, 3, and 4, which define the CRC being computed.  They say that their example has rev_in and rev_out false, but for the zlib crc, they need to be true.  Depending on the way the hardware is implemented, the polynomial will likely need to reversed as well (0xedb88320UL).  The initial CRC needs to be 0xffffffff, and the final CRC inverted to match the zlib crc.

A: I haven't tested this, but I suspect that you're not, in fact, doing an 8-bit write on the STM32.
Instead you're probably doing a write to the full width of the register (32 bits), which of course means you're computing the CRC32 of more bytes than you intended.
Disassemble the generated code to analyze the exact store instruction that is being used.

A: I had similar issues implementing a CRC on an STM32 CRC module where the final checksum was not matching. I was able to fix this by looking at the example code in stm32f30x_crc.c that is provided with STMCube. In the source it has a function for 8-bit CRC that used the following code
(uint8_t)(CRC_BASE) = (uint8_t) CRC_Data;
to write to the DR register. As stated previously, the line CRC->DR is defined as volatile uint32_t which will access the whole register. It would have been helpful if ST had been more explicit about accessing the DR register rather than simply saying it supports 8-bit types.

A: From my experience, you can not compare the CRC32 code between the STM32 CRC unit output with the online CRC32 calculator.
Please find my CRC32 calculator for STM32 in this link.
This function has been used in my project, and proved to be correct.

A: For reference, getting compliant crc32 using the Low Level API:
void crc_init(void) {
    LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_CRC);

    LL_CRC_SetPolynomialCoef(CRC, LL_CRC_DEFAULT_CRC32_POLY);
    LL_CRC_SetPolynomialSize(CRC, LL_CRC_POLYLENGTH_32B);
    LL_CRC_SetInitialData(CRC, LL_CRC_DEFAULT_CRC_INITVALUE);
    LL_CRC_SetInputDataReverseMode(CRC, LL_CRC_INDATA_REVERSE_WORD);
    LL_CRC_SetOutputDataReverseMode(CRC, LL_CRC_OUTDATA_REVERSE_BIT);
}

uint32_t crc32(const char* const buf, const uint32_t len) {
    uint32_t data;
    uint32_t index;

    LL_CRC_ResetCRCCalculationUnit(CRC);

    /* Compute the CRC of Data Buffer array*/
    for (index = 0; index < (len / 4); index++) {
        data = (uint32_t)((buf[4 * index + 3] << 24) |
                          (buf[4 * index + 2] << 16) |
                          (buf[4 * index + 1] << 8) | buf[4 * index]);
        LL_CRC_FeedData32(CRC, data);
    }

    /* Last bytes specific handling */
    if ((len % 4) != 0) {
        if (len % 4 == 1) {
            LL_CRC_FeedData8(CRC, buf[4 * index]);
        }
        if (len % 4 == 2) {
            LL_CRC_FeedData16(CRC, (uint16_t)((buf[4 * index + 1] << 8) |
                                              buf[4 * index]));
        }
        if (len % 4 == 3) {
            LL_CRC_FeedData16(CRC, (uint16_t)((buf[4 * index + 1] << 8) |
                                              buf[4 * index]));
            LL_CRC_FeedData8(CRC, buf[4 * index + 2]);
        }
    }

    return LL_CRC_ReadData32(CRC) ^ 0xffffffff;
}

Tweaked from the example here
The LL_CRC_ResetCRCCalculationUnit() re-initializes the crc unit so that repeated calls to this function return the expected value, otherwise the initial value will be whatever the result of the previous crc was, instead of 0xFFFFFFFF
You probably don't need the lines setting the polynomial to the default value because they should already be initialized to these values from reset, but I've left them in for posterity.


text:
Q: Filter out href in a list instead of soup.find_all Hi I filter out some of the announcement on a website with the following script
 gdata_even=soup.find_all("li", {"class":"list2Col even "})
 gdata_odd=soup.find_all("li", {"class":"list2Col odd "})

Finally I only take some of the announcements in gdata depending on whether the item has a certain word:
for l in range(len_data):
            if _checkDate(gdata_even[l].text):
                if _checkwordsV2(gdata_even[l].text):
                    pass
                else:
                    initial_list.append(gdata_even[l].text.encode("utf-8"))

            if _checkDate(gdata_odd[l].text):
                if _checkwordsV2(gdata_odd[l].text):
                    pass
                else:
                    initial_list.append(gdata_odd[l].text.encode("utf-8"))

The problem I am facing now is that gdata_even[l] and gdata_odd[l] has the following output:

25 Aug 2015 12:00:06 AM CEST

Frankfurt

FRA:Deletion of Instruments from XETRA - 25.08.2015-001

Here I want to get the link of the item which is embedded in the href with the following code but it doesn't work:
    h3Url = gdata[l].find("a").get("href")
    print h3Url

Can someone please assist, thank you.

A: Maybe there is an error on how you are getting gdata because your code should work.
>>> from BeautifulSoup import BeautifulSoup
>>> doc='

25 Aug 2015 12:00:06 AM CEST

Frankfurt

FRA:Deletion of Instruments from XETRA - 25.08.2015-001

'
>>> soup = BeautifulSoup(doc)
>>> h3Url = soup.find('a').get('href')
>>> print h3Url

/xetra-en/newsroom/xetra-newsboard/FRA-Deletion-of-Instruments-from-XETRA---25.08.2015-001/1913134


text:
Q: Java Methods returning Interface types I've seen related questions, but the answers only skirt the heart of the answer I'm looking for.
I have the following line of code (and it compiles and runs without error):
Document doc = dbuilder.parse(myXmlFile);
where
Document is the interface org.w3c.dom.Document
and
parse() is a method from javax.xml.parsers.DocumentBuilder
When I then executed
System.out.println(doc.getClass().getName());

its output is
com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl

which, I assume, means that DeferredDocumentImpl implements the Document interface, and that when I execute methods against my doc variable, I'm actually executing the methods of DeferredDocumentImpl.
My questions are:

*

*Is that above assumption correct, that is, am I indeed executing the implemented methods of that DeferredDocumentImpl class?

*An interface can be implemented by any number of classes, and assuming that org.w3c.dom.Document is indeed implemented by multiple classes, why did the Document type returned by parse() get cast as the DeferredDocumentImpl class, and not one of the other classes that implements Document?

*Assuming that 2. above is some kind of 'default' or 'priority' type-assignment, where do I verify - and possibly change - that assignment?

*How would I override the type-assignment I describe in 3. above at the level of the code itself?
As I say, I've searched dutifully for this, but nothing seems to give me answers to these specific questions... much appreciated.

A:
am I indeed executing the implemented methods of that DeferredDocumentImpl class?

yes

An interface can be implemented by any number of classes, and assuming that org.w3c.dom.Document is indeed implemented by multiple classes, why did the Document type returned by parse() get cast as the DeferredDocumentImpl class, and not one of the other classes that implements Document?

You would need to read the code to determine why that library returned that implementation. I wouldn't be surprised if its the only implementation that library has.
Note: org.w3c.dom.Document is an API standard interface, a library which implements this API need only provide one implementation.  A library doesn't have to create an implementation from another library.

Assuming that 2. above is some kind of 'default' or 'priority' type-assignment, where do I verify - and possibly change - that assignment?

Yes, change the object the library creates by modifying the source of the library.

How would I override the type-assignment I describe in 3. above at the level of the code itself?

Checkout a copy of the source, change it and built it.


text:
Q: When #tmp table is null ignore where I trying to ignore my where when #tmp table is empty.
Like:
    create table #tmp
    (
    my_id int
    )
create table #tmp2
    (
    my_name_id int
    )

    select * from foo
    where foo_id in (select my_id from #tmp)
and foo_name_id in (select my_name_id from #tmp2)

And now case.
When we have ituation when one of tables is empty it will not generate any result.
#tmp is not empty
#tmp1 is empty
So my where with #tmp1 should be ignored.
Got any clue how to do it?

A: Just add additional conditions:
select * from foo
where (foo_id in (select my_id from #tmp) or not exists(select * from #tmp))
and (foo_name_id in (select my_name_id from #tmp2) or not exists(select * from #tmp2))

The general form you're adopted, however, makes it look like you're taking quite a procedural approach to SQL, where you're storing partial results in temp tables and then combining them at the end. It's usually better to write the entire desired result as a single query and let SQL Server work out how best to compute the result (and cache intermediate forms if required)


text:
Q: VisualStudio - cannot execute XSLT I am trying to execute an XSLT in VisualStudio 2012 Express Edition. The buttons in the XML tool bar to run the transformation are all disabled. The transformation file itself is valid (the default file created by VisualStudio). I've specified an input file and an output file. The output file gets created, but is empty.
Is this a known issue in VS2012 Express? Is there a way to get the transformation buttons working so I can develop and test my XSLT?

A: From what I read in the feature matrix, it is a feature that you can edit and validate them. There is no feature that you can also run or debug them, as also noted in this related SO question. Usually, if a feature does not make it into the matrix, you won't find it.
There are much better XSLT editors out there anyway, and they are cheaper than a full upgrade of Visual Studio. Also, all the XML / XSLT editors support XSLT 2.0 and 3.0, both of which are not supported in any version of Visual Studio (unfortunately). Consider for instance Ogyxen (my personal favorite) or Stylevision, but there are many others out there for a variety of budget needs.


text:
Q: How to individually delete a dynamically created paragraph? I have a button that creates paragraphs dynamically in a div along with an ID.
When you create a paragraph you can also select that paragraph ("background color changes") by clicking it, along with that ("When you click on paragraph") a div is created with a link inside of it.
Tried to remove individually but it would remove all the paragraphs at once
How can I remove a paragraph that is being selected("I mean individually")?
Here is link and what I have so far:
http://jsfiddle.net/RzvV5/88/
Javascript/jQuery Code:
$(document).ready(function(){
    var id = 1;
    $("#push").on({
        click: function(){
            var pr = $('
This is text ' + id + '
');
            var d = $("#Test");
            var pclone = $(pr).clone();
            pclone.on({
                mouseenter: function(){
                    $(this).addClass("inside");
                },
                mouseleave: function(){
                    $(this).removeClass("inside");
                },
            });
            pclone.appendTo(d);
            id++;
        }
    });

    var div =  $('

');
    var del = $('Delete');
    var pcust = $(div).clone();
    var pdel = $(del).clone();

    $("#Test").on("click", "p", function(){
        var cur = $(this).css("background-color");

        if(cur=="rgb(255, 255, 255)") {
            $(this).css("background-color","red").addClass("help insider");
            $(this).after(pcust);
        }
        else {
            $(this).css("background-color","white").removeClass('help insider');
            $(pcust).remove();
        }

        $(pcust).append(pdel);

    });
});

HTML Code:

    Push

CSS Code:
.test { color: #000; padding: .5em; margin: 0px; border: 2px solid white; background: white;}

.help { border: 2px dashed #FDD }

.inside { border: 2px solid red    }

.insider { border: 2px solid #FDD; }

.delete {  font-size: 12px; }
.customD { background: yellow}

A: You can add click event handler to delete link
 $(".delete").live("click",function(){
        $(this).parent().prev().remove();
        $(this).remove();
    });

BTW. You don't have to clone each time link and its parent div, you can build up that part of dome and hold same reference, if you reuse it with
var div =  $('

');
var del = $('Delete');
div.append(del);

    $("#Test").on("click", "p", function(){

       ....
       $(pcust).append(del); //this will not clone delete div, it will actually replace its position it dome structure and move it from one paragraph to "pcust". This will save memory!!!

        ....
    };


text:
Q: SMTP RCPT TO:  returned 250 Accepted? Im working with validating emails, and im using phpmailer to connect to SMTP server, send a Mail from: header and then a RCPT TO: header, but all emails i put in there, i get a 250 accepted! instead of a "No such user here".
this is part of the extended PHPMailer class that i wrote:
    $ret[] = $this->smtpConnect();
    $ret[] = $this->smtp->mail('valid_from@valid_from.com');
    $ret[] = $this->smtp->recipient('wrong_email@right_domain.com');
    $this->smtpClose();

Testing this on my own websites so I know that I do NOT have a catch all email address,
and using a validating service online seems to work perfectly testing with the same values.
Please advise.


text:
Q: CSS multi-column layout with column gap not changing on window resize I am trying to make a multi-column layout where each column is filled with images.
There must be horizontal scroll for the container of the columns, but the column gap must not change on window resize, and the last column must be able to be shown clipped on the one side.
The coloumn height depends on the parent container and when the window height is changed, the images must be reаrranged in order to fill the column with whole images (an image should not be clipped horizontally).
img {
    height: 70px;
    width: 100px;
}

.container
{
    height:400px;
    overflow-x: scroll;
    overflow-y: hidden;
    -webkit-column-width: 100px;
    column-width: 200px;
    -webkit-column-gap: 20px;
    column-gap: 20px;
}

Here is a jsfiddle of what I currently have:
http://jsfiddle.net/9dL2F/1/
Do you have any ideas how this can be done?

A: This is tricky. The container's entire width is divided into columns, so you can't have both a fixed column-width and column-gap. As the container's width changes, the browser wants to fill the container. See Fixed gap between CSS columns.
You could manage the width of .container: (see jsfiddle)
@media (min-width: 480px) { .container { width: 480px; } }
@media (max-width: 480px) and (min-width: 360px) { .container { width: 360px; } }

...but that's a lot of queries to manage!
Does vertically-ordered images matter? If rows are fine, you could abandon CSS3 columns:
img { display: inline-block; width: 100px; height: 70px; margin-right: 20px;}

Similarly, you could float:
img { float: left; width: 100px; height: 70px; margin-right: 20px;}

I haven't used them, and there is no IE support yet, but you could try CSS3 Flexboxes.
None of these are pretty, but I don't know of a beautiful solution...maybe CSS4 will save us?

A: Mr.Anson says right. I should manage other columns:
2 left-columns in fixed position, 1 right-column in fixed position and content (or, container is auto-resized depends on the browser windows, as follows:
.in-content{
position:absolute;
height:auto;
color:#2d2d2d;
float:left;
left:280px;
top:33px;
bottom:auto;
right:14%;
padding:0px 10px 39px 0px;
text-align:justify;
text-decoration:none;
text-transform:none;
z-index:-33;
overflow:auto;
}
@media (min-width:27%) {.in-content{width:40%;}}
@media (max-width:40%) and (min-width:27%) {.in-content{width:27%;}}

That's all ^_^
Thanks.


text:
Q: VSTS - which process template to pick if primarily interested in kanban, no sprints? Will be setting up first VSTS team project and picking the process template, it seems to be down to either agile or scrum.  Reading other posts, it seems scrum is the simpler and for the most part it makes sense for our small team.  However, I do not think we want to use sprints and the "sizing" method for kanban typically uses is more loose also.  My question is if I choose the scrum template, am I forced to use the sprints and if not, can I remove them?
https://learn.microsoft.com/en-us/vsts/work/work-items/guidance/choose-process?view=vsts
https://learn.microsoft.com/en-us/vsts/work/kanban/kanban-basics?view=vsts

A: The concept of "Iterations" is a fundamental part of the work item tracking experience and you cannot change that.
However, there's nothing stopping you from setting up a completely flat iteration structure consisting of only a Backlog iteration with no defined start or end dates, then managing everything from the backlog view in a Kanban fashion.
There is no difference between any of the process templates in this regard, only in the work item names and in some rules around state transitions. I believe Agile has looser rules for state transition, whereas Scrum has stricter rules.


text:
Q: Autohotkey not able to run command line in git command prompt So I'm trying to use Autohotkey to run a basic line script:
F19::
Send git checkout master; git pull; git merge nick; git push; git checkout nick; git merge master;
return

This works in any program but command prompt. I am using a mac keyboard on a windows machine, but have no issues with the F keys. I have this routed to F19. When I hit the key in git's command prompt within SmartGit, I get nothing. I've also tried rerouting the shortcut key to another bind, again with no result.
I am wondering if there is something in my command script that I am calling improperly?
Thank you in advance.

A: I would think a bash alias would work better in this situation.
alias dostuff="git checkout master && git pull && git merge nick && git push && git checkout nick && git merge master"
EDIT:
You could also make this more flexible by letting it take parameters ie. your branch name by using a function.
dostuff() {
  git checkout master && git pull && git merge $1 && git push && git checkout $1 && git merge master
}

Calling it with dostuff nick


text:
Q: Django Authenticate returns None I have the following code snippet:
user = User(username='h@h.com',email='h@h.com')
user.set_password('pass')
user.save()
u = authenticate(username='h@h.com', password='pass') #this always returns None!!!

The problem is, u is always None. I've followed code samples on other stack overflow posts and have narrowed it down to the above lines.
Any ideas as to what might be happening?

A: Interestingly enough, check_password returns True in the following:
eml = "4@a.com"
pw = "pass"
uname = 'w2'
user = User.objects.create_user(uname,eml,pw)
user.save()
log.debug("Password check passes?")
log.debug(user.check_password(pw)) # Logs True!!!
user = authenticate(username=uname, password=pw)

A: Why don't you create a user like this:
user = User.objects.create_user( username="whatever", email="whatever@some.com", password="password")
user = authenticate( username="whatever",password="password")

A: In settings.py, add
AUTH_USER_MODEL = your custom user class

e.g if django app name is office and custom user class is Account then
AUTH_USER_MODEL = 'office.Account'

A: set_password is a misleading method, it doesn't save the password on the user table. You need to call user.save() in order for it to work on your flow

A: Put something like this in your settings
#Authentication backends
AUTHENTICATION_BACKENDS = (
        'django.contrib.auth.backends.ModelBackend',
    )

or if you are using userena for your accounts
#Authentication backends
AUTHENTICATION_BACKENDS = (
    'userena.backends.UserenaAuthenticationBackend',
    'guardian.backends.ObjectPermissionBackend',
    'django.contrib.auth.backends.ModelBackend',
)

A: You have to check whether user is active? If not, you only set active for user in admin panel, or set when creating user by adding the following line to user model:
is_active = models.BooleanField(default=True)

A: Also check that you have the right username/password combo.  sometimes the one that is created from the createsuperuser command is different than a username you would typically use.

A: As most of them suggested if we create the user's using User.objects.create_user(**validated_data) this will hash the raw password and store the hashed password. In-case if you you are using User model serializers to validate and create users, it is required to override the serializer method like this
class UserSerializers(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = "__all__"

    # this is the method responsible for insertion of data with hashed password
    def create(self, validated_data):
        return User.objects.create_user(**validated_data)

A: I puzzled with this problem for four days, and the above answers didn't help.
The problem was that I, as you, was using the user.save() and I could not see what the problem was, but then I looked at it with debug eyes, and it turns out that if you use user.save() it messes with the hashing of the password somehow, don't ask me how I don't know. So I worked around it by using the user.create() method that Django provides, worked like a charm:
@api_view(['POST'])
def create_user(request):
    new_user = UserSerializer(data=request.data)
    if new_user.is_valid():
        user_saved = new_user.create(request.data)
        return Response('User {} created'.format(user_saved.username),
                                           status=status.HTTP_200_OK)
    else:
        return Response('User not created', status=status.HTTP_200_OK)

I used something like this, but you can do as you wish just use the user.create().


text:
Q: Diophantine equation has at least $k$ positive integer solutions $k$ is a positive integer. Could we find all the pairs of positive integers $(a,b)$ such that the Diophantine equation
$$x(x+a)=y(y+b)$$
has at least $k$ positive integer solutions $(x,y)$, that is $x,y$ are all positive integers?
For example, $a=2(k+1)+\dfrac{(2k+2)!!}{2k+2},b=\dfrac{(2k+2)!!}{2k+2}-2(k+1)$. I find it luckily , without System approach
This problem's background is the 2014 China Mathematical Olympaid P2 problem. The exam is only want a pair $(a,b)$. So, I want to find all pairs $(a,b)$.

A: $x(x+a) = (x+\frac a2)^2-\frac{a^2}4$, so $x(x+a)=y(y+b)$ if and only if
$$\left(x+\frac a2\right)^2-\left(y+\frac b2\right)^2=\frac{a^2-b^2}{4}$$
if and only if
$$(2x+2y+a+b)(2x-2y+a-b)=(a+b)(a-b). $$
So if we let $c=a+b, d=a-b$, then any factorization of $cd$ into factors $c'd'$ of the same parity (i.e. $c'\equiv c\pmod 2$, $d'\equiv d\pmod 2$) gives rise to the solution $x=\frac{c'-c+d'-d}{2}$, $y=\frac{c'-c+d-d'}{2}$. And if $c'>c$ and $c'-c>|d'-d|$ these solutions are positive, and if $c>|d|\ge0$ then also $a,b>0$.
For $k>0$ let $c=3^{k+1}$, $d=3^{k}$. Then for $0< i\le k$ we can let $c'=3^{k+1+i}$, $d'=3^{k-i}$, that is with
$$ a=\frac{3^{k+1}+3^{k}}2=2\cdot 3^{k}, \qquad b=\frac{3^{k+1}-3^{k}}2=3^{k}$$
we have at least the $k$ solutions
$$ x=\frac{3^{k+1+i}-3^{k+1}-3^{k-i}+3^k}{2}, \qquad  y=\frac{3^{k+1+i}-3^{k+1}+3^{k-i}-3^k}{2}$$


text:
Q: How to optimize word_count in python I am given n words (1≤n≤10^5). Some words may repeat. For each word, I have to output its number of occurences. But the output order should correspond with the order of the first appearance of the word.
I have a working program of the problem, but for large inputs I am getting timeout. Here is my solution for the problem:
n=int(input())
l=[]
ll=[]

for x in range(n):
    l.append(raw_input())
    if l[x] not in ll:
        ll.append(l[x])

result = [ l.count(ll[x]) for x in range(len(ll)) ]

for x in range(len(result)):
    print result[x],

A: Use an ordered counter by subclassing OrderedDict and Counter:
from collections import Counter, OrderedDict

class OrderedCounter(Counter, OrderedDict):
    pass

counts = OrderedCounter(['b', 'c', 'b', 'b', 'a', 'c'])
for k, c in counts.items():
    print(k, c)

Which prints:
b 3
c 2
a 1

See the documentation for the collections module for a more complete recipe which includes a __repr__ for OrderedCounter.

A: The easiest way to count items in python is to use a Counter from the collections module.
Assuming you have a list of items in the order that you expect, passing it to a Counter should suffice:
c = collections.Counter(['foo', 'bar', 'bar'])
print(c['bar'])  # Will print 2

If words is the list of words you retrieved from the user, you can iterate over it to print the values:
seen = set()
for elem in words:
    if elem not in seen:
        print(counter[elem])
        seen.add(elem)

A: Take a look at collections.OrderedDict. It can handle this for you, and it removes the linear membership test expense using a list is imposing:
import collections

n = int(input())
l = []
ll = collections.OrderedDict()

for x in range(n):
    v = raw_input()
    l.append(v)
    ll[v] = None  # If v already in OrderedDict, does nothing, otherwise, appends

ll = list(ll)  # Can convert back to list when you're done if you like

If you need the count, you can make a custom class based on OrderedDict that both handles counts and remains ordered.
class OrderedCounter(collections.OrderedDict):
    def __missing__(self, key):
        return 0

Then change ll to an OrderedCounter, and ll[v] = None to ll[v] += 1. At the end, ll will have the ordered words with their counts; l isn't even needed:
for word, count in ll.items():
    print(word, count)

The final code would simplify to just (omitting imports and class definition):
n = int(input())
word_counts = OrderedCounter()

for x in range(n):
    word_counts[raw_input()] += 1

for cnt in word_counts.values():
    print cnt,

Much simpler, right?


text:
Q: Loop to find max value Hi I'm having a problem to write a loop which finds the largest value.
A list of integers and an integer variable are declared like this:
  List list;
  int max;
Assuming that some values (including negatives!) have been added to the list. i need to find the largest value in list and stores it in max.
//  start of test code

import java.util.*;

public class ListTest

{

private List<Integer> list;

private int max;
public void findMaxInListTest()
        {

list = new ArrayList<Integer>(); // could be a Linked list

list.add(0);
list.add(-99);

list.add(99);
list.add(1320);

list.add(470000);

list.add(12);
list.add(-5000);
list.add(300);
/*#     max = starting value

iterate through list to set max = max value in list

in this case 470000
    */

}

}

I tried using this loop but then encounter an error:
int max = list[0];
  for(int i=470000;i < list.length;i++){
    if(list[i] > max){
      max = list[i];
    }
  }
return max;

do you know which kind of loop that appropriate for this? Thanks

A: You need to iterate over the list. Start with i=0 - not 47000.
Hope this helps.

A: for(int i=470000;i < list.length;i++){

i is the index. put i=0. getting list element for index 470000 throws the exception.
also, list[i] doesn't work in java. use list.get(i).
also, list.length doesn't work on lists. use list.size().
You're misinterpreting java List - it's not an array.

A: import java.util.Collections;

Collections.sort(list);
System.out.println(list.get(list.size() - 1));

A: for(int i=470000;i < list.length;i++){

should be
for(int i=0;i < list.length;i++){

A: No loop required, use max method from java.utils.Collections (Documentation)
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Test {

    public static void main(String[] args) {

        List<Integer> list = new ArrayList<Integer>();
        list.add(0);
        list.add(-99);
        list.add(99);
        list.add(1320);
        list.add(470000);
        list.add(12);
        list.add(-5000);
        list.add(300);

        System.out.println(Collections.max(list));
    }
}


text:
Q: WooCommerce Adds-On Ultimate How to add addition condition that is not include in the plugins using action I really Need help for my project
I created a website its a tour website
example of one program is

*

*Mall Tour
With Date Field
Adult Field (Price: 100 ea)
Child Field ( Price: 50 ea)

its already working now with the help of the WooCommerce Adds-On Ultimate publish by Plugin Rep.
the problem is my teacher want to have a promotion or discount
The discount is if the current is date between March to April
there is a free Child per Adult example, if there is 2 adult there will be free 2 child, if the customer have 2 adult and 3 children then, the total is 200 for adult and just 50 for child cuz the 2 is free
I hope my explanation is good enough.
this is Code I saw but for some reason it didnt work,
add_action('woocommerce_before_calculate_totals', 'add_custom_price');
function add_custom_price( $cart_obj ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
        return;
    }

    // Specify the date range for the discount
    $start_date = '2023-03-01';
    $end_date = '2023-04-31';
    $current_date = date('Y-m-d');

    if ($current_date < $start_date || $current_date > $end_date) {
        return;
    }

    // Set the name of the adult field
    $adult_field_name = 'pewc_group_2022_2038';

    // Set the name of the child field
    $child_field_name = 'pewc_group_2022_2039';

    // Set the price of the child field
    $child_field_price = 50;

    // Initialize counters for adult and child fields
    $adult_count = 0;
    $child_count = 0;

    // Loop through each cart item
    foreach( $cart_obj->get_cart() as $key=>$value ) {

        // Check if the item has adult and child fields
        if ( !empty( $value['product_id'] ) ) {
            $adult_field = wc_get_product_addon( $value['product_id'], $adult_field_name );
            $child_field = wc_get_product_addon( $value['product_id'], $child_field_name );

            // Check if the adult field exists and add its value to the adult count
            if ( $adult_field ) {
                $adult_value = isset( $value['addons'][ $adult_field['field-name'] ] ) ? intval( $value['addons'][ $adult_field['field-name'] ] ) : 0;
                $adult_count += $adult_value;
            }

            // Check if the child field exists and add its value to the child count
            if ( $child_field ) {
                $child_value = isset( $value['addons'][ $child_field['field-name'] ] ) ? intval( $value['addons'][ $child_field['field-name'] ] ) : 0;
                $child_count += $child_value;
            }
        }
    }

    // Calculate the maximum number of free child fields based on the number of adult fields
    $max_free_child_fields = floor($adult_count);

    // Calculate the actual number of free child fields
    $free_child_fields = min($max_free_child_fields, $child_count);

    // Calculate the discount for the child fields
    $discount = $free_child_fields * $child_field_price;

    // Apply the discount to the child fields
    foreach( $cart_obj->get_cart() as $key=>$value ) {
        if ( !empty( $value['product_id'] ) ) {
            $child_field = wc_get_product_addon( $value['product_id'], $child_field_name );
            if ( $child_field ) {
                $new_price = $child_field_price;
                if ( $free_child_fields > 0 ) {
                    $new_price = 0;
                    $free_child_fields--;
                }
                $value['addons'][ $child_field['field-name'] ]['price'] = $new_price;
            }
        }
    }

    // Update cart totals
    $cart_obj->set_total( $cart_obj->get_total() - $discount );
}

im thinking if I call a wrong variable in addons?


text:
Q: How to write mongocxx (v3) query with Date data type? I have a collection and I need to extract only most recent data based on field updateDate (with data type Date).
 I use c++ driver (mongocxx (v3) ).
mongocxx::cursor cursor =
    collection.find(document{} << "updateDate" <<
                    open_document << "$gt" <<
                    (date parameter)  << close_document <<
                    finalize);

for(auto doc : cursor) {
    std::cout << bsoncxx::to_json(doc) << "\n";
}

How can I write my query for instance:
 what format, data type I need to pass as day?
Thank you.

A: You can do something like this :
replace (date parameter) with bsoncxx::types::b_date{<value>}


text:
Q: use java in python 3.4 with nltk I want to use stanford-tagger in my project but below error is occur.
  File "C:\Python34\lib\site-packages\nltk\tag\stanford.py", line 59, in tag
    return self.tag_sents([tokens])[0]
  File "C:\Python34\lib\site-packages\hazm\POSTagger.py", line 25, in tag_sents
    return super(stanford.POSTagger, self).tag_sents(refined)
  File "C:\Python34\lib\site-packages\nltk\tag\stanford.py", line 64, in tag_sents
    config_java(options=self.java_options, verbose=False)
  File "C:\Python34\lib\site-packages\nltk\internals.py", line 82, in config_java
    _java_bin = find_binary('java', bin, env_vars=['JAVAHOME', 'JAVA_HOME'], verbose=verbose, binary_names=['java.exe'])
  File "C:\Python34\lib\site-packages\nltk\internals.py", line 544, in find_binary
    binary_names, url, verbose))
  File "C:\Python34\lib\site-packages\nltk\internals.py", line 538, in find_binary_iter
    url, verbose):
  File "C:\Python34\lib\site-packages\nltk\internals.py", line 517, in find_file_iter
    raise LookupError('\n\n%s\n%s\n%s' % (div, msg, div))
LookupError:

===========================================================================
NLTK was unable to find the java file!
Use software specific configuration paramaters or set the JAVAHOME environment variable.
===========================================================================

NLTK was unable to find the java file!
Use software specific configuration paramaters or set the JAVAHOME environment variable.
please help me for set java variable. i use windows 8 64 bit and python 3.4

A: Add it to your code:
java_path = "C:/Program Files/Java/jdk1.8.0_191/bin/java.exe"
os.environ['JAVAHOME'] = java_path

A: Here's the Java documentation for setting your path.
Windows 8

*

*Drag the Mouse pointer to the Right bottom corner of the screen

*Click on the Search icon and type: Control Panel

*Click on -> Control Panel -> System -> Advanced

*Click on Environment Variables, under System Variables, find PATH, and click on it.

*In the Edit windows, modify PATH by adding the location of the class to the * value for PATH. If you do not have the item PATH, you may select to add a new variable and add PATH as the name and the location of the class as the value.

*Close the window.

*Reopen Command prompt window, and run your java code.

A: your nltk library can't find the java directory in your computer.
go to nltk library files in your venv and find internals.py in files
find this line in the code:
def config_java(bin=None, options=None, verbose=False)

change the code like this:
java_path = "C:/Program Files/Java/jre1.8.0_281/bin/java.exe" #your java file address
os.environ['JAVAHOME'] = java_path
def config_java(bin=java_path, options=None, verbose=False):
...


text:
Q: Lagrangian of an equation, a particle with a time dependent constraint I'm currently studying for an exam and I came across the following question. Consider a bead of mass m constrained to move along a wire which is on the vertical $(x, y)$ plane. The wire has equation
$y =x^2/a+ b cos(\omega t)$
where $a$, $b$ and $\omega$ are positive constants. The equation of the wire is interpreted physically as a parabola that vibrates vertically with a prescribed time dependence. The particle is under the effect of gravity with potential $V = mgy$. Find the Lagrangian of the system. I'm struggling to find generalized coordinates to represent it. I was thinking maybe cylindrical coordinates would fit the problem but I'm not sure how to apply it to the question and was wondering if somebody could point me in the right direction? Thank you!

A: Consider the lagrangian
$$
L(x,y,\lambda) = \lambda  \left(y-\frac{x^2}{a}-b \cos (\omega  t)\right)-g m y+\frac{1}{2} m \left(\dot x^2+\dot y^2\right)
$$
and then after $L_X-\frac{d}{dt}L_{\dot X} = 0$ the movement equations
$$
m\ddot x + \frac{2\lambda x}{a} = 0\\
m\ddot y - m g -\lambda = 0\\
y-\frac{x^2}{a}-b \cos (\omega  t) = 0
$$
now deriving twice the last equation we have the DE system
$$
m\ddot x + \frac{2\lambda x}{a} = 0\\
m\ddot y - m g -\lambda = 0\\
\ddot y = \frac{2}{a}(\dot x^2+\dot x\ddot x)-b\omega^2\cos(\omega t)
$$
Finally solving for $\ddot x,\ddot y,\lambda$ we get
$$
\ddot x= \frac{2 \left(a b \omega ^2 x \cos (\omega  t)-a g x-2 x \dot x^2\right)}{a^2+4 x \dot x}\\
\ddot y= -\frac{a^2 b\omega ^2 \cos (\omega  t)-2 a \dot x^2+4 g x \dot x}{a^2+4 x \dot x}\\
\lambda = \frac{a m \left(a g+2
   \dot x^2-a b \omega ^2 \cos (\omega  t)\right)}{a^2+4 x \dot x}
$$
which are the movement equations. Here $\lambda$ represents the reaction force between the bead and the curve.


text:
Q: Function returns wrong value for certain arrays I have recently started coding and was working on a function that returns the 3 largest numbers in a given array. The function works for most arrays, but not for others. Below is the code:
def findThreeLargestNumbers(array):
  list = []
  if len(set(array)) != 1:
    while len(list) <= 2:
      for element in array:
        if element == max(array):
          list.append(element)
          array.remove(element)
    list.reverse()
    return list
  else:
    for element in array:
      newlist = [element, element, element]
      return newlist

For instance, when I input the array [1,2,3,4,5] the function returns [3,4,5]. However, when I input [55, 43, 11, 3, -3, 10], the function returns 4 values: [10, 11, 43, 55].
Why is this?
Thank you so much!

A: This nested loop can add an arbitrarily large number of elements to list (which is btw a bad name for a list because it overwrites the builtin function list()):
    while len(list) <= 2:
      for element in array:
        if element == max(array):
          list.append(element)
          array.remove(element)

You only check the length of list in the outer loop, but the inner loop goes over the entire array and will potentially add all of them to list (if the array is in reverse-sorted order) before the condition is checked again.
A much simpler way to write this function would be to simply sort it and take the highest three elements:
from typing import List

def find_three_largest_numbers(array: List[int]) -> List[int]:
    """Return the three largest numbers from the array."""
    return sorted(array)[-3:]

(edit) A slightly more complex version that doesn't involve a sort:
def find_three_largest_numbers(array: List[int]) -> List[int]:
    """Return the three largest numbers from the array."""
    largest_3: List[int] = []
    for num in array:
        largest_3.append(num)
        if len(largest_3) > 3:
            largest_3.remove(min(largest_3))
    return largest_3

In this implementation, largest_3 is never permitted to grow beyond 3 elements because every time it grows to 4, we remove exactly one element before we add any more.

A: Add a break in the end of the for
  def findThreeLargestNumbers(array):
      list = []
      if len(set(array)) != 1:
        while len(list) <= 2:
          for element in array:
            if element == max(array):
              list.append(element)
              array.remove(element)
              break
        list.reverse()
        return list
      else:
        for element in array:
          newlist = [element, element, element]
          return newlist


text:
Q: bundler incorrectly trying to install "development" and "test" group gems in production I have a small web app, which uses a bunch of gems. Some of them are only used for test and development environments. Now, when I try to start unicorn on the production server using the following command, it fails.
unicorn_rails -E production -D -c config/unicorn.rb

The error I see in the log files is:
Refreshing Gem list
Could not find gem 'spork (>= 0.9.0.rc2, runtime)' in any of the gem sources listed in your Gemfile.
Try running `bundle install`.

I've pasted my gemfile below:
source 'http://rubygems.org'

gem 'rails', '3.0.1'
gem 'unicorn'
gem 'mongoid', '>= 2.0.0.beta.19'
gem 'devise'
gem 'cancan'
gem 'haml', '>= 3.0.0'
gem 'bson'
gem 'bson_ext'
gem 'formtastic'
gem 'bluecloth'

group :production do
  gem 'capistrano'
end

group :development do
  gem 'haml-rails'
  gem 'hpricot', '0.8.2'
  gem 'ruby_parser', '2.0.5'
  gem 'less'
  gem 'rspec-rails', '>= 2.0.1'
end

group :development,:test do
  gem 'spork', '>=0.9.0.rc2'
  gem 'mongoid-rspec'
end

group :test do
  gem 'factory_girl_rails'
  gem 'autotest'
  gem 'cucumber-rails'
  gem 'cucumber'
  gem 'capybara'
  gem 'shoulda'
  gem 'database_cleaner'
  gem 'test_notifier'
  gem 'rspec', '2.0.1'
  gem 'launchy'
end

Bundler is supposed to detect the right environment and ignore the other gems, right? Right now, I am deleting all the lines which are not in the default group on the server to get this working, but that's an ugly hack.

A: After a lot of digging I found the fix for this issue. All I had to do was run bundle install --without development test before starting the server. This adds a .bundle/config file in the rails root with the line BUNDLE_WITHOUT: test:development . Now whenever you run bundle install or start the server it'll ignore those groups.
From the documentation

The Bundler CLI allows you to specify
  a list of groups whose gems bundle
  install should not install with the
  --without option. To specify multiple groups to ignore, specify a list of
  groups separated by spaces.
bundle install --without test bundle
  install --without development test
  After running bundle install --without
  test, bundler will remember that you
  excluded the test group in the last
  installation. The next time you run
  bundle install, without any --without
  option, bundler will recall it.
Also, calling Bundler.setup with no
  parameters, or calling require
  "bundler/setup" will setup all groups
  except for the ones you excluded via
  --without (since they are obviously not available).

A: In my case it was installing gems from jenkins env. So i had to set my own bundle_without variable in capistrano.
Gemfile
group :test, :development, :jenkins do
  gem 'test-unit', '1.2.3'
  gem 'rspec-rails'
end

deploy.rb
set :bundle_without, [:development, :test, :jenkins]

A: You haven't defined a production group =)


text:
Q: When should we use the word 'status quo'? I know 'status quo' means the existing state of affairs, especially regarding social or political issues.
When should we use the word 'status quo'?
(Here is a related ELU question.)

A: You would use the term status quo when the following are met:

*

*there is a defined state to compare that has been (very) stable

*that everyone accepts that this defined state is stable and is somewhat considered the same by most/all people

*that your audience understands what status quo means.


text:
Q: Save last row number as variable after opening the workbook for the later use I want to save the last row number used in a particular sheet at Workbook_Open() for the later use in other modules.
So far I have this code:
ThisWorkbook:
Public last_row as long

Private Sub Workbook_Open()
    last_row = Worksheets("Sheet1").Cells(Rows.count, 1).End(xlUp).Row
    MsgBox ("This is the last row number: " & last_row)
End Sub

I get the pop-up message correctly, like "This is the last row number: 25", when I open the workbook. This is a desired output.
Module 1:
Sub ABC()
    MsgBox ("This is the last row number: " & last_row)
End Sub

But when I run the Module 1, "This is the last row number: " message is what I get.
So, I am failing in storing the "last_row" variable as public. What am I doing wrong? Thanks in advance!

A: What you want to do is a bad idea and definitely not recommended. Public variables reset the moment there is an error.
Recalculate it every time you want to use it. You can do it in two ways

*

*lRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row where ws is your worksheet object

*Create a function if you do not want to write that "long code [pun intended :)]" every time

Paste this in a module
Function GetMeLastRow() As Long
    Dim ws As Worksheet

    Set ws = Sheet1 '<~~ Change this to relevant sheet or pass it as a parameter

    With ws
        GetMeLastRow = .Range("A" & .Rows.Count).End(xlUp).Row + 1
    End With
End Function

And then use it like this
MsgBox GetMeLastRow

A: To answer your question specifically, modify your code like this:
Sub ABC()
   MsgBox ("This is the last row number: " & ThisWorkbook.last_row)
End Sub

To use a public variable declared in ThisWorkbook module you must qualify it with the module name.
Notes:

*

*You should enable Option Explicit in your VBE. It would have told you that last_row is not declared. A good habit to have;

*Although this solution will work, I 100% agree with @Siddharth Rout that this approach is a conceptually bad idea - you will end up with an unstable (unpredictable) code.

There are many better ways to solve your problem; the simpest is - save your last row number to a cell on a hidden sheet.


text:
Q: mocked JSONObject cannot retrieve value that was added I think there's something wrong when I'm trying to spy JSONObject using Mockito. Here's code from unit test method:
JSONObject json = new JSONObject();
json.put("token","value");

JSONObject spyJson = Mockito.spy(JSONObject.class);
PowerMockito.whenNew(JSONObject.class).withAnyArguments().thenReturn(spyJson);
service.getToken(json.toString());

Here's the beggining of the method getToken():
public LoginResponseData getToken(String response) throws JSONException {
    JSONObject resJson = new JSONObject(response); //resJson = {} here

    //do stuff

    }

In my build.gradle I've added:
testCompile 'org.json:json:20140107'

A: I think the code you have written is just fine. Make sure the library(java-json.jar) jar you are using is the correct one.
I've re written the same code of yours in my custom created Class JSONTest bellow and it works fine.
I've downloaded the java-jason.jar form here which has the same package as mentioned by you in the comment "org.json.JSONObject"  (you can try using the linked jar into your project).
Below is the working code snippet:
import org.json.JSONException;
import org.json.JSONObject;

    public class JSONTest {
        public static void main(String[] args) throws JSONException {
            JSONObject json = new JSONObject();
            json.put("key", "value");
            String jsonString = json.toString();

            String key = new JSONObject(jsonString).getString("key");
            System.out.println(key);

        }
    }

Output:
value

A: Actually, the problem was here:
JSONObject spyJson = Mockito.spy(JSONObject.class);

As @Sotirios Delimanolis have mentioned, I should spy on json, not the JSONObject class. Here, I was always getting the default {} value, no matter what, because spyJson was a new spy of JSONObject class and it had no knowledge of previously added token key. After changing it to:
JSONObject spyJson = Mockito.spy(json);

It works as expected.


text:
Q: How can i copy a name from a file with spaces in and create a new file with this name I am after a batch file to convert two files with the same name but different extensions
ie
test file.dat
test file.txt

I want to combine these files with a seperator (I have used ~)
I want the new file to be named a new extension but keep the original name, I have managed this but the majority of the files I use have spaces in them and I can get it to work with the spaces
The code I have so far:
type *.dat > new.andy
echo. >> new.andy
echo ~ >> new.andy
type *.txt >> new.andy
for /F %%a in ('dir /b *.dat') do set FileName=%%~na
REN new.andy %FileName%.andy

So far I have got the script to work apart from to rename the file with its full name including spaces, up to now it only goes till first space ie test.andy

A: Test the following
type "*.dat" > new.andy
echo. >> new.andy
echo ~ >> new.andy
type "*.txt" >> new.andy
for /F %%a in ('dir /b *.dat') do set FileName=%%~na
REN new.andy %FileName%.andy

A: You could start with something like this:
@echo off

for /f "tokens=*" %%a IN ('dir /b *.dat') do (
  type "%%a" >  "%%~na.andy"
  echo.      >> "%%~na.andy"
  echo ~     >> "%%~na.andy"
)

for /f "tokens=*" %%a IN ('dir /b *.txt') do (
  type "%%a" >> "%%~na.andy"
)

This will combine all *.dat files with all *.txt files, and the name of the combined file will be .andy.
Depending on what you are after and how your files are organized, this can be improved.


text:
Q: Crash with RestKit when issuing multiple requests in quick succession I have a button with two buttons which start the download of some data from a web server with RestKit.
Now if the user taps the two buttons repeatedly in quick succession my app crashes and produces the crash log below.
I initiate my requests like so:
-(void)loadDataAtPath:(NSString *)path completion:(ResultArrayBlock)completionBlock failed:(ResultFailedBlock)failedBlock
{
    RKObjectMapping *groupMapping = [Group mapping];

    [self.objectManager.mappingProvider setMapping:groupMapping forKeyPath:@"groups.group"];
    [self.objectManager.mappingProvider setObjectMapping:groupMapping forKeyPath:path];

    [self.objectManager loadObjectsAtResourcePath:path usingBlock:^(RKObjectLoader *loader) {
        loader.onDidLoadObjects = ^(NSArray *array){

            // Do the reverse mapping of the group
            for (Group *c in array) {
                for(Person *p in c.persons){
                    p.group = c;
                }
            }

            completionBlock(array);

        };
        loader.onDidFailWithError = failedBlock;
    }];
}

I first thought that the problem was the for-loop where I do some after-mapping setup of my data, but the problem still persists even when commenting the for-loop.
Curiously this problem does not occur in the simulator even when I switch on the Network Link Conditioner.prefpane
The crash
When I debug this on the device I get the following on the console.
[PLCrashReport] Terminated stack walking early: Corrupted frame
[PLCrashReport] Terminated stack walking early: Corrupted frame

The crash log looks like this:
Application Specific Information:
*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSCFDictionary: 0x3c14a0> was mutated while being enumerated.'

Last Exception Backtrace:
0   CoreFoundation                      0x3734e88f __exceptionPreprocess + 162
1   libobjc.A.dylib                     0x35053259 objc_exception_throw + 32
2   CoreFoundation                      0x3734e3b3 __NSFastEnumerationMutationHandler + 162
3   MyApp                               0x0008f5bf -[RKObjectMapper performKeyPathMappingUsingMappingDictionary:] + 407
4   MyApp                               0x0008fa45 -[RKObjectMapper performMapping] + 673
5   MyApp                               0x0008ac7d -[RKObjectLoader mapResponseWithMappingProvider:toObject:inContext:error:] + 1045
6   MyApp                               0x0008b04f -[RKObjectLoader performMapping:] + 575
7   MyApp                               0x0008b22b __47-[RKObjectLoader performMappingInDispatchQueue]_block_invoke_0 + 247
8   libdispatch.dylib                   0x3046ec59 _dispatch_call_block_and_release + 12
9   libdispatch.dylib                   0x30479cab _dispatch_queue_drain + 274
10  libdispatch.dylib                   0x30479b19 _dispatch_queue_invoke$VARIANT$up + 36
11  libdispatch.dylib                   0x3047a78b _dispatch_worker_thread2 + 214
12  libsystem_c.dylib                   0x33bbddfb _pthread_wqthread + 294
13  libsystem_c.dylib                   0x33bbdcd0 start_wqthread + 8

A: As @PhillipMills suggested, you can easily see the answer when you look inside performKeyPathMappingUsingMappingDictionary. Your problem is repeatedly setting the mapping with these lines:
[self.objectManager.mappingProvider setMapping:groupMapping forKeyPath:@"groups.group"];
[self.objectManager.mappingProvider setObjectMapping:groupMapping forKeyPath:path];

If you call this line while the response is being mapping it triggers the error because you are changing the same dictionary it is trying to fast enumerate over.
Normally, you would set the mapping somewhere in the initial configuration and NOT each time like this.


text:
Q: What information do I need to prove the integrity of my entire Git repository? Are the hashes for the tip of every branch sufficient to prove the integrity of my entire repository?  For the sake of discussion, assume you had to give your whole repository to someone, let them do anything they want to it, and determine whether or not they changed even 1 bit of data.  How would you do it?
If I'm pushing to an upstream, bare repository, is this all the data I need to guarantee I can verify the integrity of the whole repository at a later date?
git ls-remote --heads origin

fcce961b46784fae13be8a30c2622ddd34d970ec        refs/heads/develop
9da7bb692a72235451706f24790a3f7a100a64e2        refs/heads/feature-netty-testing
86020c50d86691caecff4a55d3b1f2f588f6291d        refs/heads/javafx-testing
871d715e5c072b1fbfacecc986f678214fa0b585        refs/heads/master
7ed641c96d910542edeced5fc470d63b8b4734f0        refs/heads/orphan-branch

That's from a sandbox repository I use to play around with.  The orphan-branch is a branch I intentionally orphaned as described here.  Everything seems right to me.  All the branches I expect are listed, but I'm not positive if the SHA of every branch tip is all I need.  Am I missing anything?
What about tags?  What about branches that were deleted without being merged into anything?
Updated
As pointed out in some comments, there may be other refs besides heads that may need to be considered.  For example, tags and notes may be useful depending on whether or not they are important to you or whether or not you are signing your tags.  For myself I am mainly interested in the content of commits which is why I accepted VonC's answer.

A: That seems enough in term of integrity.
Tags reference commits, so if a commit changes, a git fsck will detect the incoherency between the tag and its non-existent commit.
Note that integrity is different from trust (ie vouching for the content)
For that, "A Git Horror Story: Repository Integrity With Signed Commits" is instructive.
First its section "Commit History" details the theory behind SHA-1 integrity (also presented in "Git and Data integrity", and concludes with:

That said, it is important to understand that the integrity of your repository guaranteed only if a hash collision cannot be created — that is, if an attacker were able to create the same SHA-1 hash with different data, then the child commit(s) would still be valid and the repository would have been successfully compromised.
Vulnerabilities have been known in SHA-1 since 2005 that allow hashes to be computed faster than brute force, although they are not cheap to exploit.
  Given that, while your repository may be safe for now, there will come some point in the future where SHA-1 will be considered as crippled as MD5 is today.


text:
Q: Write the expression in terms of $\log{a}$ and $\log{b}$ Write in terms of $\log{a}$ and $\log{b}$ : $\log{\frac{a^3}{b^4}}$?
using log laws $log(\frac{x}{y})$ = $\log{x} - \log{y}$
$\log{\frac{a^3}{b^4}} = \log{a^3} - \log{b^4}$
and using log law that $\log{x^y} = y\log{x}$
$\log{a^3} = 3 \log{a}$ & $\log{b^4} = 4\log{b}$
therefore $\log{\frac{a^3}{b^4}} = 3\log{a} - 4\log{b}$
does that seem correct? please show your solution.

A: It seems correct, you used well the logarithm laws.


text:
Q: moment js how to 24 hours - current time I want to calculate 24 hours - current time so I did like this with moment.js
 moment('24:00:00').subtract(now, 'HH:mm:ss').format("HH:mm:ss")

but I recive
Invalid date

Help me

A: I resolved it like this
moment('24:00:00', 'HH:mm:ss')
  .subtract(moment().format("HH"), 'hours')
  .subtract(moment().format("mm"), 'minutes')
  .subtract(moment().format("ss"), 'seconds')
  .format("HH:mm:ss")