答:
```<code>Space_Position[np.random.randint(0, len(Space_Position))]
[np.random.randint(0, len(Space_Position))]
</code>```

gives you what you want

Body:
I have a 2d array/matrix like this, how would I randomly pick the value from this 2D matrix, for example getting value like [-62, 29.23]. I looked at the numpy.choice but it is built for 1d array.

The following is my example with 4 rows and 8 columns

Space_Position=[
      [[-62,29.23],[-49.73,29.23],[-31.82,29.23],[-14.2,29.23],[3.51,29.23],[21.21,29.23],[39.04,29.23],[57.1,29.23]],

      [[-62,11.28],[-49.73,11.28],[-31.82,11.28],[-14.2,11.28],[3.51,11.28],[21.21,11.28] ,[39.04,11.28],[57.1,11.8]],

      [[-62,-5.54],[-49.73,-5.54],[-31.82,-5.54] ,[-14.2,-5.54],[3.51,-5.54],[21.21,-5.54],[39.04,-5.54],[57.1,-5.54]],

      [[-62,-23.1],[-49.73,-23.1],[-31.82,-23.1],[-14.2,-23.1],[3.51,-23.1],[21.21,-23.1],[39.04,-23.1] ,[57.1,-23.1]]
      ]

In the answers the following solution was given:

random_index1 = np.random.randint(0, Space_Position.shape[0])
random_index2 = np.random.randint(0, Space_Position.shape[1])
Space_Position[random_index1][random_index2]

this indeed works to give me one sample, how about more than one sample like what np.choice() does?

Another way I am thinking is to tranform the matrix into a array instead of matrix like,

Space_Position=[
      [-62,29.23],[-49.73,29.23],[-31.82,29.23],[-14.2,29.23],[3.51,29.23],[21.21,29.23],[39.04,29.23],[57.1,29.23], .....   ]

and at last use np.choice(), however I could not find the ways to do the transformation, np.flatten() makes the array like

Space_Position=[-62,29.23,-49.73,29.2, ....]

Body:
Space_Position[np.random.randint(0, len(Space_Position))]
[np.random.randint(0, len(Space_Position))]

gives you what you want


来源: stackexchange

问:
When do i need to process a cube?
I have a SSAS 2008 Cube.

I've just inserted some more data (4 million transactions) in to the fact table and the dimensions are still good too. I've accidentally refreshed my Excel pivot table and noticed that my new data is there - I thought I had to reprocess the cube for this!!

That leaves me asking:

When do I need to process the cube? Is it ONLY structural changes?

When do I need to process dimensions?

If I don't need to process the cube on inserting new data into source tables, what happens if I insert bad data into the source i.e. something that does not have a matching dimension key?

答: @Warren, I know it has been a while, but I have to say the issue you mentioned here is data latency issue. It depends on the storage mode you choose on your measure groups within your multidimensional cube. For example, it is ROLAP, there is no data latency issue, you do not need to re-process the cube. However, if it is MOLAP, which means, everything (i.e. data, metadata, and aggregations) is stored in the cube. Every time you do some ETL, you need to re-process it to show the updated data.</p>

ContentLicense: CC BY-SA 3.0

Title: When do i need to process a cube?


问:
URLClassLoader loads Annotation as com.sun.$Proxy$27
I'm trying to dynamically load a java class. The basic idea is, that a jar contains modules which get loaded dynamically at runtime. This is how I do it (I know it's hacky, but there is no other method to dynamically add a jar to an already existing classloader afaik):

```<code>Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
method.setAccessible(true);
method.invoke(moduleLoader, new Object[] { file.toURI().toURL() });
Class fooClass = moduleLoader.loadClass("com.coderunner.Foo");
Object foo = fooClass.newInstance();
</code>```

Every module is annotated with an @Module annotation. So in order to gain further informations about the module, I try to get the annotation. The problem is that the annotation on foo is of type com.sun.$Proxy$27 instead of com.coderunner.Module and therefore I get a

```<code>ClassCastException: Cannot cast com.sun.proxy.$Proxy42 (id=64) to com.coderunner.Module
</code>```

I have to say I'm a bit confused what happens here. Is what I want to do possible? How?

Edit: I maybe also should mention I'm trying this in a spring/spring-mvc and tomcat environment.

答:
The fact that you get a proxy in front of your annotation type should not matter. It might actually mislead you into believing that this is the cause for problems you are having. If stuff like "isAnnotationPresent(..)" fails, it is not due to that proxy, it is because you have loaded the annotation class multiple times using multiple classloaders. For example, Jetty gives priority to the WebApp classloader by default. So if your Jetty server instance (or Tomcat or whatever) already has loaded the annotation class, and the annotation is on your WebApp's classpath, too, you can have problems like "getAnnotation()" not returning anything. Just make sure that the library containing your annotation is not loaded twice.

The solution provided by Andreas is, well, a very dirty workaround and just covers up the fact that you probably don't have your classloading under control/properly organized.

Body:
I'm trying to dynamically load a java class. The basic idea is, that a jar contains modules which get loaded dynamically at runtime. This is how I do it (I know it's hacky, but there is no other method to dynamically add a jar to an already existing classloader afaik):

Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
method.setAccessible(true);
method.invoke(moduleLoader, new Object[] { file.toURI().toURL() });
Class fooClass = moduleLoader.loadClass("com.coderunner.Foo");
Object foo = fooClass.newInstance();

Every module is annotated with an @Module annotation. So in order to gain further informations about the module, I try to get the annotation. The problem is that the annotation on foo is of type com.sun.$Proxy$27 instead of com.coderunner.Module and therefore I get a

ClassCastException: Cannot cast com.sun.proxy.$Proxy42 (id=64) to com.coderunner.Module

I have to say I'm a bit confused what happens here. Is what I want to do possible? How?

Edit: I maybe also should mention I'm trying this in a spring/spring-mvc and tomcat environment.


问:
C# Struct Generic Constructor
Using this code:

```<code>struct Foo<T1>
{
    public T1 Item1 { get; private set; }

    public Foo(T1 item1)
    {
        Item1 = item1;
    }
}
</code>```

I encounter this error:

Backing field for automatically implemented property 'Foo.Item1' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.

My question is, why is the property Item1 not fully assigned after the constructor is called?

Edit: Changed set to private set because this question has nothing to do with mutability.

答:
Add this() in here:

```<code>public Foo(T1 item1) : this()
{
    Item1 = item1;
}
</code>```

It's because you're assigning to a property, and the compiler can't deduce that the property only assigns a value to a variable; it could do other things before the instance is initialized, and that's not allowed because the structure might have garbage data. So you have to initialize it with the default constructor first, then do what you want.

ContentLicense: CC BY-SA 2.5

Title: C# Struct Generic Constructor

Body:
Using this code:

struct Foo<T1>
{
    public T1 Item1 { get; private set; }

    public Foo(T1 item1)
    {
        Item1 = item1;
    }
}

I encounter this error:

Backing field for automatically implemented property 'Foo.Item1' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.

My question is, why is the property Item1 not fully assigned after the constructor is called?

Edit: Changed set to private set because this question has nothing to do with mutability.

Body:
Add this() in here:

public Foo(T1 item1) : this()
{
    Item1 = item1;
}

It's because you're assigning to a property, and the compiler can't deduce that the property only assigns a value to a variable; it could do other things before the instance is initialized, and that's not allowed because the structure might have garbage data. So you have to initialize it with the default constructor first, then do what you want.


问:
Armadillo eigs_sym: decomposition failed
I am writing C++ code within Visual Studio and using Armadillo 7.900.1

I am having no luck getting eigs_sym function working under Armadillo (I am using the lapack and blas versions that came with Armadillo). The typical error message is as below:

```<code>error: lapack::stedc(): failed to compute all eigenvalues
warning: eigs_sym(): decomposition failed
</code>```

The code that is producing this output is:

```<code>sp_mat T(locations, values);
arma::eigs_sym(eigval, eigvec, T, num_eigs_wanted, "sm", tol);
</code>```

where

```<code>T is a 480,000x480,000 sparse matrix.
</code>```

I can get the code working if T is small (ie. 2000x2000) and tol is high (tol = 5). But once T is about 20000x20000, then no matter what values of tol or num_eigs_wanted are used then the above error occurs. (I obviously change "values" and locations" to alter the size of T).

The matrix T is symmetric, real, positive definite.

The exact same matrix has no problems when I call the eigs function within Matlab.

Any ideas? To me it seems that eigs_sym in Armadillo is broken...any alternatives that people have used?

Cheers

答:
Not an answer but way too long for a comment.  I can reproduce with the code below.  The matrix is just a diagonal matrix with ascending values on the diagonal starting at 1.  The eigenvalues are obviously 1,2,3,... and the matrix is positive definite and symmetric.

```<code>#include <iostream>
#include <armadillo>

int main()
{
  constexpr int N = 20000;
  arma::umat locations(2,N);
  arma::vec values(N);

  for (int i = 0; i < N; ++i)
  {
    locations(0,i) = i;
    locations(1,i) = i;
    values(i) = i+1;
  }

  arma::sp_mat T(locations, values);

  int num_eigs_wanted = 1;
  arma::vec eigval(num_eigs_wanted);
  arma::mat eigvec(N,num_eigs_wanted);
  double tol = 1e-6;
  arma::eigs_sym(eigval, eigvec, T, num_eigs_wanted, "sm", tol);

  std::cout << eigval << '\n';
}
</code>```

Compiler flags are

clang++-5.0 -std=c++11 test.cpp -larmadillo
```

<p>I'm using Armadillo with MKL backend and I receive:</p>

<pre class="lang-none prettyprint-override"><code>warning: eigs_sym(): decomposition failed
[matrix size: 0x1]
</code>```

It seems to be a problem of Armadillo, because when I use the unsupported Arpack support of Eigen it works just fine.

```<code>#include <iostream>
#include <Eigen/Sparse>
#include <unsupported/Eigen/ArpackSupport>

int main()
{
  constexpr int N = 20000;

  std::vector< Eigen::Triplet<double> > triplets;
  triplets.reserve(N);
  for (int i = 0; i < N; ++i)
    triplets.push_back( {i,i,i+1} );

  Eigen::SparseMatrix<double> T(N,N);
  T.setFromTriplets(triplets.begin(), triplets.end());

  int num_eigs_wanted = 1;
  double tol = 1e-6;
  Eigen::ArpackGeneralizedSelfAdjointEigenSolver< Eigen::SparseMatrix<double> > eigs_sym;
  eigs_sym.compute(T, num_eigs_wanted, "SM", Eigen::ComputeEigenvectors, tol);
  std::cout << eigs_sym.eigenvalues() << '\n';
}
</code>```

You might also want to take a look at https://github.com/yixuan/spectra/

Body:
I am writing C++ code within Visual Studio and using Armadillo 7.900.1

I am having no luck getting eigs_sym function working under Armadillo (I am using the lapack and blas versions that came with Armadillo). The typical error message is as below:

error: lapack::stedc(): failed to compute all eigenvalues
warning: eigs_sym(): decomposition failed

The code that is producing this output is:

sp_mat T(locations, values);
arma::eigs_sym(eigval, eigvec, T, num_eigs_wanted, "sm", tol);

where

T is a 480,000x480,000 sparse matrix.

I can get the code working if T is small (ie. 2000x2000) and tol is high (tol = 5). But once T is about 20000x20000, then no matter what values of tol or num_eigs_wanted are used then the above error occurs. (I obviously change "values" and locations" to alter the size of T).

The matrix T is symmetric, real, positive definite.

The exact same matrix has no problems when I call the eigs function within Matlab.

Any ideas? To me it seems that eigs_sym in Armadillo is broken...any alternatives that people have used?

Cheers

Body:
Not an answer but way too long for a comment.  I can reproduce with the code below.  The matrix is just a diagonal matrix with ascending values on the diagonal starting at 1.  The eigenvalues are obviously 1,2,3,... and the matrix is positive definite and symmetric.

#include <iostream>
#include <armadillo>

int main()
{
  constexpr int N = 20000;
  arma::umat locations(2,N);
  arma::vec values(N);

  for (int i = 0; i < N; ++i)
  {
    locations(0,i) = i;
    locations(1,i) = i;
    values(i) = i+1;
  }

  arma::sp_mat T(locations, values);

  int num_eigs_wanted = 1;
  arma::vec eigval(num_eigs_wanted);
  arma::mat eigvec(N,num_eigs_wanted);
  double tol = 1e-6;
  arma::eigs_sym(eigval, eigvec, T, num_eigs_wanted, "sm", tol);

  std::cout << eigval << '\n';
}

Compiler flags are

clang++-5.0 -std=c++11 test.cpp -larmadillo

I'm using Armadillo with MKL backend and I receive:

warning: eigs_sym(): decomposition failed
[matrix size: 0x1]

It seems to be a problem of Armadillo, because when I use the unsupported Arpack support of Eigen it works just fine.

#include <iostream>
#include <Eigen/Sparse>
#include <unsupported/Eigen/ArpackSupport>

int main()
{
  constexpr int N = 20000;

  std::vector< Eigen::Triplet<double> > triplets;
  triplets.reserve(N);
  for (int i = 0; i < N; ++i)
    triplets.push_back( {i,i,i+1} );

  Eigen::SparseMatrix<double> T(N,N);
  T.setFromTriplets(triplets.begin(), triplets.end());

  int num_eigs_wanted = 1;
  double tol = 1e-6;
  Eigen::ArpackGeneralizedSelfAdjointEigenSolver< Eigen::SparseMatrix<double> > eigs_sym;
  eigs_sym.compute(T, num_eigs_wanted, "SM", Eigen::ComputeEigenvectors, tol);
  std::cout << eigs_sym.eigenvalues() << '\n';
}

You might also want to take a look at https://github.com/yixuan/spectra/


问:
Single Page Application (SPA) vs Full Stack Applications. Constraints and Advantages.
Currently I am in the process of upgrading our web application from a traditional Spring MVC web application to a single page app with REST endpoints. Our current front-end MVC application does not use REST calls to communicate with the backend, but rather communicates with the backend (written in JAVA) by calling the necessary facades directly. Both JAR files and WAR files are being packaged in a single ear file, and deployed on our production server (currently using JBoss EAP 6).

Since we are now shifting to a single page application, and upgrading our system with a new set of APIs, I am questioning, should the Single Page Application, and the rest of the backend written in JAVA, be hosted on the same server (JBoss EAP 6)? Or should they be split onto separate servers, one to serve the SPA content and one to run the backend? In the latter case, which production server is most appropriate to host the content of the Single Page Application (JS,HTML,and CSS)? ( our backend will still be hosted on JBoss EAP 6 )

Also what are the advantages of separating the front end and backend on different servers?

I tried to search for best practices for deploying Single Page Applications with a JAVA REST endpoint but I haven't found any helpful articles applicable for our needs.

Thanks a lot in advance! :)

答:
Now a days, front-end is hosted mostly on separate servers and back-end services on cloud like AWS, In your scenario you can use FireBase for front-end (Html, CSS, JS, Angular) and sure you can use separate server for back-end services, it is also feasible to use Spring MVC as your current framework with it as a restful services.

Take a look at this demo


问:
Trouble for newbie with header code
I'm a newbie to code and pretty well illiterate. I have inserted some code into my customized header file only to realize it was the wrong place.

I since received this error message when i try to get onto my website

Parse error: syntax error, unexpected '$', expecting variable (T_VARIABLE) in /home2/seth1/public_html/wp-content/themes/TESSERACT/inc/custom-header.php on line 151

After seeing this i downloaded filezilla and removed the code I had previously  inserted. This code wasn't on or near line 151 where the error was.

The website is sethslawnandgarden
and here is a link to my code pastebin.com/s7ePRE6Q

答: You should take your backup and simply replace your ../TESSERACT/inc/custom-header.php file with the original or backup one.</p>

Title: Trouble for newbie with header code


问:
Add data manually to gridcontrol devexpress C#
I got into trouble with adding data to devexpress grid programmably. I parse data from the site with HTML Agility Pack and want to add parsed data to grid. I create 13 columns in gridcontrol with wizard.

```<code>    private void buttonGetData_Click(object sender, EventArgs e)
    {
        string url = @"____";
        HtmlWeb web = new HtmlWeb();
        HtmlDocument document = web.Load(url);
        var node = document.DocumentNode.SelectNodes("//tr[not(@class)]/td[@style='width:1%;' or @class='coef' or (@class='left' and .//a)]");

        /*foreach (var innerText in node.Select(row => row.InnerText))
        {
            gridView1.AddNewRow();
            gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["colunmDate"] , innerText);
            gridView1.UpdateCurrentRow();
        }*/
    }
</code>```

I get about 2000 elements into node. In this code i get InnerText from Node. Commented code doesn't work (and it's just for test). Please, help me with adding data to DevExpress Grid. Thanks!

答:
Assuming that document variable is well formed Xml you can load this into DataSet instance as

```<code>XmlTextReader MyReader = new XmlTextReader(new StringReader(Buffer));
MyDataSet.ReadXml(MyReader, XmlReadMode.Auto);
</code>```

Then you may attach appropriate table as GridView1.DataSource directly or transform it before attaching.

Body:
I got into trouble with adding data to devexpress grid programmably. I parse data from the site with HTML Agility Pack and want to add parsed data to grid. I create 13 columns in gridcontrol with wizard.

    private void buttonGetData_Click(object sender, EventArgs e)
    {
        string url = @"____";
        HtmlWeb web = new HtmlWeb();
        HtmlDocument document = web.Load(url);
        var node = document.DocumentNode.SelectNodes("//tr[not(@class)]/td[@style='width:1%;' or @class='coef' or (@class='left' and .//a)]");

        /*foreach (var innerText in node.Select(row => row.InnerText))
        {
            gridView1.AddNewRow();
            gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["colunmDate"] , innerText);
            gridView1.UpdateCurrentRow();
        }*/
    }

I get about 2000 elements into node. In this code i get InnerText from Node. Commented code doesn't work (and it's just for test). Please, help me with adding data to DevExpress Grid. Thanks!

Body:
Assuming that document variable is well formed Xml you can load this into DataSet instance as

XmlTextReader MyReader = new XmlTextReader(new StringReader(Buffer));
MyDataSet.ReadXml(MyReader, XmlReadMode.Auto);

Then you may attach appropriate table as GridView1.DataSource directly or transform it before attaching.


问:
Use Bisection Search to guess number
I'm writing a program that is supposed to guess the user's secret number using bisection search. I feel like I understand the concept of bisection search quite well but my IDE (Canopy) won't let me 'run' the code, which I assume is due to an error or something that it wants me to do before I run it.

```<code>lowend = 1
highend = 100
guess = 50
choice = 0

print "Please think of a number between 0 and 100!"

while choice != 'c':
    print "Is your secret number " + str(guess) + "?"
    print "Enter 'h' to indicate the guess is too high.",
    print "Enter 'l' to indicate the guess is too low.",
    choice = raw_input("Enter 'c' to indicate I guessed correctly.")
    if choice == 'c':
        break
    elif choice == 'h':
            highend = guess
            guess = (highend + lowend)/2
            print 'Is your secret number ' + str(guess) + "?"
            choice = 0
    elif choice == 'l':
            lowend = guess + 1
            guess = (highend + lowend)/2
            print 'Is your secret number ' + str(guess) + "?"
    else:
            print "Sorry, I did not understand your input."
            choice = 0

print 'Your number is: ' + str(guess) + "."
</code>```

I'm not sure if there's something I'm doing wrong, but Canopy's green 'run' button is greyed out. Why does this happen? Does anyone see anything obviously wrong with my code?

答:
Did you get this yet?
I think your initial choice should be a space: choice = " "
Also you need parenthesis on your print statements.
Maybe you don't need the raw_ for your input?
Maybe some rounding or making your answers integers.</p>

OwnerDisplayName: Adam

Title: Use Bisection Search to guess number

Body:
I'm writing a program that is supposed to guess the user's secret number using bisection search. I feel like I understand the concept of bisection search quite well but my IDE (Canopy) won't let me 'run' the code, which I assume is due to an error or something that it wants me to do before I run it.

lowend = 1
highend = 100
guess = 50
choice = 0

print "Please think of a number between 0 and 100!"

while choice != 'c':
    print "Is your secret number " + str(guess) + "?"
    print "Enter 'h' to indicate the guess is too high.",
    print "Enter 'l' to indicate the guess is too low.",
    choice = raw_input("Enter 'c' to indicate I guessed correctly.")
    if choice == 'c':
        break
    elif choice == 'h':
            highend = guess
            guess = (highend + lowend)/2
            print 'Is your secret number ' + str(guess) + "?"
            choice = 0
    elif choice == 'l':
            lowend = guess + 1
            guess = (highend + lowend)/2
            print 'Is your secret number ' + str(guess) + "?"
    else:
            print "Sorry, I did not understand your input."
            choice = 0

print 'Your number is: ' + str(guess) + "."

I'm not sure if there's something I'm doing wrong, but Canopy's green 'run' button is greyed out. Why does this happen? Does anyone see anything obviously wrong with my code?


问:
macro variable won't resolve SAS
When I run macro "quantplot" I run into the issue shown in the picture:

Picture of Error.

Essentially what appears to be happening is that none of the expressions in this form recode_&variables, out_&variables, etc. seems to be returning the correct value. It's simply reading it as recode_ and ignoring the macro variable.

I have provided the following code for sample data:

```<code>data test (drop=i);
do i=1 to 1000;
a=round(uniform(1)*4,.01);
b=round(uniform(1)*10,.01);
c=round(uniform(1)*7.5,.01);
u = rand("Uniform");
y=floor( (2)*u );
output;
end;
stop;
run;

%macro percentiles(indep_var=,num_groups=);
%let recodes=recode_%sysfunc(tranwrd(&indep_var,%str( ),%str( recode_)));
proc rank data=test out=test groups=7;
var &indep_var;
ranks &recodes;
run;
%mend;
%percentiles(indep_var=a b c);
</code>```

And also the code for the macro that is currently not working. Please help!

```<code>/*Plots to determine  functional form for quantitative variables*/
%macro quantplot(indep_var=,dep_var=);
    /* Count the number of words in the input */
    %let count=%sysfunc(countw(&indep_var));
    /* Loop through the total number of values */
    %do i = 1 %to &count;
        %let variables=%qscan(&indep_var,&i,%str( ));
        %put(&variables);
        proc means data=test;
        %put(&variables);
            class recode_&variables;
            var &dep_var;
            output out = out_&variables mean = pby_&variables;
        run;
        data p_&variables;
            set out_&variables; if _type_=1;
            lnp = log(pby_&variables/(1-pby_&variables));
        run;
        ods graphics on;
            proc gplot data = p_&variables;
                symbol value = star i=join;
                plot lnp*recode_&variables;
                plot pby_&variables*recode_&variables;
            run;
        ods graphics off;
    %end;
%mend;
%quantplot(indep_var=a b c,dep_var=y);
</code>```

答:
The problem is that you have introduced macro quoting by using %qscan:

```<code>%let variables=%qscan(&indep_var,&i,%str( ));
</code>```

and sometimes this quoting is not automatically removed when it should be, and it breaks the tokenization of:

```<code>class recode_&variables;
</code>```

Whenever MPRINT shows code that looks correct, but it errors, you should suspect a macro quoting problem.  You can either unquote the value yourself:

```<code>class %unquote(recode_&variables);
</code>```

or change your use of %qscan to %scan.

Your solution of using %sysfunc(strip()) works because %sysfunc() unquotes the value.

Title: macro variable won't resolve SAS

Body:
When I run macro "quantplot" I run into the issue shown in the picture:

Picture of Error.

Essentially what appears to be happening is that none of the expressions in this form recode_&variables, out_&variables, etc. seems to be returning the correct value. It's simply reading it as recode_ and ignoring the macro variable.

I have provided the following code for sample data:

data test (drop=i);
do i=1 to 1000;
a=round(uniform(1)*4,.01);
b=round(uniform(1)*10,.01);
c=round(uniform(1)*7.5,.01);
u = rand("Uniform");
y=floor( (2)*u );
output;
end;
stop;
run;

%macro percentiles(indep_var=,num_groups=);
%let recodes=recode_%sysfunc(tranwrd(&indep_var,%str( ),%str( recode_)));
proc rank data=test out=test groups=7;
var &indep_var;
ranks &recodes;
run;
%mend;
%percentiles(indep_var=a b c);

And also the code for the macro that is currently not working. Please help!

/*Plots to determine  functional form for quantitative variables*/
%macro quantplot(indep_var=,dep_var=);
    /* Count the number of words in the input */
    %let count=%sysfunc(countw(&indep_var));
    /* Loop through the total number of values */
    %do i = 1 %to &count;
        %let variables=%qscan(&indep_var,&i,%str( ));
        %put(&variables);
        proc means data=test;
        %put(&variables);
            class recode_&variables;
            var &dep_var;
            output out = out_&variables mean = pby_&variables;
        run;
        data p_&variables;
            set out_&variables; if _type_=1;
            lnp = log(pby_&variables/(1-pby_&variables));
        run;
        ods graphics on;
            proc gplot data = p_&variables;
                symbol value = star i=join;
                plot lnp*recode_&variables;
                plot pby_&variables*recode_&variables;
            run;
        ods graphics off;
    %end;
%mend;
%quantplot(indep_var=a b c,dep_var=y);

Body:
The problem is that you have introduced macro quoting by using %qscan:

%let variables=%qscan(&indep_var,&i,%str( ));

and sometimes this quoting is not automatically removed when it should be, and it breaks the tokenization of:

class recode_&variables;

Whenever MPRINT shows code that looks correct, but it errors, you should suspect a macro quoting problem.  You can either unquote the value yourself:

class %unquote(recode_&variables);

or change your use of %qscan to %scan.

Your solution of using %sysfunc(strip()) works because %sysfunc() unquotes the value.


问:
Run callback function after forEach is done
In the project, I have a loop going through a list of urls. It downloads file from every url and do some post process over the downloaded file.

After the all the process done (both download process and post process), I want to execute a callback function. Because post process includes some streaming task, it has close event. If the last item can be identified, I can pass the callback function to the close event. However, since the loop is async, I can't track which item is done at last.

For now, I use a 5 second timeout to make sure the callback is executed after the whole process. Obviously, this is not sustainable. What's a good way to handle this?

loop code:

```<code>exports.processArray = (items, process, callback) => {
    var todo = items.concat();
    setTimeout(function() {
        process(todo.shift());
        if(todo.length > 0) {
          // execute download and post process each second
          // however it doesn't guarantee one start after previous one done
          setTimeout(arguments.callee, 1000);
        } else {
          setTimeout(() => {callback();}, 5000);
        }
    }, 1000);
};

processArray(
  // First param, the array
  urlList,
  // Second param, download and post process
  (url) => {
    if(url.startsWith('http')) {
      getDataReg(url, uid);
    }
    else if(url.startsWith('ftp')) {
      getDataFtp(url, uid);
    }
    else {
      console.log('not a valid resource');
    }
  },
  // Third param, callback to be executed after all done
  () => {
    Request.get(`${config.demouri}bound=${request.query.boundary};uid=${uid}`, {
      method: 'GET',
      auth: auth
    })
    .on('response', (response) => {
      console.log('response event emmits');
      zipFiles(uid)
      .then((path) => {
        reply.file(path, { confine: false, filename: uid + '.zip', mode: 'inline'}).header('Content-Disposition');
      });
    });
  }
);
</code>```

Download and post process:

```<code>exports.getDataFtp = (url, uid) => {
  console.log('get into ftp');
  var usefulUrl = url.split('//')[1];
  var spliter = usefulUrl.indexOf('/');
  var host = usefulUrl.substring(0, spliter);
  var dir = usefulUrl.substring(spliter+1, usefulUrl.length);
  var client = new ftp();
  var connection = {
    host: host
  };
  var fileNameStart = dir.lastIndexOf('/') + 1;
  var fileNameEnd = dir.length;
  var fileName = dir.substring(fileNameStart, fileNameEnd);
  console.log('filename: ', fileName);

  client.on('ready', () => {
    console.log('get into ftp ready');
    client.get(dir, (err, stream) => {
      if (err) {
        console.log('get file err:', err);
        return;
      } else{
        console.log('get into ftp get');
        stream.pipe(fs.createWriteStream(datadir + `download/${uid}/${fileName}`));
        stream.on('end', () => {
          console.log('get into ftp close');
          unzipData(datadir + `download/${uid}/`, fileName, uid);
          client.end();
        });
      }
    });
  });
  client.connect(connection);
};

exports.getDataReg = (url, uid) => {
  console.log('get into http');
    var fileNameStart = url.lastIndexOf('/') + 1;
  var fileNameEnd = url.length;
  var fileName = url.substring(fileNameStart, fileNameEnd);
    var file = fs.createWriteStream(datadir + `download/${uid}/${fileName}`);
    if (url.startsWith('https')) {
    https.get(url, (response) => {
      console.log('start piping file');
      response.pipe(file);
      file.on('finish', () => {
        console.log('get into http finish');
        unzipData(datadir + `download/${uid}/`, fileName, uid);
      });
    }).on('error', (err) => { // Handle errors
      fs.unlink(datadir + `download/${uid}/${fileName}`);
      console.log('download file err: ', err);
    });
    } else {
    http.get(url, (response) => {
      console.log('start piping file');
      response.pipe(file);
      file.on('finish', () => {
        unzipData(datadir + `download/${uid}/`, fileName, uid);
      });
    }).on('error', (err) => {
      fs.unlink(datadir + `download/${uid}/${fileName}`);
      console.log('download file err: ', err);
    });
    }
};

function unzipData(path, fileName, uid) {
  console.log('get into unzip');
  console.log('creating: ', path + fileName);
    fs.createReadStream(path + fileName)
    .pipe(unzip.Extract({path: path}))
    .on('close', () => {
    console.log('get into unzip close');
    var filelist = listFile(path);
    filelist.forEach((filePath) => {
      if (!filePath.endsWith('.zip')) {
        var components = filePath.split('/');
        var component = components[components.length-1];
        mv(filePath, datadir + `processing/${uid}/${component}`, (err) => {
          if(err) {
            console.log('move file err: ');
          } else {
            console.log('move file done');
          }
        });
      }
    });
    fs.unlink(path + fileName, (err) => {});
    });
}
</code>```

答:
After the all the process done (both download process and post process), I want to execute a callback function.

The interesting thing about a series of asynchronous processes is that you can never know when exactly all processes will complete. So setting a timeout for the callback is quick&dirty way to do it, but it's not reliable for sure.

You can instead use a counter to solve this problem.
Let's say you have 10 operations to perform. At the beginning you set your counter to ten counter = 10 And after each process is completed, regardless how (it can either succeed or fail), you can decrement the counter by 1 like counter -= 1 and right after it you can check if the counter is 0, if so that means all processes are completed and we reached the end. You can now safely run your callback function, like if(counter === 0) callback();

If I were you, I would do something like this:

*Notice that the called process should return a promise, so that I can know when it finishes (again regardless how)

*If you need help about promises, this useful article might help you: https://howtonode.org/promises

*Oh and one more thing, you should avoid using arguments.callee, because it's deprecated. Here is why Why was the arguments.callee.caller property deprecated in JavaScript?

```<code>exports.processArray = (items, process, callback) => {
    var todo = [].concat(items);
    var counter = todo.length;

    runProcess();

    function runProcess() {
      // Check if the counter already reached 0
      if(checkCounter() === false) {
        // Nope. Counter is still > 0, which means we got work to do.
        var processPromise = process(todo.shift());

        processPromise
          .then(function() {
            // success
          })
          .catch(function() {
            // failure
          })
          .finally(function() {
            // The previous process is done.
            // Now we can go with the next one.
            --counter;
            runProcess();
          })
      }
    };

    function checkCounter() {
      if(counter === 0) {
        callback();
        return true;
      } else {
        return false;
      }
    }
};
</code>```

Body:
In the project, I have a loop going through a list of urls. It downloads file from every url and do some post process over the downloaded file.

After the all the process done (both download process and post process), I want to execute a callback function. Because post process includes some streaming task, it has close event. If the last item can be identified, I can pass the callback function to the close event. However, since the loop is async, I can't track which item is done at last.

For now, I use a 5 second timeout to make sure the callback is executed after the whole process. Obviously, this is not sustainable. What's a good way to handle this?

loop code:

exports.processArray = (items, process, callback) => {
    var todo = items.concat();
    setTimeout(function() {
        process(todo.shift());
        if(todo.length > 0) {
          // execute download and post process each second
          // however it doesn't guarantee one start after previous one done
          setTimeout(arguments.callee, 1000);
        } else {
          setTimeout(() => {callback();}, 5000);
        }
    }, 1000);
};

processArray(
  // First param, the array
  urlList,
  // Second param, download and post process
  (url) => {
    if(url.startsWith('http')) {
      getDataReg(url, uid);
    }
    else if(url.startsWith('ftp')) {
      getDataFtp(url, uid);
    }
    else {
      console.log('not a valid resource');
    }
  },
  // Third param, callback to be executed after all done
  () => {
    Request.get(`${config.demouri}bound=${request.query.boundary};uid=${uid}`, {
      method: 'GET',
      auth: auth
    })
    .on('response', (response) => {
      console.log('response event emmits');
      zipFiles(uid)
      .then((path) => {
        reply.file(path, { confine: false, filename: uid + '.zip', mode: 'inline'}).header('Content-Disposition');
      });
    });
  }
);

Download and post process:

exports.getDataFtp = (url, uid) => {
  console.log('get into ftp');
  var usefulUrl = url.split('//')[1];
  var spliter = usefulUrl.indexOf('/');
  var host = usefulUrl.substring(0, spliter);
  var dir = usefulUrl.substring(spliter+1, usefulUrl.length);
  var client = new ftp();
  var connection = {
    host: host
  };
  var fileNameStart = dir.lastIndexOf('/') + 1;
  var fileNameEnd = dir.length;
  var fileName = dir.substring(fileNameStart, fileNameEnd);
  console.log('filename: ', fileName);

  client.on('ready', () => {
    console.log('get into ftp ready');
    client.get(dir, (err, stream) => {
      if (err) {
        console.log('get file err:', err);
        return;
      } else{
        console.log('get into ftp get');
        stream.pipe(fs.createWriteStream(datadir + `download/${uid}/${fileName}`));
        stream.on('end', () => {
          console.log('get into ftp close');
          unzipData(datadir + `download/${uid}/`, fileName, uid);
          client.end();
        });
      }
    });
  });
  client.connect(connection);
};

exports.getDataReg = (url, uid) => {
  console.log('get into http');
    var fileNameStart = url.lastIndexOf('/') + 1;
  var fileNameEnd = url.length;
  var fileName = url.substring(fileNameStart, fileNameEnd);
    var file = fs.createWriteStream(datadir + `download/${uid}/${fileName}`);
    if (url.startsWith('https')) {
    https.get(url, (response) => {
      console.log('start piping file');
      response.pipe(file);
      file.on('finish', () => {
        console.log('get into http finish');
        unzipData(datadir + `download/${uid}/`, fileName, uid);
      });
    }).on('error', (err) => { // Handle errors
      fs.unlink(datadir + `download/${uid}/${fileName}`);
      console.log('download file err: ', err);
    });
    } else {
    http.get(url, (response) => {
      console.log('start piping file');
      response.pipe(file);
      file.on('finish', () => {
        unzipData(datadir + `download/${uid}/`, fileName, uid);
      });
    }).on('error', (err) => {
      fs.unlink(datadir + `download/${uid}/${fileName}`);
      console.log('download file err: ', err);
    });
    }
};

function unzipData(path, fileName, uid) {
  console.log('get into unzip');
  console.log('creating: ', path + fileName);
    fs.createReadStream(path + fileName)
    .pipe(unzip.Extract({path: path}))
    .on('close', () => {
    console.log('get into unzip close');
    var filelist = listFile(path);
    filelist.forEach((filePath) => {
      if (!filePath.endsWith('.zip')) {
        var components = filePath.split('/');
        var component = components[components.length-1];
        mv(filePath, datadir + `processing/${uid}/${component}`, (err) => {
          if(err) {
            console.log('move file err: ');
          } else {
            console.log('move file done');
          }
        });
      }
    });
    fs.unlink(path + fileName, (err) => {});
    });
}

Body:
After the all the process done (both download process and post process), I want to execute a callback function.

The interesting thing about a series of asynchronous processes is that you can never know when exactly all processes will complete. So setting a timeout for the callback is quick&dirty way to do it, but it's not reliable for sure.

You can instead use a counter to solve this problem.
Let's say you have 10 operations to perform. At the beginning you set your counter to ten counter = 10 And after each process is completed, regardless how (it can either succeed or fail), you can decrement the counter by 1 like counter -= 1 and right after it you can check if the counter is 0, if so that means all processes are completed and we reached the end. You can now safely run your callback function, like if(counter === 0) callback();

If I were you, I would do something like this:

*Notice that the called process should return a promise, so that I can know when it finishes (again regardless how)

*If you need help about promises, this useful article might help you: https://howtonode.org/promises

*Oh and one more thing, you should avoid using arguments.callee, because it's deprecated. Here is why Why was the arguments.callee.caller property deprecated in JavaScript?

exports.processArray = (items, process, callback) => {
    var todo = [].concat(items);
    var counter = todo.length;

    runProcess();

    function runProcess() {
      // Check if the counter already reached 0
      if(checkCounter() === false) {
        // Nope. Counter is still > 0, which means we got work to do.
        var processPromise = process(todo.shift());

        processPromise
          .then(function() {
            // success
          })
          .catch(function() {
            // failure
          })
          .finally(function() {
            // The previous process is done.
            // Now we can go with the next one.
            --counter;
            runProcess();
          })
      }
    };

    function checkCounter() {
      if(counter === 0) {
        callback();
        return true;
      } else {
        return false;
      }
    }
};


问:
Facebook URL Debug: Sorry, something went wrong. We're working on getting this fixed as soon as we can
https://developers.facebook.com/tools/debug

Does anyone know why "some" URLS get this error and others do not?

Error: Sorry, something went wrong.
We're working on getting this fixed as soon as we can.

I apologize for the lack of detail on this. I can't post a link as of yet but hoping someone has experienced this issue and found a resolution. Paging through the FB help pages directed me to here as well and it seems difficult to find the right place to report the problem directly to FB. I'm finding a lot of similar posts on StackOverflow with similar issues but no clear answers.

Thank you in advance for any suggestions.

答:
I hit this because Facebook changed the rules for what an acceptable ?state parameter.  I had % escape characters, and that appeared to no be illegal. I ended up moving my state to a query parameter on the redirect URL. </p>

<p>The specific rules are not actually documented:
https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow </p>

Body:
I hit this because Facebook changed the rules for what an acceptable ?state parameter.  I had % escape characters, and that appeared to no be illegal. I ended up moving my state to a query parameter on the redirect URL.

The specific rules are not actually documented:
https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow


问:
Dynamic_cast compatibility?
I was reading about dynamic_cast and then I encountered the following statement (from cplusplus.com):

Compatibility note: This type of dynamic_cast requires Run-Time Type
  Information (RTTI) to keep track of dynamic types. Some compilers
  support this feature as an option which is disabled by default. This
  needs to be enabled for runtime type checking using dynamic_cast to
  work properly with these types.

After the example:

```<code>// dynamic_cast
#include <iostream>
#include <exception>
using namespace std;

class Base { virtual void dummy() {} };
class Derived: public Base { int a; };

int main () {
  try {
    Base * pba = new Derived;
    Base * pbb = new Base;
    Derived * pd;

    pd = dynamic_cast<Derived*>(pba);
    if (pd==0) cout << "Null pointer on first type-cast.\n";

    pd = dynamic_cast<Derived*>(pbb);
    if (pd==0) cout << "Null pointer on second type-cast.\n";

  } catch (exception& e) {cout << "Exception: " << e.what();}
  return 0;
}
</code>```

What does the author mean by "this type of dynamic_cast"? Isn't dynamic_cast only used for polymorphic classes(almost)? And he mentions this RTTI as something that is needed for the dynamic cast to work, does that mean that you have to use dynamic_cast with caution because you do not know if it is supported fully by the compiler and therefore makes it riskier than the other casting operators which do not need this RTTI?

答:
The compatibility note relates to the immediately preceding paragraph (and code example):

But dynamic_cast can also downcast (convert from pointer-to-base to pointer-to-derived) polymorphic classes (those with virtual members) if -and only if- the pointed object is a valid complete object of the target type.

And it's true: downcasting requires an object of polymorphic type, and RTTI to traverse the object's inheritance tree at runtime.

The other type of dynamic_cast is explained in the paragraph before that:

This naturally includes pointer upcast (converting from pointer-to-derived to pointer-to-base), in the same way as allowed as an implicit conversion.

No RTTI is required here as an object's base(s) is/are always known statically.

So you only need to fully read the surrounding text in order to understand the context of the words you're reading.

I would note, however, that in my experience a compiler with RTTI disabled by default is basically unheard of. I'm not saying that none exist — there may be some niche, industry-specific compilers targeting embedded platforms that do this to save the programmer a few bytes in their Makefile. But the compilers that most people use (GCC, Clang, Visual Studio, ICC, Comeau) all, to the best of my knowledge, pack RTTI as standard and leave it on until you ask for it to be turned off.

Title: Dynamic_cast compatibility?

Body:
I was reading about dynamic_cast and then I encountered the following statement (from cplusplus.com):

Compatibility note: This type of dynamic_cast requires Run-Time Type
  Information (RTTI) to keep track of dynamic types. Some compilers
  support this feature as an option which is disabled by default. This
  needs to be enabled for runtime type checking using dynamic_cast to
  work properly with these types.

After the example:

// dynamic_cast
#include <iostream>
#include <exception>
using namespace std;

class Base { virtual void dummy() {} };
class Derived: public Base { int a; };

int main () {
  try {
    Base * pba = new Derived;
    Base * pbb = new Base;
    Derived * pd;

    pd = dynamic_cast<Derived*>(pba);
    if (pd==0) cout << "Null pointer on first type-cast.\n";

    pd = dynamic_cast<Derived*>(pbb);
    if (pd==0) cout << "Null pointer on second type-cast.\n";

  } catch (exception& e) {cout << "Exception: " << e.what();}
  return 0;
}

What does the author mean by "this type of dynamic_cast"? Isn't dynamic_cast only used for polymorphic classes(almost)? And he mentions this RTTI as something that is needed for the dynamic cast to work, does that mean that you have to use dynamic_cast with caution because you do not know if it is supported fully by the compiler and therefore makes it riskier than the other casting operators which do not need this RTTI?


问:
How do I allow my ListView to fill the entire screen in Android?
I'm making a listview in android, and my listview doesn't fill the entire screen. It has some remaining plain space below the listview (probably because i don't have enough items to fill the screen). I've searched for many solutions online, but none seem to be able to solve this problem.

Here is my layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.ListActivity">

 <ListView
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:id = "@+id/customListview">

 </ListView>

</LinearLayout>
</code>```

Here is my item_layout.xml:

```<code><?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">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id= "@+id/ItemNameSales"
        android:layout_alignParentLeft="true"
        android:text="Item Name"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id= "@+id/ItemNameQty"
        android:layout_alignParentRight="true"
        android:text="Item Quantity"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

</RelativeLayout>
</code>```

答:
Your ListView is already fill entire screen problem is that you dont have have enaf items in list. Another thing that you shoud do is to create holder class to prevant ListView loose list order.You can change dinamicly widht and height of item to fill screen but that is bad practices in coding</p>

```<code>   View itemView = convertView;
    ViewHolder holder;

    if (itemView == null) {

     itemView = getLayoutInflater().inflate(R.layout.YOURVIEW,parent,false);
     holder = new ViewHolder();
     itemView.setTag( holder );
    }else {
     holder = (ViewHolder) itemView.getTag();
    }
     SalesItemInformationLV iteminfo = item.get(position);

     holder.something = (TextView)itemView.findViewById(R.id.ItemNameSales);

     public class ViewHolder{

      public TextView something;
    }
</code>```

Body:
I'm making a listview in android, and my listview doesn't fill the entire screen. It has some remaining plain space below the listview (probably because i don't have enough items to fill the screen). I've searched for many solutions online, but none seem to be able to solve this problem.

Here is my layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.ListActivity">

 <ListView
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:id = "@+id/customListview">

 </ListView>

</LinearLayout>

Here is my item_layout.xml:

<?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">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id= "@+id/ItemNameSales"
        android:layout_alignParentLeft="true"
        android:text="Item Name"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id= "@+id/ItemNameQty"
        android:layout_alignParentRight="true"
        android:text="Item Quantity"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

</RelativeLayout>

Body:
Your ListView is already fill entire screen problem is that you dont have have enaf items in list. Another thing that you shoud do is to create holder class to prevant ListView loose list order.You can change dinamicly widht and height of item to fill screen but that is bad practices in coding

   View itemView = convertView;
    ViewHolder holder;

    if (itemView == null) {

     itemView = getLayoutInflater().inflate(R.layout.YOURVIEW,parent,false);
     holder = new ViewHolder();
     itemView.setTag( holder );
    }else {
     holder = (ViewHolder) itemView.getTag();
    }
     SalesItemInformationLV iteminfo = item.get(position);

     holder.something = (TextView)itemView.findViewById(R.id.ItemNameSales);

     public class ViewHolder{

      public TextView something;
    }


问:
Automatically publish packages to NPM with CircleCI
I'm trying to set up automated deployments for a public NPM package in CircleCI. What I'd like is for CircleCI to automatically publish the package to NPM whenever the version number has changed in package.json has changed. Is that possible with CircleCI?

答:
1 - Obtain the npm authToken for the account that you wish to use to publish the package.
 You can do that by logging in to npm (npm login). This will save the authToken to the ~/.npmrc file.

2- Go to your project settings in circleci.com, and set the NPM_TOKEN variable to the obtained authToken.

3- In your cicle.yml add a this section

```<code>dependencies:
  pre:
    - echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" >> ~/.npmrc

deployment:
  production:
    branch: master
    commands:
      - npm publish
</code>```

Whenever you commit to master branch, it will trigger npm publish.

More information in the official documentation

Body:
1 - Obtain the npm authToken for the account that you wish to use to publish the package.
 You can do that by logging in to npm (npm login). This will save the authToken to the ~/.npmrc file.

2- Go to your project settings in circleci.com, and set the NPM_TOKEN variable to the obtained authToken.

3- In your cicle.yml add a this section

dependencies:
  pre:
    - echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" >> ~/.npmrc

deployment:
  production:
    branch: master
    commands:
      - npm publish

Whenever you commit to master branch, it will trigger npm publish.

More information in the official documentation


问:
Kotlin: Pass and consume a 2 parameter function?
I'm trying to learn functional programming in Kotlin and am having difficulty making this code work:

```<code>import java.util.*

fun caseName(br: String, c: Int): String {
  if (c == 0) {
    return br.toLowerCase()
    } else {
    return br.toUpperCase()
    }
}
fun mapIt(ns: ArrayList<String>, f: (String, Int) -> String): List<String> {
  val coll: List<String> = ns.map {it -> f(it, _)}
  return coll
}

fun main(args: Array<String>) {
  val names = arrayListOf("Joe", "Bill", "Murrary")
  val cased = mapIt(names, (::caseName)(_, 0))
  println(cased.first())
}
</code>```

How do I get mapIt to recognize the case flag when mapping over the list?

Thank you!

EDIT: The case above is a simplified version of the following, which does not work either...

```<code>data class Borrower(val name: String, val maxBooks: Int) {
    companion object {

        fun getName(br: Borrower, c: Int): String {
          if (c == 0) {
            return br.name.toLowerCase()
            } else {
            return br.name.toUpperCase()
            }
        }

        fun findBorrower(n: String, brs: ArrayList<Borrower>, f: (Borrower) -> String): Borrower? {
            val coll: List<Borrower> = brs.filter { it -> f(it) == n }
            if (coll.isEmpty()) {
                return null
            } else return coll.first()
        }
    }
}

fun main(args: Array<String>) {
    val br1 = Borrower(name = "Borrower1", maxBooks = 1)
    val br2 = Borrower(name = "Borrower2", maxBooks = 2)
    val br3 = Borrower(name = "Borrower3", maxBooks = 3)
    val br4 = Borrower(name = "borrower4", maxBooks = 4)
    val br5 = Borrower(name = "BORROWER5", maxBooks = 5)
    val brs1 = arrayListOf(br1, br2, br3, br4, br5)

    val c = Borrower.findBorrower("borrower3", brs1, {Borrower.Companion::getName(it, 0)})
    println(c)
}
</code>```

答:
Your original code (the Borrower one) is actually very close to success, so I'm going to ignore your werid simplified version. You just got one line wrong:

```<code>val c = Borrower.findBorrower("borrower3", brs1, {Borrower.Companion::getName(it, 0)})
                                                                    ^^
                                                        Why you are using double colon?
</code>```

The last parameter is a lambda expression, and it just make no sense to use a function reference inside a lambda, even in scala. Just use plain dots and it will be fine.

```<code>val c = Borrower.findBorrower("borrower3", brs1, {Borrower.Companion.getName(it, 0)})
</code>```

Since members of companion objects can be called with just the main types' name, it can be further simplified into

```<code>val c = Borrower.findBorrower("borrower3", brs1, {Borrower.getName(it, 0)})
</code>```

Body:
I'm trying to learn functional programming in Kotlin and am having difficulty making this code work:

import java.util.*

fun caseName(br: String, c: Int): String {
  if (c == 0) {
    return br.toLowerCase()
    } else {
    return br.toUpperCase()
    }
}
fun mapIt(ns: ArrayList<String>, f: (String, Int) -> String): List<String> {
  val coll: List<String> = ns.map {it -> f(it, _)}
  return coll
}

fun main(args: Array<String>) {
  val names = arrayListOf("Joe", "Bill", "Murrary")
  val cased = mapIt(names, (::caseName)(_, 0))
  println(cased.first())
}

How do I get mapIt to recognize the case flag when mapping over the list?

Thank you!

EDIT: The case above is a simplified version of the following, which does not work either...

data class Borrower(val name: String, val maxBooks: Int) {
    companion object {

        fun getName(br: Borrower, c: Int): String {
          if (c == 0) {
            return br.name.toLowerCase()
            } else {
            return br.name.toUpperCase()
            }
        }

        fun findBorrower(n: String, brs: ArrayList<Borrower>, f: (Borrower) -> String): Borrower? {
            val coll: List<Borrower> = brs.filter { it -> f(it) == n }
            if (coll.isEmpty()) {
                return null
            } else return coll.first()
        }
    }
}

fun main(args: Array<String>) {
    val br1 = Borrower(name = "Borrower1", maxBooks = 1)
    val br2 = Borrower(name = "Borrower2", maxBooks = 2)
    val br3 = Borrower(name = "Borrower3", maxBooks = 3)
    val br4 = Borrower(name = "borrower4", maxBooks = 4)
    val br5 = Borrower(name = "BORROWER5", maxBooks = 5)
    val brs1 = arrayListOf(br1, br2, br3, br4, br5)

    val c = Borrower.findBorrower("borrower3", brs1, {Borrower.Companion::getName(it, 0)})
    println(c)
}

Body:
Your original code (the Borrower one) is actually very close to success, so I'm going to ignore your werid simplified version. You just got one line wrong:

val c = Borrower.findBorrower("borrower3", brs1, {Borrower.Companion::getName(it, 0)})
                                                                    ^^
                                                        Why you are using double colon?

The last parameter is a lambda expression, and it just make no sense to use a function reference inside a lambda, even in scala. Just use plain dots and it will be fine.

val c = Borrower.findBorrower("borrower3", brs1, {Borrower.Companion.getName(it, 0)})

Since members of companion objects can be called with just the main types' name, it can be further simplified into

val c = Borrower.findBorrower("borrower3", brs1, {Borrower.getName(it, 0)})


问:
In Javascript, how do I automatically move the cursor to the next text box when the current one is full?
Suppose I have two HTML textboxes on my web page:

```<code><input type='text' id='txt1' maxlength='5' />
<input type='text' id='txt2' maxlength='5' />
</code>```

Each textbox allows the user to type up to five characters.  How can I use Javascript with or without jQuery to automatically move the cursor from txt1 to txt2 when the user types five charcters into txt1?

答:
It's called autotabbing, and there are many plugins that already exist for jquery that do this.  Just google it.

If you want to know how to do it, then you bind an onkeyup event to inputs.  Every time a key is released, make sure its not a functional key such as "Tab" (You should allow the user to "Shift+Tab" or "Tab" to the input without it then autotabbing to the next field.)

Then, if the input value's length exceeds the input's maxlength attribute, set the focus on the next input (in jQuery, $currentInput.next('input').focus().

Body:
Suppose I have two HTML textboxes on my web page:

<input type='text' id='txt1' maxlength='5' />
<input type='text' id='txt2' maxlength='5' />

Each textbox allows the user to type up to five characters.  How can I use Javascript with or without jQuery to automatically move the cursor from txt1 to txt2 when the user types five charcters into txt1?


问:
Expect: answering one or two ssh password prompts then interact
I have an ssh case (can't use sshkeys) that sometimes prompts for one password, sometimes for two (prompt is the same in both cases).  I have tried variations of while, if, exp_continue, but can't seem to cook it correctly.

This works perfect if I only get one prompt:

```<code>#!/usr/bin/expect
set pwd "mypwd"
set prompt "*Password*"
set uid "*userid*"
set timeout -1
spawn -noecho ssh -q host.domain

expect $prompt
send $pwd
send \r
interact
</code>```

Tried this, but not giving giving me the results I need for sometimes two pwds plus the KnownHost case.

```<code>expect {
    "*yes/no*" { send \"yes\r\"; exp_continue }
    $prompt { send \"$pwd\r\"; exp_continue }
    $uid {interact}
}
</code>```

答:
Figured it out:</p>

```<code>#!/usr/bin/expect -f

set pwd "mypwd"
set prompt "Enter PIN for 'PIV_II (PIV Card Holder pin)': "
set uid "*userid*"
set timeout -1
spawn ssh -q host.domain

expect {
    "*yes/no*" { send "yes\r"; exp_continue }
    $prompt { send "$pwd\r"; exp_continue }
    $uid { send \r; interact }
}
</code>```

Body:
I have an ssh case (can't use sshkeys) that sometimes prompts for one password, sometimes for two (prompt is the same in both cases).  I have tried variations of while, if, exp_continue, but can't seem to cook it correctly.

This works perfect if I only get one prompt:

#!/usr/bin/expect
set pwd "mypwd"
set prompt "*Password*"
set uid "*userid*"
set timeout -1
spawn -noecho ssh -q host.domain

expect $prompt
send $pwd
send \r
interact

Tried this, but not giving giving me the results I need for sometimes two pwds plus the KnownHost case.

expect {
    "*yes/no*" { send \"yes\r\"; exp_continue }
    $prompt { send \"$pwd\r\"; exp_continue }
    $uid {interact}
}

Body:
Figured it out:

#!/usr/bin/expect -f

set pwd "mypwd"
set prompt "Enter PIN for 'PIV_II (PIV Card Holder pin)': "
set uid "*userid*"
set timeout -1
spawn ssh -q host.domain

expect {
    "*yes/no*" { send "yes\r"; exp_continue }
    $prompt { send "$pwd\r"; exp_continue }
    $uid { send \r; interact }
}


问:
Scala Unable to pimp NaturalTransformation in scalaz or cats
For some reason the following fails to work

```<code>object NtExtTest {
  implicit class NaturalTransformExt[M[_], N[_]](val self: NaturalTransformation[M,N]) extends AnyVal {
    def test(b:Boolean) = b
  }
 }
</code>```

when I call the method test on a natural transform.  Intellij recognises it as an extension function, but the compile gives value test is not a member of cats.~> . The same happens when using the scalaz NaturalTransformation.  Is there something I can do to help the compile recognise the extension?

Scala version is 2.11.8

An example which fails:

```<code>  import NtExtTest._

  class NtTest[B] extends NaturalTransformation[Either[B,?], Xor[B,?]] {
    def apply[A](fa: Either[B, A]): Xor[B, A] = {
      fa match {
        case Left(l) => Xor.left(l)
        case Right(r) => Xor.right(r)
      }
    }
  }

  val test = new NtTest[String]
  test.test(false)
</code>```

(above uses kind projector plugin, but equally fails with type lambdas, or single param higher kinded types)

答:
Probably relates to SI-8286

```<code>object NtExtTest {
  // this will work
  implicit class NatTransExt1[E](val t: NaturalTransformation[Either[E, ?], \/[E, ?]]) {
    def test1(b: Boolean): Boolean = false
  }

  // and this will work
  implicit class NatTransExt2[E](val t: NtTest[E]) {
    def test2(b: Boolean): Boolean = false
  }

  // but this will not work, because NaturalTransformation[F, G] and
  // NaturalTransformation[Either[E, ?], \/[E, ?]] of different kind
  implicit class NatTransExt3[F[_], G[_]](val s: NaturalTransformation[F, G]) {
    def test3(b: Boolean): Boolean = false
  }
}
</code>```

I.e. it is not related to NaturalTransformation. It does not work in simple case as well:

```<code>trait SomeType[F[_]]

class SomeConcreteType[A] extends SomeType[Either[A, ?]]

object SomeTypeExt {
  // this will not compile
  implicit class SomeTypeEnrich[F[_]](val t: SomeType[F]) {
    def test1: Boolean = false
  }
  // this will
  implicit class SomeConcreteEnrich[A](val t: SomeType[Either[A, ?]]) {
    def test2: Boolean = true
  }
}
</code>```

If the goal to extend NtTest, probably NatTransExt1 would be best choice if one would like to stay as generic as possible. NatTransExt2 is ok, if extension really specific to NtTest.

Body:
For some reason the following fails to work

object NtExtTest {
  implicit class NaturalTransformExt[M[_], N[_]](val self: NaturalTransformation[M,N]) extends AnyVal {
    def test(b:Boolean) = b
  }
 }

when I call the method test on a natural transform.  Intellij recognises it as an extension function, but the compile gives value test is not a member of cats.~> . The same happens when using the scalaz NaturalTransformation.  Is there something I can do to help the compile recognise the extension?

Scala version is 2.11.8

An example which fails:

  import NtExtTest._

  class NtTest[B] extends NaturalTransformation[Either[B,?], Xor[B,?]] {
    def apply[A](fa: Either[B, A]): Xor[B, A] = {
      fa match {
        case Left(l) => Xor.left(l)
        case Right(r) => Xor.right(r)
      }
    }
  }

  val test = new NtTest[String]
  test.test(false)

(above uses kind projector plugin, but equally fails with type lambdas, or single param higher kinded types)

Body:
Probably relates to SI-8286

object NtExtTest {
  // this will work
  implicit class NatTransExt1[E](val t: NaturalTransformation[Either[E, ?], \/[E, ?]]) {
    def test1(b: Boolean): Boolean = false
  }

  // and this will work
  implicit class NatTransExt2[E](val t: NtTest[E]) {
    def test2(b: Boolean): Boolean = false
  }

  // but this will not work, because NaturalTransformation[F, G] and
  // NaturalTransformation[Either[E, ?], \/[E, ?]] of different kind
  implicit class NatTransExt3[F[_], G[_]](val s: NaturalTransformation[F, G]) {
    def test3(b: Boolean): Boolean = false
  }
}

I.e. it is not related to NaturalTransformation. It does not work in simple case as well:

trait SomeType[F[_]]

class SomeConcreteType[A] extends SomeType[Either[A, ?]]

object SomeTypeExt {
  // this will not compile
  implicit class SomeTypeEnrich[F[_]](val t: SomeType[F]) {
    def test1: Boolean = false
  }
  // this will
  implicit class SomeConcreteEnrich[A](val t: SomeType[Either[A, ?]]) {
    def test2: Boolean = true
  }
}

If the goal to extend NtTest, probably NatTransExt1 would be best choice if one would like to stay as generic as possible. NatTransExt2 is ok, if extension really specific to NtTest.


问:
Python multithreading sqlite3 inserts
I would like to make a program with multiple threads. In each thread should be a database INSERT.

EDIT

But now I get the same error after a time

My code:

```<code>import threading, sqlite3

class myThread(threading.Thread):

   def __init__(self, pn, icm):
       threading.Thread.__init__(self)
       self.pn = pn
       self.icm = icm

   def run(self):

       con = sqlite3.connect("DB.db", check_same_thread=False)
       cursor = con.cursor()
       cursor.execute("CREATE TABLE IF NOT EXISTS test(pn VARCHAR(100), icm VARCHAR(100))")
       cursor.execute("INSERT INTO test VALUES('"+self.pn+"', '"+self.icm+"')")
       con.commit()
       con.close()

for i in range(0, 300):
   myThread("ABCDEFG", "1234546").start()
</code>```

I get the ERROR:

```<code>sqlite3.OperationalError: database is locked
</code>```

Thank you,
Jay

答:
Answered

```<code>import threading
import time, sqlite3

class myThread(threading.Thread):

   def __init__(self, pn, icm):
       threading.Thread.__init__(self)
       self.pn = pn
       self.icm = icm

       self.con = sqlite3.connect("DB.db", check_same_thread=False)
       self.cursor = self.con.cursor()
       self.cursor.execute("CREATE TABLE IF NOT EXISTS test(id INTEGER PRIMARY KEY AUTOINCREMENT, pn VARCHAR(100), icm VARCHAR(100))")

   def run(self):

       self.cursor.execute("INSERT INTO test VALUES(NULL, '"+self.pn+"', '"+self.icm+"')")
       self.con.commit()
       self.con.close()

for i in range(0, 300):

    myThread("ABCDEFG", "12345678").start()
</code>```

Title: Python multithreading sqlite3 inserts

Body:
I would like to make a program with multiple threads. In each thread should be a database INSERT.

EDIT

But now I get the same error after a time

My code:

import threading, sqlite3

class myThread(threading.Thread):

   def __init__(self, pn, icm):
       threading.Thread.__init__(self)
       self.pn = pn
       self.icm = icm

   def run(self):

       con = sqlite3.connect("DB.db", check_same_thread=False)
       cursor = con.cursor()
       cursor.execute("CREATE TABLE IF NOT EXISTS test(pn VARCHAR(100), icm VARCHAR(100))")
       cursor.execute("INSERT INTO test VALUES('"+self.pn+"', '"+self.icm+"')")
       con.commit()
       con.close()

for i in range(0, 300):
   myThread("ABCDEFG", "1234546").start()

I get the ERROR:

sqlite3.OperationalError: database is locked

Thank you,
Jay

Body:
Answered

import threading
import time, sqlite3

class myThread(threading.Thread):

   def __init__(self, pn, icm):
       threading.Thread.__init__(self)
       self.pn = pn
       self.icm = icm

       self.con = sqlite3.connect("DB.db", check_same_thread=False)
       self.cursor = self.con.cursor()
       self.cursor.execute("CREATE TABLE IF NOT EXISTS test(id INTEGER PRIMARY KEY AUTOINCREMENT, pn VARCHAR(100), icm VARCHAR(100))")

   def run(self):

       self.cursor.execute("INSERT INTO test VALUES(NULL, '"+self.pn+"', '"+self.icm+"')")
       self.con.commit()
       self.con.close()

for i in range(0, 300):

    myThread("ABCDEFG", "12345678").start()


问:
SQL Plus - how to pass big string to procedure CLOB's parameter
I have procedure that receives an XML:

```<code>CREATE OR REPLACE PROCEDURE PROCESS_XML(xml IN CLOB) AS
BEGIN
  DBMS_OUTPUT.PUT_LINE('XML processing started');
END;
</code>```

Now I'm doing a bash script that will download some XML files from a server and, for each one, I will call the above procedure using SQL Plus.

```<code>#!/bin/bash
file=$(curl -s "http://example.com/someFile.xml");
sqlplus myuser/mypass@myhost:1521/myscheme <<< "EXECUTE PROCESS_XML('$file')";
</code>```

It works fine for small file but for big ones, I'm getting the following error:

```<code>SQL*Plus: Release 12.1.0.2.0 Production on Thu Jun 8 18:28:19 2017
Copyright (c) 1982, 2016, Oracle.  All rights reserved.

Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
With the Partitioning, Real Application Clusters, Automatic Storage Management, OLAP
and Data Mining options
SQL> Input truncated to 7499 characters
SP2-0027: Input is too long (> 2499 characters) - line ignored
</code>```

Is there anything I could in order to send those big XML?

Thanks

答:
Could you try zipping the file data in bash, then unzipping in PLSQL using utl_compress?

Something like:

```<code>#!/bin/bash
file=$(curl -s "http://example.com/someFile.xml" | gzip -f);
sqlplus myuser/mypass@myhost:1521/myscheme <<< "EXECUTE PROCESS_XML('$file')";
</code>```

In plsql:

```<code>CREATE OR REPLACE PROCEDURE PROCESS_XML(xml IN CLOB) AS
   uncomp CLOB;
BEGIN
  UTL_COMPRESS.lz_uncompress(src => xml, dst => uncomp);
  DBMS_OUTPUT.PUT_LINE('XML processing started');
END;
</code>```

Body:
I have procedure that receives an XML:

CREATE OR REPLACE PROCEDURE PROCESS_XML(xml IN CLOB) AS
BEGIN
  DBMS_OUTPUT.PUT_LINE('XML processing started');
END;

Now I'm doing a bash script that will download some XML files from a server and, for each one, I will call the above procedure using SQL Plus.

#!/bin/bash
file=$(curl -s "http://example.com/someFile.xml");
sqlplus myuser/mypass@myhost:1521/myscheme <<< "EXECUTE PROCESS_XML('$file')";

It works fine for small file but for big ones, I'm getting the following error:

SQL*Plus: Release 12.1.0.2.0 Production on Thu Jun 8 18:28:19 2017
Copyright (c) 1982, 2016, Oracle.  All rights reserved.

Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
With the Partitioning, Real Application Clusters, Automatic Storage Management, OLAP
and Data Mining options
SQL> Input truncated to 7499 characters
SP2-0027: Input is too long (> 2499 characters) - line ignored

Is there anything I could in order to send those big XML?

Thanks

Body:
Could you try zipping the file data in bash, then unzipping in PLSQL using utl_compress?

Something like:

#!/bin/bash
file=$(curl -s "http://example.com/someFile.xml" | gzip -f);
sqlplus myuser/mypass@myhost:1521/myscheme <<< "EXECUTE PROCESS_XML('$file')";

In plsql:

CREATE OR REPLACE PROCEDURE PROCESS_XML(xml IN CLOB) AS
   uncomp CLOB;
BEGIN
  UTL_COMPRESS.lz_uncompress(src => xml, dst => uncomp);
  DBMS_OUTPUT.PUT_LINE('XML processing started');
END;


问:
Sorting an array of objects based on another array
So, there will probably be guys that will say this is a duplicate, but I read many relatively similar questions and still I'm unable to find an answer that resolves this particular problem, I've even tried some npm modules that claim to solve this, but to no avail...

Well, I have an array of objects:

```<code> var objArr = [{ '5': 1,'6': 1,'34': 3,id: 1,question: '12',author: 'Zoran  Stanić' }];
</code>```

and another array which should help in sorting the first array:

```<code>var sortingArr = [ 'id', 'question', 'author', '34', '5', '6' ];
</code>```

The result should be this:

```<code>[{id: 1, question: '12', author: 'Zoran  Stanić', '34': 3, '5': 1, '6': 1}]
</code>```

How can I achieve this?

P.S. These are the values from the database, and the order of objArr could be completely different than the one in example, depending on the db logic - it's MySQL thingy.

答:
Note: you cannot sort an object's keys, that depends on browser implementation....nor does it matter what "order" an objects keys are in, it only matters to you or your users what you display/how you display it.

If you want to print things out in a certain way, then you can do the following:

```<code>var arrOfObjects = [{...}];
var sortingArr = [ 'id', 'question', 'author', '34', '5', '6' ];

arrOfObjects.forEach(function(obj) {
   sortingArr.forEach(function(k) {
      console.log(k + ':' + obj[k]);
   });
});
</code>```

Body:
So, there will probably be guys that will say this is a duplicate, but I read many relatively similar questions and still I'm unable to find an answer that resolves this particular problem, I've even tried some npm modules that claim to solve this, but to no avail...

Well, I have an array of objects:

 var objArr = [{ '5': 1,'6': 1,'34': 3,id: 1,question: '12',author: 'Zoran  Stanić' }];

and another array which should help in sorting the first array:

var sortingArr = [ 'id', 'question', 'author', '34', '5', '6' ];

The result should be this:

[{id: 1, question: '12', author: 'Zoran  Stanić', '34': 3, '5': 1, '6': 1}]

How can I achieve this?

P.S. These are the values from the database, and the order of objArr could be completely different than the one in example, depending on the db logic - it's MySQL thingy.

Body:
Note: you cannot sort an object's keys, that depends on browser implementation....nor does it matter what "order" an objects keys are in, it only matters to you or your users what you display/how you display it.

If you want to print things out in a certain way, then you can do the following:

var arrOfObjects = [{...}];
var sortingArr = [ 'id', 'question', 'author', '34', '5', '6' ];

arrOfObjects.forEach(function(obj) {
   sortingArr.forEach(function(k) {
      console.log(k + ':' + obj[k]);
   });
});


问:
Best practice for pylons app global tmpl_context settings?
I'm writing a pylons application, and I'm wondering if there is a best practice for where to set some application specific values of the template context object (tmpl_context)?

Currently, I've added a __before__() method to the BaseController and am setting up the tmpl_context object with values there but am wondering if there is another place.

答: I think the BaseController is a good place to put that, either in __call__() or in __before__().


问:
CocoaPod with static library dependencies
I'm currently trying to create a pod for the first time that contains several dependencies.

The pods I'm currently including in my pod are as follows

FacebookCore

FacebookLogin

Fabric

TwitterKit

Google/SignIn

LinkedinSwift

My podspec file looks like this

```<code>Pod::Spec.new do |s|

  s.platform     = :ios
  s.ios.deployment_target = '8.0'
  s.name         = "Socializin"
  s.version      = "0.0.1"
  s.summary      = "A short description of Socializin."
  s.requires_arc = true

  s.author       = {"MyName" => "MyMail"}
  s.homepage     = "http://EXAMPLE/Socializin"
  s.license      = { :type => "MIT", :file => "LICENSE" }
  s.source       = { :git => "", :tag => "#{s.version}"}

  s.framework    = "UIKit"
  s.dependency 'FacebookCore', '~> 0.2.0'
  s.dependency 'FacebookLogin', '~> 0.2.0'
  s.dependency 'FacebookShare', '~> 0.2.0'
  s.dependency 'Fabric', '~> 1.6.11'
  s.dependency 'TwitterKit', '~> 2.8.1'
  s.dependency 'Google/SignIn', '~> 3.0.3'
  s.dependency 'LinkedinSwift', '~> 1.7.4'

  s.source_files = "Socializin/**/*.{swift}"
  #s.resources = "Socializin/**/*.{png,jpeg,jpg,storyboard,xib}"
end
</code>```

But the dependencies give me the following error

[!] The 'Pods-socializinTest' target has transitive dependencies that include static binaries: (/Users/x/projects/x/Examples/socializinTest/Pods/Fabric/iOS/Fabric.framework, /Users/x/projects/x/Examples/socializinTest/Pods/Google/Frameworks/GGLCore.framework, and /Users/x/projects/x/Examples/socializinTest/Pods/Google/Frameworks/GGLSignIn.framework)

Is there anyway to make sure it does work? All I want to do is create a pod that will make it easy to use all those services and being able to add more to it whenever needed.

答:
I hope you are still looking for a solution.

This is what i did:

I put the Google SignIn framework under /Dependency/GoogleDependency

And i put the TwitterKit, TwitterCore and Fabric frameworks under /Dependency/TwitterDependency/

```<code>Pod::Spec.new do |s|
  s.platform     = :ios
  s.ios.deployment_target = '9.0'
  s.name         = "Socializin"
  s.version      = "0.0.1"
  s.summary      = "A short description of Socializin."
  s.requires_arc = true

  s.author       = {"MyName" => "MyMail"}
  s.homepage     = "http://EXAMPLE/Socializin"
  s.license      = { :type => "MIT", :file => "LICENSE" }
  s.source       = { :git => "", :tag => "#{s.version}"}

  s.framework    = "UIKit"
  s.dependency 'FacebookCore', '~> 0.2.0'
  s.dependency 'FacebookLogin', '~> 0.2.0'
  s.dependency 'FacebookShare', '~> 0.2.0'
  s.dependency 'LinkedinSwift', '~> 1.7.4'

  s.source_files = "Socializin/**/*.{swift}"
  #s.resources = "Socializin/**/*.{png,jpeg,jpg,storyboard,xib}"

  #----------------------------Sub Modules-----------------#
  s.subspec 'GoogleAuthentication' do |ss|
    ss.ios.deployment_target = '9.0'
    ss.source_files = 'Socializin/Dependency/GoogleDependency/**/*.{swift}'
    ss.resources = ['Socializin/Dependency/GoogleDependency/**/*.{xib,xcdatamodeld,bundle}']
    ss.vendored_frameworks = ['Socializin/Dependency/GoogleDependency/**/*.{framework}']
    ss.preserve_paths = ['Socializin/Dependency/GoogleDependency/**/*.{framework}']
    frameworkPaths = ''
    Dir.glob('Socializin/Dependency/GoogleDependency/**/*.{framework}') do |filename|
      filePath = Pathname.new(filename)
      newFilename = filePath.dirname
      if frameworkPaths != ""
        frameworkPaths = "#{frameworkPaths} \"$(PODS_ROOT)/#{newFilename}\""
      else
        frameworkPaths = "\"$(PODS_ROOT)/#{newFilename}\""
      end
    end
    ss.xcconfig = {
      'FRAMEWORK_SEARCH_PATHS' => frameworkPaths,
      'HEADER_SEARCH_PATHS' => '"$(PODS_ROOT)/Socializin/Dependency/GoogleDependency"',
    }
    #Authentication
    # ss.dependency 'GoogleSignIn'
    ss.dependency 'GoogleToolboxForMac/NSDictionary+URLArguments'
    ss.dependency 'GoogleToolboxForMac/NSData+zlib'
  end

  s.subspec 'TwitterAuthentication' do |ss|
    ss.ios.deployment_target = '9.0'
    ss.source_files = 'Socializin/Dependency/TwitterDependency/**/*.{swift}'
    ss.resources = ['Socializin/Dependency/TwitterDependency/TwitterKit/iOS/TwitterKit.framework/*.{xib,xcdatamodeld,bundle}']
    ss.vendored_frameworks = ['Socializin/Dependency/TwitterDependency/**/*.{framework}']
    ss.preserve_paths = ['Socializin/Dependency/TwitterDependency/**/*.{framework}']
    frameworkPaths = ''
    Dir.glob('Socializin/Dependency/TwitterDependency/**/*.{framework}') do |filename|
      filePath = Pathname.new(filename)
      newFilename = filePath.dirname
      if frameworkPaths != ""
        frameworkPaths = "#{frameworkPaths} \"$(PODS_ROOT)/#{newFilename}\""
      else
        frameworkPaths = "\"$(PODS_ROOT)/#{newFilename}\""
      end
    end
    ss.xcconfig = {
      'FRAMEWORK_SEARCH_PATHS' => frameworkPaths,
      'HEADER_SEARCH_PATHS' => '"$(PODS_ROOT)/Socializin/Dependency/TwitterDependency"',
    }
    #Authentication
    # ss.dependency 'Fabric'
    # ss.dependency 'TwitterKit'
    # ss.dependency 'TwitterCore'
  end
end
</code>```

Body:
I'm currently trying to create a pod for the first time that contains several dependencies.

The pods I'm currently including in my pod are as follows

FacebookCore

FacebookLogin

Fabric

TwitterKit

Google/SignIn

LinkedinSwift

My podspec file looks like this

Pod::Spec.new do |s|

  s.platform     = :ios
  s.ios.deployment_target = '8.0'
  s.name         = "Socializin"
  s.version      = "0.0.1"
  s.summary      = "A short description of Socializin."
  s.requires_arc = true

  s.author       = {"MyName" => "MyMail"}
  s.homepage     = "http://EXAMPLE/Socializin"
  s.license      = { :type => "MIT", :file => "LICENSE" }
  s.source       = { :git => "", :tag => "#{s.version}"}

  s.framework    = "UIKit"
  s.dependency 'FacebookCore', '~> 0.2.0'
  s.dependency 'FacebookLogin', '~> 0.2.0'
  s.dependency 'FacebookShare', '~> 0.2.0'
  s.dependency 'Fabric', '~> 1.6.11'
  s.dependency 'TwitterKit', '~> 2.8.1'
  s.dependency 'Google/SignIn', '~> 3.0.3'
  s.dependency 'LinkedinSwift', '~> 1.7.4'

  s.source_files = "Socializin/**/*.{swift}"
  #s.resources = "Socializin/**/*.{png,jpeg,jpg,storyboard,xib}"
end

But the dependencies give me the following error

[!] The 'Pods-socializinTest' target has transitive dependencies that include static binaries: (/Users/x/projects/x/Examples/socializinTest/Pods/Fabric/iOS/Fabric.framework, /Users/x/projects/x/Examples/socializinTest/Pods/Google/Frameworks/GGLCore.framework, and /Users/x/projects/x/Examples/socializinTest/Pods/Google/Frameworks/GGLSignIn.framework)

Is there anyway to make sure it does work? All I want to do is create a pod that will make it easy to use all those services and being able to add more to it whenever needed.

Body:
I hope you are still looking for a solution.

This is what i did:

I put the Google SignIn framework under /Dependency/GoogleDependency

And i put the TwitterKit, TwitterCore and Fabric frameworks under /Dependency/TwitterDependency/

Pod::Spec.new do |s|
  s.platform     = :ios
  s.ios.deployment_target = '9.0'
  s.name         = "Socializin"
  s.version      = "0.0.1"
  s.summary      = "A short description of Socializin."
  s.requires_arc = true

  s.author       = {"MyName" => "MyMail"}
  s.homepage     = "http://EXAMPLE/Socializin"
  s.license      = { :type => "MIT", :file => "LICENSE" }
  s.source       = { :git => "", :tag => "#{s.version}"}

  s.framework    = "UIKit"
  s.dependency 'FacebookCore', '~> 0.2.0'
  s.dependency 'FacebookLogin', '~> 0.2.0'
  s.dependency 'FacebookShare', '~> 0.2.0'
  s.dependency 'LinkedinSwift', '~> 1.7.4'

  s.source_files = "Socializin/**/*.{swift}"
  #s.resources = "Socializin/**/*.{png,jpeg,jpg,storyboard,xib}"

  #----------------------------Sub Modules-----------------#
  s.subspec 'GoogleAuthentication' do |ss|
    ss.ios.deployment_target = '9.0'
    ss.source_files = 'Socializin/Dependency/GoogleDependency/**/*.{swift}'
    ss.resources = ['Socializin/Dependency/GoogleDependency/**/*.{xib,xcdatamodeld,bundle}']
    ss.vendored_frameworks = ['Socializin/Dependency/GoogleDependency/**/*.{framework}']
    ss.preserve_paths = ['Socializin/Dependency/GoogleDependency/**/*.{framework}']
    frameworkPaths = ''
    Dir.glob('Socializin/Dependency/GoogleDependency/**/*.{framework}') do |filename|
      filePath = Pathname.new(filename)
      newFilename = filePath.dirname
      if frameworkPaths != ""
        frameworkPaths = "#{frameworkPaths} \"$(PODS_ROOT)/#{newFilename}\""
      else
        frameworkPaths = "\"$(PODS_ROOT)/#{newFilename}\""
      end
    end
    ss.xcconfig = {
      'FRAMEWORK_SEARCH_PATHS' => frameworkPaths,
      'HEADER_SEARCH_PATHS' => '"$(PODS_ROOT)/Socializin/Dependency/GoogleDependency"',
    }
    #Authentication
    # ss.dependency 'GoogleSignIn'
    ss.dependency 'GoogleToolboxForMac/NSDictionary+URLArguments'
    ss.dependency 'GoogleToolboxForMac/NSData+zlib'
  end

  s.subspec 'TwitterAuthentication' do |ss|
    ss.ios.deployment_target = '9.0'
    ss.source_files = 'Socializin/Dependency/TwitterDependency/**/*.{swift}'
    ss.resources = ['Socializin/Dependency/TwitterDependency/TwitterKit/iOS/TwitterKit.framework/*.{xib,xcdatamodeld,bundle}']
    ss.vendored_frameworks = ['Socializin/Dependency/TwitterDependency/**/*.{framework}']
    ss.preserve_paths = ['Socializin/Dependency/TwitterDependency/**/*.{framework}']
    frameworkPaths = ''
    Dir.glob('Socializin/Dependency/TwitterDependency/**/*.{framework}') do |filename|
      filePath = Pathname.new(filename)
      newFilename = filePath.dirname
      if frameworkPaths != ""
        frameworkPaths = "#{frameworkPaths} \"$(PODS_ROOT)/#{newFilename}\""
      else
        frameworkPaths = "\"$(PODS_ROOT)/#{newFilename}\""
      end
    end
    ss.xcconfig = {
      'FRAMEWORK_SEARCH_PATHS' => frameworkPaths,
      'HEADER_SEARCH_PATHS' => '"$(PODS_ROOT)/Socializin/Dependency/TwitterDependency"',
    }
    #Authentication
    # ss.dependency 'Fabric'
    # ss.dependency 'TwitterKit'
    # ss.dependency 'TwitterCore'
  end
end


问:
Capturing camel exchange data into database
How would you recommend in Camel to define key/value expressions in routes for things you want to save for auditing, and have them be picked up and written to a database transparently?

i.e. the route contains an array or set of expressions for things to save for auditing, but doesn't know how it actually gets picked up and written to a DB.

This would be like Mule's auditing feature, where you can put <flow> elements in the Mule XML and define expressions to save to Mule's DB for tracking.

I have looked at Interceptor, Event Notifiers, Tracers, WireTaps, MDC Logging - I am sure the answer lies in one or a combination of these elements but it's not clear to me.

I'm using this example of Mule auditing XML from its documentation as a comparison:

```<code><flow name="bizFlow">
    <tracking:custom-event event-name="Retrieved Employee" doc:name="Custom Business Event">
        <tracking:meta-data key="Employee ID" value="#[payload['ID']]"/>
        <tracking:meta-data key="Employee Email" value="#[payload['Email']]"/>
        <tracking:meta-data key="Employee Git ID" value="#[payload['GITHUB_ID']]"/>
    </tracking:custom-event>
</flow>
</code>```

Thanks very much

答:
For auditing I used wireTap to send exchange to special audit route where I do what I need for auditing. Not actually to DB but to JMS queue, but it does not matter.

There is only one restriction: whatever goes for auditing must not be changed after wireTap by main route (both run in parallel), so I cloned such auditing data before wireTap to special Exchange property to be used in audit route.

Body:
How would you recommend in Camel to define key/value expressions in routes for things you want to save for auditing, and have them be picked up and written to a database transparently?

i.e. the route contains an array or set of expressions for things to save for auditing, but doesn't know how it actually gets picked up and written to a DB.

This would be like Mule's auditing feature, where you can put <flow> elements in the Mule XML and define expressions to save to Mule's DB for tracking.

I have looked at Interceptor, Event Notifiers, Tracers, WireTaps, MDC Logging - I am sure the answer lies in one or a combination of these elements but it's not clear to me.

I'm using this example of Mule auditing XML from its documentation as a comparison:

<flow name="bizFlow">
    <tracking:custom-event event-name="Retrieved Employee" doc:name="Custom Business Event">
        <tracking:meta-data key="Employee ID" value="#[payload['ID']]"/>
        <tracking:meta-data key="Employee Email" value="#[payload['Email']]"/>
        <tracking:meta-data key="Employee Git ID" value="#[payload['GITHUB_ID']]"/>
    </tracking:custom-event>
</flow>

Thanks very much


问:
on press button mass stay the color
Hi can some one please help me with this code

```<code>horse_btn_a1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      horse_btn_a1.setBackgroundColor(Color.parseColor("@drawable/ront2"));
    }
});
</code>```

and what I wanna do is when the button is pressed it must stay that color.

答:
You can achieve like this

red_circle_bg.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">

            <solid android:color="#F00"/>

        </shape>
    </item>
</layer-list>
</code>```

green_circle_bg.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">

            <solid android:color="#0F0"/>

        </shape>
    </item>
</layer-list>
</code>```

blue_circle_bg.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">

            <solid android:color="#00F"/>

        </shape>
    </item>
</layer-list>
</code>```

button_bg.xml

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/red_circle_bg" android:state_selected="true"/>
    <item android:drawable="@drawable/green_circle_bg" android:state_pressed="true"/>
    <item android:drawable="@drawable/blue_circle_bg"/>

</selector>
</code>```

In your layout, you can give like this

```<code><Button
        android:id="@+id/my_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/button_bg" />
</code>```

We should do this logic to make it work

```<code>private boolean mIsSelected = false;

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

    final Button horse_btn_a1 = findViewById(R.id.button);

    horse_btn_a1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            horse_btn_a1.setSelected(!mIsSelected);

            mIsSelected = !mIsSelected;
        }
    });
}
</code>```

or we should use Checkable Button

Title: on press button mass stay the color

Body:
Hi can some one please help me with this code

horse_btn_a1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      horse_btn_a1.setBackgroundColor(Color.parseColor("@drawable/ront2"));
    }
});

and what I wanna do is when the button is pressed it must stay that color.

Body:
You can achieve like this

red_circle_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">

            <solid android:color="#F00"/>

        </shape>
    </item>
</layer-list>

green_circle_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">

            <solid android:color="#0F0"/>

        </shape>
    </item>
</layer-list>

blue_circle_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">

            <solid android:color="#00F"/>

        </shape>
    </item>
</layer-list>

button_bg.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/red_circle_bg" android:state_selected="true"/>
    <item android:drawable="@drawable/green_circle_bg" android:state_pressed="true"/>
    <item android:drawable="@drawable/blue_circle_bg"/>

</selector>

In your layout, you can give like this

<Button
        android:id="@+id/my_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/button_bg" />

We should do this logic to make it work

private boolean mIsSelected = false;

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

    final Button horse_btn_a1 = findViewById(R.id.button);

    horse_btn_a1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            horse_btn_a1.setSelected(!mIsSelected);

            mIsSelected = !mIsSelected;
        }
    });
}

or we should use Checkable Button


问:
Clicking inside a Recycler view: Espresso
I am trying to click on a menu item inside Recycler view and I have following code.

```<code>onView(allOf(withId(R.id.section_list),isDisplayed())).perform(RecyclerViewActions.actionOnItem(hasDescendant(withText("ABC")), MyViewAction.clickChildViewWithId(R.id.payment_menu)));
</code>```

and MyViewAction looks like this:

```<code>class MyViewAction {

public static ViewAction clickChildViewWithId(final int id) {
    return new ViewAction() {
        @Override
        public Matcher<View> getConstraints() {
            return null;
        }

        @Override
        public String getDescription() {
            return "Click on a child view with specified id.";
        }

        @Override
        public void perform(UiController uiController, View view) {
            View v = view.findViewById(id);
            v.performClick();
        }
    };
}
</code>```

When I test it, I can see the Scrolling takes place to right position but the click fails with the following error

android.support.test.espresso.PerformException: Error performing 'android.support.test.espresso.contrib.RecyclerViewActions$ActionOnItemAtPositionViewAction@2fd64b56' on view 'with id: com.em3Agri.operation.debug:id/section_list'.
      at android.support.test.espresso.PerformException$Builder.build(PerformException.java:83)
      at .........
      Caused by: java.lang.IllegalStateException: No view holder at position: 38
      at android.support.test.espresso.contrib.RecyclerViewActions$ActionOnItemAtPositionViewAction.perform(RecyclerViewActions.java:290)
      at android.support.test.espresso.ViewInteraction$1.run(ViewInteraction.java:144)

答:
How about:</p>

```<code>onView(withId(R.id.section_list))
  .perform(
    RecyclerViewActions.actionOnItem(
      hasDescendant(withId(R.id.payment_menu)),
      ViewActions.click()
    )
  );
</code>```

Body:
I am trying to click on a menu item inside Recycler view and I have following code.

onView(allOf(withId(R.id.section_list),isDisplayed())).perform(RecyclerViewActions.actionOnItem(hasDescendant(withText("ABC")), MyViewAction.clickChildViewWithId(R.id.payment_menu)));

and MyViewAction looks like this:

class MyViewAction {

public static ViewAction clickChildViewWithId(final int id) {
    return new ViewAction() {
        @Override
        public Matcher<View> getConstraints() {
            return null;
        }

        @Override
        public String getDescription() {
            return "Click on a child view with specified id.";
        }

        @Override
        public void perform(UiController uiController, View view) {
            View v = view.findViewById(id);
            v.performClick();
        }
    };
}

When I test it, I can see the Scrolling takes place to right position but the click fails with the following error

android.support.test.espresso.PerformException: Error performing 'android.support.test.espresso.contrib.RecyclerViewActions$ActionOnItemAtPositionViewAction@2fd64b56' on view 'with id: com.em3Agri.operation.debug:id/section_list'.
      at android.support.test.espresso.PerformException$Builder.build(PerformException.java:83)
      at .........
      Caused by: java.lang.IllegalStateException: No view holder at position: 38
      at android.support.test.espresso.contrib.RecyclerViewActions$ActionOnItemAtPositionViewAction.perform(RecyclerViewActions.java:290)
      at android.support.test.espresso.ViewInteraction$1.run(ViewInteraction.java:144)

Body:
How about:

onView(withId(R.id.section_list))
  .perform(
    RecyclerViewActions.actionOnItem(
      hasDescendant(withId(R.id.payment_menu)),
      ViewActions.click()
    )
  );