问:
Parallel many dimensional optimization
I am building a script that generates input data [parameters] for another program to calculate. I would like to optimize the resulting data. Previously I have been using the numpy powell optimization. The psuedo code looks something like this.

```<code>def value(param):
     run_program(param)
     #Parse output
     return value

scipy.optimize.fmin_powell(value,param)
</code>```

This works great; however, it is incredibly slow as each iteration of the program can take days to run. What I would like to do is coarse grain parallelize this. So instead of running a single iteration at a time it would run (number of parameters)*2 at a time. For example:

```<code>Initial guess: param=[1,2,3,4,5]

#Modify guess by plus minus another matrix that is changeable at each iteration
jump=[1,1,1,1,1]
#Modify each variable plus/minus jump.
for num,a in enumerate(param):
    new_param1=param[:]
    new_param1[num]=new_param1[num]+jump[num]
    run_program(new_param1)
    new_param2=param[:]
    new_param2[num]=new_param2[num]-jump[num]
    run_program(new_param2)

#Wait until all programs are complete -> Parse Output
Output=[[value,param],...]
#Create new guess
#Repeat
</code>```

Number of variable can range from 3-12 so something such as this could potentially speed up the code from taking a year down to a week. All variables are dependent on each other and I am only looking for local minima from the initial guess. I have started an implementation using hessian matrices; however, that is quite involved. Is there anything out there that either does this, is there a simpler way, or any suggestions to get started?

So the primary question is the following:
Is there an algorithm that takes a starting guess, generates multiple guesses, then uses those multiple guesses to create a new guess, and repeats until a threshold is found. Only analytic derivatives are available. What is a good way of going about this, is there something built already that does this, is there other options?

Thank you for your time.

As a small update I do have this working by calculating simple parabolas through the three points of each dimension and then using the minima as the next guess. This seems to work decently, but is not optimal. I am still looking for additional options.

Current best implementation is parallelizing the inner loop of powell's method.

Thank you everyone for your comments. Unfortunately it looks like there is simply not a concise answer to this particular problem. If I get around to implementing something that does this I will paste it here; however, as the project is not particularly important or the need of results pressing I will likely be content letting it take up a node for awhile.

答:
Parallelizing local optimizers is intrinsically limited: they start from a single initial point and try to work downhill, so later points depend on the values of previous evaluations. Nevertheless there are some avenues where a modest amount of parallelization can be added.

As another answer points out, if you need to evaluate your derivative using a finite-difference method, preferably with an adaptive step size, this may require many function evaluations, but the derivative with respect to each variable may be independent; you could maybe get a speedup by a factor of twice the number of dimensions of your problem. If you've got more processors than you know what to do with, you can use higher-order-accurate gradient formulae that require more (parallel) evaluations.

Some algorithms, at certain stages, use finite differences to estimate the Hessian matrix; this requires about half the square of the number of dimensions of your matrix, and all can be done in parallel.

Some algorithms may also be able to use more parallelism at a modest algorithmic cost. For example, quasi-Newton methods try to build an approximation of the Hessian matrix, often updating this by evaluating a gradient. They then take a step towards the minimum and evaluate a new gradient to update the Hessian. If you've got enough processors so that evaluating a Hessian is as fast as evaluating the function once, you could probably improve these by evaluating the Hessian at every step.

As far as implementations go, I'm afraid you're somewhat out of luck. There are a number of clever and/or well-tested implementations out there, but they're all, as far as I know, single-threaded. Your best bet is to use an algorithm that requires a gradient and compute your own in parallel. It's not that hard to write an adaptive one that runs in parallel and chooses sensible step sizes for its numerical derivatives.

Title: Parallel many dimensional optimization

Body:
I am building a script that generates input data [parameters] for another program to calculate. I would like to optimize the resulting data. Previously I have been using the numpy powell optimization. The psuedo code looks something like this.

def value(param):
     run_program(param)
     #Parse output
     return value

scipy.optimize.fmin_powell(value,param)

This works great; however, it is incredibly slow as each iteration of the program can take days to run. What I would like to do is coarse grain parallelize this. So instead of running a single iteration at a time it would run (number of parameters)*2 at a time. For example:

Initial guess: param=[1,2,3,4,5]

#Modify guess by plus minus another matrix that is changeable at each iteration
jump=[1,1,1,1,1]
#Modify each variable plus/minus jump.
for num,a in enumerate(param):
    new_param1=param[:]
    new_param1[num]=new_param1[num]+jump[num]
    run_program(new_param1)
    new_param2=param[:]
    new_param2[num]=new_param2[num]-jump[num]
    run_program(new_param2)

#Wait until all programs are complete -> Parse Output
Output=[[value,param],...]
#Create new guess
#Repeat

Number of variable can range from 3-12 so something such as this could potentially speed up the code from taking a year down to a week. All variables are dependent on each other and I am only looking for local minima from the initial guess. I have started an implementation using hessian matrices; however, that is quite involved. Is there anything out there that either does this, is there a simpler way, or any suggestions to get started?

So the primary question is the following:
Is there an algorithm that takes a starting guess, generates multiple guesses, then uses those multiple guesses to create a new guess, and repeats until a threshold is found. Only analytic derivatives are available. What is a good way of going about this, is there something built already that does this, is there other options?

Thank you for your time.

As a small update I do have this working by calculating simple parabolas through the three points of each dimension and then using the minima as the next guess. This seems to work decently, but is not optimal. I am still looking for additional options.

Current best implementation is parallelizing the inner loop of powell's method.

Thank you everyone for your comments. Unfortunately it looks like there is simply not a concise answer to this particular problem. If I get around to implementing something that does this I will paste it here; however, as the project is not particularly important or the need of results pressing I will likely be content letting it take up a node for awhile.


来源: stackexchange

问:
List<T> add method in C#
As I know. List Add method works as below.

```<code>List<string> cities = new List<string>();
cities.Add("New York");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");
</code>```

If I designed the data structure as this

```<code>List<object> lstObj = new List<object>();
if (true)  // string members
{
    cities.Add("New York");
    cities.Add("Istanbul");
}
else // List obj members here
{
    List<object> AListObject= new List<object>();
    cities.Add(AListObject);  // how to handle this?
}
</code>```

Does the List Add method works or not if I add different types members in the same function.

答:
You can't add a List<object> to a List<string>. The only thing you can add to list of strings is strings (or null references). You could use this instead:

```<code>List<object> cities = new List<object>();
</code>```

But this seems like a bad design. When you use object as the generic type of a collection you effectively lose all the benefits of type-safety.

For parsing XML I'd suggest you look at XmlDocument.

ContentLicense: CC BY-SA 2.5

Title: List<T> add method in C#

Body:
As I know. List Add method works as below.

List<string> cities = new List<string>();
cities.Add("New York");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");

If I designed the data structure as this

List<object> lstObj = new List<object>();
if (true)  // string members
{
    cities.Add("New York");
    cities.Add("Istanbul");
}
else // List obj members here
{
    List<object> AListObject= new List<object>();
    cities.Add(AListObject);  // how to handle this?
}

Does the List Add method works or not if I add different types members in the same function.

Body:
You can't add a List<object> to a List<string>. The only thing you can add to list of strings is strings (or null references). You could use this instead:

List<object> cities = new List<object>();

But this seems like a bad design. When you use object as the generic type of a collection you effectively lose all the benefits of type-safety.

For parsing XML I'd suggest you look at XmlDocument.


问:
How to treat a var as both int and string.
```<code>def die():
    first = str(randint(1, 6))
    second = str(randint(1, 6))
    total = first + second
    print "You have rolled a " + first + " and a " + second + ", for a total score of " + total + "."
</code>```

Standard die throwing game, but I'm struggling to print the values for individual die as well as the total. Treating as a string for individual, but then sum leads to concatenation rather than actual sum.

Thanks

答:
This would also work. Don't convert first and second to str until after you perform sum on them.  Then remember to cast them as str in your print statement.

```<code>def die():
    first = randint(1, 6)
    second = randint(1, 6)
    total = str(first + second)
    print ("You have rolled a " + str(first) + " and a " + str(second) + ", for a total score of " + total + ".")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
def die():
    first = str(randint(1, 6))
    second = str(randint(1, 6))
    total = first + second
    print "You have rolled a " + first + " and a " + second + ", for a total score of " + total + "."

Standard die throwing game, but I'm struggling to print the values for individual die as well as the total. Treating as a string for individual, but then sum leads to concatenation rather than actual sum.

Thanks

Body:
This would also work. Don't convert first and second to str until after you perform sum on them.  Then remember to cast them as str in your print statement.

def die():
    first = randint(1, 6)
    second = randint(1, 6)
    total = str(first + second)
    print ("You have rolled a " + str(first) + " and a " + str(second) + ", for a total score of " + total + ".")


问:
Vue.js - Element UI - Upload file add a parameter
I'm using vue.js 2.3 and element-ui.

I'd like to use the upload-file component to send files to my server.

In the doc we can find the action "https://jsonplaceholder.typicode.com/posts/"

Question

I would like to know how can I add a parameter to the action?

Situation

I currently receive an array file with the data of my file but I would like to be able to pass other parameters

答: If you look at the list of attributes on the documentation page you linked to, there is a data attribute that lets you specify an object as "addition[al] options of [the] request".


问:
android logcat logs chatty module line expire message
I am getting lots of this kind of logcat messages related to my application.

11-19 19:04:23.872  3327  3440 I chatty  : uid=10085 com.xxxx.yyy expire 18 lines

What are these log messages? Am I missing my actual application logcat logs here?

答:
I want to add another answer because none of the existing answers actually answered the 'Am I missing my actual application logcat logs here?' question.

Yes, you're missing the logs. As soon as app considered 'chatty' by logcat (more than 5 lines per second), logs of your app will be collapsed.

You can avoid this behaviour by whitelisting your app for logcat:

adb logcat -P '<pid or uid of your app>'

You can print the current white and black lists by executing:

adb logcat -p

Also this command is helpful to print logcat statistics:

adb logcat -S

Additionally, I found useful to auto-whitelist my app for logcat directly from code during tests:

```<code>int pid = android.os.Process.myPid();
String whiteList = "logcat -P '" + pid + "'";
Runtime.getRuntime().exec(whiteList).waitFor();
</code>```

More info can be found in official docs for logcat here

Body:
I want to add another answer because none of the existing answers actually answered the 'Am I missing my actual application logcat logs here?' question.

Yes, you're missing the logs. As soon as app considered 'chatty' by logcat (more than 5 lines per second), logs of your app will be collapsed.

You can avoid this behaviour by whitelisting your app for logcat:

adb logcat -P '<pid or uid of your app>'

You can print the current white and black lists by executing:

adb logcat -p

Also this command is helpful to print logcat statistics:

adb logcat -S

Additionally, I found useful to auto-whitelist my app for logcat directly from code during tests:

int pid = android.os.Process.myPid();
String whiteList = "logcat -P '" + pid + "'";
Runtime.getRuntime().exec(whiteList).waitFor();

More info can be found in official docs for logcat here


问:
OneToMany Relations with Lift
I have a question once again and I have the feeling the solution is simple. Should be simple, in any case. I have been trying to model my mappings for my database, with the nice OneToMany trait, like so

```<code>class User extends MegaProtoUser[User] with OneToMany[Long, User] {
  def getSingleton = User

  object posts extends MappedOneToMany(Post, Post.author, OrderBy(Post.edited, Descending))
}

class Post extends LongKeyedMapper[Post] with IdPK with OneToMany[Long, Post] {
  def getSingleton = Post

  object author extends LongMappedMapper(this, User)

  object title extends MappedString(this, 100) {
    override def dbIndexed_? = true

    override def defaultValue = "New Post"
  }

  object contents extends MappedText(this)

  object edited extends MappedDate(this)
}
</code>```

All nice an done, I have my One-to-many relationship all right. But, what troubles me a real lot, how do I actually get the data in that relationship? Just supposing I've got a Post object and want to get the author's name to it?

```<code>bind("post", in, "title" -> post.title, "author" -> /* insert overly complicated method here */)
</code>```

I've learned I can get it over a Box, by post.author.obj or something. It does not quite work out, I have to do a match over it and such?

I feel the answer is simple, but yet I fail to see it.

答:
Mapper does not guarantee you that post.author can always succeed, so it must return a Box. You could use a post.author.obj.map(_.name.is) openOr "unknown name" or similar to avoid using a match statement.

Alternatively, you could create a helper method on Post which does the default handling and use that instead.

Title: OneToMany Relations with Lift

Body:
I have a question once again and I have the feeling the solution is simple. Should be simple, in any case. I have been trying to model my mappings for my database, with the nice OneToMany trait, like so

class User extends MegaProtoUser[User] with OneToMany[Long, User] {
  def getSingleton = User

  object posts extends MappedOneToMany(Post, Post.author, OrderBy(Post.edited, Descending))
}

class Post extends LongKeyedMapper[Post] with IdPK with OneToMany[Long, Post] {
  def getSingleton = Post

  object author extends LongMappedMapper(this, User)

  object title extends MappedString(this, 100) {
    override def dbIndexed_? = true

    override def defaultValue = "New Post"
  }

  object contents extends MappedText(this)

  object edited extends MappedDate(this)
}

All nice an done, I have my One-to-many relationship all right. But, what troubles me a real lot, how do I actually get the data in that relationship? Just supposing I've got a Post object and want to get the author's name to it?

bind("post", in, "title" -> post.title, "author" -> /* insert overly complicated method here */)

I've learned I can get it over a Box, by post.author.obj or something. It does not quite work out, I have to do a match over it and such?

I feel the answer is simple, but yet I fail to see it.


问:
How to create an instance of class and implement it in a subclass?
How would I create an instance of a class to use as an attribute in another class? I believe this is what I need to do:

```<code>ClassA a1 = new ClassA(); // ClassA is the super class
</code>```

This is where I get stuck, if my above code is even correct. How do I actually use this in a subclass of ClassA, say ClassB? So if ClassA has 'name' and 'age' and ClassB has 'tenant' what do I need to do in order to give tenant a name and age?

答:
If ClassB extends ClassA then ClassB will inherit all of the properties of ClassA. Here is a quick example:

```<code>public class ClassA {

     private String name;
     private int age;

     public ClassA(String name, int age)
          this.name = name;
          this.age = age;
     }

     public String getName() {
          return name;
     }

     public int ageGetAge() {
          return age;
     }
}

public class ClassB extends ClassA {

     private String tenant;

     public ClassB(String name, int age, String tenant) {
          super(name, age);
          this.tenant = tenant;
     }

     public String getTenant() {
          return tenant;
     }
}
</code>```

For these classes, if you create a ClassB object in some part of your program you will be able to call the methods getName() and getAge() because ClassB extends ClassA.

```<code>public static void main(String[] args) {
     ClassB object = new ClassB("me", 0, "you");
     System.out.println(object.getName());
     System.out.println(object.getAge() + "");
     System.out.println(object.getTenant());
}
</code>```

This bit of code would output the following:

```<code>me
0
you
</code>```

There are slightly different ways of going about this depending on whether various variables are protected, private, or public. I would recommend reading more about visibility and such.

Best of luck with your endevours.

Body:
How would I create an instance of a class to use as an attribute in another class? I believe this is what I need to do:

ClassA a1 = new ClassA(); // ClassA is the super class

This is where I get stuck, if my above code is even correct. How do I actually use this in a subclass of ClassA, say ClassB? So if ClassA has 'name' and 'age' and ClassB has 'tenant' what do I need to do in order to give tenant a name and age?

Body:
If ClassB extends ClassA then ClassB will inherit all of the properties of ClassA. Here is a quick example:

public class ClassA {

     private String name;
     private int age;

     public ClassA(String name, int age)
          this.name = name;
          this.age = age;
     }

     public String getName() {
          return name;
     }

     public int ageGetAge() {
          return age;
     }
}

public class ClassB extends ClassA {

     private String tenant;

     public ClassB(String name, int age, String tenant) {
          super(name, age);
          this.tenant = tenant;
     }

     public String getTenant() {
          return tenant;
     }
}

For these classes, if you create a ClassB object in some part of your program you will be able to call the methods getName() and getAge() because ClassB extends ClassA.

public static void main(String[] args) {
     ClassB object = new ClassB("me", 0, "you");
     System.out.println(object.getName());
     System.out.println(object.getAge() + "");
     System.out.println(object.getTenant());
}

This bit of code would output the following:

me
0
you

There are slightly different ways of going about this depending on whether various variables are protected, private, or public. I would recommend reading more about visibility and such.

Best of luck with your endevours.


问:
android: move a view on touch move (ACTION_MOVE)
I'd like to do a simple control: a container with a view inside. If I touch the container and I move the finger, I want to move the view to follow my finger.

What kind of container (layout) should I use? How to do this?

I don't need to use a surface, but a simple layout.

答:
Changed a bit a solution provided by @Vyacheslav Shylkin to remove dependencies of manually entered numbers.</p>
```<code>import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class MainActivity extends Activity implements View.OnTouchListener
{
    private int       _xDelta;
    private int       _yDelta;
    private int       _rightMargin;
    private int       _bottomMargin;
    private ImageView _floatingView;

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

        this._floatingView = (ImageView) findViewById(R.id.textView);

        this._floatingView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener()
        {
            @Override
            public boolean onPreDraw()
            {
                if (_floatingView.getViewTreeObserver().isAlive())
                    _floatingView.getViewTreeObserver().removeOnPreDrawListener(this);

                updateLayoutParams(_floatingView);
                return false;
            }
        });

        this._floatingView.setOnTouchListener(this);
    }

    private void updateLayoutParams(View view)
    {
        this._rightMargin = -view.getMeasuredWidth();
        this._bottomMargin = -view.getMeasuredHeight();

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(view.getMeasuredWidth(), view.getMeasuredHeight());
        layoutParams.bottomMargin = this._bottomMargin;
        layoutParams.rightMargin = this._rightMargin;

        view.setLayoutParams(layoutParams);
    }

    @Override
    public boolean onTouch(View view, MotionEvent event)
    {
        if (view == this._floatingView)
        {
            final int X = (int) event.getRawX();
            final int Y = (int) event.getRawY();

            switch (event.getAction() & MotionEvent.ACTION_MASK)
            {
                case MotionEvent.ACTION_DOWN:
                    RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
                    this._xDelta = X - lParams.leftMargin;
                    this._yDelta = Y - lParams.topMargin;
                    break;

                case MotionEvent.ACTION_MOVE:
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
                    layoutParams.leftMargin = X - this._xDelta;
                    layoutParams.topMargin = Y - this._yDelta;
                    layoutParams.rightMargin = this._rightMargin;
                    layoutParams.bottomMargin = this._bottomMargin;
                    view.setLayoutParams(layoutParams);
                    break;
            }

            return true;
        }
        else
        {
            return false;
        }
    }
}
</code>```

Body:
Changed a bit a solution provided by @Vyacheslav Shylkin to remove dependencies of manually entered numbers.

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class MainActivity extends Activity implements View.OnTouchListener
{
    private int       _xDelta;
    private int       _yDelta;
    private int       _rightMargin;
    private int       _bottomMargin;
    private ImageView _floatingView;

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

        this._floatingView = (ImageView) findViewById(R.id.textView);

        this._floatingView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener()
        {
            @Override
            public boolean onPreDraw()
            {
                if (_floatingView.getViewTreeObserver().isAlive())
                    _floatingView.getViewTreeObserver().removeOnPreDrawListener(this);

                updateLayoutParams(_floatingView);
                return false;
            }
        });

        this._floatingView.setOnTouchListener(this);
    }

    private void updateLayoutParams(View view)
    {
        this._rightMargin = -view.getMeasuredWidth();
        this._bottomMargin = -view.getMeasuredHeight();

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(view.getMeasuredWidth(), view.getMeasuredHeight());
        layoutParams.bottomMargin = this._bottomMargin;
        layoutParams.rightMargin = this._rightMargin;

        view.setLayoutParams(layoutParams);
    }

    @Override
    public boolean onTouch(View view, MotionEvent event)
    {
        if (view == this._floatingView)
        {
            final int X = (int) event.getRawX();
            final int Y = (int) event.getRawY();

            switch (event.getAction() & MotionEvent.ACTION_MASK)
            {
                case MotionEvent.ACTION_DOWN:
                    RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
                    this._xDelta = X - lParams.leftMargin;
                    this._yDelta = Y - lParams.topMargin;
                    break;

                case MotionEvent.ACTION_MOVE:
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
                    layoutParams.leftMargin = X - this._xDelta;
                    layoutParams.topMargin = Y - this._yDelta;
                    layoutParams.rightMargin = this._rightMargin;
                    layoutParams.bottomMargin = this._bottomMargin;
                    view.setLayoutParams(layoutParams);
                    break;
            }

            return true;
        }
        else
        {
            return false;
        }
    }
}

ContentLicense: CC BY-SA 4.0


问:
Drawing animated arc with pure CSS
I know it is possible to draw and animate arcs in SVG and canvas. However, is it possible in CSS?

I have created an arc using the following method:

```<code>.arc{
    width:150px;
    height:400px;
    border-radius:50%;
    border-right:1px solid black;
    border-left:1px solid black;
    border-top:1px solid black;
    border-bottom:1px solid white;
}
</code>```

But, how can I animate this? The only way I can think of is having a pure white div over it and sliding that div to the right gradually revealing the arc. Is there a better way?

答:
Here is working demo with minimum of hard-coded variables. This works based on animated circle halves:

.circle {
  display: inline-flex;
  overflow: hidden;
}

.circle__half {
  height: 200px;
  width: 100px;
  position: relative;
  overflow: hidden;
}

.circle__half:before {
  height: inherit;
  width: inherit;
  position: absolute;
  content: "";
  border-radius: 100px 0 0 100px;
  background-color: lime;
  transform-origin: 100% 50%;
  /* hidden by default */
  transform: rotate(180deg);
  opacity: 0.65;
  animation-name: rotate-circle-half;
  animation-duration: 4s;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
}

.circle__half--right {
  transform: scale(-1, -1);
}

.circle .circle__half--right:before {
  animation-name: rotate-circle-half--right;
}

/* show half of circle half of the time */
@keyframes rotate-circle-half {
  0% {
    transform: rotate(180deg);
  }
  50% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(0deg);
  }
}

@keyframes rotate-circle-half--right {
  0% {
    transform: rotate(180deg);
  }
  50% {
    transform: rotate(180deg);
  }
  100% {
    transform: rotate(0deg);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="circle">
  <div class="circle__half"></div>
  <div class="circle__half circle__half--right"></div>
</div></code>```

Also the same look as iConnor's answer but doesn't have drawback of hardcoded background-color:

*,
*:before,
*:after {
  box-sizing: border-box;
}

.circle {
  display: inline-flex;
  overflow: hidden;
}

.circle__half {
  height: 200px;
  width: 100px;
  position: relative;
  overflow: hidden;
}

.circle__half:before {
  height: inherit;
  width: inherit;
  position: absolute;
  content: "";
  border-radius: 100px 0 0 100px;
  border: 10px solid #00507c;
  border-right-color: transparent;
  background-color: #0087cf;
  transform-origin: 100% 50%;
  /* hidden by default */
  transform: rotate(180deg);
  opacity: 0.65;
  animation-name: rotate-circle-half;
  animation-duration: 4s;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
}

.circle__half--right {
  transform: scale(-1, -1);
}

.circle .circle__half--right:before {
  animation-name: rotate-circle-half--right;
}

/* show half of circle half of the time */
@keyframes rotate-circle-half {
  0% {
    transform: rotate(180deg);
  }
  50% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(0deg);
  }
}

@keyframes rotate-circle-half--right {
  0% {
    transform: rotate(180deg);
  }
  50% {
    transform: rotate(180deg);
  }
  100% {
    transform: rotate(0deg);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="circle">
  <div class="circle__half"></div>
  <div class="circle__half circle__half--right"></div>
</div></code>```

Title: Drawing animated arc with pure CSS

Body:
I know it is possible to draw and animate arcs in SVG and canvas. However, is it possible in CSS?

I have created an arc using the following method:

.arc{
    width:150px;
    height:400px;
    border-radius:50%;
    border-right:1px solid black;
    border-left:1px solid black;
    border-top:1px solid black;
    border-bottom:1px solid white;
}

But, how can I animate this? The only way I can think of is having a pure white div over it and sliding that div to the right gradually revealing the arc. Is there a better way?

Body:
Here is working demo with minimum of hard-coded variables. This works based on animated circle halves:

.circle {
  display: inline-flex;
  overflow: hidden;
}

.circle__half {
  height: 200px;
  width: 100px;
  position: relative;
  overflow: hidden;
}

.circle__half:before {
  height: inherit;
  width: inherit;
  position: absolute;
  content: "";
  border-radius: 100px 0 0 100px;
  background-color: lime;
  transform-origin: 100% 50%;
  /* hidden by default */
  transform: rotate(180deg);
  opacity: 0.65;
  animation-name: rotate-circle-half;
  animation-duration: 4s;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
}

.circle__half--right {
  transform: scale(-1, -1);
}

.circle .circle__half--right:before {
  animation-name: rotate-circle-half--right;
}

/* show half of circle half of the time */
@keyframes rotate-circle-half {
  0% {
    transform: rotate(180deg);
  }
  50% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(0deg);
  }
}

@keyframes rotate-circle-half--right {
  0% {
    transform: rotate(180deg);
  }
  50% {
    transform: rotate(180deg);
  }
  100% {
    transform: rotate(0deg);
  }
}

<div class="circle">
  <div class="circle__half"></div>
  <div class="circle__half circle__half--right"></div>
</div>

Also the same look as iConnor's answer but doesn't have drawback of hardcoded background-color:

*,
*:before,
*:after {
  box-sizing: border-box;
}

.circle {
  display: inline-flex;
  overflow: hidden;
}

.circle__half {
  height: 200px;
  width: 100px;
  position: relative;
  overflow: hidden;
}

.circle__half:before {
  height: inherit;
  width: inherit;
  position: absolute;
  content: "";
  border-radius: 100px 0 0 100px;
  border: 10px solid #00507c;
  border-right-color: transparent;
  background-color: #0087cf;
  transform-origin: 100% 50%;
  /* hidden by default */
  transform: rotate(180deg);
  opacity: 0.65;
  animation-name: rotate-circle-half;
  animation-duration: 4s;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
}

.circle__half--right {
  transform: scale(-1, -1);
}

.circle .circle__half--right:before {
  animation-name: rotate-circle-half--right;
}

/* show half of circle half of the time */
@keyframes rotate-circle-half {
  0% {
    transform: rotate(180deg);
  }
  50% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(0deg);
  }
}

@keyframes rotate-circle-half--right {
  0% {
    transform: rotate(180deg);
  }
  50% {
    transform: rotate(180deg);
  }
  100% {
    transform: rotate(0deg);
  }
}

<div class="circle">
  <div class="circle__half"></div>
  <div class="circle__half circle__half--right"></div>
</div>


问:
Invert Subplot Across X Axis in R Barchart
I'm trying to plot two halves of a dataset in a bar chart in R. What I want is for the datasets to be on opposite sides of the x-axis rather than layered on top of each other on the same side of the axis. My chart currently looks like this:

When I want it to look like this:

Here is my code right now:

```<code>p <- ggplot(df_customer, aes(factor(income), percent_travel, fill = gender)) +
    geom_bar(stat="identity", data = subset(df_customer, gender == "F")) +
    geom_bar(stat="identity", data = subset(df_customer, gender == "M"), stackdir = "down") +
    scale_x_discrete(name = "Annual Income ($1000's)", breaks=seq(-10, 100, 10)) +
    scale_y_discrete(name = "Income Spent on Travel (%)", breaks=seq(0, 8, 2))
p
</code>```

I tried to use stackdir but I think that's an attribute that only works for scatter plots. I might be able to get the result I want by making all the values in one of the datasets negative but it doesn't seem like an ideal solution.

Also, any idea why my y-axis scale isn't showing up?

Thanks!

答:
Here is one way to do it.  Note that y is a continuous scale, not discrete.

```<code>p <- ggplot(df_customer, aes(x = as.factor(income),
                             y = percent_travel * ((-1)^(gender == "F")),
                             fill = gender)) +
  geom_bar(stat = "identity") +
  scale_x_discrete(name = "Annual Income ($1000's)") +
  scale_y_continuous(name = "Income Spent on Travel (%)", breaks=seq(-8, 8, 2))
p
</code>```

Body:
I'm trying to plot two halves of a dataset in a bar chart in R. What I want is for the datasets to be on opposite sides of the x-axis rather than layered on top of each other on the same side of the axis. My chart currently looks like this:

When I want it to look like this:

Here is my code right now:

p <- ggplot(df_customer, aes(factor(income), percent_travel, fill = gender)) +
    geom_bar(stat="identity", data = subset(df_customer, gender == "F")) +
    geom_bar(stat="identity", data = subset(df_customer, gender == "M"), stackdir = "down") +
    scale_x_discrete(name = "Annual Income ($1000's)", breaks=seq(-10, 100, 10)) +
    scale_y_discrete(name = "Income Spent on Travel (%)", breaks=seq(0, 8, 2))
p

I tried to use stackdir but I think that's an attribute that only works for scatter plots. I might be able to get the result I want by making all the values in one of the datasets negative but it doesn't seem like an ideal solution.

Also, any idea why my y-axis scale isn't showing up?

Thanks!

Body:
Here is one way to do it.  Note that y is a continuous scale, not discrete.

p <- ggplot(df_customer, aes(x = as.factor(income),
                             y = percent_travel * ((-1)^(gender == "F")),
                             fill = gender)) +
  geom_bar(stat = "identity") +
  scale_x_discrete(name = "Annual Income ($1000's)") +
  scale_y_continuous(name = "Income Spent on Travel (%)", breaks=seq(-8, 8, 2))
p


问:
How to find the middle x in ANY plot in R using grconvertX?
I'm wondering given ANY plot drawn using BASE R (i.e., without any layout() or mfcol() or mfrow()) (see below for an example), how can one find the "X" coordinate of a point that would be always exactly in the middle of that plot (suppose "Y" for the point is arbitrary)?

I think grconvertX is designed to do this but I'm not sure how it exactly works (I appreciate a good explanation on grconvertX) as it has many settings (see below).

```<code>plot(1, t = "n", log = "x")

mean( grconvertX(0:1, "user") )
mean( grconvertX(0:1, "nic")  )
mean( grconvertX(0:1, "nfc")  )
mean( grconvertX(0:1, "ndc")  )
mean( grconvertX(0:1, "npc")  )
mean( grconvertX(0:1, "device") )
</code>```

答:
You could par("usr"). Read more at ?par. Because you are using log = x, you have to raise the par("usr")[1:2] to 10.

```<code>plot(1, type = "n", log = "x")
points(x = 10^mean(par("usr")[1:2]), y = mean(par("usr")[3:4]), pch = 19)
</code>```

Body:
I'm wondering given ANY plot drawn using BASE R (i.e., without any layout() or mfcol() or mfrow()) (see below for an example), how can one find the "X" coordinate of a point that would be always exactly in the middle of that plot (suppose "Y" for the point is arbitrary)?

I think grconvertX is designed to do this but I'm not sure how it exactly works (I appreciate a good explanation on grconvertX) as it has many settings (see below).

plot(1, t = "n", log = "x")

mean( grconvertX(0:1, "user") )
mean( grconvertX(0:1, "nic")  )
mean( grconvertX(0:1, "nfc")  )
mean( grconvertX(0:1, "ndc")  )
mean( grconvertX(0:1, "npc")  )
mean( grconvertX(0:1, "device") )

Body:
You could par("usr"). Read more at ?par. Because you are using log = x, you have to raise the par("usr")[1:2] to 10.

plot(1, type = "n", log = "x")
points(x = 10^mean(par("usr")[1:2]), y = mean(par("usr")[3:4]), pch = 19)


问:
QQuickWidget with transparent background
I added in a QDialog aQQuickWidget to load a .qml but its background color is white. My qml declares a Rectangle not filling all QQuickWidget surface. I need the not filled surface having the same background color of the dialog. What is the way to have a transparent background?

答: Use QQuickWidget::setClearColor(Qt::transparent) and set an alpha channel via the setFormat call.


问:
Python: How to quickly upload to Google BigQuery?
I track about 250,000 time-series files which I have uploaded to Google bigquery. Every day each time-series has about 200 new rows that should downloaded through some API and then uploaded to bigquery. I have set up a python script that first connects to Google BigQuery to get the last dates of each time-series, then the script uses multiprocessing to create 10 processes that each connect to some API and download the missing data. After the download, which takes about 2 seconds, I need to get the data into BigQuery. I currently use the pandas function named to_gbq to upload the data and I timed how long it takes to upload, here are the results:

```<code>  1,000 rows takes  45 seconds
 10,000 rows takes  52 seconds
100,000 rows takes 128 seconds
</code>```

so based on that I am thinking of appending to a big dataframe in memory and then using to_gbq when the dataframe reaches 100,000 rows.I have been advised to find a solution which does not depend on memory at all, and just uploads that data to bigquery as soon as it is downloaded. What is a good way to tackle this problem?

I am appending all of the downloaded data to the same table.

答:
I'd recommend using Apache Beam for this problem. It's already a distributed processing framework designed to handle this type of ETL task.

Going through this example will give you a good grasp on how to use it. You could schedule your pipeline execution using Dataflow Templates or Apache Airflow as well.

Body:
I track about 250,000 time-series files which I have uploaded to Google bigquery. Every day each time-series has about 200 new rows that should downloaded through some API and then uploaded to bigquery. I have set up a python script that first connects to Google BigQuery to get the last dates of each time-series, then the script uses multiprocessing to create 10 processes that each connect to some API and download the missing data. After the download, which takes about 2 seconds, I need to get the data into BigQuery. I currently use the pandas function named to_gbq to upload the data and I timed how long it takes to upload, here are the results:

  1,000 rows takes  45 seconds
 10,000 rows takes  52 seconds
100,000 rows takes 128 seconds

so based on that I am thinking of appending to a big dataframe in memory and then using to_gbq when the dataframe reaches 100,000 rows.I have been advised to find a solution which does not depend on memory at all, and just uploads that data to bigquery as soon as it is downloaded. What is a good way to tackle this problem?

I am appending all of the downloaded data to the same table.


问:
what will be the mime type for java application if I want to show both image and html content?
In my java web application i need to show the image that exits in the database as well as a
anchor tag for moving to another jsp page.

In my jsp page it is mentioned response.setContentType("image/jpg;");

So while running the jsp page is shows the image but do not show the html below or anywhere.

What i want that my jsp page should show the image as well as html content at a single jsp page. So please tell what mime type should i use so that to get desire result.

Thank you,

答:
Your problem is twofold. First, you send a HTML-page that contains the IMG-tag with the appropriate reference to the source image. Of course this can be surrounded by an A-tag. That page should be of text/html.

Secondly, you return the image. This is a separate call to the server. That call should be of image/jpg.


问:
Count and inner join
Look at this sql request:

```<code>select distinct erp.users.id
from erp.users
inner join prod.referral_order_delivered
on erp.users.id= prod.referral_order_delivered.user_id::uuid
inner join erp.orders
on erp.orders."userId"::uuid= erp.users.id
where
    "paidAt"::date >= '2016-06-07'
    and "paidAt"::date <= '2017-07-07'
</code>```

Let’s say I get a result like this one:

```<code>id
2
1
4
5
</code>```

Now I wanna count how many times the value of these ids appear as value of the column userId in the table erp.orders

For example, if I have erp.orders.userId which is:

```<code>userId
2
2
1
4
4
5
5
5
</code>```

I want the request that is gonna return this:

```<code>id  number_of_id
2   2
1   1
4   2
5   3
</code>```

Any ideas?

答:
You need to use the count() function and a group by clause. It'll look something like:

```<code>select
  erp.users.id
  , count(1)
from
  erp.users
  inner join prod.referral_order_delivered
    on erp.users.id = prod.referral_order_delivered.user_id::uuid
  inner join erp.orders
    on erp.orders."userId"::uuid = erp.users.id
where
    "paidAt"::date     >= '2016-06-07'
    and "paidAt"::date <= '2017-07-07'
group by
    erp.users.id
</code>```

Title: Count and inner join

Body:
Look at this sql request:

select distinct erp.users.id
from erp.users
inner join prod.referral_order_delivered
on erp.users.id= prod.referral_order_delivered.user_id::uuid
inner join erp.orders
on erp.orders."userId"::uuid= erp.users.id
where
    "paidAt"::date >= '2016-06-07'
    and "paidAt"::date <= '2017-07-07'

Let’s say I get a result like this one:

id
2
1
4
5

Now I wanna count how many times the value of these ids appear as value of the column userId in the table erp.orders

For example, if I have erp.orders.userId which is:

userId
2
2
1
4
4
5
5
5

I want the request that is gonna return this:

id  number_of_id
2   2
1   1
4   2
5   3

Any ideas?

Body:
You need to use the count() function and a group by clause. It'll look something like:

select
  erp.users.id
  , count(1)
from
  erp.users
  inner join prod.referral_order_delivered
    on erp.users.id = prod.referral_order_delivered.user_id::uuid
  inner join erp.orders
    on erp.orders."userId"::uuid = erp.users.id
where
    "paidAt"::date     >= '2016-06-07'
    and "paidAt"::date <= '2017-07-07'
group by
    erp.users.id


问:
python savefig shows error message : "TypeError: compile() expected string without null bytes"
So I am having an issue when I try to save figures in Python.
If I create a figure f, and try to save it using the line

f.savefig('Test.eps', format='eps')

It yields  yields the following error message :

```<code>TypeError: compile() expected string without null bytes.
</code>```

It doesn't depend on the figure I want to save or on the format I choose, the error remains.
An example of a code I use could be :

```<code>import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
A=np.array([1,2,3,4])
f=plt.figure(figsize=(13,11))
plt.plot(A)
f.savefig('Test.eps', format='eps')
</code>```

which will yield :

```<code>TypeError: compile() expected string without null bytes.
</code>```

Anyone knows where this might come from ?

Thanks

答:
I tried your code and I had an error but I solved it by installing python-tk. After that, I execute correctly.
Are you sure you installed the packages correctly?.</p>

Body:
So I am having an issue when I try to save figures in Python.
If I create a figure f, and try to save it using the line

f.savefig('Test.eps', format='eps')

It yields  yields the following error message :

TypeError: compile() expected string without null bytes.

It doesn't depend on the figure I want to save or on the format I choose, the error remains.
An example of a code I use could be :

import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
A=np.array([1,2,3,4])
f=plt.figure(figsize=(13,11))
plt.plot(A)
f.savefig('Test.eps', format='eps')

which will yield :

TypeError: compile() expected string without null bytes.

Anyone knows where this might come from ?

Thanks


答:
There are two ways to address your problem (and more still!). Firstly, you need to make sure you keep your integers as type int when adding them together, and then cast them to a string when you print them out.

You can do this like the below, using the str() casting method and + concatenation.

```<code>def die1():
    """Roll and print two dice using concat."""
    first = randint(1, 6) # keep these as integers
    second = randint(1, 6)
    total = first + second # so addition works
    # but now cast to str when printing
    print "You have rolled a " + str(first) + " and a " + str(second) + ", for a total score of " + str(total) + "."
</code>```

But a handier way is to use the str.format() method to put placeholders in your string, and then let python cast and format the integer values for you. If you have big numbers with 4 or more digits, an advantage of this would be that you can use a string formatting code like "my big number: {0:d,}".format(1000000) to make your string output like "my big number: 1,000,000", which is much more readable.

```<code>def die2():
    """Roll and print two dice using str.format()."""
    first = randint(1, 6)
    second = randint(1, 6)
    total = first + second
    # or use the str.format() method, which does this for you
    print "You have rolled a {0} and a {1}, for a total score of {3}.".format(first, second, total)
</code>```

Title: How to treat a var as both int and string.

Body:
def die():
    first = str(randint(1, 6))
    second = str(randint(1, 6))
    total = first + second
    print "You have rolled a " + first + " and a " + second + ", for a total score of " + total + "."

Standard die throwing game, but I'm struggling to print the values for individual die as well as the total. Treating as a string for individual, but then sum leads to concatenation rather than actual sum.

Thanks

Body:
There are two ways to address your problem (and more still!). Firstly, you need to make sure you keep your integers as type int when adding them together, and then cast them to a string when you print them out.

You can do this like the below, using the str() casting method and + concatenation.

def die1():
    """Roll and print two dice using concat."""
    first = randint(1, 6) # keep these as integers
    second = randint(1, 6)
    total = first + second # so addition works
    # but now cast to str when printing
    print "You have rolled a " + str(first) + " and a " + str(second) + ", for a total score of " + str(total) + "."

But a handier way is to use the str.format() method to put placeholders in your string, and then let python cast and format the integer values for you. If you have big numbers with 4 or more digits, an advantage of this would be that you can use a string formatting code like "my big number: {0:d,}".format(1000000) to make your string output like "my big number: 1,000,000", which is much more readable.

def die2():
    """Roll and print two dice using str.format()."""
    first = randint(1, 6)
    second = randint(1, 6)
    total = first + second
    # or use the str.format() method, which does this for you
    print "You have rolled a {0} and a {1}, for a total score of {3}.".format(first, second, total)


问:
.trigger("change") not working in .on("change")
I used .on("change") event function because there's a part in my whole code that changes dynamically. .trigger("change") works fine in .change() but not on .on("change"). Here is my code:

```<code>    $('#popupContent').on('change', '#gradeYearLevel', function() {
        var $course = $('#course');
        var $section = $('#section');

        if ($(this).val() > 4) {
            $type = 0;
        }
        else {
            $type = 1;
        }
        if ($('#gradeYearLevel').val() == '') {
            $course.empty().append($("<option>", {"value": ""}).html("-- Select --"));
            $section.empty().append($("<option>", {"value": ""}).html("-- Select --"));
        }
        else {
            $.getJSON(BASE_PATH + "getJSONCoursesByType/" + $type, function(data) {
                $course.empty().append($("<option>", {"value": ""}).html("-- Select --"));
                $.each(data, function(k,v){
                    $course.append(
                        $("<option>", {"value": v.id}).html(v.title)
                    );
                });
            });
            $.getJSON(BASE_PATH + "getJSONSectionsByType/" + $type, function(data) {
                $section.empty().append($("<option>", {"value": ""}).html("-- Select --"));
                $.each(data, function(k,v){
                    $section.append(
                        $("<option>", {"value": v.id}).html(v.name)
                    );
                });
            });
        }
    }).trigger("change");
</code>```

答:
The issue is because you're triggering the change event on the #popupContent element as returned from on(), not the #gradeYearLevel which the delegated event handler is listening for.

You need to call trigger() on the child element so that the event can bubble. Try this:

```<code>$('#popupContent').on('change', '#gradeYearLevel', function() {
    // your code here...
})

$('#gradeYearLevel').trigger("change");
</code>```

Body:
I used .on("change") event function because there's a part in my whole code that changes dynamically. .trigger("change") works fine in .change() but not on .on("change"). Here is my code:

    $('#popupContent').on('change', '#gradeYearLevel', function() {
        var $course = $('#course');
        var $section = $('#section');

        if ($(this).val() > 4) {
            $type = 0;
        }
        else {
            $type = 1;
        }
        if ($('#gradeYearLevel').val() == '') {
            $course.empty().append($("<option>", {"value": ""}).html("-- Select --"));
            $section.empty().append($("<option>", {"value": ""}).html("-- Select --"));
        }
        else {
            $.getJSON(BASE_PATH + "getJSONCoursesByType/" + $type, function(data) {
                $course.empty().append($("<option>", {"value": ""}).html("-- Select --"));
                $.each(data, function(k,v){
                    $course.append(
                        $("<option>", {"value": v.id}).html(v.title)
                    );
                });
            });
            $.getJSON(BASE_PATH + "getJSONSectionsByType/" + $type, function(data) {
                $section.empty().append($("<option>", {"value": ""}).html("-- Select --"));
                $.each(data, function(k,v){
                    $section.append(
                        $("<option>", {"value": v.id}).html(v.name)
                    );
                });
            });
        }
    }).trigger("change");

Body:
The issue is because you're triggering the change event on the #popupContent element as returned from on(), not the #gradeYearLevel which the delegated event handler is listening for.

You need to call trigger() on the child element so that the event can bubble. Try this:

$('#popupContent').on('change', '#gradeYearLevel', function() {
    // your code here...
})

$('#gradeYearLevel').trigger("change");


问:
Creating multiple Google Charts recursively in Javascript
I'm trying to create multiple Google Charts recursively with the code below. I'm using AJAX to get the chart data and to store in the array histogramData.

With this code I can create the multiple i_histogram charts, but apparently, on each loop interaction, the previous chart is overwritten by the last one.

HTML code:

```<code><div id="histogramCharts"></div>
</code>```

Javascript code:

```<code>var histogramChartElement = document.getElementById('histogramCharts');
// remove histogram chart element children
while (histogramChartElement.hasChildNodes()) {
    histogramChartElement.removeChild(histogramChartElement.childNodes[0]);
}

for (var i = 0; i < histogramLabels.length; i++) {
    var label = histogramLabels[i];
    var node = document.createElement('div');

    node.setAttribute('id', i + '_histogram');

    histogramChartElement.appendChild(node);

    var dataTable = new google.visualization.DataTable();
    dataTable.addColumn('string', 'A');
    dataTable.addColumn('number', 'B');
    dataTable.addRows(histogramData[i]);

    google.charts.setOnLoadCallback(function () {
        var options = {
            title: histogramLabels[i],
            legend: {position: 'none'},
            histogram: {bucketSize: 0.1}
        };
        var histogramChart = new google.visualization.Histogram(node);
        histogramChart.draw(dataTable, options);
    });
}
</code>```

I got this result:

```<code><div id="histogramCharts">
    <div id="0_histogram"></div>
    <div id="1_histogram"></div>
    <div id="2_histogram">
        <div style="position: relative;">....</div>
    </div>
</div>
</code>```

答:
first, setOnLoadCallback should only be called once per page load,

once it fires, you can draw as many charts as needed...

you can also depend on the callback to know when the page is ready,

instead of --> $(document).ready -- or something similar...

as such, recommend loading google first, before anything else,

then use ajax to get the data, then draw the charts...

try similar setup as follows, placing the callback in the load statement...

```<code>google.charts.load('current', {
  callback: getData,
  packages:['corechart']
});

function getData() {
  $.ajax({
    url: '...',
  }).done(drawCharts);
}

function drawCharts(data) {

  // use data to build histogramData

  var histogramChartElement = document.getElementById('histogramCharts');
  // remove histogram chart element children
  while (histogramChartElement.hasChildNodes()) {
      histogramChartElement.removeChild(histogramChartElement.childNodes[0]);
  }

  for (var i = 0; i < histogramLabels.length; i++) {
      var label = histogramLabels[i];
      var node = document.createElement('div');

      node.setAttribute('id', i + '_histogram');

      histogramChartElement.appendChild(node);

      var dataTable = new google.visualization.DataTable();
      dataTable.addColumn('string', 'A');
      dataTable.addColumn('number', 'B');
      dataTable.addRows(histogramData[i]);

      var options = {
          title: histogramLabels[i],
          legend: {position: 'none'},
          histogram: {bucketSize: 0.1}
      };
      var histogramChart = new google.visualization.Histogram(node);
      histogramChart.draw(dataTable, options);
  }
}
</code>```

Body:
I'm trying to create multiple Google Charts recursively with the code below. I'm using AJAX to get the chart data and to store in the array histogramData.

With this code I can create the multiple i_histogram charts, but apparently, on each loop interaction, the previous chart is overwritten by the last one.

HTML code:

Javascript code:

var histogramChartElement = document.getElementById('histogramCharts');
// remove histogram chart element children
while (histogramChartElement.hasChildNodes()) {
    histogramChartElement.removeChild(histogramChartElement.childNodes[0]);
}

for (var i = 0; i < histogramLabels.length; i++) {
    var label = histogramLabels[i];
    var node = document.createElement('div');

    node.setAttribute('id', i + '_histogram');

    histogramChartElement.appendChild(node);

    var dataTable = new google.visualization.DataTable();
    dataTable.addColumn('string', 'A');
    dataTable.addColumn('number', 'B');
    dataTable.addRows(histogramData[i]);

    google.charts.setOnLoadCallback(function () {
        var options = {
            title: histogramLabels[i],
            legend: {position: 'none'},
            histogram: {bucketSize: 0.1}
        };
        var histogramChart = new google.visualization.Histogram(node);
        histogramChart.draw(dataTable, options);
    });
}

I got this result:

....

Body:
first, setOnLoadCallback should only be called once per page load,

once it fires, you can draw as many charts as needed...

you can also depend on the callback to know when the page is ready,

instead of --> $(document).ready -- or something similar...

as such, recommend loading google first, before anything else,

then use ajax to get the data, then draw the charts...

try similar setup as follows, placing the callback in the load statement...

google.charts.load('current', {
  callback: getData,
  packages:['corechart']
});

function getData() {
  $.ajax({
    url: '...',
  }).done(drawCharts);
}

function drawCharts(data) {

  // use data to build histogramData

  var histogramChartElement = document.getElementById('histogramCharts');
  // remove histogram chart element children
  while (histogramChartElement.hasChildNodes()) {
      histogramChartElement.removeChild(histogramChartElement.childNodes[0]);
  }

  for (var i = 0; i < histogramLabels.length; i++) {
      var label = histogramLabels[i];
      var node = document.createElement('div');

      node.setAttribute('id', i + '_histogram');

      histogramChartElement.appendChild(node);

      var dataTable = new google.visualization.DataTable();
      dataTable.addColumn('string', 'A');
      dataTable.addColumn('number', 'B');
      dataTable.addRows(histogramData[i]);

      var options = {
          title: histogramLabels[i],
          legend: {position: 'none'},
          histogram: {bucketSize: 0.1}
      };
      var histogramChart = new google.visualization.Histogram(node);
      histogramChart.draw(dataTable, options);
  }
}


问:
Angular - how to do a dynamic alert with different type of errors?
In my web app I am showing alerts for loading content and another alert when there is an error.

I am using AngularJS/AngularStrap

right now this is what I have:

```<code>var noLinesAlert = $alert({
  title: 'Sorry, no lines at this moment :(',
  container: '.no-lines-alert',
  type: 'danger',
  dismissable: false,
  show: false
}),

loaderAlert = $alert({
  content: 'Loading content. Please wait...',
  container: '.alerts-container',
  type: 'info',
  show: true
  });
</code>```

and I am calling these alerts this way, example noLinesAlert.show() or loaderAlert.hide() and so on... but just imagine that I will have 4 more alerts for special cases, do I have to create those vars with the object inside every time or is there a way to do it more programmatically? and how.

答:
Make it dynamic by putting the $alert into a function. Allow the function to pass parameters to the $alert. Set the show property to true.

Call the function when needed. For example:

```<code>var displayAlert = function(alertTitle, className) {

    var alertOptions = {
       title: alertTitle,
       container: className,
       type: 'danger',
       dismissable: false,
       show: true
    };

    var alert = $alert(alertOptions);

}

// Call the function when needed
$scope.displayAlert('Sorry, no lines at this moment :(','.no-lines-alert')
</code>```

Body:
In my web app I am showing alerts for loading content and another alert when there is an error.

I am using AngularJS/AngularStrap

right now this is what I have:

var noLinesAlert = $alert({
  title: 'Sorry, no lines at this moment :(',
  container: '.no-lines-alert',
  type: 'danger',
  dismissable: false,
  show: false
}),

loaderAlert = $alert({
  content: 'Loading content. Please wait...',
  container: '.alerts-container',
  type: 'info',
  show: true
  });

and I am calling these alerts this way, example noLinesAlert.show() or loaderAlert.hide() and so on... but just imagine that I will have 4 more alerts for special cases, do I have to create those vars with the object inside every time or is there a way to do it more programmatically? and how.

Body:
Make it dynamic by putting the $alert into a function. Allow the function to pass parameters to the $alert. Set the show property to true.

Call the function when needed. For example:

var displayAlert = function(alertTitle, className) {

    var alertOptions = {
       title: alertTitle,
       container: className,
       type: 'danger',
       dismissable: false,
       show: true
    };

    var alert = $alert(alertOptions);

}

// Call the function when needed
$scope.displayAlert('Sorry, no lines at this moment :(','.no-lines-alert')


问:
Android move view on touch event
I would like to move two different views into my layout, so that an user can display it like his wishes.

So far I've made the following code to handle the touch event:

```<code>this.viewEvent.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent event)
    {
        final int y = (int) event.getRawY();

        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view.getLayoutParams();
        switch (event.getAction() & MotionEvent.ACTION_MASK)
        {
            case MotionEvent.ACTION_DOWN:
                element.setEventY(y - params.topMargin);
                break;

            case MotionEvent.ACTION_UP:
                viewGroup.invalidate();
                break;

            case MotionEvent.ACTION_POINTER_DOWN:
            case MotionEvent.ACTION_POINTER_UP:
                break;

            case MotionEvent.ACTION_MOVE:
                params.topMargin = y - element.getEventY();
                params.bottomMargin = screenHeight - view.getHeight() - params.topMargin;

                // Avoid out of screen
                if (params.topMargin < 0) return true;

                // Apply changes
                view.setLayoutParams(params);
                break;
        }

        return true;
    }
});
</code>```

element is an instance of a custom object to handle the position.
screenHeight is the screen height given by the Display class.

I'm able to move the element but it's blinking when I touch it and once I put my finger up, the view just disapear. I can't even retrieve it, it's just out of the screen.

Did I make something wrong ?

Thanks for your help

答:
I will provide an alternative solution for those who use Relative layout for example.</p>

```<code>import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class MainActivity extends Activity implements View.OnTouchListener
{
    private int       _xDelta;
    private int       _yDelta;
    private int       _rightMargin;
    private int       _bottomMargin;
    private ImageView _floatingView;

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

        this._floatingView = (ImageView) findViewById(R.id.textView);

        this._floatingView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener()
        {
            @Override
            public boolean onPreDraw()
            {
                if (_floatingView.getViewTreeObserver().isAlive())
                    _floatingView.getViewTreeObserver().removeOnPreDrawListener(this);

                updateLayoutParams(_floatingView);
                return false;
            }
        });

        this._floatingView.setOnTouchListener(this);
    }

    private void updateLayoutParams(View view)
    {
        this._rightMargin = -view.getMeasuredWidth();
        this._bottomMargin = -view.getMeasuredHeight();

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(view.getMeasuredWidth(), view.getMeasuredHeight());
        layoutParams.bottomMargin = this._bottomMargin;
        layoutParams.rightMargin = this._rightMargin;

        view.setLayoutParams(layoutParams);
    }

    @Override
    public boolean onTouch(View view, MotionEvent event)
    {
        if (view == this._floatingView)
        {
            final int X = (int) event.getRawX();
            final int Y = (int) event.getRawY();

            switch (event.getAction() & MotionEvent.ACTION_MASK)
            {
                case MotionEvent.ACTION_DOWN:
                    RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
                    this._xDelta = X - lParams.leftMargin;
                    this._yDelta = Y - lParams.topMargin;
                    break;

                case MotionEvent.ACTION_MOVE:
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
                    layoutParams.leftMargin = X - this._xDelta;
                    layoutParams.topMargin = Y - this._yDelta;
                    layoutParams.rightMargin = this._rightMargin;
                    layoutParams.bottomMargin = this._bottomMargin;
                    view.setLayoutParams(layoutParams);
                    break;
            }

            return true;
        }
        else
        {
            return false;
        }
    }
}
</code>```

Title: Android move view on touch event

Body:
I would like to move two different views into my layout, so that an user can display it like his wishes.

So far I've made the following code to handle the touch event:

this.viewEvent.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent event)
    {
        final int y = (int) event.getRawY();

        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view.getLayoutParams();
        switch (event.getAction() & MotionEvent.ACTION_MASK)
        {
            case MotionEvent.ACTION_DOWN:
                element.setEventY(y - params.topMargin);
                break;

            case MotionEvent.ACTION_UP:
                viewGroup.invalidate();
                break;

            case MotionEvent.ACTION_POINTER_DOWN:
            case MotionEvent.ACTION_POINTER_UP:
                break;

            case MotionEvent.ACTION_MOVE:
                params.topMargin = y - element.getEventY();
                params.bottomMargin = screenHeight - view.getHeight() - params.topMargin;

                // Avoid out of screen
                if (params.topMargin < 0) return true;

                // Apply changes
                view.setLayoutParams(params);
                break;
        }

        return true;
    }
});

element is an instance of a custom object to handle the position.
screenHeight is the screen height given by the Display class.

I'm able to move the element but it's blinking when I touch it and once I put my finger up, the view just disapear. I can't even retrieve it, it's just out of the screen.

Did I make something wrong ?

Thanks for your help

Body:
I will provide an alternative solution for those who use Relative layout for example.

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class MainActivity extends Activity implements View.OnTouchListener
{
    private int       _xDelta;
    private int       _yDelta;
    private int       _rightMargin;
    private int       _bottomMargin;
    private ImageView _floatingView;

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

        this._floatingView = (ImageView) findViewById(R.id.textView);

        this._floatingView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener()
        {
            @Override
            public boolean onPreDraw()
            {
                if (_floatingView.getViewTreeObserver().isAlive())
                    _floatingView.getViewTreeObserver().removeOnPreDrawListener(this);

                updateLayoutParams(_floatingView);
                return false;
            }
        });

        this._floatingView.setOnTouchListener(this);
    }

    private void updateLayoutParams(View view)
    {
        this._rightMargin = -view.getMeasuredWidth();
        this._bottomMargin = -view.getMeasuredHeight();

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(view.getMeasuredWidth(), view.getMeasuredHeight());
        layoutParams.bottomMargin = this._bottomMargin;
        layoutParams.rightMargin = this._rightMargin;

        view.setLayoutParams(layoutParams);
    }

    @Override
    public boolean onTouch(View view, MotionEvent event)
    {
        if (view == this._floatingView)
        {
            final int X = (int) event.getRawX();
            final int Y = (int) event.getRawY();

            switch (event.getAction() & MotionEvent.ACTION_MASK)
            {
                case MotionEvent.ACTION_DOWN:
                    RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
                    this._xDelta = X - lParams.leftMargin;
                    this._yDelta = Y - lParams.topMargin;
                    break;

                case MotionEvent.ACTION_MOVE:
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
                    layoutParams.leftMargin = X - this._xDelta;
                    layoutParams.topMargin = Y - this._yDelta;
                    layoutParams.rightMargin = this._rightMargin;
                    layoutParams.bottomMargin = this._bottomMargin;
                    view.setLayoutParams(layoutParams);
                    break;
            }

            return true;
        }
        else
        {
            return false;
        }
    }
}


问:
Determine whether one string can be made from a subset of characters in another string
I have a dictionary where letters correspond to numbers and a string, and seek to return True if each letter occurs in the string a number of times equal to or less than the number associated with that letter in the dictionary. When this problem was less complex and didn't have the limitation of counting occurrences, I used all(x in string for x in dictionary). Is there a similarly concise way to test for this based on the int value in the dictionary?

Edit: Apologies, here's what we're looking at.

```<code>def isValidWord(word, hand, wordList):
    """
    Returns True if word is in the wordList and is entirely
    composed of letters in the hand. Otherwise, returns False.

    Does not mutate hand or wordList.

    word: string
    hand: dictionary (string -> int)
    wordList: list of lowercase strings
    """
    if word.lower() in wordList and all(x in hand for x in word):
        return True
    else:
        return False
</code>```

This code returns True if any instance of the letter in the string appears as a dictionary key of Hand, when I now need it to return False unless the number of times that letter occurs is <= the int-value for that key. I've accomplished this rather messily, and was wondering if there was a way to incorporate that level of specificity into the all method or something similarly concise.

答:
From your docstring, you are trying to determine is whether word could be formed using the letters in hand. This is extremely straight forward by using collections.Counter. You don't even need to make hand a dictionary.

```<code>def is_valid_word(word, hand, word_list):
    wc, hc = Counter(word), Counter(hand)
    return word.lower() in word_list and all(wc[k] <= hc[k] for k in wc)
</code>```

If you want to keep hand as a dictionary, just use hand instead of hc in the final line and omit turning it into a Counter.

This isn't optimal in terms of complexity, but the same general idea could be used to write a good algorithm. Note that this is more efficient than using count because each string only needs to be iterated over once instead of once for each unique letter.

A more efficient function to check this might look something like:

```<code>def is_partial_anagram(word, pool):
    pool_counter = Counter(pool)
    for c in word:
        if not pool_counter[c]:
            return False
        pool_counter[c] -= 1
    return True
</code>```

The complexity here is asymptotically the same, but will return False sooner when there is no match and avoids builder a Counter for word.

Body:
I have a dictionary where letters correspond to numbers and a string, and seek to return True if each letter occurs in the string a number of times equal to or less than the number associated with that letter in the dictionary. When this problem was less complex and didn't have the limitation of counting occurrences, I used all(x in string for x in dictionary). Is there a similarly concise way to test for this based on the int value in the dictionary?

Edit: Apologies, here's what we're looking at.

def isValidWord(word, hand, wordList):
    """
    Returns True if word is in the wordList and is entirely
    composed of letters in the hand. Otherwise, returns False.

    Does not mutate hand or wordList.

    word: string
    hand: dictionary (string -> int)
    wordList: list of lowercase strings
    """
    if word.lower() in wordList and all(x in hand for x in word):
        return True
    else:
        return False

This code returns True if any instance of the letter in the string appears as a dictionary key of Hand, when I now need it to return False unless the number of times that letter occurs is <= the int-value for that key. I've accomplished this rather messily, and was wondering if there was a way to incorporate that level of specificity into the all method or something similarly concise.

Body:
From your docstring, you are trying to determine is whether word could be formed using the letters in hand. This is extremely straight forward by using collections.Counter. You don't even need to make hand a dictionary.

def is_valid_word(word, hand, word_list):
    wc, hc = Counter(word), Counter(hand)
    return word.lower() in word_list and all(wc[k] <= hc[k] for k in wc)

If you want to keep hand as a dictionary, just use hand instead of hc in the final line and omit turning it into a Counter.

This isn't optimal in terms of complexity, but the same general idea could be used to write a good algorithm. Note that this is more efficient than using count because each string only needs to be iterated over once instead of once for each unique letter.

A more efficient function to check this might look something like:

def is_partial_anagram(word, pool):
    pool_counter = Counter(pool)
    for c in word:
        if not pool_counter[c]:
            return False
        pool_counter[c] -= 1
    return True

The complexity here is asymptotically the same, but will return False sooner when there is no match and avoids builder a Counter for word.


问:
How to update NavigateUrl in asp:menu dynamically
I have 2 aspx page in the project and a menu is used to navigate between pages. It was working fine until I did some needed change to the project, and now the pages will only work if the URL has the additional string query "?UserId=XXX". The UserId is available in both the URL and a label lblUserID on the page.

Below is my menu items

```<code><asp:MenuItem Text="Send Fax" NavigateUrl="SendFax.aspx"></asp:MenuItem>
<asp:MenuItem Text="Fax Status" NavigateUrl="FaxStatus.aspx"></asp:MenuItem>
</code>```

How can I achieve my goal? through javascript or codebehind?
Please give me some hint, any help would be greatly appreciated, thanks!

答:
After reading the following post Dynamically set Hyperlink......
I was able to update the NavigateUrl through codebehind running the simple function that loop through the menu items</p>

```<code>if (!IsPostBack)
{  updateMenuItems();

.........

private void updateMenuItems()
{
    string UserId = "?UserId=" + lblUserID.Text;

    foreach (MenuItem i in Menu1.Items)
    {
        i.NavigateUrl = i.NavigateUrl + UserId;
    }
}
</code>```

Body:
I have 2 aspx page in the project and a menu is used to navigate between pages. It was working fine until I did some needed change to the project, and now the pages will only work if the URL has the additional string query "?UserId=XXX". The UserId is available in both the URL and a label lblUserID on the page.

Below is my menu items

<asp:MenuItem Text="Send Fax" NavigateUrl="SendFax.aspx"></asp:MenuItem>
<asp:MenuItem Text="Fax Status" NavigateUrl="FaxStatus.aspx"></asp:MenuItem>

How can I achieve my goal? through javascript or codebehind?
Please give me some hint, any help would be greatly appreciated, thanks!

Body:
After reading the following post Dynamically set Hyperlink......
I was able to update the NavigateUrl through codebehind running the simple function that loop through the menu items

if (!IsPostBack)
{  updateMenuItems();

.........

private void updateMenuItems()
{
    string UserId = "?UserId=" + lblUserID.Text;

    foreach (MenuItem i in Menu1.Items)
    {
        i.NavigateUrl = i.NavigateUrl + UserId;
    }
}


问:
C -> Shell - Block on a Write Until Read
I want to send a character from a c program to a shell program. I am using a named pipe to send the letter 'a' whenever it is requsted. I should only have to open the pipe once. Here's an example:

```<code>#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
int main(){
    int fd;
    mkfifo("/tmp/test", 0666);
    fd = open("/tmp/test", O_WRONLY);
    printf("Opened\n");
    char * a = "a";
    while(1){
            printf("Writing to pipe...\n");
            write(fd,a,1);
            sleep(1);
    }
}
</code>```

And the shell executes this command as many times as it wants...

```<code>head -c 1 /tmp/test
</code>```

The issue is after one head, the c will endlessly stream into the pipe, even if nobody's there.

I noticed that open() blocks until someone is on the other end. How to I tell write() to block until somebody is reading?

I would rather have this feature on write() than read(), as I think there's lots of overhead on opening the file for each request.

Thanks!

UPDATE

This is how I'm handling it in Java, it waits until I have somebody listening  on this pipe before it continues on. Maybe just because it's a higher level language.

```<code>public static void writeToPipe(int val, String pipename){
    try{
        pipe_out = new PrintStream("/tmp/" + pipename);
    }catch(Exception e){
        System.out.println("Could not open a pipe for output!");
        e.printStackTrace();
    }
    try{
        pipe_out.println(val);
    }catch(Exception e){
        System.out.println("Could not write to pipe!");
        e.printStackTrace();
    }

    try{
        pipe_out.close();
    }catch(Exception e){
        System.out.println("Could not close the output pipe!");
        e.printStackTrace();
    }
}
</code>```

UPDATE #2 - THIS IS THE SOLUTION

Here is my code based on David's idea, it's rough, but it works. I'm not checking if the named pipe exists and just supressing it from quitting.

```<code>#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc, char **argv){
    mkfifo("/tmp/test", 0666);
    while(1){
      int fd, status;
            if ((fd = open ("/tmp/test", O_WRONLY)) == -1) {
         perror ("open failed");
         return 1;
            }
     printf("Opened Pipe\n");
     char a = 'a';
            int f  = fork();
            if(f == -1){
                    perror("fork");
                    exit(1);
            }else if(f == 0){
                    //This is by the child process
                    if (write (fd, &a, 1) == -1) {
                            close(fd);
                    perror ("open failed");
                            return 1;
         }

            }else{
                    //This is the parent process
                    int w = waitpid(f, &status, WUNTRACED | WCONTINUED);
                    if (w == -1){
                            perror("waitpid");
                            exit(EXIT_FAILURE);
                    }
            }
    }
}
</code>```

答:
Since you don't bother to check the return of write, you don't even notice that it is failing.  (That is, it's not endlessly streaming into the pipe; it's just lying to you and printing "Writing to pipe..." while failing to write to the pipe.)

The only way to block on the write is to fill the pipe.  But that's not your problem.  The problem is that the pipe has been terminated.  If you want to keep that pipe open, you'll need to have some process still alive reading from it.  For example, you could do sleep 500 < /tmp/test in some other shell.  Or just open the fifo for reading in the program doing the writing. (eg, add the line open("/tmp/fifo", O_RDONLY);)

The more curious issue is; why isn't your program terminating from the SIGPIPE?

Body:
I want to send a character from a c program to a shell program. I am using a named pipe to send the letter 'a' whenever it is requsted. I should only have to open the pipe once. Here's an example:

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
int main(){
    int fd;
    mkfifo("/tmp/test", 0666);
    fd = open("/tmp/test", O_WRONLY);
    printf("Opened\n");
    char * a = "a";
    while(1){
            printf("Writing to pipe...\n");
            write(fd,a,1);
            sleep(1);
    }
}

And the shell executes this command as many times as it wants...

head -c 1 /tmp/test

The issue is after one head, the c will endlessly stream into the pipe, even if nobody's there.

I noticed that open() blocks until someone is on the other end. How to I tell write() to block until somebody is reading?

I would rather have this feature on write() than read(), as I think there's lots of overhead on opening the file for each request.

Thanks!

UPDATE

This is how I'm handling it in Java, it waits until I have somebody listening  on this pipe before it continues on. Maybe just because it's a higher level language.

public static void writeToPipe(int val, String pipename){
    try{
        pipe_out = new PrintStream("/tmp/" + pipename);
    }catch(Exception e){
        System.out.println("Could not open a pipe for output!");
        e.printStackTrace();
    }
    try{
        pipe_out.println(val);
    }catch(Exception e){
        System.out.println("Could not write to pipe!");
        e.printStackTrace();
    }

    try{
        pipe_out.close();
    }catch(Exception e){
        System.out.println("Could not close the output pipe!");
        e.printStackTrace();
    }
}

UPDATE #2 - THIS IS THE SOLUTION

Here is my code based on David's idea, it's rough, but it works. I'm not checking if the named pipe exists and just supressing it from quitting.

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc, char **argv){
    mkfifo("/tmp/test", 0666);
    while(1){
      int fd, status;
            if ((fd = open ("/tmp/test", O_WRONLY)) == -1) {
         perror ("open failed");
         return 1;
            }
     printf("Opened Pipe\n");
     char a = 'a';
            int f  = fork();
            if(f == -1){
                    perror("fork");
                    exit(1);
            }else if(f == 0){
                    //This is by the child process
                    if (write (fd, &a, 1) == -1) {
                            close(fd);
                    perror ("open failed");
                            return 1;
         }

            }else{
                    //This is the parent process
                    int w = waitpid(f, &status, WUNTRACED | WCONTINUED);
                    if (w == -1){
                            perror("waitpid");
                            exit(EXIT_FAILURE);
                    }
            }
    }
}


问:
get the result of JButton in another class
I created an instance of a class in another class. In the class, I created a JFrame with radiobuttons and button. When the user clicked on button, I want the text of radiobutton selected return to the another class. But it doesn't work. in other words the a variable not returned. What should I do?

The code of my first class:

```<code>public class SelectLayoutCreator {
public JFrame  f = new  JFrame("Choos Rule");
public String a;
public SelectLayoutCreator(ArrayList<String> choose) {
// TODO Auto-generated constructor stub
ArrayList<JRadioButton> ruleRadioButtions = new ArrayList<JRadioButton>();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 300);
f.setLayout(null);
JTextField ruleText = new JTextField();
ruleText.setBounds(30, 67, 90, 10);
f.add(ruleText);
JLabel ruleLabel = new JLabel ("Which of the following rules should be execute?");
ruleLabel.setBounds(20, 20, 350, 20);
f.add(ruleLabel);
ButtonGroup group = new ButtonGroup();
 for (int i = 0; i < choose.size(); i++) {
  JRadioButton radio = new JRadioButton(choose.get(i));
  radio.setActionCommand(choose.get(i));
  ruleRadioButtions.add(radio);
  ruleRadioButtions.get(i).setBounds(20, 50+20*i, 200, 30);
  group.add(ruleRadioButtions.get(i));
  f.add(ruleRadioButtions.get(i));
  }
 JButton b = new JButton("Select");
 b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    **a** =  group.getSelection().getActionCommand();
       }
    });
f.add(b);
b.setBounds(270,220,100, 40);
e.setBounds(170,120,100, 40);
f.setVisible(true);
 }
</code>```

The cod of another class:

```<code>public class interfaceRule {
public String call(ArrayList<String> choose)
{
  SelectLayoutCreator s = new SelectLayoutCreator(choose);
  return s.a;
}
}
</code>```

答:
There is a problem in the way you designed and implemented the current solution. When a call to the call() method is made, this is what happens:

1) The JFrame with the RadioButtons is created and shown on the screen.

```<code>SelectLayoutCreator s = new SelectLayoutCreator(choose);
</code>```

2) Execution of the method continues, because the GUI runs on a separate thread. So, the return statement is executed and it returns a null value as the String was not initialized yet.

```<code>return s.a;
</code>```

Your code right now does not wait for the user to make a selection and click the "Select" button.

Here is a working example based on your solution (I refactored some of your code due to the bad coding style). You can put this in a Main.java file and run it:

```<code>import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

class SelectLayoutCreator {

    private JFrame f = new JFrame("Choose Rule");
    private String a;

    public SelectLayoutCreator(ArrayList<String> choose, Object lock) {
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(400, 300);
        f.setLayout(null);

        JTextField ruleText = new JTextField();
        ruleText.setBounds(30, 67, 90, 10);
        f.add(ruleText);

        JLabel ruleLabel = new JLabel("Which of the following rules should be executed?");
        ruleLabel.setBounds(20, 20, 350, 20);
        f.add(ruleLabel);

        ButtonGroup group = new ButtonGroup();
        ArrayList<JRadioButton> ruleRadioButtions = new ArrayList<JRadioButton>();
        for (int i = 0; i < choose.size(); i++) {
            JRadioButton radio = new JRadioButton(choose.get(i));
            radio.setActionCommand(choose.get(i));
            ruleRadioButtions.add(radio);
            ruleRadioButtions.get(i).setBounds(20, 50 + 20 * i, 200, 30);

            group.add(ruleRadioButtions.get(i));
            f.add(ruleRadioButtions.get(i));
        }

        JButton b = new JButton("Select");
        b.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                a = group.getSelection().getActionCommand();

                /* wake up the thread waiting inside InterfaceRule */
                synchronized (lock) {
                    lock.notify();
                }

                f.dispose();
            }
        });
        b.setBounds(270, 220, 100, 40);
        f.add(b);

        f.setVisible(true);
    }

    public String getA() {
        return a;
    }

}

class InterfaceRule {

    private static Object lock = new Object();

    public String call(ArrayList<String> choose) {
        SelectLayoutCreator s = new SelectLayoutCreator(choose, lock);

        /* wait for the String to be populated */
        synchronized (lock) {
            try {
                lock.wait();
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return s.getA();
    }

}

public class Main {

    public static void main(String[] args) {
        ArrayList<String> choose = new ArrayList<String>();
        choose.add("1");
        choose.add("2");
        choose.add("3");

        String chosen = new InterfaceRule().call(choose);
        System.out.println(chosen);
    }

}
</code>```

Body:
I created an instance of a class in another class. In the class, I created a JFrame with radiobuttons and button. When the user clicked on button, I want the text of radiobutton selected return to the another class. But it doesn't work. in other words the a variable not returned. What should I do?

The code of my first class:

public class SelectLayoutCreator {
public JFrame  f = new  JFrame("Choos Rule");
public String a;
public SelectLayoutCreator(ArrayList<String> choose) {
// TODO Auto-generated constructor stub
ArrayList<JRadioButton> ruleRadioButtions = new ArrayList<JRadioButton>();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 300);
f.setLayout(null);
JTextField ruleText = new JTextField();
ruleText.setBounds(30, 67, 90, 10);
f.add(ruleText);
JLabel ruleLabel = new JLabel ("Which of the following rules should be execute?");
ruleLabel.setBounds(20, 20, 350, 20);
f.add(ruleLabel);
ButtonGroup group = new ButtonGroup();
 for (int i = 0; i < choose.size(); i++) {
  JRadioButton radio = new JRadioButton(choose.get(i));
  radio.setActionCommand(choose.get(i));
  ruleRadioButtions.add(radio);
  ruleRadioButtions.get(i).setBounds(20, 50+20*i, 200, 30);
  group.add(ruleRadioButtions.get(i));
  f.add(ruleRadioButtions.get(i));
  }
 JButton b = new JButton("Select");
 b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    **a** =  group.getSelection().getActionCommand();
       }
    });
f.add(b);
b.setBounds(270,220,100, 40);
e.setBounds(170,120,100, 40);
f.setVisible(true);
 }

The cod of another class:

public class interfaceRule {
public String call(ArrayList<String> choose)
{
  SelectLayoutCreator s = new SelectLayoutCreator(choose);
  return s.a;
}
}

Body:
There is a problem in the way you designed and implemented the current solution. When a call to the call() method is made, this is what happens:

1) The JFrame with the RadioButtons is created and shown on the screen.

SelectLayoutCreator s = new SelectLayoutCreator(choose);

2) Execution of the method continues, because the GUI runs on a separate thread. So, the return statement is executed and it returns a null value as the String was not initialized yet.

return s.a;

Your code right now does not wait for the user to make a selection and click the "Select" button.

Here is a working example based on your solution (I refactored some of your code due to the bad coding style). You can put this in a Main.java file and run it:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

class SelectLayoutCreator {

    private JFrame f = new JFrame("Choose Rule");
    private String a;

    public SelectLayoutCreator(ArrayList<String> choose, Object lock) {
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(400, 300);
        f.setLayout(null);

        JTextField ruleText = new JTextField();
        ruleText.setBounds(30, 67, 90, 10);
        f.add(ruleText);

        JLabel ruleLabel = new JLabel("Which of the following rules should be executed?");
        ruleLabel.setBounds(20, 20, 350, 20);
        f.add(ruleLabel);

        ButtonGroup group = new ButtonGroup();
        ArrayList<JRadioButton> ruleRadioButtions = new ArrayList<JRadioButton>();
        for (int i = 0; i < choose.size(); i++) {
            JRadioButton radio = new JRadioButton(choose.get(i));
            radio.setActionCommand(choose.get(i));
            ruleRadioButtions.add(radio);
            ruleRadioButtions.get(i).setBounds(20, 50 + 20 * i, 200, 30);

            group.add(ruleRadioButtions.get(i));
            f.add(ruleRadioButtions.get(i));
        }

        JButton b = new JButton("Select");
        b.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                a = group.getSelection().getActionCommand();

                /* wake up the thread waiting inside InterfaceRule */
                synchronized (lock) {
                    lock.notify();
                }

                f.dispose();
            }
        });
        b.setBounds(270, 220, 100, 40);
        f.add(b);

        f.setVisible(true);
    }

    public String getA() {
        return a;
    }

}

class InterfaceRule {

    private static Object lock = new Object();

    public String call(ArrayList<String> choose) {
        SelectLayoutCreator s = new SelectLayoutCreator(choose, lock);

        /* wait for the String to be populated */
        synchronized (lock) {
            try {
                lock.wait();
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return s.getA();
    }

}

public class Main {

    public static void main(String[] args) {
        ArrayList<String> choose = new ArrayList<String>();
        choose.add("1");
        choose.add("2");
        choose.add("3");

        String chosen = new InterfaceRule().call(choose);
        System.out.println(chosen);
    }

}


问:
Use utf-8 character for QComboBox::down-arrow {image}
I would like to make changing the color theme for my gui as easy as possible. As such I would like to use the ▼ as the drop-down arrow image which is then painted in the color defined by color.

So in summery I'm looking for something like this:

```<code>QComboBox::down-arrow {
   image: ▼;
}
</code>```

Is this possible?

答: Qt doesn't implement that. You could patch Qt to implement it, though.</p>

Body:
I would like to make changing the color theme for my gui as easy as possible. As such I would like to use the ▼ as the drop-down arrow image which is then painted in the color defined by color.

So in summery I'm looking for something like this:

QComboBox::down-arrow {
   image: ▼;
}

Is this possible?