问:
Position of a point in a circle
Hello again first part is working like a charm, thank you everyone.

But I've another question...

As I've no interface, is there a way to do the same thing with out not knowing the radius of the circle?

Should have refresh the page CodeMonkey solution is exactly what I was looking for...

Thank you again.

============================

First I'm not a developer, I'm a simple woodworker that left school far too early...

I'm trying to make one of my tool to work with an autonomous robot.
I made them communicate by reading a lot of tutorials.

But I have one problem I cant figure out.

Robot expect position of the tool as (X,Y) but tool's output is (A,B,C)
A is the distance from tool to north
B distance to east
C distance at 120 degree clockwise from east axe

the border is a circle, radius may change, and may or may not be something I know.

I've been on that for 1 month, and I can't find a way to transform those value into the position.

I made a test with 3 nails on a circle I draw on wood, and if I have the distance there is only one position possible, so I guess its possible.
But how?

Also, if someone as an answer I'd love pseudo code not code so I can practice.

If there is a tool to make a drawing I can use to make it clearer can you point it out to me?

Thank you.

hope it helps :

X, Y are coordinate from center, Da,Db, Dc are known.

Trying to make it more clear (sorry its so clear in my head).

X,Y are the coordinate of the point where is the tool (P).
Center is at 0,0

A is the point where vertical line cut the circle from P, with Da distance P to A;

B is the point where horizontal line cuts the circle fom P, with Db distance P to B.

C is the point where the line at 120 clockwise from horizontal cuts the circle from P, with Dc distance P to C.

Output from tool is an array of int (unit mm): A=123, B=114, C=89
Those are the only informations I have

thanks for all the ideas I'll try them at home later,
Hope it works :)

答:
From your diagram you have point P that you need it's X & Y coordinate. So we need to find Px and Py or (Px,Py). We know that Ax = Px and By = Py. We can use these for substitution if needed. We know that C & P create a line and all lines have slope in the form of y = mx + b. Where the slope is m and the y intercept is b. We don't know m or b at this point but they can be found. We know that the angle of between two vectors where the vectors are CP and PB gives an angle of 120°, but this does not put the angle in standard position since this is a CW rotation. When working with circles and trig functions along with linear equations of slope within them it is best to work in standard form. So if this line of y = mx + b where the points C & P belong to it the angle above the horizontal line that is parallel to the horizontal axis that is made by the points P & B will be 180° - 120° = 60° We also know that the cos angle between two vectors is also equal to the dot product of those vectors divided by the product of their magnitudes.

We don't have exact numbers yet but we can construct a formula: Since theta = 60° above the horizontal in the standard position we know that the slope m is also the tangent of that angle; so the slope of this line is tan(60°). So let's go back to our linear equation y = tan(60°)x + b. Since b is the y intercept we need to find what x is when y is equal to 0. Since we still have three undefined variables y, x, and b we can use the points on this line to help us here. We know that the points C & P are on this line. So this vector of y = tan(60°)x + b is constructed from (Px, Py) - (Cx, Cy). The vector is then (Px-Cx, Py-Cy) that has an angle of 60° above the horizontal that is parallel to the horizontal axis. We need to use another form of the linear equation that involves the points and the slope this time which happens to be y - y1 = m(x - x1) so this then becomes y - Py = tan(60°)(x - Px) well I did say earlier that we could substitute so let's go ahead and do that: y - By = tan(60°)(x - Ax) then y - By = tan(60°)x - tan(60°)Ax. And this becomes known if you know the actual coordinate points of A & B. The only thing here is that you have to convert your angle of 120° to standard form. It all depends on what your known and unknowns are. So if you need P and you have both A & B are known from your diagram the work is easy because the points you need for P will be P(Ax,By). And since you already said that you know Da, Db & Dc with their lengths then its just a matter of apply the correct trig functions with the proper angle and or using the Pythagorean Theorem to find the length of another leg of the triangle. It shouldn't be all that hard to find what P(x,y) is from the other points. You can use the trig functions, linear equations, the Pythagorean theorem, vector calculations etc. If you can find the equation of the line that points C & P knowing that P has A's x value and has B's y value and having the slope of that line that is defined by the tangent above the horizontal which is 180° - phi where phi is the angle you are giving that is CW rotation and theta would be the angle in standard position or above the horizontal you have a general form of y - By = tan(180° - phi)(x - Ax) and from this equation you can find any point on that line.

There are other methods such as using the existing points and the vectors that they create between each other and then generate an equilateral triangle using those points and then from that equilateral if you can generate one, you can use the perpendicular bisectors of that triangle to find the centroid of that triangle. That is another method that can be done. The only thing you may have to consider is the linear translation of the line from the origin. Thus you will have a shift in the line of (Ax - origin, By - origin) and to find one set the other to 0 and vise versa. There are many different methods to find it.

I just showed you several mathematical techniques that can help you to find a general equation based on your known(s) and unknown(s). It just a matter of recognizing which equations work in which scenario. Once you recognize the correct equations for the givens; the rest is fairly easy. I hope this helps you.

EDIT

I did forget to mention one thing; and that is the line of CP has a point on the edge of the circle defined by (cos(60°), sin(60°)) in the 1st quadrant. In the third quadrant you will have a point on this line and the circle defined by (-cos(60°), -sin(60°)) provided that this line goes through the origin (0,0) where there is no y nor x intercepts and if this is the case then the point on the circle at either end and the origin will be the radius of that circle.

Title: Position of a point in a circle


来源: stackexchange

问:
why could member names in a union be the same as typedef names in C?
I found this definition below in the "compiler_defs.h" that comes with SiLabs IDE for 8-bit MCU applications. I have done a little search work, it seems to be relevant to name spaces and identifier visibility issue. There are 5 name spaces used in C (ref: Name Spaces):

Statement labels

Structure, union, and enumeration tags

Members of structures or unions

Ordinary identifiers

Typedef names

and an example is:

```<code>struct student {
    char student[20];
    int class;
    int id;
    } student;
</code>```

I am OK with the above example, but I am still confused about the code below, so why could the typedef names be the same as the member names in a union definition?  Would you please shed some light on this? Thanks.

Code excerpt from "compiler_defs.h":

```<code>typedef unsigned char U8;
typedef unsigned int U16;
typedef unsigned long U32;

typedef signed char S8;
typedef signed int S16;
typedef signed long S32;

typedef union UU16
{
   U16 U16; // [typedef name] [member variable name]
   S16 S16;
   U8 U8[2];
   S8 S8[2];
} UU16;

typedef union UU32
{
   U32 U32;
   S32 S32;
   UU16 UU16[2];
   U16 U16[2];
   S16 S16[2];
   U8 U8[4];
   S8 S8[4];
} UU32;
</code>```

Create my own main.c and include compiler_defs.h:

```<code>U16 U16; // this line in main.c cause compiler error: redefinition in VS2015, WHY?
</code>```

答:
Well you sort of answered your own question:

Statement labels

Structure, union, and enumeration tags

Members of structures or unions

Ordinary identifiers

Typedef names

These are separate namespaces, i.e. a name in one won't clash with the same name in another one. In your case:

```<code>U16 U16; // [typedef name] [member variable name]
</code>```

The first U16 is in namespace #5 in your list. The second is in namespace #3. Separate namespaces, so the names can be the same without conflict.

ContentLicense: CC BY-SA 3.0

Body:
I found this definition below in the "compiler_defs.h" that comes with SiLabs IDE for 8-bit MCU applications. I have done a little search work, it seems to be relevant to name spaces and identifier visibility issue. There are 5 name spaces used in C (ref: Name Spaces):

Statement labels

Structure, union, and enumeration tags

Members of structures or unions

Ordinary identifiers

Typedef names

and an example is:

struct student {
    char student[20];
    int class;
    int id;
    } student;

I am OK with the above example, but I am still confused about the code below, so why could the typedef names be the same as the member names in a union definition?  Would you please shed some light on this? Thanks.

Code excerpt from "compiler_defs.h":

typedef unsigned char U8;
typedef unsigned int U16;
typedef unsigned long U32;

typedef signed char S8;
typedef signed int S16;
typedef signed long S32;

typedef union UU16
{
   U16 U16; // [typedef name] [member variable name]
   S16 S16;
   U8 U8[2];
   S8 S8[2];
} UU16;

typedef union UU32
{
   U32 U32;
   S32 S32;
   UU16 UU16[2];
   U16 U16[2];
   S16 S16[2];
   U8 U8[4];
   S8 S8[4];
} UU32;

Create my own main.c and include compiler_defs.h:

U16 U16; // this line in main.c cause compiler error: redefinition in VS2015, WHY?

Body:
Well you sort of answered your own question:

Statement labels

Structure, union, and enumeration tags

Members of structures or unions

Ordinary identifiers

Typedef names

These are separate namespaces, i.e. a name in one won't clash with the same name in another one. In your case:

U16 U16; // [typedef name] [member variable name]

The first U16 is in namespace #5 in your list. The second is in namespace #3. Separate namespaces, so the names can be the same without conflict.


问:
ASP.NET - MVC 5 SQL Server Database Navigation
Could somebody please explain how to insert data from a SQL Server database into an existing ASP.NET MVC 5 project?

I have a file Shared/_layout.vbhtml which has the following lines:

```<code><li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</code>```

However I would like to replace this with the actual data from the Navigation table. I have added a new Data Connection to SQL Server within the ASP.NET MVC 5 project, but I am now unsure as how to bind the connection this page.

Any examples or advice would be much appreciated :-)

答:
Below is the way to solve out your problem.

Your controller code

```<code>        public ActionResult Index()
        {
            StringBuilder sb = new StringBuilder();

            // Simply fetch from the database and set the action name and controller name with your own logic like using of loop or any.

            // Also, You have to set style and css what you want exactly as per your theme.

            sb.AppendFormat("First Link", Url.Action("ActionName", "ControllerName"));
            sb.AppendFormat("Second Link", Url.Action("ActionName", "ControllerName"));
            sb.AppendFormat("Third Link", Url.Action("ActionName", "ControllerName"));

            // Set ViewBag property with string builder object
            ViewBag.DynamicActions = sb.ToString();

            return View();

        }
</code>```

Place the below code in _layout view file.

```<code><div>
    @if (ViewBag.DynamicActions != null)
    {
      @Html.Raw(ViewBag.DynamicActions)
    }
</div>
</code>```

Body:
Could somebody please explain how to insert data from a SQL Server database into an existing ASP.NET MVC 5 project?

I have a file Shared/_layout.vbhtml which has the following lines:

@Html.ActionLink("Home", "Index", "Home")

@Html.ActionLink("About", "About", "Home")

@Html.ActionLink("Contact", "Contact", "Home")

However I would like to replace this with the actual data from the Navigation table. I have added a new Data Connection to SQL Server within the ASP.NET MVC 5 project, but I am now unsure as how to bind the connection this page.

Any examples or advice would be much appreciated :-)

Body:
Below is the way to solve out your problem.

Your controller code

        public ActionResult Index()
        {
            StringBuilder sb = new StringBuilder();

            // Simply fetch from the database and set the action name and controller name with your own logic like using of loop or any.

            // Also, You have to set style and css what you want exactly as per your theme.

            sb.AppendFormat("First Link", Url.Action("ActionName", "ControllerName"));
            sb.AppendFormat("Second Link", Url.Action("ActionName", "ControllerName"));
            sb.AppendFormat("Third Link", Url.Action("ActionName", "ControllerName"));

            // Set ViewBag property with string builder object
            ViewBag.DynamicActions = sb.ToString();

            return View();

        }

Place the below code in _layout view file.

<div>
    @if (ViewBag.DynamicActions != null)
    {
      @Html.Raw(ViewBag.DynamicActions)
    }
</div>


问:
Force show keyboard on autofocus ios web browser
There are lots of topics that address this issue, but all seem to be old and not relevant (ass further ios releases come out).

I have developed an applciation that is run via a web browser, be it safari or firefox (on an iPad). The webpage has an autofocus on an input, and I need to force the keyboard open.

I have tried without any success to do this with numerous jQuery hacks for focus, with timeouts etc etc. I have read that this might be possible with cordova, but before I re-develop the application is there anyway to do this with another JS libary thats easily "pluginable" to my existing html pages.

The closest I have come is this code, that when I press a button on the page, it then puts a focus on my form input and shows the keyboard:

```<code><script type="text/javascript">
    window.addEventListener('DOMContentLoaded', function() {
      var button = document.querySelector('#button');
      var input = document.querySelector('#input');
      var focus = function(e) {
        e.stopPropagation();
        e.preventDefault();
        var clone = input.cloneNode(true);
        var parent = input.parentElement;
        parent.appendChild(clone);
        parent.replaceChild(clone, input);
        input = clone;
        window.setTimeout(function() {
          input.value = input.value || "";
          input.focus();
        }, 0);
      }
      button.addEventListener('mousedown', focus);
      button.addEventListener('touchstart', focus);
    }, false);
  </script>
</code>```

Is there any way I can simulate clicking the button, I have tried the following but this does not work on any browser, let alone IOS:

```<code><script type="text/javascript">
$(document).ready(function() {
    $("#button").click();
});

</script>
</code>```

So in short, can I simulate a click on this button? If I can get this working on my desktop, I will cross my fingers it then works on IOS.

Or if anyone else has any suggestions/ideas/hacks I would be extremely grateful.

Working example of my above code is taken from here

EDIT:

So I can force the button to be pressed after a time delay (with a MouseEvent), to simulate a real life touchdown event, but it only puts focus on the input box on ios, it does not bring up they keyboard prompt sigh (it does work on desktop browsers though), Looks like I will have to re-write in cordova.

```<code><script type="text/javascript">
    $(document).ready(function() {

        function focusinput(){
        var evt = new MouseEvent("touchstart", {
            view: window,
            bubbles: true,
            cancelable: true,
            clientX: 20,
            /* whatever properties you want to give it */
        }),
            ele = document.getElementById("button");
        ele.dispatchEvent(evt);
        }

        function focusinputa(){
        var evt = new MouseEvent("mousedown", {
            view: window,
            bubbles: true,
            cancelable: true,
            clientX: 20,
            /* whatever properties you want to give it */
        }),
            ele = document.getElementById("button");
        ele.dispatchEvent(evt);
        }

        ;

        setTimeout(focusinput, 1000);
        setTimeout(focusinputa, 1500);

    });

</script>
</code>```

EDIT2:

It seems there is no way at all to do this (as of writing this ios 9.1), inside a native html/js webpage, if anyone has any other solutions or ideas to test I would be happy to test them, but as for now I have had to resort to a a manual click of a button to focus the input and bring up the keyboard prompt.

答:
I had a similar issue, and after a lot of tests i've got a simple solution, I hope it helps anyone ;)

First of all, Safari apparently make the focus, but do not open the keyboard. So I tried to change my < button> for a . This worked for me.

```<code><label for="search" id="mobile-search">Search</label>
<input type="text" name="search" id="search" value="">

<script type="text/javascript">
  $('#mobile-search').on('click', function() {
    // do your stuff, in my case some class changes
  });
</script>
</code>```

Just be sure that you are not to using a .preventDefault(); on the click event.

Body:
There are lots of topics that address this issue, but all seem to be old and not relevant (ass further ios releases come out).

I have developed an applciation that is run via a web browser, be it safari or firefox (on an iPad). The webpage has an autofocus on an input, and I need to force the keyboard open.

I have tried without any success to do this with numerous jQuery hacks for focus, with timeouts etc etc. I have read that this might be possible with cordova, but before I re-develop the application is there anyway to do this with another JS libary thats easily "pluginable" to my existing html pages.

The closest I have come is this code, that when I press a button on the page, it then puts a focus on my form input and shows the keyboard:

Is there any way I can simulate clicking the button, I have tried the following but this does not work on any browser, let alone IOS:

So in short, can I simulate a click on this button? If I can get this working on my desktop, I will cross my fingers it then works on IOS.

Or if anyone else has any suggestions/ideas/hacks I would be extremely grateful.

Working example of my above code is taken from here

EDIT:

So I can force the button to be pressed after a time delay (with a MouseEvent), to simulate a real life touchdown event, but it only puts focus on the input box on ios, it does not bring up they keyboard prompt sigh (it does work on desktop browsers though), Looks like I will have to re-write in cordova.

EDIT2:

It seems there is no way at all to do this (as of writing this ios 9.1), inside a native html/js webpage, if anyone has any other solutions or ideas to test I would be happy to test them, but as for now I have had to resort to a a manual click of a button to focus the input and bring up the keyboard prompt.

Body:
I had a similar issue, and after a lot of tests i've got a simple solution, I hope it helps anyone ;)

First of all, Safari apparently make the focus, but do not open the keyboard. So I tried to change my < button> for a < label>. This worked for me.

<label for="search" id="mobile-search">Search</label>
<input type="text" name="search" id="search" value="">

<script type="text/javascript">
  $('#mobile-search').on('click', function() {
    // do your stuff, in my case some class changes
  });
</script>

Just be sure that you are not to using a .preventDefault(); on the click event.


问:
IE10 and after pseudoelements
I'm doing a very simple transition on a h3 hover with an after pseudoelement. I've read that ::after works on IE10 (and it does as it renders it), but not the hover.

h3 {
  position:relative;
}
h3::after {
  content: '';
  display: block;
  position: absolute;
  bottom: -5px;
  width: 10px;
  height: 2px;
  background: blue;
  left: 0;
  -ms-transition: all .5s;
  transition: all .5s;
}
h3:hover::after {
  width: 100%;
}
h3 a {
  text-decoration: none;
  position: relative;
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<h3>
Hello
</h3></code>```

Other browsers works as a charm, I don't know what happens with IE10...

答:
Try adding empty hover selector for h3.
h3:hover {}</p>

Title: IE10 and after pseudoelements

Body:
I'm doing a very simple transition on a h3 hover with an after pseudoelement. I've read that ::after works on IE10 (and it does as it renders it), but not the hover.

h3 {
  position:relative;
}
h3::after {
  content: '';
  display: block;
  position: absolute;
  bottom: -5px;
  width: 10px;
  height: 2px;
  background: blue;
  left: 0;
  -ms-transition: all .5s;
  transition: all .5s;
}
h3:hover::after {
  width: 100%;
}
h3 a {
  text-decoration: none;
  position: relative;
  display: inline-block;
}

<!DOCTYPE html>

Hello

Other browsers works as a charm, I don't know what happens with IE10...


问:
Picasso Load Image Failed and App Crashing
I'm new to Android development, I'm trying to load image from url using Picasso, but it failed when I navigate to the Picasso loading activity.

Below is the code that i use for:

```<code>//Declaring Variable
ImageView ImageView1 = (ImageView)findViewById(R.id.forthImage);
Context context = this;

//In onCreate()
Picasso.with(context).load("http://postimg.org/image/wjidfl5pd/").into(ImageView1);
</code>```

In my XML:

```<code><ImageView
    android:id="@+id/forthImage"
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/thirdImage"
    />
</code>```

And my catLog:

```<code>09-02 09:11:39.632: E/AndroidRuntime(8680): FATAL EXCEPTION: main
09-02 09:11:39.632: E/AndroidRuntime(8680): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.toppan.toppan_android_v1/com.toppan.toppan_android_v1.Animation_Run}: java.lang.NullPointerException
09-02 09:11:39.632: E/AndroidRuntime(8680):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2151)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at android.app.ActivityThread.access$600(ActivityThread.java:144)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1259)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at android.os.Looper.loop(Looper.java:137)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at android.app.ActivityThread.main(ActivityThread.java:5166)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at java.lang.reflect.Method.invokeNative(Native Method)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at java.lang.reflect.Method.invoke(Method.java:525)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:768)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at dalvik.system.NativeStart.main(Native Method)
09-02 09:11:39.632: E/AndroidRuntime(8680): Caused by: java.lang.NullPointerException
09-02 09:11:39.632: E/AndroidRuntime(8680):     at android.app.Activity.findViewById(Activity.java:1902)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at com.toppan.toppan_android_v1.Animation_Run.<init>(Animation_Run.java:17)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at java.lang.Class.newInstanceImpl(Native Method)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at java.lang.Class.newInstance(Class.java:1130)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at android.app.Instrumentation.newActivity(Instrumentation.java:1064)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2142)
09-02 09:11:39.632: E/AndroidRuntime(8680):     ... 11 more
</code>```

I don't know what reason cause it failed. I've downloaded the picasso library from "http://square.github.io/picasso/", and added inside my library folder.
Also, added INTERNET permission into my manifest file.

Any idea guys??

答:
```<code>final Target mTarget = new Target() {
        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom loadedFrom) {
            Log.d("DEBUG", "onBitmapLoaded");
            progress_bar.setVisibility(View.GONE);
            cropImageView.setImageBitmap(bitmap);
        }

        @Override
        public void onBitmapFailed(Drawable drawable) {
            Log.d("DEBUG", "onBitmapFailed");
        }

        @Override
        public void onPrepareLoad(Drawable drawable) {
            Log.d("DEBUG", "onPrepareLoad");
        }
    };
    Picasso.with(this).load(wallpaper.getMain_image()).into(mTarget);
    cropImageView.setTag(mTarget);
</code>```

Note:cropImageView is ImageView

Body:
I'm new to Android development, I'm trying to load image from url using Picasso, but it failed when I navigate to the Picasso loading activity.

Below is the code that i use for:

//Declaring Variable
ImageView ImageView1 = (ImageView)findViewById(R.id.forthImage);
Context context = this;

//In onCreate()
Picasso.with(context).load("http://postimg.org/image/wjidfl5pd/").into(ImageView1);

In my XML:

<ImageView
    android:id="@+id/forthImage"
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/thirdImage"
    />

And my catLog:

09-02 09:11:39.632: E/AndroidRuntime(8680): FATAL EXCEPTION: main
09-02 09:11:39.632: E/AndroidRuntime(8680): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.toppan.toppan_android_v1/com.toppan.toppan_android_v1.Animation_Run}: java.lang.NullPointerException
09-02 09:11:39.632: E/AndroidRuntime(8680):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2151)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at android.app.ActivityThread.access$600(ActivityThread.java:144)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1259)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at android.os.Looper.loop(Looper.java:137)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at android.app.ActivityThread.main(ActivityThread.java:5166)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at java.lang.reflect.Method.invokeNative(Native Method)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at java.lang.reflect.Method.invoke(Method.java:525)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:768)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at dalvik.system.NativeStart.main(Native Method)
09-02 09:11:39.632: E/AndroidRuntime(8680): Caused by: java.lang.NullPointerException
09-02 09:11:39.632: E/AndroidRuntime(8680):     at android.app.Activity.findViewById(Activity.java:1902)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at com.toppan.toppan_android_v1.Animation_Run.<init>(Animation_Run.java:17)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at java.lang.Class.newInstanceImpl(Native Method)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at java.lang.Class.newInstance(Class.java:1130)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at android.app.Instrumentation.newActivity(Instrumentation.java:1064)
09-02 09:11:39.632: E/AndroidRuntime(8680):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2142)
09-02 09:11:39.632: E/AndroidRuntime(8680):     ... 11 more

I don't know what reason cause it failed. I've downloaded the picasso library from "http://square.github.io/picasso/", and added inside my library folder.
Also, added INTERNET permission into my manifest file.

Any idea guys??

Body:
final Target mTarget = new Target() {
        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom loadedFrom) {
            Log.d("DEBUG", "onBitmapLoaded");
            progress_bar.setVisibility(View.GONE);
            cropImageView.setImageBitmap(bitmap);
        }

        @Override
        public void onBitmapFailed(Drawable drawable) {
            Log.d("DEBUG", "onBitmapFailed");
        }

        @Override
        public void onPrepareLoad(Drawable drawable) {
            Log.d("DEBUG", "onPrepareLoad");
        }
    };
    Picasso.with(this).load(wallpaper.getMain_image()).into(mTarget);
    cropImageView.setTag(mTarget);

Note:cropImageView is ImageView


问:
how to print reverse number pattern triangle in java
This is my code:

```<code>for (int i = 4; i >= 1; i--) {
    for (int j = 1; j < i; j++) {
        System.out.print(" ");
    }
    for (int k = i; k <= 4; k++) {
        System.out.print(k+"");
    }
    System.out.println();
}
</code>```

Current output:

```<code>   4
  34
 234
1234
</code>```

Desired output:

```<code>   1
  21
 321
4321
</code>```

What changes are necessary in order for me to get the desired output as shown above?

答:
Here you go:</p>

```<code>public static void main(String[] args) {
    for (int i = 1; i <= 4; i++) {
        for (int j = 4; j > i; j--) {
            System.out.print(" ");
        }
        for (int k = i; k >= 1; k--){
            System.out.print(k + "");
        }
        System.out.println();
    }
}
</code>```

Body:
This is my code:

for (int i = 4; i >= 1; i--) {
    for (int j = 1; j < i; j++) {
        System.out.print(" ");
    }
    for (int k = i; k <= 4; k++) {
        System.out.print(k+"");
    }
    System.out.println();
}

Current output:

   4
  34
 234
1234

Desired output:

   1
  21
 321
4321

What changes are necessary in order for me to get the desired output as shown above?

Body:
Here you go:

public static void main(String[] args) {
    for (int i = 1; i <= 4; i++) {
        for (int j = 4; j > i; j--) {
            System.out.print(" ");
        }
        for (int k = i; k >= 1; k--){
            System.out.print(k + "");
        }
        System.out.println();
    }
}


问:
C# Multiple Indexers
Is it possible to have something like the following:

```<code>class C
{
    public Foo Foos[int i]
    {
        ...
    }

    public Bar Bars[int i]
    {
        ...
    }
}
</code>```

If not, then are what are some of the ways I can achieve this? I know I could make functions called getFoo(int i) and getBar(int i) but I was hoping to do this with properties.

答:
Not in C#, no.

However, you can always return collections from properties, as follows:

```<code>public IList<Foo> Foos
{
    get { return ...; }
}

public IList<Bar> Bars
{
    get { return ...; }
}
</code>```

IList<T> has an indexer, so you can write the following:

```<code>C whatever = new C();
Foo myFoo = whatever.Foos[13];
</code>```

On the lines "return ...;" you can return whatever implements IList<T>, but you might what to return a read-only wrapper around your collection, see AsReadOnly() method.

ContentLicense: CC BY-SA 2.5

Title: C# Multiple Indexers

Body:
Is it possible to have something like the following:

class C
{
    public Foo Foos[int i]
    {
        ...
    }

    public Bar Bars[int i]
    {
        ...
    }
}

If not, then are what are some of the ways I can achieve this? I know I could make functions called getFoo(int i) and getBar(int i) but I was hoping to do this with properties.

Body:
Not in C#, no.

However, you can always return collections from properties, as follows:

public IList<Foo> Foos
{
    get { return ...; }
}

public IList<Bar> Bars
{
    get { return ...; }
}

IList<T> has an indexer, so you can write the following:

C whatever = new C();
Foo myFoo = whatever.Foos[13];

On the lines "return ...;" you can return whatever implements IList<T>, but you might what to return a read-only wrapper around your collection, see AsReadOnly() method.


问:
Web Scraping a wikipedia page
In some wikipedia pages, after the title of the article (appearing in bold), there is some text inside of parentheses used to explain the pronunciation and phonetics of the words in the title. For example, on this, after the bold title diglossia in the
, there is an open parenthesis. In order to find the corresponding close parenthesis, you would have to iterate through the text nodes one by one to find it, which is simple. What I'm trying to do is find the very next href link and store it.

The issue here is that (AFAIK), there isn't a way to uniquely identify the text node with the close parenthesis and then get the following href. Is there any straight forward (not convoluted) way to get the first link outside of the initial parentheses?

EDIT

In the case of the link provided here, the href to be stored should be: https://en.wikipedia.org/wiki/Dialects since that is the first link outside of the parenthesis

答:
Is this what you want?

```<code>import requests
rs = requests.get('https://en.wikipedia.org/wiki/Diglossia', verify=False)
parsed_html = BeautifulSoup(rs.text)
print parsed_html.body.findAll('p')[0].findAll('a')[0]
</code>```

This gives:

```<code><a href="/wiki/Linguistics" title="Linguistics">linguistics</a>
</code>```

if you want to extract href then you can use this:

```<code>parsed_html.body.findAll('p')[0].findAll('a')[0].attrs[0][1]
</code>```

UPDATE
It seems you want href after parentheses not the before one.
I have written script for it. Try this:

```<code>import requests
from BeautifulSoup import BeautifulSoup
rs = requests.get('https://en.wikipedia.org/wiki/Diglossia', verify=False)
parsed_html = BeautifulSoup(rs.text)

temp = parsed_html.body.findAll('p')[0]

start_count = 0
started = False
found = False

while temp.next and found is False:
    temp = temp.next
    if '(' in temp:
        start_count += 1
        if started is False:
            started = True
    if ')' in temp and started and start_count > 1:
        start_count -= 1
    elif ')' in temp and started and start_count == 1:
        found = True

print temp.findNext('a').attrs[0][1]
</code>```

Title: Web Scraping a wikipedia page

Body:
Is this what you want?

import requests
rs = requests.get('https://en.wikipedia.org/wiki/Diglossia', verify=False)
parsed_html = BeautifulSoup(rs.text)
print parsed_html.body.findAll('p')[0].findAll('a')[0]

This gives:

<a href="/wiki/Linguistics" title="Linguistics">linguistics</a>

if you want to extract href then you can use this:

parsed_html.body.findAll('p')[0].findAll('a')[0].attrs[0][1]

UPDATE
It seems you want href after parentheses not the before one.
I have written script for it. Try this:

import requests
from BeautifulSoup import BeautifulSoup
rs = requests.get('https://en.wikipedia.org/wiki/Diglossia', verify=False)
parsed_html = BeautifulSoup(rs.text)

temp = parsed_html.body.findAll('p')[0]

start_count = 0
started = False
found = False

while temp.next and found is False:
    temp = temp.next
    if '(' in temp:
        start_count += 1
        if started is False:
            started = True
    if ')' in temp and started and start_count > 1:
        start_count -= 1
    elif ')' in temp and started and start_count == 1:
        found = True

print temp.findNext('a').attrs[0][1]


问:
mkvirtualenv ImportError: No module named stevedore
I've got a Mac which has python installed and virtualenvwrapper installed. I'm trying to create a new environment by running:

```<code>mkvirtualenv Test
</code>```

To which I get the following error:

```<code>New python executable in /Users/sidharthnayyar/.virtualenvs/Test/bin/python
Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 174, in _run_module_as_main
        "__main__", fname, loader, pkg_name)
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code
        exec code in run_globals
    File "/Library/Python/2.7/site-packages/virtualenvwrapper/hook_loader.py", line 16, in <module>
        from stevedore import ExtensionManager
ImportError: No module named stevedore
</code>```

I have python installed here:

```<code>$ which -a python
    /usr/local/bin/python
    /usr/bin/python
</code>```

If I try sudo pip install stevedore then it says its already installed with some warnings:

```<code>sudo /usr/local/bin/pip install stevedore
The directory '/Users/sidharthnayyar/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/sidharthnayyar/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Requirement already satisfied (use --upgrade to upgrade): stevedore in ./Library/Python/2.7/lib/python/site-packages
Requirement already satisfied (use --upgrade to upgrade): pbr>=1.6 in /Library/Python/2.7/site-packages (from stevedore)
Requirement already satisfied (use --upgrade to upgrade): six>=1.9.0 in ./Library/Python/2.7/lib/python/site-packages (from stevedore)
</code>```

If I try sudo -H pip install stevedore then I get the following errors:

```<code>sudo -H /usr/local/bin/pip install stevedore

Collecting stevedore
    Using cached stevedore-1.18.0-py2.py3-none-any.whl
Requirement already satisfied (use --upgrade to upgrade): pbr>=1.6 in /Library/Python/2.7/site-packages (from stevedore)
Collecting six>=1.9.0 (from stevedore)
    Using cached six-1.10.0-py2.py3-none-any.whl
Installing collected packages: six, stevedore
    Found existing installation: six 1.4.1
        DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
        Uninstalling six-1.4.1:
Exception:
Traceback (most recent call last):
    File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 215, in main
        status = self.run(options, args)
    File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 317, in run
        prefix=options.prefix_path,
    File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 736, in install
        requirement.uninstall(auto_confirm=True)
    File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 742, in uninstall
        paths_to_remove.remove(auto_confirm)
    File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py", line 115, in remove
        renames(path, new_path)
    File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 267, in renames
        shutil.move(old, new)
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move
        copy2(src, real_dst)
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2
        copystat(src, dst)
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat
        os.chflags(dst, st.st_flags)
OSError: [Errno 1] Operation not permitted: '/tmp/pip-NOex2K-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info'
</code>```

If I create a .bash_profile and put into it:

```<code>export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/Devel
export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python
export VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/bin/virtualenv
source /usr/local/bin/virtualenvwrapper.sh
</code>```

and reload a terminal window then I get the following error:

```<code>source ~/.bash_profile
Traceback (most recent call last):
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 174, in _run_module_as_main
        "__main__", fname, loader, pkg_name)
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code
        exec code in run_globals
    File "/Library/Python/2.7/site-packages/virtualenvwrapper/hook_loader.py", line 16, in <module>
        from stevedore import ExtensionManager
ImportError: No module named stevedore
virtualenvwrapper.sh: There was a problem running the initialization hooks.

If Python could not import the module virtualenvwrapper.hook_loader,
check that virtualenvwrapper has been installed for
VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python and that PATH is
set properly.
</code>```

Curious and curiouser.

Any suggestions on what's going wrong and how to fix this?

Thanks
Sidharth

答:
I was very confused with this problem, too. And I have solved it by uninstalling the old stevedore and reinstall it.</p>

```<code>sudo pip uninstall stevedore
sudo pip install stevedore
</code>```

Body:
I've got a Mac which has python installed and virtualenvwrapper installed. I'm trying to create a new environment by running:

mkvirtualenv Test

To which I get the following error:

New python executable in /Users/sidharthnayyar/.virtualenvs/Test/bin/python
Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 174, in _run_module_as_main
        "__main__", fname, loader, pkg_name)
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code
        exec code in run_globals
    File "/Library/Python/2.7/site-packages/virtualenvwrapper/hook_loader.py", line 16, in <module>
        from stevedore import ExtensionManager
ImportError: No module named stevedore

I have python installed here:

$ which -a python
    /usr/local/bin/python
    /usr/bin/python

If I try sudo pip install stevedore then it says its already installed with some warnings:

sudo /usr/local/bin/pip install stevedore
The directory '/Users/sidharthnayyar/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/sidharthnayyar/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Requirement already satisfied (use --upgrade to upgrade): stevedore in ./Library/Python/2.7/lib/python/site-packages
Requirement already satisfied (use --upgrade to upgrade): pbr>=1.6 in /Library/Python/2.7/site-packages (from stevedore)
Requirement already satisfied (use --upgrade to upgrade): six>=1.9.0 in ./Library/Python/2.7/lib/python/site-packages (from stevedore)

If I try sudo -H pip install stevedore then I get the following errors:

sudo -H /usr/local/bin/pip install stevedore

Collecting stevedore
    Using cached stevedore-1.18.0-py2.py3-none-any.whl
Requirement already satisfied (use --upgrade to upgrade): pbr>=1.6 in /Library/Python/2.7/site-packages (from stevedore)
Collecting six>=1.9.0 (from stevedore)
    Using cached six-1.10.0-py2.py3-none-any.whl
Installing collected packages: six, stevedore
    Found existing installation: six 1.4.1
        DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
        Uninstalling six-1.4.1:
Exception:
Traceback (most recent call last):
    File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 215, in main
        status = self.run(options, args)
    File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 317, in run
        prefix=options.prefix_path,
    File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 736, in install
        requirement.uninstall(auto_confirm=True)
    File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 742, in uninstall
        paths_to_remove.remove(auto_confirm)
    File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py", line 115, in remove
        renames(path, new_path)
    File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 267, in renames
        shutil.move(old, new)
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move
        copy2(src, real_dst)
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2
        copystat(src, dst)
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat
        os.chflags(dst, st.st_flags)
OSError: [Errno 1] Operation not permitted: '/tmp/pip-NOex2K-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info'

If I create a .bash_profile and put into it:

export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/Devel
export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python
export VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/bin/virtualenv
source /usr/local/bin/virtualenvwrapper.sh

and reload a terminal window then I get the following error:

source ~/.bash_profile
Traceback (most recent call last):
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 174, in _run_module_as_main
        "__main__", fname, loader, pkg_name)
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code
        exec code in run_globals
    File "/Library/Python/2.7/site-packages/virtualenvwrapper/hook_loader.py", line 16, in <module>
        from stevedore import ExtensionManager
ImportError: No module named stevedore
virtualenvwrapper.sh: There was a problem running the initialization hooks.

If Python could not import the module virtualenvwrapper.hook_loader,
check that virtualenvwrapper has been installed for
VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python and that PATH is
set properly.

Curious and curiouser.

Any suggestions on what's going wrong and how to fix this?

Thanks
Sidharth

Body:
I was very confused with this problem, too. And I have solved it by uninstalling the old stevedore and reinstall it.

sudo pip uninstall stevedore
sudo pip install stevedore


答:
Let the first loop (i) run from 1 to 4 and the second (j) from 4 to i.
This reverses your output.</p>

Title: how to print reverse number pattern triangle in java


问:
unable to integrate Neo4j 3 with Gephi 0.9
I tried all possible ways to connect Neo4j 3.1.1 database with Gephi 0.9.1 but it is not connecting

Environment :
OS: Windows 7 professional
JDK: 1.8
Neo4j: 3.1.1
Gephi: 0.9.1

答:
Looks like the same issue as on Github

Possible Solution would be :

The plugin at https://marketplace.gephi.org works only in Gephi 0.8.2.

The plugin still needs to be adapted to 0.9.1


问:
Get number of sets in array
```<code>Sub test()
    Dim Relevant_Sheets As Variant
    Set Relevant_Sheets = Sheets(Array("btw.facturen", "btw.filelist", "btw.controle", "intervat", "voorblad", "medecontractanten", "Vak 01", "Vak 03", "Vak 45", "Vak 54", "Vak 55", "Vak 56", "Vak 59", "Vak 81", "Vak 82", "Vak 83", "Vak 84", "Vak 85", "Vak 86", "Vak 88"))
    Number_of_Relevant_Sheets = 20
End Sub
</code>```

This is an extract of my code. Relevant_Sheets gets used multiple times afterwards, and I use it so that I only have to set which pages to use once.

I would like Number_of_Relevant_Sheets to count the number of sheets in Relevant_Sheets (in this case 20), so that I don't have to manually change it when I add or remove a sheet from the list.

If anyone could point me in the right direction?

答: You can use Relevant_Sheets.Count instead of Number_of_Relevant_Sheets

Title: Get number of sets in array

Body:
Sub test()
    Dim Relevant_Sheets As Variant
    Set Relevant_Sheets = Sheets(Array("btw.facturen", "btw.filelist", "btw.controle", "intervat", "voorblad", "medecontractanten", "Vak 01", "Vak 03", "Vak 45", "Vak 54", "Vak 55", "Vak 56", "Vak 59", "Vak 81", "Vak 82", "Vak 83", "Vak 84", "Vak 85", "Vak 86", "Vak 88"))
    Number_of_Relevant_Sheets = 20
End Sub

This is an extract of my code. Relevant_Sheets gets used multiple times afterwards, and I use it so that I only have to set which pages to use once.

I would like Number_of_Relevant_Sheets to count the number of sheets in Relevant_Sheets (in this case 20), so that I don't have to manually change it when I add or remove a sheet from the list.

If anyone could point me in the right direction?


问:
How to set ToolTip Visibility for the Grid column using DependencyProperty inside of IValueConverter
I want to set Visibility for ToolTip (DependencyProperty) inside of IValueConverter using special logic. I want to show/hide ToolTip only when I have the special condition.

How can I do this?

</UserControl.Resources>
    <converters:ToolTipMessageConverter x:Key="ToolTipMessageConverter" />
</UserControl.Resources>

<telerik:RadGridView ItemsSource="{Binding Data}" AutoGenerateColumns="False">
    <telerik:GridViewDataColumn DataMemberBinding="{Binding DataField}">
        <telerik:GridViewDataColumn.ToolTipTemplate>
            <TextBlock Text="{Binding OtherData,Converter={StaticResource ToolTipMessageConverter}}"  Visibility=??? />
        </telerik:GridViewDataColumn.ToolTipTemplate>
    </telerik:GridViewDataColum>
<telerik:RadGridView>
```

<pre class="lang-csharp prettyprint-override"><code>public class ToolTipMessageConverter : FrameworkElement, IValueConverter
{
    public Visibility ToolTipVisibility
    {
        get { return (Visibility)GetValue(ToolTipVisibilityProperty); }
        set { SetValue(ToolTipVisibilityProperty, value); }
    }
    public static readonly DependencyProperty ToolTipVisibilityProperty =
        DependencyProperty.Register("ToolTipVisibility", typeof(Visibility), typeof(ToolTipMessageConverter), new PropertyMetadata(Visibility.Visible));

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var status = (string)value;
        var mess = string.Empty;
        if (status == "Available")
        {
            this.SetValue(ToolTipVisibilityProperty, Visibility.Hidden);
        }
        else
        {
            mess = "User message... " + value;
            this.SetValue(ToolTipVisibilityProperty, Visibility.Visible);
        }
        return mess;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return null;
    }
}
</code>```

答:
So it should work:</p>

```<code><TextBlock Text="{Binding OtherData,Converter={StaticResource ToolTipMessageConverter}}"  Visibility="{Binding ToolTipVisibility, Source={StaticResource ToolTipMessageConverter}}" />
</code>```

Body:
I want to set Visibility for ToolTip (DependencyProperty) inside of IValueConverter using special logic. I want to show/hide ToolTip only when I have the special condition.

How can I do this?

</UserControl.Resources>
    <converters:ToolTipMessageConverter x:Key="ToolTipMessageConverter" />
</UserControl.Resources>

<telerik:RadGridView ItemsSource="{Binding Data}" AutoGenerateColumns="False">
    <telerik:GridViewDataColumn DataMemberBinding="{Binding DataField}">
        <telerik:GridViewDataColumn.ToolTipTemplate>
            <TextBlock Text="{Binding OtherData,Converter={StaticResource ToolTipMessageConverter}}"  Visibility=??? />
        </telerik:GridViewDataColumn.ToolTipTemplate>
    </telerik:GridViewDataColum>
<telerik:RadGridView>

public class ToolTipMessageConverter : FrameworkElement, IValueConverter
{
    public Visibility ToolTipVisibility
    {
        get { return (Visibility)GetValue(ToolTipVisibilityProperty); }
        set { SetValue(ToolTipVisibilityProperty, value); }
    }
    public static readonly DependencyProperty ToolTipVisibilityProperty =
        DependencyProperty.Register("ToolTipVisibility", typeof(Visibility), typeof(ToolTipMessageConverter), new PropertyMetadata(Visibility.Visible));

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var status = (string)value;
        var mess = string.Empty;
        if (status == "Available")
        {
            this.SetValue(ToolTipVisibilityProperty, Visibility.Hidden);
        }
        else
        {
            mess = "User message... " + value;
            this.SetValue(ToolTipVisibilityProperty, Visibility.Visible);
        }
        return mess;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return null;
    }
}

Body:
So it should work:

<TextBlock Text="{Binding OtherData,Converter={StaticResource ToolTipMessageConverter}}"  Visibility="{Binding ToolTipVisibility, Source={StaticResource ToolTipMessageConverter}}" />


问:
Sudden DTU spikes in Azure SQL
Our SQL Azure databases gets sudden spikes on random moments during the week. Once these spikes happen they don't stop anymore. There is nothing happening abnormally at those moments.

If we scale up or scale down our SQL the spikes stop and we have our normal behavior again.

How can we troubleshoot this problem? I have a feeling something is 'stuck' and is suddenly hogging our SQL.

答:
Use Query Store to identify the culprits. Activate Query Performance Insight on your account and then review the top consuming queries when the DTU spikes occur.

If we scale up or scale down our SQL the spikes stop and we have our normal behavior again

That looks like something only an Azure ticket can investigate.

Title: Sudden DTU spikes in Azure SQL


问:
How to use FIND_IN_SET() query in codeigniter
I have two tables- One with attendance details and another one with student detail. The following are the table structures:

tbl_attendance

aid             date                     attendance

1           2017-03-09            5,6,9

 2            2017-04-06          12,6,10

  tbl_students

student_id          name

5                               John

6                   Bryan

9                   Anna

10                 Mathew

12                 Susan

Now, I want to display the names of the absentees in the view  as something like say. for example:

Date                 Absentees

2017-03-09   John, Bryan, Anna

2017-03-06   Susan, Bryan, Mathew

I was trying to do it with FIND_IN_SET()..but it seems bad luck..Is there a better way to sort this out?

UPDATE

I used this query instead and it echoed only the first id's name in each row...

```<code>    $query = $this->db
   ->select("tbl_attendance.*,tbl_students.name")
   ->from("tbl_attendance")
   ->join("tbl_students","tbl_students.student_id=tbl_attendance.attendance")
   ->where('FIND_IN_SET(tbl_students.student_id, tbl_attendance.attendance)')
   ->GROUP_BY('tbl_students.student_id')
   ->get()->result_array();
</code>```

But as there are three numbers separated by commas in each row I want the rest to be echoed as well.

答:
How about that ?</p>

```<code>$query = $this->db
    ->select("td.Date, GROUP_CONCAT(ts.student_name)")
    ->from("tbl_students AS ts")
    ->join("tbl_attendance AS ta","find_in_set(ts.st_id,ta.attendance)","left",false)
    ->get();
</code>```

Body:
I have two tables- One with attendance details and another one with student detail. The following are the table structures:

tbl_attendance

aid             date                     attendance

1           2017-03-09            5,6,9

 2            2017-04-06          12,6,10

  tbl_students

student_id          name

5                               John

6                   Bryan

9                   Anna

10                 Mathew

12                 Susan

Now, I want to display the names of the absentees in the view  as something like say. for example:

Date                 Absentees

2017-03-09   John, Bryan, Anna

2017-03-06   Susan, Bryan, Mathew

I was trying to do it with FIND_IN_SET()..but it seems bad luck..Is there a better way to sort this out?

UPDATE

I used this query instead and it echoed only the first id's name in each row...

    $query = $this->db
   ->select("tbl_attendance.*,tbl_students.name")
   ->from("tbl_attendance")
   ->join("tbl_students","tbl_students.student_id=tbl_attendance.attendance")
   ->where('FIND_IN_SET(tbl_students.student_id, tbl_attendance.attendance)')
   ->GROUP_BY('tbl_students.student_id')
   ->get()->result_array();

But as there are three numbers separated by commas in each row I want the rest to be echoed as well.

Body:
How about that ?

$query = $this->db
    ->select("td.Date, GROUP_CONCAT(ts.student_name)")
    ->from("tbl_students AS ts")
    ->join("tbl_attendance AS ta","find_in_set(ts.st_id,ta.attendance)","left",false)
    ->get();


问:
How to get the table row index based on value in a particular column
Fairly simple question: I want to get the row index of the table based on value in a particular column. Lets say the column name is "ID", it has unique values in my TableView.

Now, I want to retrieve the row index where the column "ID" is 22.

I only have access to the TableView object and the column("ID") value with me.

答:
Use this code.</p>

```<code>   for (int i = 0; i < tableView.getItems().size(); i++) {
        if (tableView.getItems().get(i).getId() == 22) {
            System.out.println("Selected Index : "+i);
        }
    }
</code>```

Body:
Use this code.

   for (int i = 0; i < tableView.getItems().size(); i++) {
        if (tableView.getItems().get(i).getId() == 22) {
            System.out.println("Selected Index : "+i);
        }
    }


问:
How do I remove the light grey border around my Canvas widget?
I've been messing with the Tkinter Canvas widget in order to see if I could make some aesthetically pleasing widgets, and I have a few questions.

First, why is there a light grey border around my Canvas widget, and how do I get rid of it?

Secondly, why is the top left most position in the Canvas (2,2)? It seems like it should be (0,0).

My current script:

```<code>from Tkinter import *

master = Tk()
master.configure(bg='black')
master.wm_attributes("-topmost", 1)

w = Canvas(master, width=150, height=40, bd=0,relief='ridge',)
w.pack()

color = 100
x0 = 2
y0 = 2
x1 = 151
y1 = 2

while y0 < 20 :
    r = color
    g = color
    b = color
    rgb = r, g, b
    Hex = '#%02x%02x%02x' % rgb
    w.create_line(x0, y0, x1, y1,fill=str(Hex), width=1)
    color = color - 2
    y0 = y0 + 1
    y1 = y1 + 1

color = 10

while y0 < 40 :
    r = color
    g = color
    b = color
    rgb = r, g, b
    Hex = '#%02x%02x%02x' % rgb
    w.create_line(x0, y0, x1, y1,fill=str(Hex), width=1)
    color = color + 4
    y0 = y0 + 1
    y1 = y1 + 1

mainloop()
</code>```

答:
The short answer is, the Canvas has two components which affect the edges: the border (borderwidth attribute) and highlight ring (highlightthickness attribute).

If you have a border width of zero and a highlight thickness of zero, the canvas coordinates will begin at 0,0. Otherwise, these two components of the canvas infringe upon the coordinate space.

What I most often do is set these attributes to zero. Then, if I actually want a border I'll put that canvas inside a frame and give the frame a border.

Body:
I've been messing with the Tkinter Canvas widget in order to see if I could make some aesthetically pleasing widgets, and I have a few questions.

First, why is there a light grey border around my Canvas widget, and how do I get rid of it?

Secondly, why is the top left most position in the Canvas (2,2)? It seems like it should be (0,0).

My current script:

from Tkinter import *

master = Tk()
master.configure(bg='black')
master.wm_attributes("-topmost", 1)

w = Canvas(master, width=150, height=40, bd=0,relief='ridge',)
w.pack()

color = 100
x0 = 2
y0 = 2
x1 = 151
y1 = 2

while y0 < 20 :
    r = color
    g = color
    b = color
    rgb = r, g, b
    Hex = '#%02x%02x%02x' % rgb
    w.create_line(x0, y0, x1, y1,fill=str(Hex), width=1)
    color = color - 2
    y0 = y0 + 1
    y1 = y1 + 1

color = 10

while y0 < 40 :
    r = color
    g = color
    b = color
    rgb = r, g, b
    Hex = '#%02x%02x%02x' % rgb
    w.create_line(x0, y0, x1, y1,fill=str(Hex), width=1)
    color = color + 4
    y0 = y0 + 1
    y1 = y1 + 1

mainloop()


问:
Android Facebook "You have already authorised appname"
I have integrated the Facebook SDK into my Android app (authenticating to Firebase). I am requesting "email" and "public_profile" permissions. I am testing this on a phone without the Facebook app, so the following is happening in Chrome through facebook.com.

The first time the user clicks the LoginButton he is asked to accept permissions. After doing so he is returned to my app and authentication is successful.

After that, however, when the user clicks the LoginButton again, he is shown a screen saying "You have already authorised ..."

I want this step to be skipped ff the user already did authorised my app, but how?

答: U can't , better way is to make first login from facebook ,then ask them to make login id and password for your app .don't make them login again with facebook</p>


问:
how to monitor JVM on cloud applications
we are using cloud applications say spark with jre1.8
i want to know JVM of my spark instance and same need to be monitored using nagios core server.
can you please share inputs to view JVM stats.
i noticed, jstat command will be used to know JVM but unfortunately jstat is not working on jre.</p>

答: You can use Jprofiler to monitor the server.</p>


问:
I can't put a CSS class on a template
I'm reading a book about Angular 2 and one of the chapters is about Forms. I'm using Semantic UI Framework and when I put a class, specify the "error" class the div is disappear. Is very very strange I don't know what happened. I have to mention what works perfectly if I replace "error" class with another like "negative" for instead.</p>

```<code>import { Component } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators,
  AbstractControl,
  FormControl
} from '@angular/forms';

@Component({
  selector: 'demo-form-sku-builder',
  template: `
  <div class="ui raised segment">
    <h2 class="ui header">Demo Form: Sku with Builder</h2>
    <form [formGroup]="myForm"
      (ngSubmit)="onSubmit(myForm.value)"
      class="ui form">

      <div class="field"
        [class.error]="!sku.valid && sku.touched">
        <label for="skuInput">SKU</label>
        <input type="text"
          id="skuInput"
          placeholder="SKU"
          [formControl]="myForm.controls['sku']">
        <div *ngIf="!sku.valid"
          class="ui error message">SKU is invalid</div>
        <div *ngIf="!sku.hasError('required')"
          class="ui error message">SKU is required</div>
      </div>

    <button type="submit" class="ui button">Submit</button>
    </form>
  </div>
  `
})
export class DemoFormSkuBuilder {
  myForm: FormGroup;
  sku: AbstractControl;

  constructor(fb: FormBuilder) {
    this.myForm = fb.group({
      'sku': ['', Validators.required]
    });

    this.sku = this.myForm.controls['sku'];
  }

  onSubmit(value: string): void {
    console.log('you submitted value: ', value);
  }
}
</code>```

答:
Is this if statement backwards?

```<code><div *ngIf="!sku.hasError('required')"
      class="ui error message">SKU is required</div>
</code>```

Shouldn't it be:

```<code><div *ngIf="sku.hasError('required')"
      class="ui error message">SKU is required</div>
</code>```

Without the not operator?

Title: I can't put a CSS class on a template

Body:
I'm reading a book about Angular 2 and one of the chapters is about Forms. I'm using Semantic UI Framework and when I put a class, specify the "error" class the div is disappear. Is very very strange I don't know what happened. I have to mention what works perfectly if I replace "error" class with another like "negative" for instead.

import { Component } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators,
  AbstractControl,
  FormControl
} from '@angular/forms';

@Component({
  selector: 'demo-form-sku-builder',
  template: `

Demo Form: Sku with Builder

    <form [formGroup]="myForm"
      (ngSubmit)="onSubmit(myForm.value)"
      class="ui form">

        SKU
        <input type="text"
          id="skuInput"
          placeholder="SKU"
          [formControl]="myForm.controls['sku']">

SKU is invalid

SKU is required

    <button type="submit" class="ui button">Submit</button>
    </form>

  `
})
export class DemoFormSkuBuilder {
  myForm: FormGroup;
  sku: AbstractControl;

  constructor(fb: FormBuilder) {
    this.myForm = fb.group({
      'sku': ['', Validators.required]
    });

    this.sku = this.myForm.controls['sku'];
  }

  onSubmit(value: string): void {
    console.log('you submitted value: ', value);
  }
}

Body:
Is this if statement backwards?

<div *ngIf="!sku.hasError('required')"
      class="ui error message">SKU is required</div>

Shouldn't it be:

<div *ngIf="sku.hasError('required')"
      class="ui error message">SKU is required</div>

Without the not operator?


问:
Template tag polyfill for IE 11 - not working with table tr and td
I work with polyfill js that allows to process  tags for browsers that does not support it.

Source code of polyfill on jsfiddle

Source question

But I've noticed that in IE 11 this polyfill fails to work with templates that include
 and  tags

My sample on jsfiddle

The problem is that when we try to get childNodes from template tag node

```<code>elPlate.childNodes
</code>```

it returns everything but
 and  children as if there were no such tags inside <template>.

Am I missing something? Is there any workarounds for this issue?

P.S I was not able to add a comment to source issue due to lack of reputation. Sorry for that.

答:
You can work your way around it if you really want to work with
 in templates in IE11.

What you do is, instead of putting the
 directly in the templates, you put in an entire table like so

```<code><template>
   <table>
      <tr>
         //foo bar
      </tr>
   </table>
</template>
</code>```

This causes IE11 to no longer "correct" your HTML and return it as is. Once you cloned the HTML from the template, you can then extract the
 correctly out of the table and use it wherever it's needed.

Body:
I work with polyfill js that allows to process  tags for browsers that does not support it.

Source code of polyfill on jsfiddle

Source question

But I've noticed that in IE 11 this polyfill fails to work with templates that include
 and  tags

My sample on jsfiddle

The problem is that when we try to get childNodes from template tag node

elPlate.childNodes

it returns everything but
 and  children as if there were no such tags inside <template>.

Am I missing something? Is there any workarounds for this issue?

P.S I was not able to add a comment to source issue due to lack of reputation. Sorry for that.

Body:
You can work your way around it if you really want to work with <tr> in templates in IE11.

What you do is, instead of putting the <tr> directly in the templates, you put in an entire table like so

<template>
   <table>
      <tr>
         //foo bar
      </tr>
   </table>
</template>

This causes IE11 to no longer "correct" your HTML and return it as is. Once you cloned the HTML from the template, you can then extract the <tr> correctly out of the table and use it wherever it's needed.


问:
Qt/QML SwipeDelegate doesn't work properly on mobile devices (Android, iOS)
I'm new to Qt/QML programming and am trying to get the following example to run properly on a mobile device. When I try to "swipe right" and then tap the remove button, the "Listview-item" will not be deleted. On Desktop all works fine, but on a mobile device it doesn't work properly. Can anyone help me with my problem?</p>

```<code>import QtQuick 2.7
import QtQuick.Controls 2.0

ApplicationWindow {
    id: appWindow
    visible: true

    ListView {
        id: listView
        anchors.fill: parent
        model: ListModel {
            ListElement { name: "Swipe Delegate - Test 1" }
            ListElement { name: "Swipe Delegate - Test 2" }
            ListElement { name: "Swipe Delegate - Test 3" }
            ListElement { name: "Swipe Delegate - Test 4" }
        }
        delegate: SwipeDelegate {
            id: swipeDelegate
            text: model.name
            width: parent.width

            ListView.onRemove: SequentialAnimation {
                PropertyAction {
                    target: swipeDelegate
                    property: "ListView.delayRemove"
                    value: true
                }
                NumberAnimation {
                    target: swipeDelegate
                    property: "height"
                    to: 0
                    easing.type: Easing.InOutQuad
                }
                PropertyAction {
                    target: swipeDelegate;
                    property: "ListView.delayRemove";
                    value: false
                }
            }

            swipe.right: Label {
                id: deleteLabel
                text: qsTr("Delete")
                color: "white"
                verticalAlignment: Label.AlignVCenter
                padding: 12
                height: parent.height
                anchors.right: parent.right

                SwipeDelegate.onClicked: listView.model.remove(index)

                background: Rectangle {
                    color: deleteLabel.SwipeDelegate.pressed ? Qt.darker("tomato", 1.1) : "tomato"
                }
            }
        }
    }
}
</code>```

答:
You can add a MouseArea with an onClicked-event inside the Rectangle. Here is the example: </p>

```<code> background: Rectangle {
                color: deleteLabel.SwipeDelegate.pressed ? Qt.darker("tomato", 1.1) : "tomato"
                MouseArea {
                    anchors.fill: parent
                    onClicked: listView.model.remove(index)
                }
}
</code>```

Body:
I'm new to Qt/QML programming and am trying to get the following example to run properly on a mobile device. When I try to "swipe right" and then tap the remove button, the "Listview-item" will not be deleted. On Desktop all works fine, but on a mobile device it doesn't work properly. Can anyone help me with my problem?

import QtQuick 2.7
import QtQuick.Controls 2.0

ApplicationWindow {
    id: appWindow
    visible: true

    ListView {
        id: listView
        anchors.fill: parent
        model: ListModel {
            ListElement { name: "Swipe Delegate - Test 1" }
            ListElement { name: "Swipe Delegate - Test 2" }
            ListElement { name: "Swipe Delegate - Test 3" }
            ListElement { name: "Swipe Delegate - Test 4" }
        }
        delegate: SwipeDelegate {
            id: swipeDelegate
            text: model.name
            width: parent.width

            ListView.onRemove: SequentialAnimation {
                PropertyAction {
                    target: swipeDelegate
                    property: "ListView.delayRemove"
                    value: true
                }
                NumberAnimation {
                    target: swipeDelegate
                    property: "height"
                    to: 0
                    easing.type: Easing.InOutQuad
                }
                PropertyAction {
                    target: swipeDelegate;
                    property: "ListView.delayRemove";
                    value: false
                }
            }

            swipe.right: Label {
                id: deleteLabel
                text: qsTr("Delete")
                color: "white"
                verticalAlignment: Label.AlignVCenter
                padding: 12
                height: parent.height
                anchors.right: parent.right

                SwipeDelegate.onClicked: listView.model.remove(index)

                background: Rectangle {
                    color: deleteLabel.SwipeDelegate.pressed ? Qt.darker("tomato", 1.1) : "tomato"
                }
            }
        }
    }
}

Body:
You can add a MouseArea with an onClicked-event inside the Rectangle. Here is the example:

 background: Rectangle {
                color: deleteLabel.SwipeDelegate.pressed ? Qt.darker("tomato", 1.1) : "tomato"
                MouseArea {
                    anchors.fill: parent
                    onClicked: listView.model.remove(index)
                }
}


问:
Can an endless/perpetual counter be built using jQuery?
A client asks:

...Our company hauls sand and to date, we've hauled 1.7 billion
  pounds and counting. I am looking to have a counter made; it needs to be
  continuously counting and not revert back to the original number after
  the page is refreshed. I need the counter to start at 1.7 billion
  pounds and be adding 154 pounds per second.

Would there need to be a data source, or would such a calculation be tied to time? (eg: current server time)

I assuming there's probably a need to lock-in the current actual value, so the calculation would need to be adjusted weekly/monthly to reflect what's real. But it's really only SAND (not rocket science).

答:
Yes easy.</p>

```<code>var startDate = new Date("2017-03-01T01:10:00");
var vStart =1700000000
var vPerSec = 151

setInterval(function(){
    var timeDiffSec = (new Date.getTime()-startDate.getTime())/1000
   var vCur = vStart +( timeDiffSec * vPerSec);
},1000);
   document.write(vCur);
</code>```

Body:
Yes easy.

var startDate = new Date("2017-03-01T01:10:00");
var vStart =1700000000
var vPerSec = 151

setInterval(function(){
    var timeDiffSec = (new Date.getTime()-startDate.getTime())/1000
   var vCur = vStart +( timeDiffSec * vPerSec);
},1000);
   document.write(vCur);


问:
How to fix linker error "cannot find crt1.o"?
I have a virtual Debian system which I use to develop. Today I wanted to try llvm/clang. After installing clang I can't compile my old c-projects (with gcc).

This is the error:

/usr/bin/ld: cannot find crt1.o: No such file or directory
/usr/bin/ld: cannot find crti.o: No such file or directory
collect2: ld returned 1 exit status
```

I uninstalled clang and it still did not work. Does anyone have any idea how I can fix this?

答:
This worked for me with Ubuntu 16.04</p>
```<code>$ export LIBRARY_PATH=/usr/lib/x86_64-linux-gnu
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a virtual Debian system which I use to develop. Today I wanted to try llvm/clang. After installing clang I can't compile my old c-projects (with gcc).

This is the error:

/usr/bin/ld: cannot find crt1.o: No such file or directory
/usr/bin/ld: cannot find crti.o: No such file or directory
collect2: ld returned 1 exit status

I uninstalled clang and it still did not work. Does anyone have any idea how I can fix this?

Body:
This worked for me with Ubuntu 16.04

$ export LIBRARY_PATH=/usr/lib/x86_64-linux-gnu


问:
how to print reverse number pattern triangle in java
This is my code:

```<code>for (int i = 4; i >= 1; i--) {
    for (int j = 1; j < i; j++) {
        System.out.print(" ");
    }
    for (int k = i; k <= 4; k++) {
        System.out.print(k+"");
    }
    System.out.println();
}
</code>```

Current output:

```<code>   4
  34
 234
1234
</code>```

Desired output:

```<code>   1
  21
 321
4321
</code>```

What changes are necessary in order for me to get the desired output as shown above?

答:
You did every thing right, just the last for should have a very minor change:</p>

```<code>for (int k = 5-i; k >= 1; k--){
</code>```

Body:
This is my code:

for (int i = 4; i >= 1; i--) {
    for (int j = 1; j < i; j++) {
        System.out.print(" ");
    }
    for (int k = i; k <= 4; k++) {
        System.out.print(k+"");
    }
    System.out.println();
}

Current output:

   4
  34
 234
1234

Desired output:

   1
  21
 321
4321

What changes are necessary in order for me to get the desired output as shown above?

Body:
You did every thing right, just the last for should have a very minor change:

for (int k = 5-i; k >= 1; k--){


问:
Tree and its preorder traversal - Code error
```<code>#include<iostream>
#include<stdio.h>
#include<conio.h>
using namespace std;

struct Node  //Tree Node
{
    int key;
    struct Node *left;
    struct Node *right;
};

int nodes[21], counter; //nodes[] array keeps all the nodes of the tree
                        //in increasing order
                        //counter tracks the current index of the array

void preorder(Node* node){    //Preorder traversal of the tree
    if(node==NULL){
        return;
    }
    preorder(node->left);
    nodes[counter++]=node->key;
    preorder(node->right);
}

struct Node* createNode(int key){     //Tree Node Creation
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->key = key;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

void createTree(struct Node* newNode, struct Node* node){  //Creates a
                                                     //binary search tree
    if(!node){
        node=newNode;    //Problem Line
        return;
    }
    if(newNode->key<node->key){
        createTree(newNode, node->left);
    }
    else if(newNode->key>node->key){
        createTree(newNode, node->right);
    }
}

int main(){
    int node_count, node_value;
    struct Node* root = NULL;
    cout<<"Enter number of nodes"<<endl;
    cin>>node_count;
    cout<<"Enter node values in a space-separated format"<<endl;
    for(int i=0;i<node_count;i++){
        cin>>node_value;
        struct Node* newNode = createNode(node_value);
        if(!root){
            root = newNode;
        }
        else{
            createTree(newNode, root);
        }
        cout<<root->left<<" "<<root->right<<endl;
    }
    counter=0;
    preorder(root);
    for(int i=0;i<counter;i++){
        cout<<nodes[i]<<" ";
    }
    cout<<endl;

    getch();
    return 0;
}
</code>```

<p>Above is the code for creating a BST and then storing its preorder traversal in an array. I have mentioned the problem line(the assignment of the pointer is not happening). Can someone, please help me out with this. </p>

答:
You do not assing any node to left and right pointers.
This should solve the problem.</p>

```<code>void createTree(struct Node* newNode, struct Node* node) {
    if (!node) {
        node = newNode;
        return;
    }

    if (newNode->key < node->key) {
        // if left node is null assign new node
        if (!node->left) {
            node->left = newNode;
            return;
        }
        else {
            createTree(newNode, node->left);
        }
    }
    else if (newNode->key > node->key) {
        // if right node is null assign new node
        if (!node->right) {
            node->right = newNode;
            return;
        }
        else {
            createTree(newNode, node->right);
        }
    }
}
</code>```

Body:
#include<iostream>
#include<stdio.h>
#include<conio.h>
using namespace std;

struct Node  //Tree Node
{
    int key;
    struct Node *left;
    struct Node *right;
};

int nodes[21], counter; //nodes[] array keeps all the nodes of the tree
                        //in increasing order
                        //counter tracks the current index of the array

void preorder(Node* node){    //Preorder traversal of the tree
    if(node==NULL){
        return;
    }
    preorder(node->left);
    nodes[counter++]=node->key;
    preorder(node->right);
}

struct Node* createNode(int key){     //Tree Node Creation
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->key = key;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

void createTree(struct Node* newNode, struct Node* node){  //Creates a
                                                     //binary search tree
    if(!node){
        node=newNode;    //Problem Line
        return;
    }
    if(newNode->key<node->key){
        createTree(newNode, node->left);
    }
    else if(newNode->key>node->key){
        createTree(newNode, node->right);
    }
}

int main(){
    int node_count, node_value;
    struct Node* root = NULL;
    cout<<"Enter number of nodes"<<endl;
    cin>>node_count;
    cout<<"Enter node values in a space-separated format"<<endl;
    for(int i=0;i<node_count;i++){
        cin>>node_value;
        struct Node* newNode = createNode(node_value);
        if(!root){
            root = newNode;
        }
        else{
            createTree(newNode, root);
        }
        cout<<root->left<<" "<<root->right<<endl;
    }
    counter=0;
    preorder(root);
    for(int i=0;i<counter;i++){
        cout<<nodes[i]<<" ";
    }
    cout<<endl;

    getch();
    return 0;
}

Above is the code for creating a BST and then storing its preorder traversal in an array. I have mentioned the problem line(the assignment of the pointer is not happening). Can someone, please help me out with this.

Body:
You do not assing any node to left and right pointers.
This should solve the problem.

void createTree(struct Node* newNode, struct Node* node) {
    if (!node) {
        node = newNode;
        return;
    }

    if (newNode->key < node->key) {
        // if left node is null assign new node
        if (!node->left) {
            node->left = newNode;
            return;
        }
        else {
            createTree(newNode, node->left);
        }
    }
    else if (newNode->key > node->key) {
        // if right node is null assign new node
        if (!node->right) {
            node->right = newNode;
            return;
        }
        else {
            createTree(newNode, node->right);
        }
    }
}


问:
Append addition String to SimpleCursorAdapter
I want to append a String to an ID that I pull from my database into a Cursor. I have a ListView with 2 item and I want the text to write Id+" some text". I use SimpleCursorAdapter and simple_list_item_2.</p>

```<code>final Cursor data=myDb.vrniKorFaktor();
 if(data.getCount()==0) {
        Toast.makeText(KorFaktor.this, "Ni podatkov", Toast.LENGTH_SHORT).show();
    }else{
        while (data.moveToNext()){
            idFaktorja.add(data.getInt(0));
            String[] faktorji= new String[]{"_id","korfaktor" };
            int[] toViewId=new int[]{android.R.id.text1,android.R.id.text2};

            SimpleCursorAdapter adapter=new SimpleCursorAdapter(getBaseContext(),android.R.layout.simple_list_item_2, data, faktorji, toViewId );
            list.setAdapter(adapter);

        }
    }
</code>```

答:
Assuming you have "_id","korfaktor" these two as your column name. You can use '||' operator to append some string to your _id. So your query is like below.

Query

```<code>select _id ||" hello" as _id , korfaktor from your_table_name
</code>```

Note : " hello" you can replace the string your version.

Hope this works for you.

Body:
I want to append a String to an ID that I pull from my database into a Cursor. I have a ListView with 2 item and I want the text to write Id+" some text". I use SimpleCursorAdapter and simple_list_item_2.

final Cursor data=myDb.vrniKorFaktor();
 if(data.getCount()==0) {
        Toast.makeText(KorFaktor.this, "Ni podatkov", Toast.LENGTH_SHORT).show();
    }else{
        while (data.moveToNext()){
            idFaktorja.add(data.getInt(0));
            String[] faktorji= new String[]{"_id","korfaktor" };
            int[] toViewId=new int[]{android.R.id.text1,android.R.id.text2};

            SimpleCursorAdapter adapter=new SimpleCursorAdapter(getBaseContext(),android.R.layout.simple_list_item_2, data, faktorji, toViewId );
            list.setAdapter(adapter);

        }
    }

Body:
Assuming you have "_id","korfaktor" these two as your column name. You can use '||' operator to append some string to your _id. So your query is like below.

Query

select _id ||" hello" as _id , korfaktor from your_table_name

Note : " hello" you can replace the string your version.

Hope this works for you.


问:
Singleton pattern by using Unity
Unity allows to create a singleton with:

```<code>this.UnityContainer.RegisterType<MyClass>(new ContainerControlledLifetimeManager());
var instance = this.UnityContainer.Resolve<MyClass>();
</code>```

The access to the MyClass's constructor must be public to allow the container to be able to create a new instance (for another project like a module, ...).

In this case, developers can still create a new instance by using the constructor directly:

```<code>var instance = new MyClass();
</code>```

How do I prevent developers from doing this?

Another way is to create an instance (constructor access of the class is private now - singleton pattern) and register it with unity like below, I lose the dependency property injection, and my workaround is to use the service locator to initialize the dependency properties in the static method Instance:

```<code>this.UnityContainer.RegisterInstance<MyClass>(MyClass.Instance);
</code>```

What is the best way to define the singleton pattern in both cases simultaneous (with and without unity)?

答:
Hide the class away from your users if you want to prevent them from creating it.

That means creating a public interface for your class, while the class itself is not public. Having an interface for your service is a good idea anyway, think of unit testing, for example...

Several options come to mind for the non-publicness of your service implementation:

put it in a different assembly and make it internal

put it in another class and make it private

But be aware of the fact that malicious users can always use reflection to create their own instances... no 100% safety.

Title: Singleton pattern by using Unity

Body:
Unity allows to create a singleton with:

this.UnityContainer.RegisterType<MyClass>(new ContainerControlledLifetimeManager());
var instance = this.UnityContainer.Resolve<MyClass>();

The access to the MyClass's constructor must be public to allow the container to be able to create a new instance (for another project like a module, ...).

In this case, developers can still create a new instance by using the constructor directly:

var instance = new MyClass();

How do I prevent developers from doing this?

Another way is to create an instance (constructor access of the class is private now - singleton pattern) and register it with unity like below, I lose the dependency property injection, and my workaround is to use the service locator to initialize the dependency properties in the static method Instance:

this.UnityContainer.RegisterInstance<MyClass>(MyClass.Instance);

What is the best way to define the singleton pattern in both cases simultaneous (with and without unity)?


问:
How can I normalize colormap in matplotlib scatter plot?
The matplotlib documentation explain in detail how to normalize colormaps for a pcolormesh, but how can I correctly do it for a scatter plot?

```<code>normalize = mcolors.Normalize(vmin=-1, vmax=1)
plt.scatter(x,y,z,cmap=colormap(normalize),marker='*',s=5)
</code>```

doesn't work (TypeError: Cannot cast array data from dtype('O') to dtype('int64') according to the rule 'safe')

it's just that the z data are not exactly from -1 to 1, I am plotting multiple datasets that have the limits around +/- 0.93 - 98, but I want the colours to be centered at zero and go from -1 to 1 so that I have the same reference for all the various datasets.

Oh, and when I don't attempt to normalize, I get TypeError: scatter() got multiple values for keyword argument 's'. Clearly I don't know how to use colormap in scatter plots.

答:
The syntax you're using is completely different to the one in the linked documentation. There is essentially no difference between normalizing a scatter or a pcolor(mesh) or just any other scalar mappable object.

It's always

```<code>colormap = plt.cm.bwr #or any other colormap
normalize = matplotlib.colors.Normalize(vmin=-1, vmax=1)
plt.scatter(x, y, c=z, s=5, cmap=colormap, norm=normalize, marker='*')
</code>```

Body:
The matplotlib documentation explain in detail how to normalize colormaps for a pcolormesh, but how can I correctly do it for a scatter plot?

normalize = mcolors.Normalize(vmin=-1, vmax=1)
plt.scatter(x,y,z,cmap=colormap(normalize),marker='*',s=5)

doesn't work (TypeError: Cannot cast array data from dtype('O') to dtype('int64') according to the rule 'safe')

it's just that the z data are not exactly from -1 to 1, I am plotting multiple datasets that have the limits around +/- 0.93 - 98, but I want the colours to be centered at zero and go from -1 to 1 so that I have the same reference for all the various datasets.

Oh, and when I don't attempt to normalize, I get TypeError: scatter() got multiple values for keyword argument 's'. Clearly I don't know how to use colormap in scatter plots.

Body:
The syntax you're using is completely different to the one in the linked documentation. There is essentially no difference between normalizing a scatter or a pcolor(mesh) or just any other scalar mappable object.

It's always

colormap = plt.cm.bwr #or any other colormap
normalize = matplotlib.colors.Normalize(vmin=-1, vmax=1)
plt.scatter(x, y, c=z, s=5, cmap=colormap, norm=normalize, marker='*')


问:
Adding values at the end of horizontal bar plots
I'm trying to annotate values at the end of my horizontal bar plot given by:

```<code>UK.groupby(['College/University']).size().sort_values(ascending=True).plot(kind='barh',figsize=(8,8),title='UK Uni')
</code>```

If this helps:
y=list(UK.groupby(['College/University']).size())
returns
[2, 1, 5, 2, 6, 1, 13, 1, 4, 1, 1, 1, 11, 1, 1, 2, 12]

Any idea? :)

答:
Use can use matplotlib's annotation functionality for that:

```<code>sizes = UK.groupby(['College/University']).size().sort_values(ascending=True)
sizes.plot(kind='barh',figsize=(8,8),title='UK Uni')

for y, x in enumerate(sizes['size']):
    plt.annotate(str(x), xy=(x, y), va='center')
</code>```

Body:
I'm trying to annotate values at the end of my horizontal bar plot given by:

UK.groupby(['College/University']).size().sort_values(ascending=True).plot(kind='barh',figsize=(8,8),title='UK Uni')

If this helps:
y=list(UK.groupby(['College/University']).size())
returns
[2, 1, 5, 2, 6, 1, 13, 1, 4, 1, 1, 1, 11, 1, 1, 2, 12]

Any idea? :)

Body:
Use can use matplotlib's annotation functionality for that:

sizes = UK.groupby(['College/University']).size().sort_values(ascending=True)
sizes.plot(kind='barh',figsize=(8,8),title='UK Uni')

for y, x in enumerate(sizes['size']):
    plt.annotate(str(x), xy=(x, y), va='center')


问:
How to enumerate an enum?
How can you enumerate an enum in C#?

E.g. the following code does not compile:

public enum Suit
{
    Spades,
    Hearts,
    Clubs,
    Diamonds
}

public void EnumerateAllSuitsDemoMethod()
{
    foreach (Suit suit in Suit)
    {
        DoSomething(suit);
    }
}
```

And it gives the following compile-time error:

'Suit' is a 'type' but is used like a 'variable'

It fails on the Suit keyword, the second one.

答:
Add method public static IEnumerable<T> GetValues<T>() to your class, like:

```<code>public static IEnumerable<T> GetValues<T>()
{
    return Enum.GetValues(typeof(T)).Cast<T>();
}
</code>```

Call and pass your enum. Now you can iterate through it using foreach:

```<code> public static void EnumerateAllSuitsDemoMethod()
 {
     // Custom method
     var foos = GetValues<Suit>();
     foreach (var foo in foos)
     {
         // Do something
     }
 }
</code>```

Title: How to enumerate an enum?

Body:
How can you enumerate an enum in C#?

E.g. the following code does not compile:

public enum Suit
{
    Spades,
    Hearts,
    Clubs,
    Diamonds
}

public void EnumerateAllSuitsDemoMethod()
{
    foreach (Suit suit in Suit)
    {
        DoSomething(suit);
    }
}

And it gives the following compile-time error:

'Suit' is a 'type' but is used like a 'variable'

It fails on the Suit keyword, the second one.

LastEditorDisplayName: alexandrul

Body:
Add method public static IEnumerable<T> GetValues<T>() to your class, like:

public static IEnumerable<T> GetValues<T>()
{
    return Enum.GetValues(typeof(T)).Cast<T>();
}

Call and pass your enum. Now you can iterate through it using foreach:

 public static void EnumerateAllSuitsDemoMethod()
 {
     // Custom method
     var foos = GetValues<Suit>();
     foreach (var foo in foos)
     {
         // Do something
     }
 }


问:
How to get a specific part of a string in Javascript?
I have a string:

```<code>string = 'XXXXXXXXXXXXtext:hello,XXXXXXX'
</code>```

I want to retrieve hello. XXXXXXXX is some random text. The only thing I know is that hello is between text: and ,.

答:
You can use a regular expression to retrieve the text you need. Try this:

var str = 'XXXXXXXXXXXXtext:hello,XXXXXXX';
var matches = /text\:(.+),/gi.exec(str);

console.log(matches[1]);```

If there are multiple instances of text: within your string then you can use a loop to iterate through the result of exec() and retrieve them all.

Body:
I have a string:

string = 'XXXXXXXXXXXXtext:hello,XXXXXXX'

I want to retrieve hello. XXXXXXXX is some random text. The only thing I know is that hello is between text: and ,.

Body:
You can use a regular expression to retrieve the text you need. Try this:

var str = 'XXXXXXXXXXXXtext:hello,XXXXXXX';
var matches = /text\:(.+),/gi.exec(str);

console.log(matches[1]);

If there are multiple instances of text: within your string then you can use a loop to iterate through the result of exec() and retrieve them all.


问:
Displaying JSON object on blade template
I'm trying to display a JSON object that is returned to my blade template that should look the output below

```<code>2007 | Kanye | UltralightBeam
2008 | JayZ  | 99 Problems
</code>```

JSON looks like this

```<code>{
    "2007":{
        "name" : "Kanye",
        "song" : "UltralightBeam"
    },
    "2008":{
        "name" : "JayZ",
        "song" : "99 Problems"
    }
}
</code>```

So far I have something like this that shows the name and song

```<code>@foreach($data['data_obj'] as $obj)
    {{$obj['name']}} | {{$obj['song']}}
@endforeach
</code>```

But I'm just not sure how I can get it to show the year as well?

Any guidance would be appreciated. Thank you!

答:
you could use this

```<code> @foreach ($data['data_obj'] as $year => $obj)
 {{ $year }} | {{ $obj->name }} | {{ $obj->song }}
 @endforeach
</code>```

Body:
I'm trying to display a JSON object that is returned to my blade template that should look the output below

2007 | Kanye | UltralightBeam
2008 | JayZ  | 99 Problems

JSON looks like this

{
    "2007":{
        "name" : "Kanye",
        "song" : "UltralightBeam"
    },
    "2008":{
        "name" : "JayZ",
        "song" : "99 Problems"
    }
}

So far I have something like this that shows the name and song

@foreach($data['data_obj'] as $obj)
    {{$obj['name']}} | {{$obj['song']}}
@endforeach

But I'm just not sure how I can get it to show the year as well?

Any guidance would be appreciated. Thank you!

Body:
you could use this

 @foreach ($data['data_obj'] as $year => $obj)
 {{ $year }} | {{ $obj->name }} | {{ $obj->song }}
 @endforeach