text:
Q: Recycler View error I'm creating Recycler View.
Here is MainActivity Code:
package com.example.nemes.myapplication;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import android.view.Menu;
import android.view.MenuItem;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity

    implements NavigationView.OnNavigationItemSelectedListener {
    private List<Movie> movieList = new ArrayList<>();
    private RecyclerView recyclerView;
    private MoviesAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        mAdapter = new MoviesAdapter(movieList);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));

// set the adapter
        recyclerView.setAdapter(mAdapter);
        prepareMovieData();

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    private void prepareMovieData() {
        Movie movie = new Movie("Mad Max: Fury Road", "Action & Adventure", "2015");
        movieList.add(movie);

        movie = new Movie("Inside Out", "Animation, Kids & Family", "2015");
        movieList.add(movie);

        movie = new Movie("Star Wars: Episode VII - The Force Awakens", "Action", "2015");
        movieList.add(movie);

        movie = new Movie("Shaun the Sheep", "Animation", "2015");
        movieList.add(movie);

        movie = new Movie("The Martian", "Science Fiction & Fantasy", "2015");
        movieList.add(movie);

        movie = new Movie("Mission: Impossible Rogue Nation", "Action", "2015");
        movieList.add(movie);

        movie = new Movie("Up", "Animation", "2009");
        movieList.add(movie);

        movie = new Movie("Star Trek", "Science Fiction", "2009");
        movieList.add(movie);

        movie = new Movie("The LEGO Movie", "Animation", "2014");
        movieList.add(movie);

        movie = new Movie("Iron Man", "Action & Adventure", "2008");
        movieList.add(movie);

        movie = new Movie("Aliens", "Science Fiction", "1986");
        movieList.add(movie);

        movie = new Movie("Chicken Run", "Animation", "2000");
        movieList.add(movie);

        movie = new Movie("Back to the Future", "Science Fiction", "1985");
        movieList.add(movie);

        movie = new Movie("Raiders of the Lost Ark", "Action & Adventure", "1981");
        movieList.add(movie);

        movie = new Movie("Goldfinger", "Action & Adventure", "1965");
        movieList.add(movie);

        movie = new Movie("Guardians of the Galaxy", "Science Fiction & Fantasy", "2014");
        movieList.add(movie);

        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

And Adapter class:
package com.example.nemes.myapplication;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {

    private List<Movie> moviesList;

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView title, year, genre;

        public MyViewHolder(View view) {
            super(view);
            title = (TextView) view.findViewById(R.id.title);
            genre = (TextView) view.findViewById(R.id.genre);
            year = (TextView) view.findViewById(R.id.year);
        }
    }

    public MoviesAdapter(List<Movie> moviesList) {
        this.moviesList = moviesList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.movie_list_row, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Movie movie = moviesList.get(position);
        holder.title.setText(movie.getTitle());
        holder.genre.setText(movie.getGenre());
        holder.year.setText(movie.getYear());
    }

    @Override
    public int getItemCount() {
        return moviesList.size();
    }
}

My problem is - when i launch app all okay, I see movies and info
Here is screen:

But when I scroll activity, I have this

It turns bigger.
Where is error?
Thank's for help.
UPDATE
Here is movie_list_row layout
 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:focusable="true"
                android:paddingLeft="16dp"
                android:paddingRight="16dp"
                android:paddingTop="10dp"
                android:paddingBottom="10dp"
                android:clickable="true"
                android:background="?android:attr/selectableItemBackground"
                android:orientation="vertical">

    <TextView
        android:id="@+id/title"
        android:textColor="@color/title"
        android:textSize="16dp"
        android:textStyle="bold"
        android:layout_alignParentTop="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/genre"
        android:layout_below="@id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/year"
        android:textColor="@color/year"
        android:layout_width="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_height="wrap_content" />

</RelativeLayout>

A: In your movie_list_row, change your RelativeLayout's height to
android:layout_height="wrap_content"

Or set an exact value like 100dip.

A: In your movie_list_row just change the layout_height of relative layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:focusable="true"
                android:paddingLeft="16dp"
                android:paddingRight="16dp"
                android:paddingTop="10dp"
                android:paddingBottom="10dp"
                android:clickable="true"
              android:background="?android:attr/selectableItemBackground"
                android:orientation="vertical">


text:
Q: Why the sum of all coefficients is 1 in Affine Combination? In Vector Space $V$, any vector $v$ can be written in $\textbf{linear combination}$ of a basis $\{e_1, e_2, \dots e_n\}$ such as
$$
v = \sum_{i=1}^{n} \alpha_i e_i
$$
In Affine Space, any point $p$ can be written in $\textbf{affine combination}$ of $\{p_1, p_1, \dots p_n\}$ such as
$$
p = \sum_{i=1}^{n} \beta_i p_i \quad \mbox{ where } 1 = \sum_{i=1}^{n} \beta_i
$$
My Questions:
Why we need the condition in $\textbf{Affine combination}$ such as
$$
1 = \sum_{i=1}^{n} \beta_i
$$
What is wrong with that if we DO NOT have the constraint

A: Think of the affine combination as a linear combination of position vectors, which we want to specify a point. Now, a position vector has two parts; a base vector to whatever point we're calling zero, and a displacement from that. Suppose you have coordinates based on the street grid numbers in a city - the vector says to go to the "zero point" downtown, and then move away from that a specified amount in each direction.
What happens when we apply an affine combination to these? Every vector in the combination has the same base vector, so we add a total of $1$ times that. The displacement vectors vary, and we get a new displacement vector from that. Overall, it's a position vector in the same form.
If, instead, we applied a linear combination without requiring the sum of coefficients to be $1$, we would multiply the base vector by that sum, whatever it is. Our new position vector would go to somewhere completely new as its base, then displace from there.
So what that sum condition means? It means that we can take an affine combination of position vectors for various points and get the position vector for a new point, in a way that doesn't depend on exactly which coordinate system we were using. Translating our coordinate system (choosing a new base point) translates that affine combination in exactly the same way, so that it still represents the same point.

A: Perhaps a small example is useful. Considider the two standard vectors in $\mathbb{R}^n$:
$\begin{pmatrix}1 \\ 0\end{pmatrix}$ and $\begin{pmatrix}0 \\ 1\end{pmatrix}$. The set of linear combinations is $\mathbb{R}^2$ while the set of affine combinations is the line through the two vectors: $\left\{\begin{pmatrix}x \\ 1-x\end{pmatrix} : x \in \mathbb{R}\right\}$. The set of affine combinations is the smallest affine set that contains the vectors.

A: It's helpful to recognize that, since affine combinations are particular linear combinations with the property given for the coefficients, every affine hull sits inside of a linear span. Conversely, if we are handed a vector space $V$ we can recover any affine space sitting inside of it by 1) choosing a 1-form $\omega : V\to k$, and 2) selecting a scalar $\lambda: \ast \to (k)$. The affine space is the set of vectors $v:V$ satisfying $\omega (v) = \lambda$. If $\lambda \neq 0$, then this set is a hyperplane in $V$ of codimension 1 which is offset from the origin. This corresponds to the description of affine space as a vector space which "forgot" its origin. If $\lambda = 0$, then you always have a preferred affine combination whose coefficients are all zero, so the reason zero has this exceptional quality (and hence why a generic nonzero $\lambda$ is conventionally used) is because zero is the additive identity in $k$ and the "affinity" of a linear combination is characterized by an additive expression in the coefficients.
The property of having a fixed sum $\lambda$ of the coefficients is what allows us to take differences of affine points and obtain vectors, which is a geometric restatement of the associativity and commutativity of scalar addition in the ring $k$. The statement $\lambda \neq 0$ is what prevents us from taking sums of affine points; if we add the coordinates pointwise then the resulting coordinates will instead sum to $2\lambda$, which is not equal $\lambda$ if we chose $\lambda \neq 0$. The important part is just that $\lambda$ be nonzero, because this obstructs our attempts to add points as vectors, and through this obstruction we formalize the idea that an affine space has lost its additional structure of having a distinguished origin, or additive identity element.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What kind of file does Microsoft QnA Maker accepts in the knowledge base? I recently started creating a bot using QnA maker. I tried feeding it a bunch of pdf files. But it seems like QnA maker is very particular about the format of the files it is being fed. For example: it can not read documents with columns (IEEE format).
Does anyone know if there is a knowledge base document rules that the QnA maker abide by?
Also where can I find the source code for the QnA maker so I can customize it?

A: Data must be in faq format or tsv format otherwise file can't feed
 Tsv format like this
Question   answer  source  metadata
How are you ?    I am fine  file2.pdf


text:
Q: How to send id to the webservice to retrieve the response in android? I need to get a response from the server using the id.
I tried to send the request using following code:
    soapObj = new SoapObject(sNameSpace, sMethodName);
    soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    soapObj.addProperty("VideoID", 85);

    soapEnvelope.dotNet = true;
    soapEnvelope.setOutputSoapObject(soapObj);

    HttpTransportSE http = new HttpTransportSE(sUrl);
    http.debug = true;

but i am getting an exception that
11-22 11:37:16.012: WARN/System.err(554): SoapFault - faultcode:
  'a:InternalServiceFault' faultstring: 'Specified argument was out of the range of
  valid values.
  11-22 11:37:16.012: WARN/System.err(554): Parameter name: VideoID' faultactor: 'null'
 detail: org.kxml2.kdom.Node@44f67890
  11-22 11:37:16.012: WARN/System.err(554):     at
       org.ksoap2.serialization.SoapSerializationEnvelope.parseBody(SoapSerializationEnvelope.java:136)
11-22 11:37:16.022: WARN/System.err(554):     at org.ksoap2.SoapEnvelope.parse(SoapEnvelope.java:137)
11-22 11:37:16.022: WARN/System.err(554):     at org.ksoap2.transport.Transport.parseResponse(Transport.java:96)
11-22 11:37:16.022: WARN/System.err(554):     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:189)
11-22 11:37:16.022: WARN/System.err(554):     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:95)
11-22 11:37:16.022: WARN/System.err(554):     at com.utils.WsdlService.getResponse(WsdlService.java:57)
11-22 11:37:16.022: WARN/System.err(554):     at com.scopra.screens.TableOfContents.onCreate(TableOfContents.java:46)
11-22 11:37:16.022: WARN/System.err(554):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-22 11:37:16.022: WARN/System.err(554):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
11-22 11:37:16.022: WARN/System.err(554):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
11-22 11:37:16.022: WARN/System.err(554):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
11-22 11:37:16.032: WARN/System.err(554):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
11-22 11:37:16.032: WARN/System.err(554):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-22 11:37:16.032: WARN/System.err(554):     at android.os.Looper.loop(Looper.java:123)
11-22 11:37:16.032: WARN/System.err(554):     at android.app.ActivityThread.main(ActivityThread.java:4627)
11-22 11:37:16.032: WARN/System.err(554):     at java.lang.reflect.Method.invokeNative(Native Method)
11-22 11:37:16.032: WARN/System.err(554):     at java.lang.reflect.Method.invoke(Method.java:521)
11-22 11:37:16.032: WARN/System.err(554):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-22 11:37:16.032: WARN/System.err(554):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-22 11:37:16.032: WARN/System.err(554):     at dalvik.system.NativeStart.main(Native      Method)

I dont whats the mistake.
Can anybody suggest help me in this.
Thanks

A: First find  SoapAction for desired operation (sMethodName) from WSDL.Then try this:
PropertyInfo pi = new PropertyInfo();
pi.setName("VideoID");
pi.setValue(85);
pi.setType(PropertyInfo.INTEGER_CLASS);

SoapObject request = new SoapObject(sNameSpace, sMethodName);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
//Uncomment this line for .NET based Web Services:
//envelope.dotNet = true;
envelope.setOutputSoapObject(Request);
AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(sUrl);
androidHttpTransport.debug = true;
try
{
androidHttpTransport.call(SoapAction, envelope);
}
catch(Exception e)
{
e.printStackTrace();
}


text:
Q: Conditionally invoke method with same name from two different classes I want an implementation where I need to invoke a method from one of two classes based on a condition. To illustrate, lets say I have two simplistic classes:
public class A implements IObject {
    @Override
    public void doIt() {
        System.out.println("OBJECTA");
    }
}

public class B implements IObject {
    @Override
    public void doIt() {
        System.out.println("OBJECTB");
    }
}

and an interface
public interface IObject {
    void doIt();
}

My method to dynamically call a class function is implemented as:
void call(String s, A a, B b, Consumer<IObject> o) {
    if(s.equalsIgnoreCase("CONDITION")) {
        o.accept(a);
    } else {
        o.accept(b);
    }
}

I can call the method as
A objectA = new A();
B objectB = new B();

call("CONDITION", objectA, objectB, IObject::doIt);
call("OTHER", objectA, objectB, IObject::doIt);

This will essentially invoke doIt on class A or B depending upon the condition parameter
Is there a cleaner way to achieve this by perhaps reducing the number of parameters an hence the function call signature?
Thanks

A: For my understanding of your problem:

*

*You have a condition

*You have a context to use (object a and b)

*You would not ask such a question if there was not an intent to generalize your code for more than one condition or object (a, b). Otherwise, a ternary operator or a if would be far more easier to maintain (eg: ((condition) a:b).doIt() vs the code below).

Why not using a pattern like this:
A a = new A();
B b = new B();
String hint = ...;

List<Executor> list = new ArrayList<>();
list.add(new Executor("CONDITION"::equalsIgnoreCase, a::doIt));
list.add(new Executor(s -> true, b::doIt));
for (Executor executor : list) {
  if (executor.process(hint)) {
    break;
  }
}

With Executor class:
class Executor {
  private final Predicate<String> predicate;
  private final Runnable runnable;
  ...
  public boolean process(String s) {
    if (!predicate.test(s)) {
      return false;
    }
    runnable.run();
    return true;
  }
}

The loop will evaluate the condition, then run the code if true, otherwise continue onto the next element.
The Executor class is technically not bound to a or b; only the initial setup is.

A: Here is a complete different approach, utilizing java.lang.reflect.Proxy:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 *
 * @author ben
 */
public class Test {

    public interface IObject {
        void doIt();
    }
    public static class A implements IObject {
        @Override
        public void doIt() {
            System.out.println("OBJECTA");
        }
    }
    public static class B implements IObject {
        @Override
        public void doIt() {
            System.out.println("OBJECTB");
        }
    }

    public static void main(String[] args) {

        final boolean condition = true;

        IObject proxyObj =  (IObject)Proxy.newProxyInstance(Test.class.getClassLoader(), new Class[]{IObject.class}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if (condition)
                    new A().doIt();
                else
                    new B().doIt();
                return null;
             }
        });

        proxyObj.doIt();
    }
}

Here, you are creating a Proxy-Object for your Interface.
When you call .doIt() on this object, the invocation-handler will call the appropriate implementation, based on a condition.
You could then pass the proxy around and work with the invocation handler.
(It should be clear that this code should only give an idea and is only an example of how proxied interfaces/objects could be used to solve this problem.)

A: It really depends on your use cases. If the use cases are as simple as what you've described, you could remove the Consumer and just call doIt directly in the call function. However, I would recommend generalizing the function even further:
static <T> void ifElse(boolean decider, T optionA, T optionB, Consumer<T> callback) {
    if (decider) {
        callback.accept(optionA);
    } else {
        callback.accept(optionB);
    }
}

Then call it with:
A a = new A();
B b = new B();
ifElse(condition.equals("CONDITION"), a, b, IObject::doIt);

Doing it this way is cleaner and more expandable. It also takes the same amount of code. (Untested, may have errors, but you get the idea). This approach is what you might see in purely ("purely") functional programming languages, where an if statement is just a function that takes a conditional and two functions (one for true, one for false).

A: The above requirement can be implemented easily by using the 'Factory design pattern'
The factory design pattern involves these 3 steps:

*

*Define the common interface for both the object types

*Define the different classes that implement the common interface

*Create a Factory class with a static method that returns one of the object types based on the input condition

Here is a working demo:
// File name: Demo.java

interface IObject {
    public void doIT();
}

class A implements IObject {
    public void doIT() {
        System.out.println("DoIT - Class A");
    }
}

class B implements IObject {
    public void doIT() {
        System.out.println("DoIT - Class B");
    }
}

class IObjectFactory {
    static IObject getObject(String CONDITION) {
        if(CONDITION.equalsIgnoreCase("CONDITION")) {
            return (new A());
        }
        return (new B());
    }
}

public class Demo {
    public static void main(String[] args) {
        IObject io1 = IObjectFactory.getObject("condition");
        IObject io2 = IObjectFactory.getObject("no condition");
        io1.doIT();
        io2.doIT();
    }
}

Output:
> javac Demo.java

> java Demo

DoIT - Class A
DoIT - Class B


text:
Q: cluster Analysis, Error in dimnames(x) <- dn : length of 'dimnames' [2] not equal to array extent I'm trying to use the poLCA package for Latent Clustering Analaysis.
My data frame can be downloaded here as an rda file and saved it into your working directory:
   https://drive.google.com/open?id=1eGJprHaXdoVhKNlGD5VcsoND7iyIoNwJ
load(file = "QuestionData.rda")

When I try to run the LCA :
library("MPsychoR")
library("poLCA")
formula <- cbind(Question1, Question2, Question3, Question4) ~ 1
OneClass <- poLCA(formula, data = Output, nclass = 1, nrep = 3)
TwoClass <- poLCA(formula, data = Output, nclass = 2, nrep = 3)

I get the following error:
Error in dimnames(x) <- dn :
length of 'dimnames' [2] not equal to array extent

From reading around and looking at others who've encountered this error, it seems to arise because there is a difference between the number of columns in their data frame and the number of column names they entered into a function... but I have 4 columns in my data frame and 4 added into the poLCA function. Can anyone help me to understand why I'm encountering this error?
If you're not wanting to download my data, the general structure of my data frame is as follows:
Question1 <- c('Sufficient', 'Problematic', 'Problematic', 'Sufficient',
'Excellent')
Question2 <- c('Insufficient', 'Insufficient', 'Insufficient', 'Sufficient',
'Sufficient')
Question3 <- c('Sufficient', 'Sufficient', 'Insufficient', 'Sufficient',
'Sufficient')
Question4 <- c('Problematic', 'Insufficient', 'Problematic', 'Problematic',
'Excellent')
Question5 <- c('Insufficient', 'Sufficient', 'Sufficient', 'Exceptional',
'Exceptional')

DF <- data.frame(Participants, Question1, Question2, Question3, Question4,
Question5)

DF$Question1 <- factor(DF$Question1, levels = c("Problematic",
"Insufficient", "Sufficient", "Excellent"), ordered=TRUE)
DF$Question2 <- factor(DF$Question2, levels = c("Problematic",
"Insufficient", "Sufficient", "Excellent"), ordered=TRUE)
DF$Question3 <- factor(DF$Question3, levels = c("Problematic",
"Insufficient", "Sufficient", "Excellent"), ordered=TRUE)
DF$Question4 <- factor(DF$Question4, levels = c("Problematic",
"Insufficient", "Sufficient", "Excellent"), ordered=TRUE)
DF$Question5 <- factor(DF$Question5, levels = c("Problematic",
"Insufficient", "Sufficient", "Excellent", "Exceptional"), ordered=TRUE)

A: You have different levels for each your response variables:
summary(Output)
        Question1          Question2          Question3           Question4
 Problematic :150   Problematic : 57   Problematic :181   Problematic  :456
 Insufficient:211   Insufficient:157   Insufficient:320   Insufficient :130
 Sufficient  :238   Sufficient  :692   Sufficient  :405   Sufficient   : 48
 Excellent   :307   Excellent   :  0                      Excellent    :272
                                                          ExcellentPlus:  0

If I am not wrong (not so familiar with your data), you can have them with the same levels:
NewOutput = Output
for(i in 1:ncol(NewOutput)){
    NewOutput[,i] = factor(as.character(Output[,i]),order=TRUE,
    levels=c("Problematic","Insufficient","Sufficient","Excellent"))
}
poLCA(cbind(Question1,Question2,Question3,Question4)~1,data=NewOutput,nclass=1)

I omitted "ExcellentPlus" from your factors as it is not found in your example data.


text:
Q: AlertDialog after AlertDialog I am keep getting an error on my Code. I am trying to call a new AlertDialog inside of an AlertDialog.
It seems to have a Problem showing salert, but i can't see why...
public String passA = "";
public String passB = "";

public void createPassword() {
    final AlertDialog.Builder alert = new AlertDialog.Builder(this);
    final AlertDialog.Builder salert = new AlertDialog.Builder(this);
    final EditText input = new EditText(this);
    input.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD
            | InputType.TYPE_CLASS_TEXT);

    salert.setView(input); // edit text added to alert
    alert.setView(input); // edit text added to alert
    salert.setTitle("Widerholen Sie Ihre PIN"); // title setted
    alert.setTitle("Geben Sie eine PIN an"); // title setted

    final OnClickListener b = new OnClickListener() {
        public void onClick(DialogInterface arg0, int arg1) {
            passB = input.getText().toString();
            if (passA.equals(passB)) {
                editor = settings.edit();
                editor.putString("password", passA);
                editor.commit();
                logged_in = true;
                return;
            }
        }
    };
    salert.setPositiveButton("OK", b);

    OnClickListener a = new OnClickListener() {
        public void onClick(DialogInterface arg0, int arg1) {
            passA = input.getText().toString();

            salert.show();
            return;
        }
    };

    alert.setPositiveButton("OK", a);

    alert.setOnCancelListener(new OnCancelListener() {

        public void onCancel(DialogInterface dialog) {
            // TODO Auto-generated method stub
            Functions.writeError("Falsche PIN Eingabe.");
            finish();
        }

    });
    alert.show();
}

The Error i am getting is:
10-24 12:02:32.836: E/AndroidRuntime(2446): FATAL EXCEPTION: main
10-24 12:02:32.836: E/AndroidRuntime(2446): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
10-24 12:02:32.836: E/AndroidRuntime(2446):     at android.view.ViewGroup.addViewInner(ViewGroup.java:3337)
10-24 12:02:32.836: E/AndroidRuntime(2446):     at android.view.ViewGroup.addView(ViewGroup.java:3208)
10-24 12:02:32.836: E/AndroidRuntime(2446):     at android.view.ViewGroup.addView(ViewGroup.java:3188)
10-24 12:02:32.836: E/AndroidRuntime(2446):     at com.android.internal.app.AlertController.setupView(AlertController.java:401)
10-24 12:02:32.836: E/AndroidRuntime(2446):     at com.android.internal.app.AlertController.installContent(AlertController.java:241)
10-24 12:02:32.836: E/AndroidRuntime(2446):     at android.app.AlertDialog.onCreate(AlertDialog.java:336)
10-24 12:02:32.836: E/AndroidRuntime(2446):     at android.app.Dialog.dispatchOnCreate(Dialog.java:353)
10-24 12:02:32.836: E/AndroidRuntime(2446):     at android.app.Dialog.show(Dialog.java:257)
10-24 12:02:32.836: E/AndroidRuntime(2446):     at android.app.AlertDialog$Builder.show(AlertDialog.java:932)
10-24 12:02:32.836: E/AndroidRuntime(2446):     at de.pixelstein.nativ.NativeTestActivity$5.onClick(NativeTestActivity.java:257)
10-24 12:02:32.836: E/AndroidRuntime(2446):     at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
10-24 12:02:32.836: E/AndroidRuntime(2446):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-24 12:02:32.836: E/AndroidRuntime(2446):     at android.os.Looper.loop(Looper.java:137)
10-24 12:02:32.836: E/AndroidRuntime(2446):     at android.app.ActivityThread.main(ActivityThread.java:4514)
10-24 12:02:32.836: E/AndroidRuntime(2446):     at java.lang.reflect.Method.invokeNative(Native Method)
10-24 12:02:32.836: E/AndroidRuntime(2446):     at java.lang.reflect.Method.invoke(Method.java:511)
10-24 12:02:32.836: E/AndroidRuntime(2446):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
10-24 12:02:32.836: E/AndroidRuntime(2446):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
10-24 12:02:32.836: E/AndroidRuntime(2446):     at dalvik.system.NativeStart.main(Native Method)

Any help or information would be helpfull.

A: You are using one view for multiple dialogs, one view can just have one parent.
Change:
final EditText input = new EditText(this);

salert.setView(input); // edit text added to alert
alert.setView(input); // edit text added to alert

To:
final EditText firstInput = new EditText(this);
final EditText secondInput = new EditText(this);

salert.setView(firstInput); // edit text added to alert
alert.setView(secondInput); // edit text added to alert


text:
Q: Reducing tuple values with reduceByKey in Pyspark I'm starting to work with the MapReduce paradigm with Pyspark, I'm stuck with a problem and I don't know if it a programming error or that I shouldn't do it this way.
I have data from which I am extracting the following information with map for each line:
(id, (date, length, counter)), I did it this way to extract all the info I need from the raw data file and filtering the noisy lines so I don't have to use the raw data file again. Btw: Counter is originally 1, and it is intended for addition in future reduceByKey.
Now the data looks like this:
data = [('45', ('28/5/2010', 0.63, 1)), ('43', ('21/2/2012', 2.166, 1)), ('9', ('12/1/2009', 2.33, 1))]
First, I am trying to count the number of key-value pairs, so it is a simple reduceByKey adding the counters, I tried to do it this way: data.reduceByKey(lambda a,b: a[2] + b[2]) which provides the following error TypeError: 'int' object is not subscriptable.
If a and b are supposed to get the value of the pair, the element 2 is supposed to have the counter of it, I cannot get my head around it. Is it better to map several times the raw data file extracting every-time a different needed value? Should I map this data variable extracting (key, value) pairs each time with the value needed from the tuple? Is it just that I'm making a programming error?
Any guidance is welcome, thanks!

A: Ok, I found the issue.
When reducing for example (id, (x, x, 1)), (id, (y, y, 1)), (id, (z, z, 1)), in the first reduce you would obtain (id, 2), (id, (z, z, 1)) so when trying to reducing again, the number 2 in the first element is non subscriptable, I must keep the data structure during the process.


text:
Q: How to pass value to another static page via javascript? I am trying to pass  value to another page and read the value in the another page. I use only JavaScript and jQuery. Not use others language as PHP. I don't want to be as like (http://www.example.com/?value=test). I am trying to use POST or GET method.
On first page:
$.post("second_page.html",{q:"test"});
window.location.replace("second_page.html");

On second page:
var location_query = window.location.search.substring(1);
    var vars = location_query.split("&");
    for (var i in vars) {
        var param = vars[i].split("=");
        params[param[0].toString()] = param[1];
    }

If I pass value as like http://www.example.com/?q=test , the second page script is read the value, but I use this line: $.post("second.html",{q:"test"}); not read.
How to pass value from first page to another static page via JavaScript or jQuery or ajax?

A: See this post says:

POST data is data that is handled server side. And Javascript is on client side. So there is no way you can read a post data using JavaScript.

but you can use cookies to read and store values:
<script src="/path/to/jquery.cookie.js"></script>

you can get it from here
Try with reading the documentation and see if this works for you.

A: Without using GET or POST you can transfer the content using HTML5 Local Storage or
Web SQL

A: $.post and $.get send AJAX request and waiting response on current page, you cant send params for next window.location.replace by this.
Use url get-params window.location.replace("404.html?q=404"); and look this for get params on second page.


text:
Q: Webservice @httpPost method authentication Quick response on this would be helpful. I'm able to send request body from Workbench as source to my org as destination for creation of records. But what i need is how to perform the same operation using Postman tool or something else. Basically i have add authentication on my webservice class(means i have to allow my @httpPost method to access by only those for whom i give permission in my salesforce org based on username and password / Oauth methos.). Its for Webservice class @httpPost method.

A: This is the way i found out to do,
I tried this with postman tool.
First enter the below URL with respective parameters and make a request for access token
Endpoint url = https://"yourOrgInstance".salesforce.com/services/oauth2/token

PARAMETERS
client_id  =  3MVG99S6MzYiT5k8Wklml6FnGX5UVDSDSASADSAV.lWcKcPlMhaikiPoapcdX,
client_secret  =  641362283729873987213897123,
username = jayanth@christ.dev,
password  = *********,
grant_type  = password.

AFTER OBTAINING THE ACCESS TOKEN
Endpoint url = https://"yourOrgInstance".salesforce.com/services/apexrest/StudentsDetails

HEADERS
Content-Type = application/json,
Authorization = Bearer 00D0l000000Cssm!AQEAQAhRNEsMvWDunFuM7XaPUs58vyI5wWYyLu06I5tUdCmoG3O5FsqRiVuL0JYM6091nUP0UlHGuzN60rBvkTMIiKyEQ6aK
or
Authorization = Bearer "AccessToken"

now add your request body and make a call.


text:
Q: Display chosen radio-buttons and checkboxes aside in real time before submitting I have a form in which people choose from radio-buttons and checkboxes...The thing is i need to show in the  part of the page the chosen data before they put their mail and submit!
I need to do it without refreshing so i cannot work with php for that part! How can i show the chosen data as soon as the radio-button/checkbox is clicked??
html:

                <form action="higuera.php" method="post" name="form" id="form">

1.Elegí tu abono MENSUAL:

                        <input type='radio' name='abono' value="cinco clases" id="cinco-clases"/>
                        <input type='radio' name='abono' value="nueve clases" id="nueve-clases"/>
                        <input type='radio' name='abono' value="abono libre" id="abono-libre"/>
                        <input type='radio' name='abono' value="clase suelta" id="clase-suelta"/>
                        <input type='radio' name='abono' value="clases grupales" id="clases-grupales"/>

2.Elegí los horarios de las clases según tu abono.

this is only a portion! then the chosen data is stored in php variables.

A: You can use JavaScript to do this. Write a function in JavaScript that will display what you have selected onClick. I have written a sample code for you
<form>
    <input type='radio' name='abono-radio' value="cinco clases radio" id="cinco-clases-radio" onclick="displaySelectedRadio(this)" />
    cinco clases radio
    <input type='radio' name='abono-radio' value="nueve clases radio" id="nueve-clases-radio" onclick="displaySelectedRadio(this)" />
    nueve clases radio

    <input type='checkbox' name='abono' value="cinco clases" id="cinco-clases" onclick="displaySelectedCheckBox(this)" />
    cinco clases
    <input type='checkbox' name='abono' value="nueve clases" id="nueve-clases" onclick="displaySelectedCheckBox(this)" />
    nueve clases

</form>

JavaScript function
function displaySelectedRadio(id) {
    document.getElementById("dispSelectedRadio").innerHTML = id.value;
}

function displaySelectedCheckBox(id) {
    if (id.checked) {
        if (document.getElementById(id.value + "-disp")) {
            document.getElementById(id.value + "-disp").innerHTML = id.value;
        } else {
            document.getElementById("displayHere").innerHTML = document.getElementById("displayHere").innerHTML + '
' + id.value + '
';
        }
    } else {
        document.getElementById(id.value + "-disp").innerHTML = "";
    }
}

Live Demo here

A: I think this kind of functionality could be implemented with the use of JavaScript as it looks for DOM events. For example when the user has unfocused on the element it is stored within a variable that is then used later down the page to fill in what you need.


text:
Q: References on binomial coefficients of the form $\binom{-1/m}{k} $ I'm interested in binomial coefficients of the form $$\binom{-1/m}{k} .$$
Although I have found some sources indicating this expression can be rewritten in an interesting way when $m=2$, I have found little information so far on it when $m \in \mathbb{Z}_{\geq 3}$.
I am therefore curious as to whether any articles or book chapters on this particular binomial expression have been written. Information regarding sums involving this expression is also much appreciated.

A: Consider the formal power series $y(x)$ satisfying $y^m = \frac{1}{1 - mx}$, which gives
$$y(x) = (1 - mx)^{- \frac 1 m} = \sum_{n \ge 0} (-1)^n m^n {-\frac 1 m \choose n} x^n.$$
Taking logs and exponentiating again gives
$$y(x) = \exp \left( \frac{1}{m} \log \frac{1}{1 - mx} \right) = \exp \left( \sum_{k \ge 1} \frac{m^{n-1} x^n}{n} \right).$$
This gives us that $n! [x^n] y(x)$ counts permutations but where a permutation with cycles of length $\ell_1, \dots \ell_n$ is weighted by $m^{\sum (\ell_i - 1)}$. The quantity $\sum (\ell_i - 1)$ is sometimes called the length of a permutation; it gives the minimal $\ell$ such that a permutation can be expressed as a product of $\ell$ transpositions. It's equal to $n$ minus the number of cycles, which means we get the Stirling numbers of the first kind but in reverse order:
$$\boxed{ (-1)^n m^n {-\frac 1 m \choose n} = \frac{1}{n!} \sum_{i=0}^n \left[ {n \atop i} \right] m^{n-i} }.$$
Compare to the generating function for the Stirling numbers in the usual order, which is
$$(-1)^n {-m \choose n} = {n+m-1 \choose n} = \frac{1}{n!} \sum_{i=0}^n \left[ {n \atop i} \right] m^i$$
and which corresponds to looking at $(1 - x)^{-m}$.

What you might've been hoping for was an expression in terms of ${mn \choose n}$ generalizing the case $m = 2$, and it turns out that some nice things can be said about this sequence. Using Lagrange inversion or the more explicit combinatorial argument in this blog post we can show that the formal power series $z(x)$ satisfying $z = 1 + xz^m$ has coefficients
$$z(x) = \sum_{n \ge 0} \frac{1}{(m-1)n + 1} {mn \choose n} x^n$$
which generalizes the well-known generating function for the Catalan numbers, to which it reduces when $m = 2$ (and in fact these coefficients count $m$-ary trees in a way that generalizes the way the Catalan numbers count binary trees). This is Example 6.2.6 in Stanley's Enumerative Combinatorics, Vol. II. Example 6.2.7 uses this to show that the formal power series $w(x) = \sum_{n \ge 0} {mn \choose n} x^n$ satisfies
$$\frac{w - 1}{1 + (m-1)w} = x \left( \frac{mw}{1 + (m-1)w} \right)^m$$
so like $y$ and $z$ it is also algebraic, but its minimal polynomial appears to be more complicated. For example, setting $m = 3$ and clearing denominators gives that $w = \sum_{n \ge 0} {3n \choose n} x^n$ satisfies
$$(w - 1)(1 + 2w)^2 = 27x w^3$$
and expanding and rearranging gives
$$(27x - 4) w^3 + 3w + 1 = 0.$$
So more complicated than $(1 - 3x) y^3 = 1$, unfortunately. Stanley is probably your best bet for learning more about this sort of thing; it's extremely comprehensive, especially the exercises. The series $w$ appears again in Exercise 6.13.

A: A simple identity:
$${(1+x)^{1/m}}=\sum_{k\geq 0}{\binom{1/m}{k}}x^k.$$
converting it to the binomial  form $$\binom{km}{k}$$ is far harder though
For m=3, it arises when finding the roots of a cubic equation [1] and certain enumerative combinatorics problems in which the characteristic equation is a cubic  , such as random walks involving two steps forward and one step back. The 1 step forward, one step back process involves the usual m=2, but m=3  case is far harder and nice analytic expressions as far as I know do not exist ,except for simple cases in which there is a single absorbing barrier.
see:
[1] Find the second real root for cubic $x^3+1-x/b=0$


text:
Q: How can I retrieve Notifications list of status bar programmatically? How can I retrieve Notification list of status bar programmatically on android?
I found some ways like NotificationListenerService, but I would be happy to know any methods or apis that I can retrieve every StatusBarNotification s in one method call.
public List<StatusBarNotification> getNotifications()
{
    //...
}

EDIT
Thanks to comment I found some way. I'll post it later when I am finished, for further users.


text:
Q: In Recycler View I want to remove specific index items but index gets change after removing first item and the result gets change I have ArrayList like {A B C D E f} and I want to remove index by 1,3,5 positions respectively,
After removing an item from 1 position, then ArrayList look like { A C D E F}.
Then after if I remove an item from the 3rd position, it removes E instead of D so I do not get the required result.
I have tried all methods of notify...();
public class branchadapter extends RecyclerView.Adapter<branchadapter.MyViewHolder>  {
    public static ArrayList<branchdata> ndata;

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView textView;
        private final Context context;

        public MyViewHolder(View itemView) {
            super(itemView);
            context = itemView.getContext();
            textView = itemView.findViewById(R.id.t2);
        }
    }
    public branchadapter(ArrayList<branchdata> list) {
        ndata = list;
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from((viewGroup.getContext())).inflate(R.layout.branchcard, viewGroup, false);
        MyViewHolder evh = new MyViewHolder(v);
        return evh;
    }
    @Override

    public void onBindViewHolder(final MyViewHolder myViewHolder, final int i) {
        branchdata mlist = ndata.get(i);
        myViewHolder.textView.setText(mlist.getText());

    }

    @Override
    public int getItemCount() {
        return ndata.size();
    }

    public void removeAt(int position) {

                    ndata.remove(position);
    }
}

A: Suppose you have different element in your list,
you can use list.remove(element) instead of list.remove(position)
list = arrayListOf("a", "b", "c")
list.remove("b")

A: Use some id such as id of the item or item itself for deletion rather than the position.
Your remove method should take an item as an argument and look for its position in the current list and then remove it.
public void removeAt(Item item) {
    int itemPosition = nData.indexOf(item);
    ndata.remove(itemPosition);
}

Also, make sure to notify adapter that item at itemPosition has been removed.


text:
Q: PersistenceException occured : org.hibernate.exception.ConstraintViolationException: could not insert: [models.User] I have got this exception!!
here is my model class
@Entity
public class User extends Model {

    @OneToMany(mappedBy="email", cascade=CascadeType.ALL)
    public List<Photo> photo;

    @Email
    @Required
    @Unique
    public String email;

    @Required
    public String passwordHash;

    @Required
    public String education;

    @Required
    public String fname;

    @Required
    public String lname;

    @Required
    public Date dob;

    @Required
    public String gender;

    @Required
    public String country;

    @Required
    public Long phone;

    @Required
    public String status;

    @Required
    public String jobtitle;

    @Required
    public String company;

    @Required
    public String industry;

    @Required
    public Date addDate;

    public String needConfirmation;

public User(String email, String password, String fname,
                String lname, Date dob, String gender, String country,
                Long phone, String status, String education, String jobtitle, String company, String industry) {
        //all initialization here
    }
}

can you please tell me where I am going wrong
playframework× 2289

this is my photo class, and please tell me how can I allow JPA to generate my database

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package models;

import controllers.Users;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import play.db.jpa.Model;

/**
 *
 * @author nPandey
 */
@Entity
public class Photo extends Model{

    public String photoname;

    @ManyToOne
    public User email;

    public String owner;

    public Photo(){

    }

    public Photo(User email, String photo){
        this.photoname=photo;
        this.email=email;
        this.owner=email.email;
    }

}

A: Check that your entity isn't missing any required fields when it's being persisted / updated. Also check what constraints are set on the User-table in the DB (unique keys, foreign keys, non nulls...).

A: Your mappedBy value makes little sense. It is used on the passive end of a bi-directional association. In those cases it points to the attribute on the other class on the other side of the relationship. You are pointing it to one of the attributes of the User class. Perhaps your Photo class has a email attribute, but is that of type User ( i am guessing not). So if this is a bi-directional association, set the mappedBy value to the attribute on Photo having the corresponding @ManyToOne "back" to the User. If it is a unidirectional association, remove the mappedBy and perhaps use @JoinColumn to use the foreign key mapping strategy of unidirectional one-to-many

A: I was facing same issue and it got resolved by changing relationship related notation from OneToMany to ManyToMany. In My case there was ManyToMany relation between Job and Person Table and I was trying to add same jobList to multiple person object in a loop.
The problem was with the annotation used in Person Entity class for Job Entity:
@ManyToMany // Changed from OneToMany to ManyToMany
private List<Job> jobList = new ArrayList<Job>();

A: Try editing the code as below -
In User Model
    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    public List<Photo> photos;

In Photo Model
    @ManyToOne
    @NotFound(action = NotFoundAction.IGNORE)
    @JoinColumn(name = "email", nullable = false, insertable = false, updatable = false)
    public User user;

Check this for reference - http://en.wikibooks.org/wiki/Java_Persistence/OneToMany#Example_of_a_OneToMany_relationship_and_inverse_ManyToOne_annotations


text:
Q: Missing H2ConsoleProperties bean in Spring Boot MockMvc test I have spring boot application (mvc, thymeleaf, data jpa, h2) with configuration that permits all users to access h2-console:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    PathRequest.H2ConsoleRequestMatcher h2ConsoleRequestMatcher = PathRequest.toH2Console();
    http.authorizeHttpRequests(requests -> requests
            .requestMatchers("/").permitAll()
            .requestMatchers(h2ConsoleRequestMatcher).permitAll()
            .anyRequest().authenticated()
    );
    http.csrf(csrf -> csrf.ignoringRequestMatchers(h2ConsoleRequestMatcher));
    http.headers().frameOptions().sameOrigin();
    //...

    return http.build();
}

I also have test where I want to verify, that h2-console is accessible:
@SpringBootTest
@AutoConfigureMockMvc
class SecurityApplicationTests {
@Autowired
MockMvc mockMvc;

@Test
void shouldAccessH2Console() throws Exception {
    mockMvc.perform(get("/h2-console"))
            .andExpect(status().isOk());
}

}
When I run test I get the NoSuchBeanDefinitionException:
No qualifying bean of type 'org.springframework.boot.autoconfigure.h2.H2ConsoleProperties' available
But if I start application from main(), everything works as expected and I can access H2 from the browser.
I would expect that @SpringBootTest provides full application context as the @SpringBootApplication does
Why the H2ConsoleProperties bean is not created in tests, and how can I fix this?


text:
Q: angular-gettext does not pick the strings from .PO files I have installed everything according to documentation. Some of the things are working as per the documentation. Is there something like Django translation which automatically replaces the translation for specific language if you select those lang ?
Index.html
<!DOCTYPE HTML>

{% load static %}

    <translate>Hello!</translate> Sagar

Hello!

PO file
msgid ""
msgstr ""
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Project-Id-Version: \n"
"POT-Creation-Date: \n"
"PO-Revision-Date: \n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"X-Generator: Poedit 2.2.3\n"
"Last-Translator: \n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
"Language: fr\n"

#: ui/templates/admin/firsttranslate/index.html:24
#: ui/templates/admin/firsttranslate/index.html:26
msgid "Hello!"
msgstr "Halo !"

When I run my code It searches for Hello and Replaces with Bonjour But I want it to be replace automatically as Django does
Thanks in advance.

A: I forgot mentioned the path of file in Gruntfile.js
'use strict';

module.exports = function (grunt) {
grunt.initConfig({
    nggettext_extract: {
        pot: {
            files: {
                'po/template.pot': ['ui/templates/admin/firsttranslate/*.html', 'js/first.js']
            }
        },
    },

    nggettext_compile: {
        all: {
            files: {
                'js/translations.js': ['fr/LC_MESSAGES/djangojs.po']
            }
        },
    },
});

grunt.loadNpmTasks('grunt-angular-gettext');

grunt.registerTask('default', ['nggettext_extract', 'nggettext_compile']);
};


text:
Q: OnClIck in Javascript Not Working For Image I have OnClick Function and On ClientClick Function as
<asp:ImageButton ID="imgbtnSchedule" runat="server" ClientIDMode="Static" ImageUrl="~/images/Update2.png" ToolTip="Refresh"  OnClick="imgbtnSchedule_Click"   OnClientClick="return validateUpdate(1);"  />

My OnClick Function Is Not Working so I Started Debugging using F12. but Here I can see my OnClick function Is Not there and Onclientclick property is showing as OnClick.

A:
I have Onlick Function On Server side and An OnClientClick Function On
client side,I am expecting Ececution Of both OnClick and
OnClientClick,How To Achive this

base on that code
<asp:ImageButton ID="imgbtnSchedule" runat="server" ClientIDMode="Static" ImageUrl="~/images/Update2.png" ToolTip="Refresh"
    OnClick="imgbtnSchedule_Click"
    OnClientClick="return validateUpdate(1);"  />

If the validateUpdate(1) returns false, then the imgbtnSchedule_Click will not called.


text:
Q: How to store the file as an array in scala? I am trying to make a code that reads the lines in file and then store it as an array in scala?
The following is the code I wrote:
import scala.io.Source
val fname = args(0)
for (line <- Source.fromFile(fname).getLines)

I don't know what to do next?
Thank you in advance.

A: If you want an array, you simply can call toArray on the getLines method.
val arrayOfLines = Source.fromFile(fname).getLines.toArray

(or .toList for an immutable list)


text:
Q: How to read .docx on Android with Apache Poi I have .docx file in assets folder and use this part of code to to read it
  AssetManager am = context.getAssets();

   InputStream is;

  is = (InputStream) am.open("amaretti.docx");

  XWPFDocument hdoc=new XWPFDocument(OPCPackage.open(is));

and jars for this are:
   poi.jar
   poi-ooxml.jar

But shows me an error:
  08-27 18:16:31.660: I/dalvikvm(23221): Could not find method           org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDocument1$Factory.newInstance, referenced from method org.apache.poi.xwpf.usermodel.XWPFDocument.onDocumentCreate

I guess some jar or classes are missing.
Any suggestion would be useful.
Thanks in advance

A: You're missing some jars. In order to read Word 2007 files using POI you also need the following libraries (they're all available in the archive you download from the official Apache POI site):
poi-ooxml-schemas (the one you're getting the error about)
xmlbeans
dom4j
stax
According to the official website, dom4j and stax are no longer needed but I found I had problems when I didn't add them.
Unfortunately, you're bound to discover that adding all of these libraries will result in a Dalvik dex error (an Android classes.dex can hold up to 64k of method declarations, which you will cross). The "official" explanation for this is that POI is simply not designed for Android. Unfortunately I have not been able to find an easy, manageable solution for that problem (there have been attempts, some partially successful, of porting POI to Android, but they're too cumbersome for my taste). I solved that problem by sending the Word 2007 files to a remote server, converted them to the old format and returned to the mobile device to be opened by POI.


text:
Q: Algorithm to get all zeniths crossing a box in three dimensions, MATLAB implementation I have a 3D geometry problem and I am not certain of the best approach to solve it. I have a model with two boxes, one above the others. They have the same dimension, L (length) * p (depth) * e (thickness), and are separated by a height of h. They are perfectly superposed, with no offset between them.
For each point of my bottom box, I want to get the zenith of all lines that can cross the top box and arrive to this point. It doesn't matter if the line crosses the top box by the top or the side.
The zenith is the angle of "looking up". In our case, a zenith of 0 represents the point directly above the point P, and an angle of 90 is directly looking in front. A zenith of 180 would be looking below the point, but for our use, it's useless. The zeniths we look for are between 0 and 90°.
For a more intuitive visualization, let's say that I have a hole in the ceiling, and that I want to map the zenith of all light that crosses this hole and reaches the floor.
This is what it looks like:

For any point P of the bottom box, I want an array containing the zeniths of all "rays" that cross the top box before arriving on P. The red lines are the "edges", the last zeniths I would get for each corner.
I am working on a way to code it in MATLAB and I was wondering if there was a better algorithm that I am not seeing. My approach, in pseudocode, would be this:

bottomBox = [1:L, 1:p, 1:e];
topBox = [1:L, 1:p, 1+h:e+h];

results = zeros(L:p) * NaN; % Array of results, one per "case" on the bottom box
zeniths = zeros(L:p) * NaN; % Array of zeniths for each result case

for i = 1:L
    for j = 1:p      % Browsing the bottom box case by case
        for k = 1:L
           for l = 1:p
               for m = 1:e    % For each bottom box case, browsing the top box case by case
                   p1 = topBox(k,l,m);     % p1 is each case on the top box
                   p2 = bottomBox(i,j,1);  % p2 is the current bottom box case, z doesn't mattter
                   p3 = topBox(i,j,m);     % p3 is the projection of p2 on the top box (zenith = 0)

                   v1 = p1 - p2;
                   v2 = p3 - p2;

                   zeniths(k,l) = rad2deg(atan2(norm(cross(p1, p2)), dot(p1, p2)));
               end
            end
         end
         results(i,j) = zeniths;
     end
end

I tried to implement this and I couldn't get it to work. More specifically, the angle calculation doesn't seem to work, I have an error stating:

Error using cross;
A and B must be of length 3 in the dimension in which the cross product is taken.

I am looking for advice on how to build the algorithm.
Please tell me if the question is better suited for another StackExchange community, such as Math.

A: Zenith angle is just
atan2(h, sqrt(dx^2+dy^2))

where dx, dy are coordinate differences along L and p axes (i-k and j-l in your loops)
Perhaps h+m (m as your variable for m = 1:e) instead of h if you need points inside top box

A: I'll get you started showing you one way to do it for 1 point and I'll let you build the final loop to do the calc for all your points.
As expressed in the comment, for the purpose of these calculations, you do not need to consider the thickness of your plates, you can model them simply with two parallel planes separated by a distance H.
I don't know the size of your plates nor the grid size you want so I'll keep it simple for this example:
H = 5 ; % distance between the planes

[X,Y] = meshgrid(-3:3,-2:2) ;
GridSize = size(X) ;
Zb = zeros(GridSize) ;
Zt = zeros(GridSize) + H ;

This gives you 4 matrices, defining 2 planes. The bottom plane is composed of [X,Y,Zb] and the top plane is formed by [X,Y,Zt].
If you want to visualise them, you can run the following code (optional):
%% Display planes
figure ;
ht = surf(X,Y,Zt, 'FaceColor',[.8 .8 .8],'DisplayName','Top plate') ;
hold on
hb = surf(X,Y,Zb, 'FaceColor',[.6 .6 .6],'DisplayName','Bottom plate') ;
xlabel('X') ; ylabel('Y') ; zlabel('Z') ;
axis equal ; legend show

Now for the rest of the example, I selected a point P, at coordinate [-2,1,0]. This choice is completely arbitrary, just for the example. In your final algorythm you will still have to loop over several points Pi (although remember that your problem is symetric so if your domain is too large you can reduce your computations by using the symetries of your model).
%% This will have to be embedded into a loop over the points Pi
% Assuming points P=(-2,1,0)
p = [-2;1;0] ;

zn = [0;0;1] ; % unitary vector, oriented Oz

dx = X - p(1) ; % `x` distance between all points of the plane and P
dy = Y - p(2) ; % `y` distance between all points of the plane and P
dz = zeros(size(X)) + H ;   % `z` distance (all the same)
V = [dx(:) dy(:) dz(:)].' ; % to obtain list of vector V = [dx;dy;dz] ;

nv = size(V,2) ;            % number of points/angle to calculate
zenith = zeros(nv,1) ;      % preallocate result matrix (always good!)
for k=1:nv
    % [u] is the vector going from `P` to the current point considered on the top plane
    u = V(:,k) ;
    % determine the angle between [u] and [zn]
    zenith(k) = atan2( norm(cross(u,zn)) , dot(u,zn) ) ;
end
% Reshape "zenith" from vector to matrix so it matches the base grid system
zenith = reshape( zenith , GridSize ) ;

You now have, for this point P, a matrix of angle with every other point of the top plane:
>> rad2deg(zenith)
ans =
         32.31         30.96         32.31         35.80         40.32         45.00         49.39
         24.09         21.80         24.09         29.50         35.80         41.81         47.12
         15.79         11.31         15.79         24.09         32.31         39.51         45.56
         11.31             0         11.31         21.80         30.96         38.66         45.00
         15.79         11.31         15.79         24.09         32.31         39.51         45.56

Once again, completely optionally, if you want to visualise the vectors which were used for the calculations:
for k=1:nv
    hp(k) = plot3([p(1) X(k)],[p(2) Y(k)],[0 H],'Marker','o','MarkerFaceColor','k') ;
end

will yield:

Now for your final result, remember you have a 2D matrix for each point P of your bottom plane, so your final result will either be a collection of 2D matrices or a large 3D matrix.


text:
Q: std::vector as a global variable in Visual c++ I'm making a windows form application using c++ (perhaps a foolish idea?)
and i have a few global variables:
private: System::Windows::Forms::OpenFileDialog^  openFileDialog;
private: System::Windows::Forms::ListBox^  outputListBox;
private: bool done;
private: array<String^>^ filesList;
private: vector< FrequencyDataSet > storedModels;

however when i compile it it says:
Error   1   error C4368: cannot define 'storedModels' as a member of managed 'Project::Form1': mixed types are not supported

what i want to happen, is that when the application loads, a thread starts in the background and loads in the stored data models. and stores them so they can be accessed by other functions at a later stage. everything else works fine so far, just need to be able to store the models globally.
can anyone suggest an alternative to how i'm going about it?

A: std::vector is not a managed type. The error message is pretty clear. Instead of vector, use a managed collection class. System::Collections::Generic::List<FrequencyDataSet> is nice this time of year, I've heard.

A: Is FrequencyDataSet a native type used by some library you're using?
If not, then go with System::Collections::Generic::List<FrequencyDataSet> storedModels as Seva suggested.
If it is, then you need a native collection to manage your native types, and std::vector is a good choice.  But std::vector can't be directly inside your Form, since the .NET garbage collector will move your Form instances around to compact memory.  So you need to put the vector where it won't move.  One option is a real global variable:
In your header file:
extern std::vector<FrequencyDataSet> g_storedModels;

and in one .cpp file:
std::vector<FrequencyDataSet> g_storedModels;

However, if you need one copy for each instance of your Form or other class, you need to use dynamic allocation from the native heap (which won't move around) and keep a pointer.  This would work (inside your ref class MyForm or whatever you called it):
std::vector<FrequencyDataSet>* storedModels;
MyForm() : storedModels(new std::vector<FrequencyDataSet>())
{
    /* the rest of your constructor... InitializeComponents and so forth */
}

But this vector isn't managed by the garbage collector, now you'd need to remember to free it when your Form is destroyed.  A smart pointer will help with that.
clr_scoped_ptr<std::vector<FrequencyDataSet>> storedModels;
MyForm() : storedModels(new std::vector<FrequencyDataSet>())
{
    /* the rest of your constructor... InitializeComponents and so forth */
}

See here for my clr_scoped_ptr, which you may use as long as you abide by the license in the comments.  Or you can study it to learn how to write your own.


text:
Q: Read column value in a CSV file starting from another column value? I am working on extracting certain data from OECD statistics. These are available in a CSV file and look as follows (excerpt):
"COUNTRY","Country","DAGEGR","Age groups","DSEX","Gender","DSTATUS","Status of population","YEAR","Year","Value","Flag Codes","Flags"
"AUS","Australia","900000","All ages","90","Total males+females","90","All population","2002","2002",19640979,,
"AUS","Australia","900000","All ages","90","Total males+females","90","All population","2003","2003",19872646,,
"AUS","Australia","900000","All ages","90","Total males+females","90","All population","2004","2004",20091504,,
"AUS","Australia","900000","All ages","90","Total males+females","90","All population","2005","2005",20339759,,
"AUS","Australia","900000","All ages","90","Total males+females","90","All population","2006","2006",20605488,,
"AUS","Australia","900000","All ages","90","Total males+females","90","All population","2007","2007",21015042,,
"AUS","Australia","900000","All ages","90","Total males+females","90","All population","2008","2008",21431781,,
"AUS","Australia","900000","All ages","90","Total males+females","90","All population","2009","2009",21874920,,
"AUS","Australia","900000","All ages","90","Total males+females","90","All population","2010","2010",22342398,,
"AUS","Australia","900000","All ages","90","Total males+females","90","All population","2011","2011",22620554,,
"AUS","Australia","900000","All ages","90","Total males+females","90","All population","2012","2012",22683573,,
"LUX","Luxembourg","900000","All ages","90","Total males+females","90","All population","2002","2002",444050,,
"LUX","Luxembourg","900000","All ages","90","Total males+females","90","All population","2003","2003",448300,,
"LUX","Luxembourg","900000","All ages","90","Total males+females","90","All population","2004","2004",451600,,
"LUX","Luxembourg","900000","All ages","90","Total males+females","90","All population","2005","2005",455000,,
"LUX","Luxembourg","900000","All ages","90","Total males+females","90","All population","2006","2006",469086,,
"LUX","Luxembourg","900000","All ages","90","Total males+females","90","All population","2007","2007",476187,,
"LUX","Luxembourg","900000","All ages","90","Total males+females","90","All population","2008","2008",483799,,
"LUX","Luxembourg","900000","All ages","90","Total males+females","90","All population","2009","2009",493500,,
"LUX","Luxembourg","900000","All ages","90","Total males+females","90","All population","2010","2010",502066,,
"LUX","Luxembourg","900000","All ages","90","Total males+females","90","All population","2011","2011",511840,,
"LUX","Luxembourg","900000","All ages","90","Total males+females","90","All population","2012","2012",524853,,
"ESP","Spain","900000","All ages","90","Total males+females","90","All population","2002","2002",40409330,,
"ESP","Spain","900000","All ages","90","Total males+females","90","All population","2003","2003",41550584,,
"ESP","Spain","900000","All ages","90","Total males+females","90","All population","2004","2004",42345342,,
"ESP","Spain","900000","All ages","90","Total males+females","90","All population","2005","2005",43038035,,
"ESP","Spain","900000","All ages","90","Total males+females","90","All population","2006","2006",43758250,,
"ESP","Spain","900000","All ages","90","Total males+females","90","All population","2007","2007",44474631,,
"ESP","Spain","900000","All ages","90","Total males+females","90","All population","2008","2008",45283259,,
"ESP","Spain","900000","All ages","90","Total males+females","90","All population","2009","2009",45828172,,
"ESP","Spain","900000","All ages","90","Total males+females","90","All population","2010","2010",45989016,,
"ESP","Spain","900000","All ages","90","Total males+females","90","All population","2011","2011",46152926,,
"ESP","Spain","900000","All ages","90","Total males+females","90","All population","2012","2012",46818221,,

What I am trying to do is to automatically read out how many inhabitants Spain (ESP) had in 2007. To achieve this I use the following command:
cat RPOP_16012023145346836.csv | cut -d "," -f 1,9,11 | sort

This command returns me the country, the year and the number of inhabitants, e.g.:
"AUS","2002",19640979
"AUS","2003",19872646
"AUS","2004",20091504
"AUS","2005",20339759
"AUS","2006",20605488
"AUS","2007",21015042
"AUS","2008",21431781
"AUS","2009",21874920
"AUS","2010",22342398
"AUS","2011",22620554
"AUS","2012",22683573
"AUT","2002",8139310
"AUT","2003",8067289
"AUT","2004",8140122
"AUT","2005",8206524
"AUT","2006",8265925
"AUT","2007",8298923
"AUT","2008",8331930
"AUT","2009",8355260
"AUT","2010",8375290
"AUT","2011",8404252
"AUT","2012",8443018
"ESP","2002",40409330
"ESP","2003",41550584
"ESP","2004",42345342
"ESP","2005",43038035
"ESP","2006",43758250
"ESP","2007",44474631
"ESP","2008",45283259
"ESP","2009",45828172
"ESP","2010",45989016
"ESP","2011",46152926
"ESP","2012",46818221
"LUX","2002",444050
"LUX","2003",448300
"LUX","2004",451600
"LUX","2005",455000
"LUX","2006",469086
"LUX","2007",476187
"LUX","2008",483799
"LUX","2009",493500
"LUX","2010",502066
"LUX","2011",511840
"LUX","2012",524853

I would like to pass this result using a pipe to a statement that returns the third column (column 3 = population) based on the country (column 1 = ESP) and the year (column 2 = 2007). Unfortunately, I do not have the appropriate command for this. Can someone help me with this?
Expected output is: 44474631

A: Using Miller (mlr) to first filter the data for only the record relating to Spain in 2007 using the two named fields COUNTRY and YEAR, and then to cut out the Value field from that record.  The output will be presented without a header.
mlr --csv --headerless-csv-output \
    filter '$COUNTRY == "ESP" && $YEAR == 2007' then \
    cut -f Value \
    RPOP_16012023145346836.csv

Given the data in the question, this would output
44474631

Instead of the filter expression
$COUNTRY == "ESP" && $YEAR == 2007

... you could use
$Country == "Spain" && $Year == 2007

... since those named fields also exist.

A: If the aim really is to simply return the number 44474631, you can do all in one using awk on the original input file:
awk -F, '$1=="\"ESP\"" && $9=="\"2007\"" {print $11}' RPOP_16012023145346836.csv

This will set the field separator to , and print the content of column 11, but only if column 1 is equal to "ESP" (including quotes), and column 9 is equal to "2007" (again, including quotes).

A: You could use awk for that:
$ sed 's/"//g' input_file | awk -F, '($1=="ESP" && $9==2007){print $1,$9,$11}'
ESP 2007 44474631


text:
Q: Set Minimum width to 320px on Mac OSX Is it possible to set a min width for an OSX window to 320px?
The default min width in Safari is greater than this which makes it difficult to program with media queries and replicate on OSX. Please see my screenshot, which will make things clearer.
Incidentally if you are going to post techy answers (I assume someone will) please bear in mind I have no experience with backend code, the most I know is CSS / PHP / JS.
I don't mind getting my hands dirty, but the instructions need to be verbose :-)

A: Taken from This Link - worked for me in both chrome and safari on OS X
var location = 'http://www.my-app-address.com'
javascript:open(location,'iPhone:portrait','innerWidth='+(320+15)+',innerHeight='+(480+15)+',scrollbars=yes');

and for landscape:
javascript:open(location,'iPhone:landscape','innerWidth='+(480+15)+',innerHeight='+(320+15)+',scrollbars=yes');

A: In Safari, you can install an extension called 'Resizer' and you have the option of putting in custom sizes.
The funny thing is, once you use Resizer to change the window size, it can then be resized by hand to any size you want. It is almost like using Resizer unlocks the window.

A: I've created a chrome extension,OSX Resizer, that makes a 320px pop-up of the current window.
Basically the same as Rubinsh's solution, but code free.
The Resizer extension that drummin mentions does not provide this behavior for me.

A: This can be emulated through Chrome Dev Tools now.
Open Inspector, click the gear on the bottom right, and goto the 'Overrides' tab.
You can even spoof your user agent :)

A: If your goal is to see how sites will look on an iPhone, you can always download Xcode for free from the Mac App Store, which includes the iOS Simulator.
Alternatively, if you have an iPhone (I assume you do if you're developing sites for it), iOS 6 includes a remote debugging feature that lets you use the Web Inspector on your Mac to inspect and edit a site loaded on your iPhone.


text:
Q: How do I summon a mob that drops an item with custom durability? I have tried and failed to summon a mob with a fixed durability item. Every time the entity is killed, it drops the item with a randomized durability, because such is the way. But is there a way to over-ride this and give the item a fixed durability on drop? I have tried:
/summon zombie ~ ~1 ~ {HandItems:[{Count:1,id:stone_sword,tag:{Damage:1,display:{Name:"\"Blade\""}}},{}],HandDropChances:[1.0f,0.0f]}

The test being the "Damage:1" bit.

A: You need to override its loot table with your own. To add your own loot table, you will need a data pack (which is a folder from which the game will load your loot table) and you need the loot table itself which you can either write manually or generate using an online loot table generator.
I already made this data pack, you can download it here:
https://www.dropbox.com/sh/bc0obb1ffcevdla/AAAmA49J_C-olU25uxGWwwKva?dl=0
to apply it to your save, paste the folder "zombie_loot_table" inside .minecraft/saves/your_save/datapacks and make sure to /reload if you are already in the game.
but in case you want to do it yourself, here is all the information you need:
Data pack structure - https://minecraft.gamepedia.com/Data_pack
loot table generator - https://misode.github.io/loot-table/
my tutorial on loot tables - https://datapackcenter.com/projects/loot-tables.72/


text:
Q: Can't select an md-select dropdown option using Selenium I have an angular-material dropdown with a set of options, and am attempting to select one of the options. I'm selecting them as follows:
html file:
<md-select name="myDropdown"
           ng-model="addCompany.details.someModel"
           ng-change="addCompany.swapDisplayedAreas()"
           required>

    <md-option value="Company A">Company A</md-option>
    <md-option value="Company B">Company B</md-option>
</md-select>

python test:
input = self.browser.find_element_by_name('myDropdown')
input.click()
choice = self.browser.find_element_by_xpath("//*[contains(text(), 'Company A')]")
choice.click()

However, no matter how I try to select the option, I either get the following error:

selenium.common.exceptions.WebDriverException: Message: Element is not
      clickable at point (750, 423). Other element would receive the click:
      <md-backdrop style="position: fixed;" class="md-select-backdrop
      md-click-catcher ng-scope"></md-backdrop>

Or I can see that the element is clicked on, but that the dropdown still stays pulled out. Attempting to click on any other element on the page while the dropdown is still pulled out gives a similar md-backdrop would receive the click error.
Any idea how I can choose a dropdown selection for an md-select element? I've tried disabling md-backdrop for my input elements without any success.

A: You should try using WebDriverWait to wait until options open from the dropdown and getting visible and clickable before click as below :-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

#find dropdown and click to open options
input = self.browser.find_element_by_name('myDropdown')
input.click()

#now wait until options getting visible and clickable
choice = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "md-option[value = 'Company A']")))
choice.click()

A: I would guess the issue may be one of the following:

*

*There is another element on the page with the text "Company A" and that element is trying to be clicked even though the dropdown option is clearly the element you want selenium to click. This is because selenium clicks the first element that satisfies the identifier. To check if this is the problem I would use the find elements and check how many elements are found. If that is the problem try using the css selectors such as value.

*If you are using chrome I came across a similar problem with the chrome webdriver when testing an angular application.
This is the issue https://code.google.com/p/selenium/issues/detail?id=2766
I tried elegant workarounds but nothing worked...in the end I used the solution by Lukeis.
In java
int n=10;
    String errorMessage;
    for (int i=1; i<=n; i++)
    {
        try {
            clickThis.click();
            break;
        } catch(WebDriverException driverException) {
            Thread.sleep(1000);
            errorMessage = driverException.toString();
        }
        if(i==n)
        {
            Assert.fail("Failed to click "+n+" times \n" + errorMessage);
        }
    }

It pretty much tries to click the element 10 times.


text:
Q: Post File name variable using tcpsend autoit I need to know how to post file name variable to desired one instead of "upload.zip"
i know how to automate file name using php only but required autoit to post variable of file name using tcpsend method
Thanks
PHP code:
<?php
print_r($_POST);
print_r($_FILES);
copy($_FILES["upload"]["tmp_name"], "upload.zip");
?>

Autoit code:
ConsoleWrite(_PHPupload('192.168.1.2', _OSmacros(), 89, '/upload/index.php', 'application/zip') & @CRLF)

    Func _PHPupload($pIP, $pMacros, $pPort, $phpPath, $pContent)
        If FileExists($pFile) = 0 Then Return SetError(1, 1, '')
        $pTcpc = TCPConnect($pIP, $pPort)
        If @error Then Return SetError(1, 2, '')
        Local $pBound = "-----" & Random(10000000, 99999999, 1)
        Local $pData1 = "--" & $pBound & @CRLF
        $pData1 &= 'Content-Disposition: form-data; name="upload";  filename="' & $pFile & '"' & @CRLF & 'Content-Type: ' & $pContent & @CRLF & @CRLF
        Local $pData2 = @CRLF & "--" & $pBound & @CRLF & 'Content-Disposition: form-data ;name="test"' & @CRLF & @CRLF & "variable" & @CRLF
        $pData2 &= "--" & $pBound & "--" & @CRLF & @CRLF
        Local $pHeader = 'POST ' & $phpPath & ' HTTP/1.1' & @CRLF
        $pHeader &= 'Host: ' & $pIP & @CRLF
        $pHeader &= 'User-Agent: ' & $pMacros & @CRLF
        $pHeader &= 'Content-Type: multipart/form-data; boundary=' & $pBound & @CRLF
        $pHeader &= 'Content-Length: ' & (StringLen($pData1) + StringLen($pData2) + FileGetSize($pFile)) & @CRLF & @CRLF
        Local $pFopen = FileOpen($pFile, $FO_READ)
        If $pFopen = -1 Then Return SetError(1, 3, '')
        Local $sFread = FileRead($pFopen)
        TCPSend($pTcpc, $pHeader & $pData1 & $sFread & $pData2)
        If @error Then Return SetError(1, 4, '')

        Local $pBuffer = ""

        While 1
            $pBuffer &= TCPRecv($pTcpc, 1024)
            If @error Then
                Return SetError(1, 5, '')
            Else
                ExitLoop
            EndIf
        WEnd

        MsgBox(64, "", $pBuffer)

    EndFunc   ;==>_PHPupload

A:
$pFile is not declared, but even if it is, it wont work because its a
  filepath and you are sending it as a filename at

filename="' & $pFile

This should work:
ConsoleWrite(_PHPupload('192.168.1.2', _OSmacros(), 89, '/upload/index.php', 'application/zip', "c:\somedir", "somefile.zip") & @CRLF)

    Func _PHPupload($pIP, $pMacros, $pPort, $phpPath, $pContent, $pFilePath, $pFileName)
        $pFile = $pFilePath & "\" & $pFileName
        If FileExists($pFile) = 0 Then Return SetError(1, 1, '')
        $pTcpc = TCPConnect($pIP, $pPort)
        If @error Then Return SetError(1, 2, '')
        Local $pBound = "-----" & Random(10000000, 99999999, 1)
        Local $pData1 = "--" & $pBound & @CRLF
        $pData1 &= 'Content-Disposition: form-data; name="upload";  filename="' & $pFileName & '"' & @CRLF & 'Content-Type: ' & $pContent & @CRLF & @CRLF
        Local $pData2 = @CRLF & "--" & $pBound & @CRLF & 'Content-Disposition: form-data ;name="test"' & @CRLF & @CRLF & "variable" & @CRLF
        $pData2 &= "--" & $pBound & "--" & @CRLF & @CRLF
        Local $pHeader = 'POST ' & $phpPath & ' HTTP/1.1' & @CRLF
        $pHeader &= 'Host: ' & $pIP & @CRLF
        $pHeader &= 'User-Agent: ' & $pMacros & @CRLF
        $pHeader &= 'Content-Type: multipart/form-data; boundary=' & $pBound & @CRLF
        $pHeader &= 'Content-Length: ' & (StringLen($pData1) + StringLen($pData2) + FileGetSize($pFile)) & @CRLF & @CRLF
        Local $pFopen = FileOpen($pFile, $FO_READ)
        If $pFopen = -1 Then Return SetError(1, 3, '')
        Local $sFread = FileRead($pFopen)
        TCPSend($pTcpc, $pHeader & $pData1 & $sFread & $pData2)
        If @error Then Return SetError(1, 4, '')

        Local $pBuffer = ""

        While 1
            $pBuffer &= TCPRecv($pTcpc, 1024)
            If @error Then
                Return SetError(1, 5, '')
            Else
                ExitLoop
            EndIf
        WEnd

        MsgBox(64, "", $pBuffer)

    EndFunc   ;==>_PHPupload


text:
Q: How to find a fractal with a predetermined Hausdorff dimension? For many patterns that display self-similarity, the Hausdorff dimension can be found. Sometimes the dimension is calculated and approximate - as is the case with the Feigenbaum attractor - but often its closed form in terms of known mathematical constants be obtained - for instance, the Hausdorff dimension of the Cantor set is $ \log_{3}(2)$.
I am interested in the inverse problem: suppose we consider a mathematical constant like $\pi^{-1}$ or $\gamma e$. Can we always find and describe a fractal whose Hausdorff dimension is equal to this preset number?

A: We can construct a fractal similar to the Koch curve with arbitrary dimension $1<D<2$.
Consider starting with a line segment of length 1. We divide it into 2 line segments at a slight angle. Then replace each of those segments again with the opposite angle. And so on.
If we pick the relative length of the line segments such that after 2 iterations we get a equilateral triangle, we have the "normal" Koch curve with dimension $D=\log_3 4$. Otherwise we get a curve with an arbitrary dimension $1 <D <2$.
If we pick $f$ as the length fraction of the original line segment that we divide into 2 segments, then the length of the curve with respect to dimension $D$ after $n$ iterations is:
$$L_n = 2^n (f^n)^D = (2f^D)^n$$
It means that the dimension $D$ of the curve is such that
$$2f^D=1 \implies f=e^{-\ln 2/D}$$
Fill in $D=\gamma e$ to get the corresponding curve.
Similarly we can construct a Cantor set with $D=\pi^{-1}$ as @Claude pointed out.


text:
Q: Updating an object for the current user logged in on Parse I have successfully created a user log-in and register that allows users to access the application. Within my PFUser class on parse, I have the column of type 'string' called 'Check In'.
How would i update this column (or object?) when say, a button is pressed on the application (to update the current users status)?
PFUser *user = [PFUser currentUser];
//update the object under column 'check in' (i.e in/out)

Thanks!


text:
Q: How can I flush HTTP Headers from Controller? I want to stream a .csv export file to the client. I need to send HTTP headers to the client so the client shows the downloading file. Then I want to start streaming the .csv file to the client.
The code below doesn't work for me. The method Response.Body.Flush() repeats the whole ExecuteExport() method.
public FileStreamResult ExecuteExport()
{
    Response.Headers.Add("Content-type", "someType");
    Response.Headers.Add("Content-disposition", "export.csv");

    // Trying to flush Http Headers
    Response.Body.Flush();

    MemoryStream outputStream = new MemoryStream();

    // Start exporting and streaming .csv file to client
    this.ExportAndStream(ref outputStream);

    return new FileStreamResult(outputStream, type)
    {
        FileDownloadName = "export.csv"
    };
}

A: If you want to clear the Headers, you shouldn't flush the Body... For one, flushing makes sure all currently buffered output is sent to the client. And second, body != headers.
You can use the HttpResponse.ClearHeaders Method

Clears all headers from the buffer stream.

Be sure to clear the headers before you add yours:
Response.ClearHeaders();
Response.Headers.Add("Content-type", "someType");
Response.Headers.Add("Content-disposition", "export.csv");


text:
Q: Extracting excel files with SSIS i am trying to create a ForEachLoop container that extracts excel files within a source folder.
i have created an execute sql task within a ForEachLoop container that stores my excel files full paths in an sql server table
and now i can't figure how to make it go through that list and extract each file into an ole db destination table
ps: the excel files have different types of data, columns change almost from one file to another (28 files)
can you please help me ? thank you in advance.

A: It won't work within a for each loop because your destination for each spreadsheet has to be a table that matches the columns coming in. If it was 25 different spreadsheets with the same columns types and number of columns you could insert all the rows into one table but it sounds like you need to create separate data flows for each one. You can then combine the datasource--> transform--> Ole Destination onto one data flow (which could run in parallel) and you would have (for 26 imports) three steps for each spreadsheet.


text:
Q: When to use worker and factory function in angularjs i am learning angularjs from Pro angularjs by adam freeman.
This is an example he defined an directive in angularjs
myApp.directive("highlight", function () {
  return function (scope, element, attrs) {
    if (scope.day == attrs["highlight"]) {
      element.css("color", "red");
    }
  };
});

the first function the writer calls is factory function and it returns a worker function. I' m not able to understand why he returns another function.
When i write the code below, the code returns an error.
I don't know what i'm doing wrong.
myApp.directive("highlight", function (scope, element, attrs) {
  if (scope.day == attrs["highlight"]) {
    return element.css("color","red")
  }
});

A: If you take a look at the Angular docs about directives, you'll see that there are two ways you can define a directive. One is to use the directive definition object and the other is to just return a postLink function.
The example in your book shows the latter form. The reason your function doesn't work is because Angular calls your function and expects it to return a directive definition object or a postLink function. Instead the function you defined returns nothing or the result of element.css("color", "red") depending on your if statement.


text:
Q: Sencha touch, fieldset onChange Listener I just want to console.log('some info') everytime when user selects an option on the fieldset, I tried this doesn't work for me.
                    {
                    xtype: 'fieldset',
                    items: [{
                            id: 'selVehiclename',
                            xtype: 'selectfield',
                            store:'itemvehicles',
                            valueField:'itemID',
                            displayField: 'name'
                            }],
                    listeners:{
                         change: function(slider, thumb, obj1, val)
                         {
                             console.log('some info');
                         }
                    }
                },

A: There is no Change listener for fieldset.You should listen to change event inside the selectfield
{
                    xtype: 'fieldset',
                    items: [{
                            id: 'selVehiclename',
                            xtype: 'selectfield',
                            store:'itemvehicles',
                            valueField:'itemID',
                            displayField: 'name',
 listeners:{
                         change: function(slider, thumb, obj1, val)
                         {
                             console.log('some info');
                         }
                    }
                            }],

                },


text:
Q: Calculate the limit $\lim_{h \to 0}\frac{f(x_{0}+2h)-f(x_{0}-h)}{5h}$ The function $f$ is differentiable at $x_{0}$.Calculate the limit $\lim_{h \to 0}\frac{f(x_{0}+2h)-f(x_{0}-h)}{5h}$.That's what I have tried:
$$\begin{align}\lim_{h \to 0}\frac{f(x_{0}+2h)-f(x_{0}-h)}{5h}&=\frac{2}{5}\lim_{h \to 0}\frac{f(x_{0}+h)}{2h}+\frac{1}{5}\frac{f(x_{0}-h)}{-h}\\&=\frac{2}{5}(f'(x_{0})+\lim_{h \to 0}\frac{f({x_{0}})}{h})+\frac{1}{5}(f'(x_{0})+\lim_{h\to 0}\frac{f(x_{0})}{h})\\&=\frac{3}{5}(f'(x_{0})+\lim_{h\to0}\frac{f(x_{0})}{h})\end{align}$$
Could you tell me if it is right?

A: Better rewrite
$$\frac{f(x_0+2h)-f(x_0-h)}{5h} =\frac{f(x_0+2h)-f(x_0)+f(x_0)-f(x_0-h)}{5h}=\frac25\frac{f(x_0+2h)-f(x_0)}{2h}+\frac15\frac{f(x_0-h)-f(x_0)}{-h}$$

A: Hint
$$\lim_{h \to 0}\frac{f(x_{0}+2h)-f(x_{0}-h)}{5h}=\frac 1 5\left[2\lim_{h \to 0}\frac{f(x_{0}+2h)-f(x_{0})}{2h}+\lim_{h \to 0}\frac{f(x_{0}-h)-f(x_{0})}{-h}\right]$$


text:
Q: Practical Usage of HttpSessionBindingListener And HttpSessionAttributeListener I am reading through head first JSP and servlets. Going through different type of listeners, I came across HttpSessionBindingListener and HttpSessionAttributeListener.
I was thinking about the difference between the two - I want to see the practical usages in real world examples of those two listeners. I tested HttpSessionBindingListener by implementing valueBound() and valueUnBound() - why would an object need to know whether it has been added or not?
I am pretty confused about the practical usages. Please help in clarifying this.

A: The HttpSessionBindingListener is to be implemented on the class whose instances may be stored in the session, such as the logged-in user.
E.g.
public class ActiveUser implements HttpSessionBindingListener {

    @Override
    public void valueBound(HttpSessionBindingEvent event) {
        logins.add(this);
    }

    @Override
    public void valueUnbound(HttpSessionBindingEvent event) {
        logins.remove(this);
    }

}

When an instance of this ActiveUser get set as a session attribute by HttpSession#setAttribute(), then the valueBound() will be invoked. When it get removed by either HttpSession#removeAttribute(), or an invalidate of the session, or get replaced by another HttpSession#setAttribute(), then the valueUnbound() will be invoked.
Here are some real world use cases:

*

*Getting SessionScoped bean from HttpSessionListener?

*How to call a method before the session object is destroyed?

*Call an action when closing a JSP

*implementing HttpSessionListener

*How to access HTTP sessions in Java
The HttpSessionAttributeListener is to be implemented as an application wide @WebListener which get invoked when any attribute is added, removed or replaced in the HttpSession. Continuing with the above ActiveUser example, this is particularly useful if you can't modify the ActiveUser class to implement HttpSessionBindingListener (because it's 3rd party or so), or when you want to make use of a "marker interface" on an arbitrary amount of classes so that you can do the listening job in a single central place.
@WebListener
public class ActiveUserListener implements HttpSessionAttributeListener {

    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        if (event.getValue() instanceof ActiveUser) {
            logins.add(event.getValue());
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        if (event.getValue() instanceof ActiveUser) {
            logins.remove(event.getValue());
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        if (event.getValue() instanceof ActiveUser) {
            logins.add(event.getValue());
        }
    }

}

Here's a real world use case:

*

*Getting notification when bounded/unbounded to a HTTP session


text:
Q: Parsing data from a text file into an array I have a flat text file that contains the following data;

Following are the names and ages in a text file.

26|Rachel
29|Chris
26|Nathan

The data is kept on a server (e.g http://domain.com/info.dat), I'd like to read this text file and insert it into an array (age and name). I'd like to ignore the first line (Following are....).
I've sorted the code to grab the data file using a webclient and the code to open the dat file using streamreader as follows;
using (StreamReader sr = new StreamReader(path))
                {
                    while (sr.Peek() >= 0)
                    {
                        string[] channels = Text.Split('|');

                        foreach (string s in channels)
                        {

                        }
                    }
                }

The problem with the above code is when it comes to inputting it into an array with the correct columns. Could anyone give me some pointers?
Many thanks

A: How about an answer that uses some LINQ:
var results = from str in File.ReadAllLines(path).Skip(1)
              where !String.IsNullOrEmpty(str)
              let data = str.Split('|')
              where data.Length == 2
              select new Person { Age = Int32.Parse(data[0], NumberStyles.Integer, CultureInfo.CurrentCulture), Name = data[1] };

results is now IEnumerable<Person> which you can do ToList or ToArray on to get a List<Person> or Person[], or you can simply use the results with a foreach loop.
UPDATE: here is the Person class needed to make this more functional.
public class Person
{
   public int Age { get; set; }
   public string Name { get; set; }
}

A: You could do something like this. (There is no error checking, you might want to check for errors when parsing the age etc.
class Person
{
  string Name {get;set;}
  int Age {get;set;}
}

List<Person> people = new List<Person>();
string line;
using (StreamReader sr = new StreamReader(path))
{
  sr.ReadLine();
  while ((line == sr.ReadLine()) != null)
  {
    string[] channels = line.Split('|');
    people.Add(new Person() {Age=int.Parse(channels[0]), Name=channels[1]});
  }
}

A: You should use Dictionary and not Array to store the data.
Sample code:
FileStream fs = new FileStream("filename");
Dictionary<int,string> dict = new Dictionary<int,string>();
string line = "";
fs.ReadLine(); //skip the first line
while( (line = fs.ReadLine()) != null)
{
    string parts = line.split("|".ToCharArray());
    dict.Add(int.Parse(parts[0]), parts[1]);
}


text:
Q: How to separate one list in two via list comprehension or otherwise If have a list of dictionary items like so:
L = [{"a":1, "b":0}, {"a":3, "b":1}...]

I would like to split these entries based upon the value of "b", either 0 or 1.
A(b=0) = [{"a":1, "b":1}, ....]
B(b=1) = [{"a":3, "b":2}, .....]

I am comfortable with using simple list comprehensions, and i am currently looping through the list L two times.
A = [d for d in L if d["b"] == 0]
B = [d for d in L if d["b"] != 0]

Clearly this is not the most efficient way.
An else clause does not seem to be available within the list comprehension functionality.
Can I do what I want via list comprehension?
Is there a better way to do this?
I am looking for a good balance between readability and efficiency, leaning towards readability.
Thanks!
update:
thanks everyone for the comments and ideas! the most easiest one for me to read is the one by Thomas. but i will look at Alex' suggestion as well. i had not found any reference to the collections module before.

A: Don't use a list comprehension. List comprehensions are for when you want a single list result. You obviously don't :) Use a regular for loop:
A = []
B = []
for item in L:
    if item['b'] == 0:
        target = A
    else:
        target = B
    target.append(item)

You can shorten the snippet by doing, say, (A, B)[item['b'] != 0].append(item), but why bother?

A: If the b value can be only 0 or 1, @Thomas's simple solution is probably best. For a more general case (in which you want to discriminate among several possible values of b -- your sample "expected results" appear to be completely divorced from and contradictory to your question's text, so it's far from obvious whether you actually need some generality;-):
from collections import defaultdict

separated = defaultdict(list)
for x in L:
  separated[x['b']].append(x)

When this code executes, separated ends up with a dict (actually an instance of collections.defaultdict, a dict subclass) whose keys are all values for b that actually occur in dicts in list L, the corresponding values being the separated sublists.  So, for example, if b takes only the values 0 and 1, separated[0] would be what (in your question's text as opposed to the example) you want as list A, and separated[1] what you want as list B.