问:
enable_shared_from_this - empty internal weak pointer?
I'm using enable_shared_from_this<Base> and then inherit from Base. When trying to use shared_from_this() in Derived's constructor (not initializer list), I get an exception. Turns out that the internal weak pointer is null and doesn't point to this at all. How can this happen? My other use case of exactly this works perfectly fine. I don't even know where to start. I looked down at the source code of enable_shared_from_this, and it looks to me like that pointer would always be nullptr.

答:
You cannot call shared_from_this() in the object's constructor.  shared_from_this() requires that the object is owned by at least one shared_ptr.  An object cannot be owned by a shared_ptr before it is constructed.

I would guess that the internal weak pointer is set when a shared_ptr takes ownership of the object for the first time.  Before that point, there is no reference count struct that the weak pointer can reference.


来源: stackexchange

问:
No resource identifier found for attribute 'text color' in package 'android' --- When building
I am new and now using Android Studio. I have created single page design using XML but when i run the code using the emulator this message appears:

Information:Gradle tasks [:app:assembleDebug]
  C:\Users\MHTAREQ\AndroidStudioProjects\JustJava\app\src\main\res\layout\activity_main.xml
  Error:(10) No resource identifier found for attribute 'fontColor' in
  package 'android' Error:(21) No resource identifier found for
  attribute 'fontColor' in package 'android'

C:\Users\MHTAREQ\AndroidStudioProjects\JustJava\app\build\intermediates\res\merged\debug\layout\activity_main.xml

Error:(10) No resource identifier found for attribute 'fontColor' in
  package 'android' Error:(21) No resource identifier found for
  attribute 'fontColor' in package 'android' Error:Execution failed for
  task ':app:processDebugResources'.

com.android.ide.common.process.ProcessException: Failed to execute aapt Information:BUILD FAILED Information:Total time: 1 mins 25.346 secs Information:5 errors Information:0 warnings Information:See complete output in console

Here is the XML code:

```<code>xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.justjava.MainActivity">

<TextView
    android:id="@+id/quantity_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="quantity"
    android:textAllCaps="true"
    android:textSize="16sp"
    android:fontColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<TextView
    android:id="@+id/zero_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    android:layout_below="@+id/quantity_text_view"
    android:textSize="16sp"
    android:fontColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="order"
    android:textAllCaps="true"
    android:layout_below="@+id/zero_text_view"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"
    android:onClick="submitOrder"/>
</code>```

Please help.

答: try using android:textColor tag instead of fontColor</p>

ContentLicense: CC BY-SA 3.0

Body:
I am new and now using Android Studio. I have created single page design using XML but when i run the code using the emulator this message appears:

Information:Gradle tasks [:app:assembleDebug]
  C:\Users\MHTAREQ\AndroidStudioProjects\JustJava\app\src\main\res\layout\activity_main.xml
  Error:(10) No resource identifier found for attribute 'fontColor' in
  package 'android' Error:(21) No resource identifier found for
  attribute 'fontColor' in package 'android'

C:\Users\MHTAREQ\AndroidStudioProjects\JustJava\app\build\intermediates\res\merged\debug\layout\activity_main.xml

Error:(10) No resource identifier found for attribute 'fontColor' in
  package 'android' Error:(21) No resource identifier found for
  attribute 'fontColor' in package 'android' Error:Execution failed for
  task ':app:processDebugResources'.

com.android.ide.common.process.ProcessException: Failed to execute aapt Information:BUILD FAILED Information:Total time: 1 mins 25.346 secs Information:5 errors Information:0 warnings Information:See complete output in console

Here is the XML code:

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.justjava.MainActivity">

<TextView
    android:id="@+id/quantity_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="quantity"
    android:textAllCaps="true"
    android:textSize="16sp"
    android:fontColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<TextView
    android:id="@+id/zero_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    android:layout_below="@+id/quantity_text_view"
    android:textSize="16sp"
    android:fontColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="order"
    android:textAllCaps="true"
    android:layout_below="@+id/zero_text_view"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"
    android:onClick="submitOrder"/>

Please help.


问:
Cordova camera plugin distorts aspect ratio
I'm having trouble with the Cordova camera plugin and ionic 2. Here is my code.

Camera.getPicture({
        targetWidth: 1500,
        targetHeight:2500,
        quality: 80,
        destinationType: Camera.DestinationType.DATA_URL,
        allowEdit: true,
        encodingType: Camera.EncodingType.JPEG,
        sourceType: Camera.PictureSourceType.CAMERA,
        correctOrientation: true
      })```

My problem is that as soon as the user changes the crop, the image distorts. If I make the width and height the same, then it makes a square and doesn't allow the box size to change and the crop works fine, but with different values for width and height, it allows the user to edit the box ration and then it distorts the image.

Am I missing a trick here? It feels like it shouldn't allow me to modify the cropping box size?

答:
I was facing the same problem, I have work around .

In my application,

I am not setting target width and height for plugin, as well as not using allowEdit option.

Instead of that I am taking base64 string from plugin, apply it on image and use cropper.js  for cropping capture image.

So I always get image with required aspect ratio.

Also for better user experience I am applying face detection using external js as like cropper.js

Hope this will help you.

Body:
I'm having trouble with the Cordova camera plugin and ionic 2. Here is my code.

Camera.getPicture({
        targetWidth: 1500,
        targetHeight:2500,
        quality: 80,
        destinationType: Camera.DestinationType.DATA_URL,
        allowEdit: true,
        encodingType: Camera.EncodingType.JPEG,
        sourceType: Camera.PictureSourceType.CAMERA,
        correctOrientation: true
      })

My problem is that as soon as the user changes the crop, the image distorts. If I make the width and height the same, then it makes a square and doesn't allow the box size to change and the crop works fine, but with different values for width and height, it allows the user to edit the box ration and then it distorts the image.

Am I missing a trick here? It feels like it shouldn't allow me to modify the cropping box size?


问:
PayPal API with ASP.NET MVC
Is it the paypal API compatible with asp.net MVC?
Does anyone know of any expamples of how to implement it?
Thank you.</p>

答:
yes it is compatible.

Have a look at MVC Storefront Starter Kit videos.

Episode 22 is dedicated to Paypal

ContentLicense: CC BY-SA 2.5

Title: PayPal API with ASP.NET MVC


问:
IIS 7.5 redirect certain requests to other server using ip address
Here is a problem I have been struggling with for a while.

I host a website with the address www.mywebsite.com in server I but the images of the site come from server II (ip: 1.2.3.4) so if there are requests such as www.mywebsite.com/images/123.jpg I would like to redirect them to the image server(Server II).

I would like that requests that contain (.*jpg.*) regex will redirect to Server II.

Using Url rewrite I added a rule:

```<code><rewrite>
        <rules>
            <rule name="Ignore images requests" enabled="true" stopProcessing="true">
                <match url="(.*jpg.*)" />
                <action type="Rewrite" url="https://www.petfinder.com/wp-content/uploads/2012/11/91615172-find-a-lump-on-cats-skin-632x475.jpg" />
            </rule>
        </rules>
    </rewrite>
</code>```

It rewrites the request to a static image as you can see, how can I define it to go to 1.2.3.4/images/imagename.jpg?

The best solution would be if I could just ignore requests containing jpg via my host file, is there a way to that?

答:
You redirect rule should be like that:

```<code><rule name="image redirect" stopProcessing="true">
    <match url=".*" />
    <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" pattern="(.*?)\.jpg$" />
        <add input="{REQUEST_FILENAME}" matchType="IsFile" />
    </conditions>
  <action type="Redirect" url="http://1.2.3.4/{R:1}" appendQueryString="false" />
</rule>
</code>```

It will redirect all requests to files with .jpg extension to 1.2.3.4 domain
For example:

http://www.mywebsite.com/dog-1210559_960_720.jpg to http://1.2.3.4/dog-1210559_960_720.jpg

http://www.mywebsite.com/UserFiles/Entities/TopBanners/top50161616_586.jpg to http://1.2.3.4/UserFiles/Entities/TopBanners/top50161616_586.jpg

Body:
Here is a problem I have been struggling with for a while.

I host a website with the address www.mywebsite.com in server I but the images of the site come from server II (ip: 1.2.3.4) so if there are requests such as www.mywebsite.com/images/123.jpg I would like to redirect them to the image server(Server II).

I would like that requests that contain (.*jpg.*) regex will redirect to Server II.

Using Url rewrite I added a rule:

<rewrite>
        <rules>
            <rule name="Ignore images requests" enabled="true" stopProcessing="true">
                <match url="(.*jpg.*)" />
                <action type="Rewrite" url="https://www.petfinder.com/wp-content/uploads/2012/11/91615172-find-a-lump-on-cats-skin-632x475.jpg" />
            </rule>
        </rules>
    </rewrite>

It rewrites the request to a static image as you can see, how can I define it to go to 1.2.3.4/images/imagename.jpg?

The best solution would be if I could just ignore requests containing jpg via my host file, is there a way to that?

Body:
You redirect rule should be like that:

<rule name="image redirect" stopProcessing="true">
    <match url=".*" />
    <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" pattern="(.*?)\.jpg$" />
        <add input="{REQUEST_FILENAME}" matchType="IsFile" />
    </conditions>
  <action type="Redirect" url="http://1.2.3.4/{R:1}" appendQueryString="false" />
</rule>

It will redirect all requests to files with .jpg extension to 1.2.3.4 domain
For example:

http://www.mywebsite.com/dog-1210559_960_720.jpg to http://1.2.3.4/dog-1210559_960_720.jpg

http://www.mywebsite.com/UserFiles/Entities/TopBanners/top50161616_586.jpg to http://1.2.3.4/UserFiles/Entities/TopBanners/top50161616_586.jpg


问:
Targeting nested lists
Wanting to do a nested list. Where I can make the outer-list displayed as inline-block and the inner list and as a block. I must be targetting the classes of each list wrong because I'm not able to apply these preferences? thanks :)

.days ul li {
  display: inline-block
}

.points ul li {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li class="days">
    <h2>Title</h2>

    <ul class="points">
      <li>Point 1</li>
      <li>Point 2</li>
  </li>
  </ul>
</ul</code>```

答:
The selector in your CSS is wrong. You're selecting the ul "inside" element with .days and .points class. What you need is a li inside your ul element, in this case .days and .points.

Another problem is your html synthax. Only li can be ul descendant, so you need to put the second ul inside the li.

.days li {
  display: inline-block;
  width: 150px;
}

.points li {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="days">
  <li>
    <h2>Title</h2>
    <ul class="points">
      <li>Point 1</li>
      <li>Point 2</li>
    </ul>
  </li>
  <li>
    <h2>Title 2</h2>
    <ul class="points">
      <li>Point 1</li>
      <li>Point 2</li>
    </ul>
  </li>
</ul></code>```

Title: Targeting nested lists

Body:
Wanting to do a nested list. Where I can make the outer-list displayed as inline-block and the inner list and as a block. I must be targetting the classes of each list wrong because I'm not able to apply these preferences? thanks :)

.days ul li {
  display: inline-block
}

.points ul li {
  display: block;
}

Title

Point 1

Point 2

</ul

Body:
The selector in your CSS is wrong. You're selecting the ul "inside" element with .days and .points class. What you need is a li inside your ul element, in this case .days and .points.

Another problem is your html synthax. Only li can be ul descendant, so you need to put the second ul inside the li.

.days li {
  display: inline-block;
  width: 150px;
}

.points li {
  display: block;
}

<ul class="days">
  <li>
    <h2>Title</h2>
    <ul class="points">
      <li>Point 1</li>
      <li>Point 2</li>
    </ul>
  </li>
  <li>
    <h2>Title 2</h2>
    <ul class="points">
      <li>Point 1</li>
      <li>Point 2</li>
    </ul>
  </li>
</ul>


问:
Center buttons in middle of image
I try to make buttons that will be in the middle of the picture, but the problem is that either those buttons are in the middle of the page or under the picture. Any suggestions how to fix it and what I do wrong? https://jsfiddle.net/m5g16vt7/

* {
  box-sizing: border-box
}

body {
  font-family: Verdana, sans-serif;
  margin: 0
}

imageSlide-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}

.prev,
.next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -22px;
  color: pink;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
}

.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

.prev:hover,
.next:hover {
  background-color: rgba(0, 0, 0, 0.8)
}

@media only screen and (max-width: 300px) {
  .prev,
  .next,
  .text {
    font-size: 11px
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="imageSlide-container">
  <img class="imageSlide" src="img_nature_wide.jpg" style="width: 100%">

  ❮
  ❯
</div></code>```

答:
check below snippet

* {box-sizing:border-box}
   body {font-family: Verdana,sans-serif;margin:0}

        .imageSlide-container {
          max-width: 1000px;
          position: relative;
          margin: auto;
            }

   .prev, .next {
    cursor: pointer;
    position: absolute;
        top: 50%;
    width: auto;
    padding: 16px;
    margin-top: -22px;
    color: pink;
    font-weight: bold;
    font-size: 18px;
    transition: 0.6s ease;
    border-radius: 0 3px 3px 0;
        transform: translateY(-50%;)
   }
   .next {
    right: 0;
    border-radius: 3px 0 0 3px;
   }
   .prev:hover, .next:hover {
    background-color: rgba(0,0,0,0.8)
   }
            @media only screen and (max-width: 300px) {
     .prev, .next,.text {font-size: 11px}
     }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <meta name="viewport" content="width=device-width, initial-scale=1">
<div class="imageSlide-container">
   <img class="imageSlide" src="https://www.w3schools.com/howto/img_nature_wide.jpg" style="width: 100%">

      ❮
      ❯
</div></code>```

You forgot  to add . before class name  imageSlide-container in css
and you need to add transform: translateY(-50%;) and top:50% to adjust arrows vertically centered.

Title: Center buttons in middle of image

Body:
I try to make buttons that will be in the middle of the picture, but the problem is that either those buttons are in the middle of the page or under the picture. Any suggestions how to fix it and what I do wrong? https://jsfiddle.net/m5g16vt7/

* {
  box-sizing: border-box
}

body {
  font-family: Verdana, sans-serif;
  margin: 0
}

imageSlide-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}

.prev,
.next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -22px;
  color: pink;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
}

.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

.prev:hover,
.next:hover {
  background-color: rgba(0, 0, 0, 0.8)
}

@media only screen and (max-width: 300px) {
  .prev,
  .next,
  .text {
    font-size: 11px
  }
}

  ❮
  ❯

Body:
check below snippet

* {box-sizing:border-box}
   body {font-family: Verdana,sans-serif;margin:0}

        .imageSlide-container {
          max-width: 1000px;
          position: relative;
          margin: auto;
            }

   .prev, .next {
    cursor: pointer;
    position: absolute;
        top: 50%;
    width: auto;
    padding: 16px;
    margin-top: -22px;
    color: pink;
    font-weight: bold;
    font-size: 18px;
    transition: 0.6s ease;
    border-radius: 0 3px 3px 0;
        transform: translateY(-50%;)
   }
   .next {
    right: 0;
    border-radius: 3px 0 0 3px;
   }
   .prev:hover, .next:hover {
    background-color: rgba(0,0,0,0.8)
   }
            @media only screen and (max-width: 300px) {
     .prev, .next,.text {font-size: 11px}
     }

 <meta name="viewport" content="width=device-width, initial-scale=1">
<div class="imageSlide-container">
   <img class="imageSlide" src="https://www.w3schools.com/howto/img_nature_wide.jpg" style="width: 100%">

      <a class="prev" onclick="plusSlide-button(-1)">&#10094;</a>
      <a class="next" onclick="plusSlide-button(1)">&#10095;</a>
</div>

You forgot  to add . before class name  imageSlide-container in css
and you need to add transform: translateY(-50%;) and top:50% to adjust arrows vertically centered.


问:
Can't assign a specific class name to a collection of div's using JavaScript/jQuery
Hi ) I have a task and have done only a half of it, need some help:

need to make a board of 10/10 div's;

need to assign to each div a common class "box" and a specific one "box-x-y", where x and y are coordinates of the div;

I can't do the second task (the last half), for example for first div the class should be "box-1-1", and so on, like in the picture I have attached.
Image

  for(var i = 0; i < 10; i++) {
      for (var j = 0; j < 10; j++){
          $("

").addClass("box").appendTo("#carousel");
      }
      $("

").css("clear", "both").appendTo("#carousel");
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
    float:left;
    width:50px;
    height:50px;
    margin-right:2px;
    margin-bottom:2px;
    border: 1px solid black;
}</code>```

```

答:
You have already done the hardwork, create the class using string concatenation and then use addClass() method.

```<code>var cls = 'box-' + (i+1) + '-' + (j+1);
$("<div></div>").addClass("box").addClass(cls).appendTo("#carousel");
</code>```

Note: I have used text() for demo

for (var i = 0; i < 10; i++) {
  for (var j = 0; j < 10; j++) {
    var cls = 'box-' + (i+1) + '-' + (j+1);
    $("

").addClass("box").addClass(cls).text(cls).appendTo("#carousel");
  }
  $("

").css("clear", "both").appendTo("#carousel");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
  float: left;
  width: 50px;
  height: 50px;
  margin-right: 2px;
  margin-bottom: 2px;
  border: 1px solid black;
}</code>```

```

Body:
Hi ) I have a task and have done only a half of it, need some help:

need to make a board of 10/10 div's;

need to assign to each div a common class "box" and a specific one "box-x-y", where x and y are coordinates of the div;

I can't do the second task (the last half), for example for first div the class should be "box-1-1", and so on, like in the picture I have attached.
Image

  for(var i = 0; i < 10; i++) {
      for (var j = 0; j < 10; j++){
          $("

").addClass("box").appendTo("#carousel");
      }
      $("

").css("clear", "both").appendTo("#carousel");
  }

.box {
    float:left;
    width:50px;
    height:50px;
    margin-right:2px;
    margin-bottom:2px;
    border: 1px solid black;
}

Body:
You have already done the hardwork, create the class using string concatenation and then use addClass() method.

var cls = 'box-' + (i+1) + '-' + (j+1);
$("<div></div>").addClass("box").addClass(cls).appendTo("#carousel");

Note: I have used text() for demo

for (var i = 0; i < 10; i++) {
  for (var j = 0; j < 10; j++) {
    var cls = 'box-' + (i+1) + '-' + (j+1);
    $("<div></div>").addClass("box").addClass(cls).text(cls).appendTo("#carousel");
  }
  $("<div></div>").css("clear", "both").appendTo("#carousel");
}

.box {
  float: left;
  width: 50px;
  height: 50px;
  margin-right: 2px;
  margin-bottom: 2px;
  border: 1px solid black;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="carousel">

</div>


问:
Airport ticker effect in Adobe trials
When you run an Adobe product in a trial, a window appears each time asking if you have have a serial number yet or if you would like to continue with the trial. Next to that is a lovely 'number ticker', like the ones they used to have at airports (see image).

Does anyone know where I can get one of these, preferably gratis, to use as a component in a flex application?

答:
A very good looking component can be found here:

http://www.flashcomponents.net/component/sense_flip_clock_3d.html

It does cost 8$, though. :)

Title: Airport ticker effect in Adobe trials


问:
Issue with creating shaped div at 100% width
I am trying to create diagonal div, at the bottom of another div. It should look like this: http://storage8.static.itmages.com/i/17/0706/h_1499339517_4995911_421bf6ae42.png.

I have problem when I adding 100vw value to my border-left, because horizontal scrollbar appears on my website. I also tried use Jquery to find the width of the body. It works but when I resize my browser, border width does not change. Any suggestions how to fix it?

     var actualInnerWidth = $(".background-gradient").prop("clientWidth");
$('.background-gradient').css({
   'border-top':'50px solid red',
   'border-left': actualInnerWidth + 'px solid transparent'
}); ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    .banner {
   min-height: 50vh;
   margin: 0;
   padding:0;
   background-color: red;
 }
.background-gradient {
   width:100%;
   height:50px;
   background-color:yellow;
 }</code>```

```

Here is jsfiddle: https://jsfiddle.net/b49mmm9a/1/

答:
.kontainer {
  width: 100%;
  overflow: hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="kontainer">
  <div class="banner"></div>
 <div class="background-gradient"></div>
</div></code>```

Body:
I am trying to create diagonal div, at the bottom of another div. It should look like this: http://storage8.static.itmages.com/i/17/0706/h_1499339517_4995911_421bf6ae42.png.

I have problem when I adding 100vw value to my border-left, because horizontal scrollbar appears on my website. I also tried use Jquery to find the width of the body. It works but when I resize my browser, border width does not change. Any suggestions how to fix it?

     var actualInnerWidth = $(".background-gradient").prop("clientWidth");
$('.background-gradient').css({
   'border-top':'50px solid red',
   'border-left': actualInnerWidth + 'px solid transparent'
});

    .banner {
   min-height: 50vh;
   margin: 0;
   padding:0;
   background-color: red;
 }
.background-gradient {
   width:100%;
   height:50px;
   background-color:yellow;
 }

Here is jsfiddle: https://jsfiddle.net/b49mmm9a/1/

Body:
.kontainer {
  width: 100%;
  overflow: hidden;
}

<div class="kontainer">
  <div class="banner"></div>
 <div class="background-gradient"></div>
</div>


问:
Best way to insert users authorization on standard OSGi with Apache Karaf container and Play framewok
my web application based on standard OSGi with three different bundles that expose the API Rest (CXF library) for back-end otherwise Play framework for Front-end that calls the api exposed from three bundles before cited. Actually there is already authentication process by SSO and password with in front of an Apache proxy configured with virtual host listened on a port defined. How and where can I insert authorization layer to cover all three bundles that expose the API services ? What is your advise ?</p>

答: You can add a CXF interceptor . Just implement/override the common CXF interceptors to customize the authentification process.</p>


问:
I want to count all the rows for todays / yesterdays date based on a DATETIME - mysql+php
I have database "db2" with table "menjava"

In table menjava have "id", "author" and "date_submitted" field

id - auto_increment

author - int(11)

date_submitted - datetime

I want to count all the rows for todays date and all the rows for yesterdays date (so there will be two codes with conditions) based on a DATETIME field called 'date_submitted' that holds the date and time of each record's creation.

In the file result.php, there is this count displayed, but it does not work. In the same file (result.php) I have some other code to display data from different database, so I think that povezava.php is working ok.

My code:

```<code> <?
    require "povezava.php";
    $q=mysql_query(" SELECT COUNT(*) AS total_number FROM menjava
WHERE date_submitted >= DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)",$link2);
// now you can
if ( $nt = mysql_fetch_array($q)){
echo $nt["total_number"];
$q=mysql_query($nt) or die(mysql_error());
}

    ?>
</code>```

my file povezava.php looks like this:

```<code><?
$servername='localhost';

$dbusername='user';
$dbpassword='pass';

$dbname1='db1';
$dbname2='db2';

$link1 = connecttodb($servername,$dbname1,$dbusername,$dbpassword);
$link2 = connecttodb($servername,$dbname2,$dbusername,$dbpassword);

function connecttodb($servername,$dbname,$dbusername,$dbpassword)
{
    $link=mysql_connect ("$servername","$dbusername","$dbpassword",TRUE);
    if(!$link){die("Could not connect to MySQL");}
    mysql_select_db("$dbname",$link) or die ("could not open db".mysql_error());
    return $link;
}
    ?>
</code>```

Error that I get:

```<code>A PHP Error was encountered

Severity: NoticeMessage: Array to string conversionFilename: templates/master.phpLine Number: 231 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Array' at line 1
</code>```

Fixed:

```<code><?
    require "povezava.php";
    $q=mysql_query("SELECT COUNT(*) AS total_number FROM menjava WHERE date_submitted >= DATE_SUB(CURRENT_DATE(), INTERVAL 0 DAY)",$link2);
// working
if ( $nt = mysql_fetch_array($q)){
echo $nt["total_number"];
}

    ?>
</code>```

Thank you!

答:
Please try the following SQL commands:</p>

```<code>$sqlToday = "Select COUNT(*) FROM menjava WHERE DATE(date_submitted) = CURRENT_DATE()";

$sqlYesterday = "Select COUNT(*) FROM menjava WHERE DATE(dc_created) = CURDATE() - INTERVAL 1 DAY";
</code>```

Body:
I have database "db2" with table "menjava"

In table menjava have "id", "author" and "date_submitted" field

id - auto_increment

author - int(11)

date_submitted - datetime

I want to count all the rows for todays date and all the rows for yesterdays date (so there will be two codes with conditions) based on a DATETIME field called 'date_submitted' that holds the date and time of each record's creation.

In the file result.php, there is this count displayed, but it does not work. In the same file (result.php) I have some other code to display data from different database, so I think that povezava.php is working ok.

My code:

 <?
    require "povezava.php";
    $q=mysql_query(" SELECT COUNT(*) AS total_number FROM menjava
WHERE date_submitted >= DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)",$link2);
// now you can
if ( $nt = mysql_fetch_array($q)){
echo $nt["total_number"];
$q=mysql_query($nt) or die(mysql_error());
}

    ?>

my file povezava.php looks like this:

<?
$servername='localhost';

$dbusername='user';
$dbpassword='pass';

$dbname1='db1';
$dbname2='db2';

$link1 = connecttodb($servername,$dbname1,$dbusername,$dbpassword);
$link2 = connecttodb($servername,$dbname2,$dbusername,$dbpassword);

function connecttodb($servername,$dbname,$dbusername,$dbpassword)
{
    $link=mysql_connect ("$servername","$dbusername","$dbpassword",TRUE);
    if(!$link){die("Could not connect to MySQL");}
    mysql_select_db("$dbname",$link) or die ("could not open db".mysql_error());
    return $link;
}
    ?>

Error that I get:

A PHP Error was encountered

Severity: NoticeMessage: Array to string conversionFilename: templates/master.phpLine Number: 231 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Array' at line 1

Fixed:

<?
    require "povezava.php";
    $q=mysql_query("SELECT COUNT(*) AS total_number FROM menjava WHERE date_submitted >= DATE_SUB(CURRENT_DATE(), INTERVAL 0 DAY)",$link2);
// working
if ( $nt = mysql_fetch_array($q)){
echo $nt["total_number"];
}

    ?>

Thank you!

Body:
Please try the following SQL commands:

$sqlToday = "Select COUNT(*) FROM menjava WHERE DATE(date_submitted) = CURRENT_DATE()";

$sqlYesterday = "Select COUNT(*) FROM menjava WHERE DATE(dc_created) = CURDATE() - INTERVAL 1 DAY";


问:
How to translate Next, Cancel, Quit Buttons ? (Qt Installer Framework based)
I would like to translate my installer wizard (Qt Installer Framework based) in English or French (OS language depends).

I added those lines in the "installscript.qs" file :

```<code>Component.prototype.retranslateUi = function()
{
    component.languageChanged();
}
</code>```

and I added those in "config.xml" file :

```<code><Installer>
    ...
    <Translations>
        <Translation>fr.qm</Translation>
    </Translations>
</Installer>
</code>```

But everything is ok (all long texts are translated) (in French) but the buttons like "Next", "Cancel", "Quit" are not translated (see the screenshot) :

ps: I don't want to use C++ code. (only Script or Xml)

答:
You need to load the Qt translation file in addition to your own .qm file(s). The file is located in the translation sub-folder of your Qt installation folder (e.g. ./usr/share/qt5/translations/). For some languages it seems sufficient to load qt_xx (where XX should be replaced with your locale), but for German I had to load "qtbase_XX" to translate the Next and Cancel buttons. In example for the fr locale they are named qt_fr.qm and qtbase_fr.qm.

EDIT:

Because of the comment of John Smith I checked the Installer framework source and the framework is not capable loading more than one translation file:

See installer-framework/src/libs/installer/component.cpp

```<code>/*!
     Loads the translations matching the name filters \a qms inside \a directory. Only translations
    with a base name matching the current locale's name are loaded. For more information, see
    \l{Translating Pages}.
*/
void Component::loadTranslations(const QDir &directory, const QStringList &qms)
</code>```

So my original answer above (which would lead to a translated QWizard::CancelButton) is not working.

I got the Quit button of the Installer Frameworks translation example translated to German by correcting the de.ts file provided within the framworks source in installer-framework/src/sdk/translations

The original translation coming with the feramework is missing an &:

So, changing:

```<code><context>
    <name>QInstaller::IntroductionPage</name>
    ...
    <message>
        <source>Quit</source>
        <translation>Beenden</translation>
    </message>
</code>```

to

```<code><context>
    <name>QInstaller::IntroductionPage</name>
    ...
    <message>
        <source>&Quit</source>
        <translation>Beenden</translation>
    </message>
</code>```

and recompiling the Framework leads to a translated Quit button (Beenden) within the framework.

I did not tried, but studying /installer-framework/src/libs/installer/packagemanagergui.cpp should enable you to translate the Next button, too.

Body:
I would like to translate my installer wizard (Qt Installer Framework based) in English or French (OS language depends).

I added those lines in the "installscript.qs" file :

Component.prototype.retranslateUi = function()
{
    component.languageChanged();
}

and I added those in "config.xml" file :

<Installer>
    ...
    <Translations>
        <Translation>fr.qm</Translation>
    </Translations>
</Installer>

But everything is ok (all long texts are translated) (in French) but the buttons like "Next", "Cancel", "Quit" are not translated (see the screenshot) :

ps: I don't want to use C++ code. (only Script or Xml)

Body:
You need to load the Qt translation file in addition to your own .qm file(s). The file is located in the translation sub-folder of your Qt installation folder (e.g. ./usr/share/qt5/translations/). For some languages it seems sufficient to load qt_xx (where XX should be replaced with your locale), but for German I had to load "qtbase_XX" to translate the Next and Cancel buttons. In example for the fr locale they are named qt_fr.qm and qtbase_fr.qm.

EDIT:

Because of the comment of John Smith I checked the Installer framework source and the framework is not capable loading more than one translation file:

See installer-framework/src/libs/installer/component.cpp

/*!
     Loads the translations matching the name filters \a qms inside \a directory. Only translations
    with a base name matching the current locale's name are loaded. For more information, see
    \l{Translating Pages}.
*/
void Component::loadTranslations(const QDir &directory, const QStringList &qms)

So my original answer above (which would lead to a translated QWizard::CancelButton) is not working.

I got the Quit button of the Installer Frameworks translation example translated to German by correcting the de.ts file provided within the framworks source in installer-framework/src/sdk/translations

The original translation coming with the feramework is missing an &amp;:

So, changing:

<context>
    <name>QInstaller::IntroductionPage</name>
    ...
    <message>
        <source>Quit</source>
        <translation>Beenden</translation>
    </message>

to

<context>
    <name>QInstaller::IntroductionPage</name>
    ...
    <message>
        <source>&amp;Quit</source>
        <translation>Beenden</translation>
    </message>

and recompiling the Framework leads to a translated Quit button (Beenden) within the framework.

I did not tried, but studying /installer-framework/src/libs/installer/packagemanagergui.cpp should enable you to translate the Next button, too.


问:
std::stable_sort: How to choose memory-optimised algorithm over time-optimised algorithm?
I wish to make use of std::stable_sort. The complexity of the algorithm is stated as

O(N·log^2(N)), where N = std::distance(first, last) applications of cmp. If additional memory is available, then the complexity is O(N·log(N)). http://en.cppreference.com/w/cpp/algorithm/stable_sort

In my application, memory is critical, therefore, I would prefer std::stable_sort to use the memory-optimised O(N·log^2(N))
algorithm, rather than the time-optimised O(N·log(N)) algorithm.
I understand that the time-optimised version will only be chosen if it is safe
to do so (memory available). However, I aim to benchmark my application, and therefore, as memory is critical, want to benchmark the algorithm when memory consumption is lowest. As my system currently has enough memory to allocate
the buffer, it will automatically chose the O(N·log^2(N)) version of std::stable_sort. I would therefore like to assert to std::stable_sort to
take the memory-optimised version. Is this possible?

The execution policy appears
to be a parameter that can modify the algorithm, however, it appears
to only alter the extent of parallelism.
http://en.cppreference.com/w/cpp/algorithm/execution_policy_tag_t

Although choosing either
the parallel or sequential version may actually be choosing the O(N·log(N)) or
O(N·log^2(N)) versions respectively, this is not stated anywhere on the webpage.

I wonder if anyone has any experience in asserting this choice. If so
would they be able to provide any advice?

答:
Unfortunately there is no standard way to tell stable_sort to do the in-place sort.  In C++14 the only options we have

```<code>template<class RandomAccessIterator>
void stable_sort(RandomAccessIterator first, RandomAccessIterator last);

template<class RandomAccessIterator, class Compare>
void stable_sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp);
</code>```

C++17 added versions that allow the execution policy as you point out but those will not affect the decision either.  If we look at the complexity requirement in [stable.sort] we get

Complexity: It does at most N log²(N) (where N == last - first) comparisons; if enough extra memory is available, it is N log(N).

So it is mandated to use more memory if it is available.

You're either going to have to write your own and you can see Worst case O(nlnn)O(nlnn) in place stable sort? about that or find a library that provides the function for you.

Body:
Unfortunately there is no standard way to tell stable_sort to do the in-place sort.  In C++14 the only options we have

template<class RandomAccessIterator>
void stable_sort(RandomAccessIterator first, RandomAccessIterator last);

template<class RandomAccessIterator, class Compare>
void stable_sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp);

C++17 added versions that allow the execution policy as you point out but those will not affect the decision either.  If we look at the complexity requirement in [stable.sort] we get

Complexity: It does at most N log²(N) (where N == last - first) comparisons; if enough extra memory is available, it is N log(N).

So it is mandated to use more memory if it is available.

You're either going to have to write your own and you can see Worst case O(nlnn)O(nlnn) in place stable sort? about that or find a library that provides the function for you.


问:
How can I persuade System.Xaml.XamlXmlWriter.WriteValue to fire if the Value is NULL
I'm using the XamlServices.Transform to take an object model and serialize it to Xaml.

I've implemented a class which inherits from XamlXmlWriter which overrides WriteValue. I'm using this to reinstantiate a custom MarkupExtension back into the rendered Xaml. My code works fine except when the value of the property is null, in which case the WriteValue doesn't fire and I don't get chance to "swap out" the value in the overriden class.

A related issue is where a property has the same value as that specified by the System.ComponentModel.DefaultValue() attribute. For example say i've got a property in my object model decorated like this:

```<code>[DefaultValue(true)]
public Boolean IsVisible {get; set;}
</code>```

Then the WriteValue method only fires if the IsVisible property is false (which kind of makes sense).

The Remarks section in the documentation (http://msdn.microsoft.com/en-us/library/system.xaml.xamlxmlwriter.writevalue.aspx) mentions something about null values, but I don't understand it:

The input value may be null, which
  supports explicitly writing out null
  as a serialized value. This behavior
  uses the XamlLanguage.Null definition
  as WriteStartObject input and then
  immediately calls WriteEndObject.

How to I a) make the "WriteValue" fire when the property is null, and b) make the "WriteValue" fire when the property is the same as the DefaultValue Attribute?

I'm not sure if they are related, a solution for either of them would be very welcome.

Thanks,

Daniel

答:
To answer ‘b’ first:  The XamlObjectReader’s intended behavior is to skip properties whose value is the declared “default value” and we have no configuration feature to override that.  Note that “default value” here is the one declared with the [DefaultValue()] attribute, not the C# language default(T), so things may not be as bad as you fear.   I mean not every “0” in an “Int” property is skipped because it is the “default value”.

‘a’: The XamlXmlWriter’s output Node stream for a null value is not “WriteValue(null)”, but instead is “WriteStartObject(nullExtensions); WriteEndObject()”.  This is the behavior the documentation you quoted was describing.  So you should be fine.  Look for StartObject “nullExtension” instead of value “null”.

Body:
I'm using the XamlServices.Transform to take an object model and serialize it to Xaml.

I've implemented a class which inherits from XamlXmlWriter which overrides WriteValue. I'm using this to reinstantiate a custom MarkupExtension back into the rendered Xaml. My code works fine except when the value of the property is null, in which case the WriteValue doesn't fire and I don't get chance to "swap out" the value in the overriden class.

A related issue is where a property has the same value as that specified by the System.ComponentModel.DefaultValue() attribute. For example say i've got a property in my object model decorated like this:

[DefaultValue(true)]
public Boolean IsVisible {get; set;}

Then the WriteValue method only fires if the IsVisible property is false (which kind of makes sense).

The Remarks section in the documentation (http://msdn.microsoft.com/en-us/library/system.xaml.xamlxmlwriter.writevalue.aspx) mentions something about null values, but I don't understand it:

The input value may be null, which
  supports explicitly writing out null
  as a serialized value. This behavior
  uses the XamlLanguage.Null definition
  as WriteStartObject input and then
  immediately calls WriteEndObject.

How to I a) make the "WriteValue" fire when the property is null, and b) make the "WriteValue" fire when the property is the same as the DefaultValue Attribute?

I'm not sure if they are related, a solution for either of them would be very welcome.

Thanks,

Daniel


问:
For lower to upper
Need a RegEx to do the following:

Lower to upper case till the first dot (.) From left

Only 'S' will go upper case in s6a to S6a

Rest remains same.

For example:
nhe7-s6a-mme.epc.mnc001.mcc505.3gppnetwork.org
change to

NHE7-S6a-MME.epc.mnc001.mcc505.3gppnetwork.org

答:
I don't really want to contribute to such a poorly phrased question, but here is a regex pattern to do this

```<code>match on: ([\w]+)\-(?:(\w)([\w]+))\-([\w]+)\.
substitue: \U\1\-\2\E\3\-\U\4\.

input: nhe7-s6a-mme.epc.mnc001.mcc505.3gppnetwork.org
output: NHE7-S6a-MME.epc.mnc001.mcc505.3gppnetwork.org
</code>```

Example seen here: https://regex101.com/r/GqRcPQ/2

Title: For lower to upper

Body:
I don't really want to contribute to such a poorly phrased question, but here is a regex pattern to do this

match on: ([\w]+)\-(?:(\w)([\w]+))\-([\w]+)\.
substitue: \U\1\-\2\E\3\-\U\4\.

input: nhe7-s6a-mme.epc.mnc001.mcc505.3gppnetwork.org
output: NHE7-S6a-MME.epc.mnc001.mcc505.3gppnetwork.org

Example seen here: https://regex101.com/r/GqRcPQ/2


问:
UIBlurEffect on StatusBar only (not on UINavigationBar)
Similar to this:
How to make a Navigation Bar and Status Bar blurred (UIBlurEffect)? iOS, Swift 3

but we'd like to apply the UIBlurEffect on the StatusBar only, not the navigationbar. Is this possible?

答:
You can get your statusBar view by following code, then try add to visual effect like here</p>

```<code>     let statWindow = UIApplication.shared.value(forKey:"statusBarWindow") as! UIView
        let statusBar = statWindow.subviews[0] as UIView
//        statusBar.backgroundColor = UIColor(red: 23 / 255.0, green: 0 / 255.0, blue: 154 / 255.0, alpha: 0.7)
        statusBar.backgroundColor = UIColor(red: 213 / 255.0, green: 0 / 255.0, blue: 0 / 255.0, alpha: 0.7)
</code>```

Body:
You can get your statusBar view by following code, then try add to visual effect like here

     let statWindow = UIApplication.shared.value(forKey:"statusBarWindow") as! UIView
        let statusBar = statWindow.subviews[0] as UIView
//        statusBar.backgroundColor = UIColor(red: 23 / 255.0, green: 0 / 255.0, blue: 154 / 255.0, alpha: 0.7)
        statusBar.backgroundColor = UIColor(red: 213 / 255.0, green: 0 / 255.0, blue: 0 / 255.0, alpha: 0.7)


问:
EntityFramework-Plus check if data implements an interface
I have a filter

```<code> this.Filter<BaseModel>(q => q.Where(x => x.CompanyId == companyId);
</code>```

Is there a way to check whatever "x" is implementing my custom interface "IGlobalDatabaseObject" ?

```<code> this.Filter<BaseModel>(q => q.Where(x => x.CompanyId == companyId || x is IGlobalDatabaseObject ); ?
</code>```

So, the db queries will return the data where "x.CompanyId== companyId" or if that data implements Global Interface

I am using Ef plus library (github.com/zzzprojects/EntityFramework-Plus )

答:
I think you are seeking for
EF+ Query Filter Enable/Disable feature. In your case, something like this:</p>

```<code>// The key identifying your filter
var key = new object();

// Create filter for classes that inherit BaseModel
this.Filter<BaseModel>(key, q => q.Where(x => x.CompanyId == companyId));

// Disable the filter for classes that implement IGlobalDatabaseObject
this.Filter<IGlobalDatabaseObject>(key).Disable();
</code>```

Body:
I have a filter

 this.Filter<BaseModel>(q => q.Where(x => x.CompanyId == companyId);

Is there a way to check whatever "x" is implementing my custom interface "IGlobalDatabaseObject" ?

 this.Filter<BaseModel>(q => q.Where(x => x.CompanyId == companyId || x is IGlobalDatabaseObject ); ?

So, the db queries will return the data where "x.CompanyId== companyId" or if that data implements Global Interface

I am using Ef plus library (github.com/zzzprojects/EntityFramework-Plus )

Body:
I think you are seeking for
EF+ Query Filter Enable/Disable feature. In your case, something like this:

// The key identifying your filter
var key = new object();

// Create filter for classes that inherit BaseModel
this.Filter<BaseModel>(key, q => q.Where(x => x.CompanyId == companyId));

// Disable the filter for classes that implement IGlobalDatabaseObject
this.Filter<IGlobalDatabaseObject>(key).Disable();


问:
sorting of objects in memory mapped file
I have a structure as below:

```<code>struct XX
{
   int x;
   char szT[200];
   int y;
} ;
</code>```

I have a file that stores several of these XX objects, written through fwrite call. Now when I read the file as a memory mmaped file using mmap, I use as:

```<code>// sz = size of the file in bytes
// fd = file descriptor of the file opened through fopen in O_RDWR mode
char *p = (char *) mmap(0,sz,PROT_READ | PROT_WRITE,MAP_SHARED,fd,0);
unsigned int N = (sz / sizeof(XX)); // number of objects
</code>```

Thus, if I have N objects of type XX, I may access the first object as:

```<code>XX *px = (XX*) p;
</code>```

And, i-th object I can access as px + i where i <= N.
May I use std::sort to sort the contents of a memory mapped file being accessed as px being the pointer of first record, and px+i pointing to i-th record.
I don't like to store px, px+1, px+2 etc in a vector of XX pointers as vector<XX*>, as I can access the records directly from the memory-mapped file.
Please suggest.

答:
Read documentation of std::sort

The following compiles cleanly. It sorts a raw array with a peculiar lambda (comparing squares of numbers)

```<code> #include <algorithm>
 #include <functional>

 void sort_array(int *p, size_t n) {
   std::sort(p, p+n, [=](int x, int y) { return x*x < y*y; });
 }
</code>```

You should be able to adapt that to  your situation:

```<code> void sort_xx (XX*p, size_t n) {
   std::sort(p, p+n, [=](const XX& x, const XX& y)
    { return strcmp(x.szT, y.szT)<0; });
 }
</code>```

Read more about lambda expressions in C++. [=] is a capture-list by value (actually by copy) notation (for all closed variables, theoretically the only one here being strcmp which the compiler is likely to optimize - so won't close it naively; probably the lambda-abstraction and its application would be inlined by an optimizing compiler).

Body:
I have a structure as below:

struct XX
{
   int x;
   char szT[200];
   int y;
} ;

I have a file that stores several of these XX objects, written through fwrite call. Now when I read the file as a memory mmaped file using mmap, I use as:

// sz = size of the file in bytes
// fd = file descriptor of the file opened through fopen in O_RDWR mode
char *p = (char *) mmap(0,sz,PROT_READ | PROT_WRITE,MAP_SHARED,fd,0);
unsigned int N = (sz / sizeof(XX)); // number of objects

Thus, if I have N objects of type XX, I may access the first object as:

XX *px = (XX*) p;

And, i-th object I can access as px + i where i <= N.
May I use std::sort to sort the contents of a memory mapped file being accessed as px being the pointer of first record, and px+i pointing to i-th record.
I don't like to store px, px+1, px+2 etc in a vector of XX pointers as vector<XX*>, as I can access the records directly from the memory-mapped file.
Please suggest.

Body:
Read documentation of std::sort

The following compiles cleanly. It sorts a raw array with a peculiar lambda (comparing squares of numbers)

 #include <algorithm>
 #include <functional>

 void sort_array(int *p, size_t n) {
   std::sort(p, p+n, [=](int x, int y) { return x*x < y*y; });
 }

You should be able to adapt that to  your situation:

 void sort_xx (XX*p, size_t n) {
   std::sort(p, p+n, [=](const XX& x, const XX& y)
    { return strcmp(x.szT, y.szT)<0; });
 }

Read more about lambda expressions in C++. [=] is a capture-list by value (actually by copy) notation (for all closed variables, theoretically the only one here being strcmp which the compiler is likely to optimize - so won't close it naively; probably the lambda-abstraction and its application would be inlined by an optimizing compiler).


问:
Chrome extension: move downloaded file to input field
I am trying to migrate images with a small chrome extension i have built. the extension consists of 5 files:

popup.html - the plugin html document

```<code> Has some html buttons
also has script link to my settings.js file that listens for the image downlaod button to be clicked and send a message to my content script : run.js to find the images
</code>```

run.js - content script ( has access to the webpages DOM ).

```<code>This script recieves the message from run.js which then finds all the images names and image links i want to download. It puts them into an object and sends them via message to the backgorund script : bootstrap.js
</code>```

bootstrap.js - runs the background page and has access to the chrome api.

```<code>var Downloads = [];
chrome.extension.onMessage.addListener(function(request, sender, sendResponse)
{
if(request.message.method == 'download'){
    for( var d = 0; d <= request.message.imageLinks.length; d++ ){
      chrome.downloads.download( {url: request.message.imageLinks[d],
             filename: request.message.imageName[d]}, function(id){

        });
          sendResponse('done');
    }
}
});
</code>```

This all works fine and dandy. It loops through the images and downloads them.
What i need to be able to do now is: Take the images i just downloaded, and insert them into the file upload fields on the other website (which i have open in another tab) which have the same field names ect..
I see chrome has a

```<code>//Initiate dragging the downloaded file to another application. Call in a javascript ondragstart handler.
chrome.downloads.drag(integer downloadId)
</code>```

At first i thought this might work since you can manually drag the downloaded image into the html file upload field without having to click and select the file. But i can't find any documentation / examples on it.

Does anyone know it is possible to get accomplish this with javascript / chrome api?

答:
First you need to access the content of the files you downloaded.

For that, you need to add a permission to file://*in your manifest file.
Then you can loop through your downloaded files with chrome.downloads.search for instance and get each file's path in the system (DownloadItem.filename property). For each file, make a GET XMLHttpRequest to the url file://{filepath} to get the file's content.

Once you have that content, you can convert it to a DataUrl and programmatically add the file to the FormData of your form (not the actual inputs though, just the FormData submitted in the end). See this answer for this part.

Body:
I am trying to migrate images with a small chrome extension i have built. the extension consists of 5 files:

popup.html - the plugin html document

 Has some html buttons
also has script link to my settings.js file that listens for the image downlaod button to be clicked and send a message to my content script : run.js to find the images

run.js - content script ( has access to the webpages DOM ).

This script recieves the message from run.js which then finds all the images names and image links i want to download. It puts them into an object and sends them via message to the backgorund script : bootstrap.js

bootstrap.js - runs the background page and has access to the chrome api.

var Downloads = [];
chrome.extension.onMessage.addListener(function(request, sender, sendResponse)
{
if(request.message.method == 'download'){
    for( var d = 0; d <= request.message.imageLinks.length; d++ ){
      chrome.downloads.download( {url: request.message.imageLinks[d],
             filename: request.message.imageName[d]}, function(id){

        });
          sendResponse('done');
    }
}
});

This all works fine and dandy. It loops through the images and downloads them.
What i need to be able to do now is: Take the images i just downloaded, and insert them into the file upload fields on the other website (which i have open in another tab) which have the same field names ect..
I see chrome has a

//Initiate dragging the downloaded file to another application. Call in a javascript ondragstart handler.
chrome.downloads.drag(integer downloadId)

At first i thought this might work since you can manually drag the downloaded image into the html file upload field without having to click and select the file. But i can't find any documentation / examples on it.

Does anyone know it is possible to get accomplish this with javascript / chrome api?


问:
regex alphanumeric jquery
```<code>var regx = /^[A-Za-z0-9 _.-]+$/;

if(regx.test($($input).val()))
  alert ("correct");
else
  alert('Incorrect!');
}
</code>```

If I enter in input, character @ or # works? for me this works, but I think that must be incorrect...

Why does not works fine?

答:
regex alphanumeric jquery with length 5-10
var regx=/^([a-zA-Z0-9 _.-]){3,10}$/</p>

```<code>    $('#txtSearchIn').keyup(function() {
        if (regx.test(this.value))
            $('#lblErrorMsg').val('');
        else
            $('#lblErrorMsg').val('text should be alphanumeric as well as max length 5-10 charater');
    });
</code>```

Title: regex alphanumeric jquery

Body:
var regx = /^[A-Za-z0-9 _.-]+$/;

if(regx.test($($input).val()))
  alert ("correct");
else
  alert('Incorrect!');
}

If I enter in input, character @ or # works? for me this works, but I think that must be incorrect...

Why does not works fine?

Body:
regex alphanumeric jquery with length 5-10
var regx=/^([a-zA-Z0-9 _.-]){3,10}$/

    $('#txtSearchIn').keyup(function() {
        if (regx.test(this.value))
            $('#lblErrorMsg').val('');
        else
            $('#lblErrorMsg').val('text should be alphanumeric as well as max length 5-10 charater');
    });


问:
Jquery autocomplete is not a function after added all jquery files
Hello everyone I am using jquery autocomplete function to fill text box auto completely here is my code

```<code>$("#txtcountry").autocomplete({

            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "home/GetCountry",
                    data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
                    dataType: "json",
                    success: function (data)
                    {
                        response(data.d);
                    },
                    error: function (result) {
                        alert("Error");
                    }
                });
            }
    });
</code>```

and order of my Jquery plugins is

```<code><link href="http://code.jquery.com/ui/1.11.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</code>```

But it stills showing error in console that $(...).autocomplete is not a function
please suggest me where I am going wrong
thanks in advance.

答:
I have just replaced jQuery library import with one which I have because in your question, it is relative import.

Below code working fine in my case with fix provided tags for autocomplete but it is not throwing error on autocomplete function.

```<code>    <script src="jquery-1.x-git.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <script>
        $(function () {
            var availableTags = [
                "Apple",
                "Pineapple",
                "Java",
                "ASP",
                "PHP"
            ];
            $("#txtcountry").autocomplete({
                source: availableTags
            });
        });
    </script>
</body>
</code>```

Body:
Hello everyone I am using jquery autocomplete function to fill text box auto completely here is my code

$("#txtcountry").autocomplete({

            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "home/GetCountry",
                    data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
                    dataType: "json",
                    success: function (data)
                    {
                        response(data.d);
                    },
                    error: function (result) {
                        alert("Error");
                    }
                });
            }
    });

and order of my Jquery plugins is

<link href="http://code.jquery.com/ui/1.11.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet" type="text/css" />

But it stills showing error in console that $(...).autocomplete is not a function
please suggest me where I am going wrong
thanks in advance.

Body:
I have just replaced jQuery library import with one which I have because in your question, it is relative import.

Below code working fine in my case with fix provided tags for autocomplete but it is not throwing error on autocomplete function.

    <script src="jquery-1.x-git.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <script>
        $(function () {
            var availableTags = [
                "Apple",
                "Pineapple",
                "Java",
                "ASP",
                "PHP"
            ];
            $("#txtcountry").autocomplete({
                source: availableTags
            });
        });
    </script>
</body>


问:
Getting geolocation from IP address
I need to track user details, for that client's location and IP address is needed.

I got IP address from

```<code>$this->input->ip_address();
</code>```

in codiigniter.
 Now the problem is how can i make their location in google map by using their respective IP address

答:
freegeoip.net provides a public HTTP API to search the geolocation of IP addresses. It uses a database of IP addresses that are associated to cities along with other relevant information like time zone, latitude and longitude.

You're allowed up to 15,000 queries per hour.
If you need more than that, you can run the freegeoip  as a web server on your own infrastructure. See: freegeoip on github

Title: Getting geolocation from IP address

Body:
I need to track user details, for that client's location and IP address is needed.

I got IP address from

$this->input->ip_address();

in codiigniter.
 Now the problem is how can i make their location in google map by using their respective IP address


问:
Need to implement javascript valiadation in Datalist
Hi I have my page layout as below image showing

What I want is on click of Sizing checkbox inner radio button get auto checked and on click on stone resetting the inner radio button list get an auto check.

My HTML code looks like

```<code><asp:DataList ID="dtbindjewellery" runat="server"  OnItemDataBound="dtbindjewellery_ItemDataBound" Width="100%">
            <ItemTemplate>
                             <div class="col-md-12 col-sm-12 col-xs-12 jewelerymain">
                                <asp:CheckBox ID="Servicechkbox" runat="server" Text='<%#Eval("ServiceName")%>' />
                                <asp:HiddenField ID="hdserviceid" runat="server" Value='<%#Eval("ServiceId")%>' />
                            </div>
                 <%-- Sizing Radiobutton--%>
                        <div id="divsizing" runat="server" class="col-md-12 col-sm-12 col-xs-12 subservices" visible="false">
                            <asp:RadioButton ID="rdsizing1" runat="server" GroupName="ringsize" />
                            <asp:DropDownList ID="ddselectSize" runat="server"></asp:DropDownList>
                            <br />
                            <asp:RadioButton ID="rdsizing2" runat="server" GroupName="ringsize" />
                            <asp:TextBox ID="txtsize" runat="server" CssClass="txtNumericUpDownExtender"></asp:TextBox>

                        </div>
                       <%-- Stone resetting Radiobutton--%>
                        <asp:RadioButtonList ID="radiosub" runat="server"></asp:RadioButtonList>
            </ItemTemplate>
        </asp:DataList>
</code>```

here sizing had 2 unique radio button and stone resetting has radio button list.

I bind it on basis of different ids and the Id of checkbox and radio get changes in the data list.

How should I place validation on checkbox click in javascript?

答:
Use as below.</p>

```<code> function Specialinstruction() {
        var datalist = document.getElementById("<%=dtbindjewellery.ClientID%>");
        var count = datalist.rows.length;

        for (i = 0; i < count; i++) {
            var chkid = document.getElementById('ContentPlaceHolder1_JewelleryServices_dtbindjewellery_Servicechkbox_' + i);
            //var checkboxid = document.getElementById(id);
            if (chkid.checked == true) {
                // alert("hello");
                var hdservice = document.getElementById('ContentPlaceHolder1_JewelleryServices_dtbindjewellery_hdserviceid_' + i);
                var value = hdservice.value;

                if (value == 3) {
                    var rdsizing1 = document.getElementById('ContentPlaceHolder1_JewelleryServices_dtbindjewellery_rdsizing1_' + i);
                    var rdsizing2 = document.getElementById('ContentPlaceHolder1_JewelleryServices_dtbindjewellery_rdsizing2_' + i);
                    if (rdsizing1.checked == false && rdsizing2.checked == false)
                    { rdsizing1.checked = true; }
                }
}
}

   <asp:CheckBox ID="Servicechkbox" CssClass="cb" onClick="Specialinstruction();" runat="server" Text='<%#Eval("ServiceName")%>' />
</code>```

Body:
Hi I have my page layout as below image showing

What I want is on click of Sizing checkbox inner radio button get auto checked and on click on stone resetting the inner radio button list get an auto check.

My HTML code looks like

<asp:DataList ID="dtbindjewellery" runat="server"  OnItemDataBound="dtbindjewellery_ItemDataBound" Width="100%">
            <ItemTemplate>

                                <asp:CheckBox ID="Servicechkbox" runat="server" Text='<%#Eval("ServiceName")%>' />
                                <asp:HiddenField ID="hdserviceid" runat="server" Value='<%#Eval("ServiceId")%>' />

                 <%-- Sizing Radiobutton--%>

                            <asp:RadioButton ID="rdsizing1" runat="server" GroupName="ringsize" />
                            <asp:DropDownList ID="ddselectSize" runat="server"></asp:DropDownList>

                            <asp:RadioButton ID="rdsizing2" runat="server" GroupName="ringsize" />
                            <asp:TextBox ID="txtsize" runat="server" CssClass="txtNumericUpDownExtender"></asp:TextBox>

                       <%-- Stone resetting Radiobutton--%>
                        <asp:RadioButtonList ID="radiosub" runat="server"></asp:RadioButtonList>
            </ItemTemplate>
        </asp:DataList>

here sizing had 2 unique radio button and stone resetting has radio button list.

I bind it on basis of different ids and the Id of checkbox and radio get changes in the data list.

How should I place validation on checkbox click in javascript?

Body:
Use as below.

 function Specialinstruction() {
        var datalist = document.getElementById("<%=dtbindjewellery.ClientID%>");
        var count = datalist.rows.length;

        for (i = 0; i < count; i++) {
            var chkid = document.getElementById('ContentPlaceHolder1_JewelleryServices_dtbindjewellery_Servicechkbox_' + i);
            //var checkboxid = document.getElementById(id);
            if (chkid.checked == true) {
                // alert("hello");
                var hdservice = document.getElementById('ContentPlaceHolder1_JewelleryServices_dtbindjewellery_hdserviceid_' + i);
                var value = hdservice.value;

                if (value == 3) {
                    var rdsizing1 = document.getElementById('ContentPlaceHolder1_JewelleryServices_dtbindjewellery_rdsizing1_' + i);
                    var rdsizing2 = document.getElementById('ContentPlaceHolder1_JewelleryServices_dtbindjewellery_rdsizing2_' + i);
                    if (rdsizing1.checked == false && rdsizing2.checked == false)
                    { rdsizing1.checked = true; }
                }
}
}

   <asp:CheckBox ID="Servicechkbox" CssClass="cb" onClick="Specialinstruction();" runat="server" Text='<%#Eval("ServiceName")%>' />


问:
Third level of sub navigation php
I have the following code which works perfectly for producing a two tier navigation system, the problem is I have a requirement where one section has a third level of pages below it.

Edit: The code produces a two tier side navigation item that lists the pages in this section along with the parent item detailed at the top like so:

Page Title

Sub Page 1

Sub Page 2

Another Sub Page 1

Further Sub Page 1

Another Sub Page 1

Sub Page 3

There isn't any abnormal behaviour or error messages, it fails to display the further sub page 1 items in the list.

```<code>function insection_make_ul($tree, $level=0) {
$indent = str_repeat("   ", $level);
$result = "\n".$indent."<ul>\n";
foreach($tree as $id => $item) {
    $result .= $indent."<li><a href=\"".$item['permalink']."\" class=\""
        .($item['selected'] == true ? 'selected' : '')
        .($level == 0 ? ' root' : '')."\" >" . $item['title']."</a>";
    if(count(@$item['items'])) {
        $result .= insection_make_ul($item['items'], ($level+1));
        $result .= $indent."</li>\n";
    }else{
        $result .= "</li>\n";
    }
}
$result .= $indent."</ul>\n";
return $result;
</code>```

}

```<code>function insection($structure_id,$custom_selected=false){
$tree = insection_array($structure_id,$custom_selected);
return insection_make_ul($tree);
</code>```

}

and the code to build the array

```<code>function insection_array($data,$custom_selected=false){
global $link;
if(is_numeric($data))
    $data = fetch_row('SELECT * FROM content_structure WHERE id = '.$data);
$selected_id = $data['id'];

if($custom_selected) // dynamic item of 'real' parent
    $selected_id .= '_'.$custom_selected;

$insection = array();
if($data['parent_id'] > 0){
    if(HIDE_EMPTY_STRUCTURE){
        $sql = 'SELECT * FROM content_structure WHERE parent_id = '.$data['id'].' AND visible = 1 AND in_menu = 1
                                                      AND (item_id > 0 OR redirect <> "")';
    }else{
        $sql = 'SELECT * FROM content_structure WHERE parent_id = '.$data['id'].' AND visible = 1 AND in_menu = 1';
    }
    $result = mysqli_query($link, $sql);
    if(mysqli_num_rows($result) > 0 || $data['children_php'] != ''){
        $parent_id = $data['id'];
    }else{
        $parent_id = $data['parent_id'];
    }
}else{
    $parent_id = $data['id'];
}
while($parent_id > 0){
    $data = fetch_row('SELECT * FROM content_structure WHERE id = '.$parent_id);
    $insection[$parent_id] = array('id' => $data['id'],
        'title' => $data['menu_title'],
        'permalink' => navlink($data),
        'selected' => ($data['id'] == $selected_id ? true : false) );

    if(HIDE_EMPTY_STRUCTURE){
        $sql = 'SELECT * FROM content_structure WHERE parent_id = '.$parent_id.' AND visible = 1 AND in_menu = 1
                                                      AND (item_id > 0 OR redirect <> "") ORDER BY '
            .($data['sort_auto'] == 1 ? 'menu_title' : 'sort_order');
    }else{
        $sql = 'SELECT * FROM content_structure WHERE parent_id = '.$parent_id.' AND visible = 1 AND in_menu = 1 ORDER BY '
            .($data['sort_auto'] == 1 ? 'menu_title' : 'sort_order');
    }
    $result = mysqli_query($link, $sql);
    if(!$result){ die('error: '.mysqli_error($link)); }
    while($row = mysqli_fetch_assoc($result)){
        $insection[$parent_id]['items'][$row['id']] = array('id' => $row['id'],
            'title' => $row['menu_title'],
            'permalink' => navlink($row),
            'selected' => ($row['id'] == $selected_id ? true : false) );
    }

    // custom start
    if($data['children_php'] != ''){ // custom sub items?
        $sub_item_result = custom_navigation_array($data['children_php']);
        foreach($sub_item_result as $sub_item){
            $id = $data['id'].'_'.$sub_item['id']; // realparent_customid
            $insection[$parent_id]['items'][$id] = array('id' => $id,
                'title' => $sub_item['menu_title'],
                'permalink' => $sub_item['href'],
                'selected' => ($id == $selected_id ? true : false) );
        }
    }
    //custom end
    $parent_id = $data['parent_id'];
}

$insection = array_reverse($insection,true);
$temp = current($insection);
$root_id = @$temp['id'];
$insection_tree[$root_id] = current($insection);

$found_selected = false;
if(is_array(@$insection_tree[$root_id]['items'])){
    foreach($insection_tree[$root_id]['items'] as $id => $item){
        if(!empty($insection[$id])){
            if($insection_tree[$root_id]['items'][$id]['selected'] == true)
                $found_selected = true;
            $insection_tree[$root_id]['items'][$id] = $insection[$id];
        }
    }
}
//if(!$found_selected){
//  while(!$found_selected){
//
//  }
//}

return $insection_tree;
</code>```

}

Any pointers where I might get this working.

thanks

答:
Personally I'd advise re-looking at your code. There is a lot of code there doing the same thing. Repetition is bad. As a helping hand, here's something to get you going.

Take this menu structure as an example but It's really upto you to produce this array yourself the main thing to notice is the function which will build the array into a

 string.

```<code>        $menuItems = array(
        array(// Top level items
            "name" => "item1",
            "subs" => array(// Second Level items
                array(
                    "name" => "1a",
                    "href" => "something"
                ),
                array(
                    "name" => "1b",
                    "subs" => array(// Third Level Items
                        array("name" => "1ba", "href" => "something"),
                        array("name" => "1bb", array(
                                array("name" => "1cca", "href" => "something"),
                            )
                        )
                    )
                )
            )
        ),
        array(// Top level items
            "name" => "item2",
            "subs" => array(// Second Level items
                array(
                    "name" => "2a",
                    "href" => "something"
                ),
                array(
                    "name" => "2b",
                    "subs" => array(// Third Level Items
                        array("name" => "2ba", "href" => "something"),
                        array("name" => "2bb", array(
                                array("name" => "2cca", "href" => "something"),
                            )
                        )
                    )
                )
            )
        )
    );
        $this->menuIterator($menuItems);
        die();
</code>```

The following logic is the important bit, it'll mean your menu could be any levels deep you want and it'll still produce the same result:

```<code>public function menuIterator($items) {
    print "<ul>";
    foreach ($items as $item) {
        print "<li>";
        print "<a>{$item['name']}</a>";
        if (isset($item['subs'])) {
            $this->menuIterator($item['subs']);
        }
        print "</li>";
    }
    print "</ul>";
    return;
}
</code>```

And the result is:

item1

1a

1b

1ba

1bb

item2

2a

2b

2ba

2bb

```

Title: Third level of sub navigation php

Body:
I have the following code which works perfectly for producing a two tier navigation system, the problem is I have a requirement where one section has a third level of pages below it.

Edit: The code produces a two tier side navigation item that lists the pages in this section along with the parent item detailed at the top like so:

Page Title

Sub Page 1

Sub Page 2

Another Sub Page 1

Further Sub Page 1

Another Sub Page 1

Sub Page 3

There isn't any abnormal behaviour or error messages, it fails to display the further sub page 1 items in the list.

function insection_make_ul($tree, $level=0) {
$indent = str_repeat("   ", $level);
$result = "\n".$indent."
\n";
foreach($tree as $id => $item) {
    $result .= $indent."
" . $item['title']."";
    if(count(@$item['items'])) {
        $result .= insection_make_ul($item['items'], ($level+1));
        $result .= $indent."
\n";
    }else{
        $result .= "
\n";
    }
}
$result .= $indent."
\n";
return $result;

}

function insection($structure_id,$custom_selected=false){
$tree = insection_array($structure_id,$custom_selected);
return insection_make_ul($tree);

}

and the code to build the array

function insection_array($data,$custom_selected=false){
global $link;
if(is_numeric($data))
    $data = fetch_row('SELECT * FROM content_structure WHERE id = '.$data);
$selected_id = $data['id'];

if($custom_selected) // dynamic item of 'real' parent
    $selected_id .= '_'.$custom_selected;

$insection = array();
if($data['parent_id'] > 0){
    if(HIDE_EMPTY_STRUCTURE){
        $sql = 'SELECT * FROM content_structure WHERE parent_id = '.$data['id'].' AND visible = 1 AND in_menu = 1
                                                      AND (item_id > 0 OR redirect <> "")';
    }else{
        $sql = 'SELECT * FROM content_structure WHERE parent_id = '.$data['id'].' AND visible = 1 AND in_menu = 1';
    }
    $result = mysqli_query($link, $sql);
    if(mysqli_num_rows($result) > 0 || $data['children_php'] != ''){
        $parent_id = $data['id'];
    }else{
        $parent_id = $data['parent_id'];
    }
}else{
    $parent_id = $data['id'];
}
while($parent_id > 0){
    $data = fetch_row('SELECT * FROM content_structure WHERE id = '.$parent_id);
    $insection[$parent_id] = array('id' => $data['id'],
        'title' => $data['menu_title'],
        'permalink' => navlink($data),
        'selected' => ($data['id'] == $selected_id ? true : false) );

    if(HIDE_EMPTY_STRUCTURE){
        $sql = 'SELECT * FROM content_structure WHERE parent_id = '.$parent_id.' AND visible = 1 AND in_menu = 1
                                                      AND (item_id > 0 OR redirect <> "") ORDER BY '
            .($data['sort_auto'] == 1 ? 'menu_title' : 'sort_order');
    }else{
        $sql = 'SELECT * FROM content_structure WHERE parent_id = '.$parent_id.' AND visible = 1 AND in_menu = 1 ORDER BY '
            .($data['sort_auto'] == 1 ? 'menu_title' : 'sort_order');
    }
    $result = mysqli_query($link, $sql);
    if(!$result){ die('error: '.mysqli_error($link)); }
    while($row = mysqli_fetch_assoc($result)){
        $insection[$parent_id]['items'][$row['id']] = array('id' => $row['id'],
            'title' => $row['menu_title'],
            'permalink' => navlink($row),
            'selected' => ($row['id'] == $selected_id ? true : false) );
    }

    // custom start
    if($data['children_php'] != ''){ // custom sub items?
        $sub_item_result = custom_navigation_array($data['children_php']);
        foreach($sub_item_result as $sub_item){
            $id = $data['id'].'_'.$sub_item['id']; // realparent_customid
            $insection[$parent_id]['items'][$id] = array('id' => $id,
                'title' => $sub_item['menu_title'],
                'permalink' => $sub_item['href'],
                'selected' => ($id == $selected_id ? true : false) );
        }
    }
    //custom end
    $parent_id = $data['parent_id'];
}

$insection = array_reverse($insection,true);
$temp = current($insection);
$root_id = @$temp['id'];
$insection_tree[$root_id] = current($insection);

$found_selected = false;
if(is_array(@$insection_tree[$root_id]['items'])){
    foreach($insection_tree[$root_id]['items'] as $id => $item){
        if(!empty($insection[$id])){
            if($insection_tree[$root_id]['items'][$id]['selected'] == true)
                $found_selected = true;
            $insection_tree[$root_id]['items'][$id] = $insection[$id];
        }
    }
}
//if(!$found_selected){
//  while(!$found_selected){
//
//  }
//}

return $insection_tree;

}

Any pointers where I might get this working.

thanks

Body:
Personally I'd advise re-looking at your code. There is a lot of code there doing the same thing. Repetition is bad. As a helping hand, here's something to get you going.

Take this menu structure as an example but It's really upto you to produce this array yourself the main thing to notice is the function which will build the array into a <ul><li> string.

        $menuItems = array(
        array(// Top level items
            "name" => "item1",
            "subs" => array(// Second Level items
                array(
                    "name" => "1a",
                    "href" => "something"
                ),
                array(
                    "name" => "1b",
                    "subs" => array(// Third Level Items
                        array("name" => "1ba", "href" => "something"),
                        array("name" => "1bb", array(
                                array("name" => "1cca", "href" => "something"),
                            )
                        )
                    )
                )
            )
        ),
        array(// Top level items
            "name" => "item2",
            "subs" => array(// Second Level items
                array(
                    "name" => "2a",
                    "href" => "something"
                ),
                array(
                    "name" => "2b",
                    "subs" => array(// Third Level Items
                        array("name" => "2ba", "href" => "something"),
                        array("name" => "2bb", array(
                                array("name" => "2cca", "href" => "something"),
                            )
                        )
                    )
                )
            )
        )
    );
        $this->menuIterator($menuItems);
        die();

The following logic is the important bit, it'll mean your menu could be any levels deep you want and it'll still produce the same result:

public function menuIterator($items) {
    print "<ul>";
    foreach ($items as $item) {
        print "<li>";
        print "<a>{$item['name']}</a>";
        if (isset($item['subs'])) {
            $this->menuIterator($item['subs']);
        }
        print "</li>";
    }
    print "</ul>";
    return;
}

And the result is:

<ul><li><a>item1</a><ul><li><a>1a</a></li><li><a>1b</a><ul><li><a>1ba</a></li><li><a>1bb</a></li></ul></li></ul></li><li><a>item2</a><ul><li><a>2a</a></li><li><a>2b</a><ul><li><a>2ba</a></li><li><a>2bb</a></li></ul></li></ul></li></ul>


问:
Splitting a project VB/C#, and References
I've inherited a project written mostly in VB. I'd like to maintain what I have in VB while slowly converting to C# when I can. The only way I've found to do this is to create a separate C# project. However, this causes problems because of dependencies and references. I can't have VBProject reference CSharpProject and vice versa because it creates a circular reference. This is a problem because I need both projects to be able to reference the other. Is there a better way to do this, or am I stuck writing in VB (or completely translating to C#)?

Also, these projects are in the same solution. Shouldn't I be able to import/use them without creating a reference or some other easier way?

答:
You will not be able to do this while the c# project has a dependency on the VB project.

You need to extract classes from the VB.net project into the c# project so that the classes/functions are stand alone and do not depend on the VB project.

This is something I battle against at work every day, and I am slowly moving towards the light (c#)


问:
How to force an app to change language in iOS/Objective-C?
I'm having a problem with make app change language immediately like this app.

I've found a lot of similar question like this and this.

But, unfortunately, the related answers to these question don't work for me. I need my app change language immediately when I tap on an cell.

Any ideas? Thank in advance.

答: You should look at this once : HERE</p>

Body: You should look at this once : HERE


问:
Piping output into multiple files iteratively on Unix
I've got a large amount of .mid files in directory foo, and when I apply the command midicsv bar.mid > bar.csv , a .mid file is converted into a newly created .csv file of the same name.

How can I do this iteratively for hundreds of .mid files, outputting the result into files of their respective names in .csv format?

Sorry if I am being unclear at any moment, Bash scripting isn't my peak skill.

答:
Use a loop and parameter expansion.</p>

```<code>for f in foo/*.mid; do
    midicsv "$f" > "${f%.mid}.csv"
done
</code>```

Body:
Use a loop and parameter expansion.

for f in foo/*.mid; do
    midicsv "$f" > "${f%.mid}.csv"
done


问:
How to stub (to bypass) a Sailsjs auth policy to allow for controller testing?
I have a Sailsjs controller that does some stuff, but currently it is under a policy that requires authentication (i.e. isAuthenticated).

Before having applied that policy, the integration test for my controller worked fine. Now it will not work because it requires the user to login.

For reasons not stated, I cannot make a request to login before each test, so I have to find a way to skip that policy. I would like to stub it so it always lets the route go through. How would you do that in Sailsjs v0.12.11?

答:
You can add an API key in your isAuthenticated method and check for this key. If the key is available, call the next() function.

Code snippet:

```<code>module.exports = function (req, res, next) {
if (req.isAuthenticated() || req.headers['api-key'] == 'apiKeyValue') {
    return next();
} else {
    if (!req.headers['api-key'] && !req.isAuthenticated()) {
        return res.redirect('/auth/login');
    } else {
        res.status(403);
        return res.json({
            error: 'Invalid Api Key'
        });
    }
}
</code>```

So essentially, pass an API key via header and modify the logic in isAuthenticated function. So whenever the API key is available, it will call the next() callback.

Body:
You can add an API key in your isAuthenticated method and check for this key. If the key is available, call the next() function.

Code snippet:

module.exports = function (req, res, next) {
if (req.isAuthenticated() || req.headers['api-key'] == 'apiKeyValue') {
    return next();
} else {
    if (!req.headers['api-key'] && !req.isAuthenticated()) {
        return res.redirect('/auth/login');
    } else {
        res.status(403);
        return res.json({
            error: 'Invalid Api Key'
        });
    }
}

So essentially, pass an API key via header and modify the logic in isAuthenticated function. So whenever the API key is available, it will call the next() callback.


问:
What is the meaning of 'mean_test_score' in cv_result?
Hello I'm doing a GridSearchCV and I'm printing the result with the .cv_results_ function from scikit learn.

My problem is that when I'm evaluating by hand the mean on all the test score splits I obtain a different number compared to what it is written in 'mean_test_score'. Which is different from the standard np.mean()?

I attach here the code with the result:

```<code>n_estimators = [100]
max_depth = [3]
learning_rate = [0.1]

param_grid = dict(max_depth=max_depth, n_estimators=n_estimators, learning_rate=learning_rate)

gkf = GroupKFold(n_splits=7)

grid_search = GridSearchCV(model, param_grid, scoring=score_auc, cv=gkf)
grid_result = grid_search.fit(X, Y, groups=patients)

grid_result.cv_results_
</code>```

The result of this operation is:

```<code>{'mean_fit_time': array([ 8.92773601]),
 'mean_score_time': array([ 0.04288721]),
 'mean_test_score': array([ 0.83490629]),
 'mean_train_score': array([ 0.95167036]),
 'param_learning_rate': masked_array(data = [0.1],
              mask = [False],
        fill_value = ?),
 'param_max_depth': masked_array(data = [3],
              mask = [False],
        fill_value = ?),
 'param_n_estimators': masked_array(data = [100],
              mask = [False],
        fill_value = ?),
 'params': ({'learning_rate': 0.1, 'max_depth': 3, 'n_estimators': 100},),
 'rank_test_score': array([1]),
 'split0_test_score': array([ 0.74821666]),
 'split0_train_score': array([ 0.97564995]),
 'split1_test_score': array([ 0.80089016]),
 'split1_train_score': array([ 0.95361201]),
 'split2_test_score': array([ 0.92876979]),
 'split2_train_score': array([ 0.93935856]),
 'split3_test_score': array([ 0.95540287]),
 'split3_train_score': array([ 0.94718634]),
 'split4_test_score': array([ 0.89083901]),
 'split4_train_score': array([ 0.94787374]),
 'split5_test_score': array([ 0.90926355]),
 'split5_train_score': array([ 0.94829775]),
 'split6_test_score': array([ 0.82520379]),
 'split6_train_score': array([ 0.94971417]),
 'std_fit_time': array([ 1.79167576]),
 'std_score_time': array([ 0.02970254]),
 'std_test_score': array([ 0.0809713]),
 'std_train_score': array([ 0.0105566])}
</code>```

As you can see, doing the np.mean of all the test_score it gives you a value approximately of 0.8655122606479532 while the 'mean_test_score' is 0.83490629

Thanks for you help,
Leonardo.

答:
If you see the original code of GridSearchCV in their github repository, they dont use np.mean() instead they use np.average() with weights. Hence the difference. Here's their code:

```<code>n_splits = 3
test_sample_counts = np.array(test_sample_counts[:n_splits],
                                    dtype=np.int)
weights = test_sample_counts if self.iid else None
means = np.average(test_scores, axis=1, weights=weights)
stds = np.sqrt(np.average((test_scores - means[:, np.newaxis])
                               axis=1, weights=weights))

 cv_results = dict()
 for split_i in range(n_splits):
        cv_results["split%d_test_score" % split_i] = test_scores[:,
                                                              split_i]
 cv_results["mean_test_score"] = means
 cv_results["std_test_score"] = stds
</code>```

In case you want to know more about the difference between them take a look
Difference between np.mean() and np.average()

Body:
Hello I'm doing a GridSearchCV and I'm printing the result with the .cv_results_ function from scikit learn.

My problem is that when I'm evaluating by hand the mean on all the test score splits I obtain a different number compared to what it is written in 'mean_test_score'. Which is different from the standard np.mean()?

I attach here the code with the result:

n_estimators = [100]
max_depth = [3]
learning_rate = [0.1]

param_grid = dict(max_depth=max_depth, n_estimators=n_estimators, learning_rate=learning_rate)

gkf = GroupKFold(n_splits=7)

grid_search = GridSearchCV(model, param_grid, scoring=score_auc, cv=gkf)
grid_result = grid_search.fit(X, Y, groups=patients)

grid_result.cv_results_

The result of this operation is:

{'mean_fit_time': array([ 8.92773601]),
 'mean_score_time': array([ 0.04288721]),
 'mean_test_score': array([ 0.83490629]),
 'mean_train_score': array([ 0.95167036]),
 'param_learning_rate': masked_array(data = [0.1],
              mask = [False],
        fill_value = ?),
 'param_max_depth': masked_array(data = [3],
              mask = [False],
        fill_value = ?),
 'param_n_estimators': masked_array(data = [100],
              mask = [False],
        fill_value = ?),
 'params': ({'learning_rate': 0.1, 'max_depth': 3, 'n_estimators': 100},),
 'rank_test_score': array([1]),
 'split0_test_score': array([ 0.74821666]),
 'split0_train_score': array([ 0.97564995]),
 'split1_test_score': array([ 0.80089016]),
 'split1_train_score': array([ 0.95361201]),
 'split2_test_score': array([ 0.92876979]),
 'split2_train_score': array([ 0.93935856]),
 'split3_test_score': array([ 0.95540287]),
 'split3_train_score': array([ 0.94718634]),
 'split4_test_score': array([ 0.89083901]),
 'split4_train_score': array([ 0.94787374]),
 'split5_test_score': array([ 0.90926355]),
 'split5_train_score': array([ 0.94829775]),
 'split6_test_score': array([ 0.82520379]),
 'split6_train_score': array([ 0.94971417]),
 'std_fit_time': array([ 1.79167576]),
 'std_score_time': array([ 0.02970254]),
 'std_test_score': array([ 0.0809713]),
 'std_train_score': array([ 0.0105566])}

As you can see, doing the np.mean of all the test_score it gives you a value approximately of 0.8655122606479532 while the 'mean_test_score' is 0.83490629

Thanks for you help,
Leonardo.

Body:
If you see the original code of GridSearchCV in their github repository, they dont use np.mean() instead they use np.average() with weights. Hence the difference. Here's their code:

n_splits = 3
test_sample_counts = np.array(test_sample_counts[:n_splits],
                                    dtype=np.int)
weights = test_sample_counts if self.iid else None
means = np.average(test_scores, axis=1, weights=weights)
stds = np.sqrt(np.average((test_scores - means[:, np.newaxis])
                               axis=1, weights=weights))

 cv_results = dict()
 for split_i in range(n_splits):
        cv_results["split%d_test_score" % split_i] = test_scores[:,
                                                              split_i]
 cv_results["mean_test_score"] = means
 cv_results["std_test_score"] = stds

In case you want to know more about the difference between them take a look
Difference between np.mean() and np.average()


问:
Can't assign a specific class name to a collection of div's using JavaScript/jQuery
Hi ) I have a task and have done only a half of it, need some help:

need to make a board of 10/10 div's;

need to assign to each div a common class "box" and a specific one "box-x-y", where x and y are coordinates of the div;

I can't do the second task (the last half), for example for first div the class should be "box-1-1", and so on, like in the picture I have attached.
Image

  for(var i = 0; i < 10; i++) {
      for (var j = 0; j < 10; j++){
          $("

").addClass("box").appendTo("#carousel");
      }
      $("

").css("clear", "both").appendTo("#carousel");
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
    float:left;
    width:50px;
    height:50px;
    margin-right:2px;
    margin-bottom:2px;
    border: 1px solid black;
}</code>```

```

答:
Try this</p>

```<code>for(var i = 0; i < 10; i++) {
      for (var j = 0; j < 10; j++){
          $("<div></div>").addClass("box").addClass("box-"+(i+1)+"-"+(j+1)).appendTo("#carousel");
      }
      $("<div></div>").css("clear", "both").appendTo("#carousel");
  }
</code>```

Body:
Hi ) I have a task and have done only a half of it, need some help:

need to make a board of 10/10 div's;

need to assign to each div a common class "box" and a specific one "box-x-y", where x and y are coordinates of the div;

I can't do the second task (the last half), for example for first div the class should be "box-1-1", and so on, like in the picture I have attached.
Image

  for(var i = 0; i < 10; i++) {
      for (var j = 0; j < 10; j++){
          $("

").addClass("box").appendTo("#carousel");
      }
      $("

").css("clear", "both").appendTo("#carousel");
  }

.box {
    float:left;
    width:50px;
    height:50px;
    margin-right:2px;
    margin-bottom:2px;
    border: 1px solid black;
}

Body:
Try this

for(var i = 0; i < 10; i++) {
      for (var j = 0; j < 10; j++){
          $("<div></div>").addClass("box").addClass("box-"+(i+1)+"-"+(j+1)).appendTo("#carousel");
      }
      $("<div></div>").css("clear", "both").appendTo("#carousel");
  }


问:
Doctype breaks jquery fadeOut method in IE!
I recently added a doctype to my page to help fix a little IE rendering problem. It looks like so:

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
</code>```

My fadeOut code (I'm using stop(true,true) to restart the animation if its in progress):

```<code>$('#myElement').stop(true, true).show().fadeOut(5000);
</code>```

Now, my jquery fadeOut(5000) method doesn't fade in IE anymore. Does anyone know of a fix for this?

EDIT:
I've tried pretty much every flavor of DOCTYPE out there, and no matter which one I use, the fadeOut animation does NOT work in IE.

答: i think that its not about doctype. All ie versions always having troubles with fade animations.</p>

Body:
I recently added a doctype to my page to help fix a little IE rendering problem. It looks like so:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

My fadeOut code (I'm using stop(true,true) to restart the animation if its in progress):

$('#myElement').stop(true, true).show().fadeOut(5000);

Now, my jquery fadeOut(5000) method doesn't fade in IE anymore. Does anyone know of a fix for this?

EDIT:
I've tried pretty much every flavor of DOCTYPE out there, and no matter which one I use, the fadeOut animation does NOT work in IE.


答:
```<code>for(var i = 0; i < 10; i++) {
      for (var j = 0; j < 10; j++){

          var classes = "box "+"box-"+i+"-"+j;
          $("<div></div>").addClass(classes).appendTo("#carousel");
      }
      $("<div></div>").css("clear", "both").appendTo("#carousel");
  }
</code>```

Title: Can't assign a specific class name to a collection of div's using JavaScript/jQuery


问:
Gettitng ReferenceError: "CryptoJS" is not defined
I have written javascript to for RSASHA256 but gettitng error crypto.js is not defined.</p>

```<code> function aaa(message,secret) {
     <script src="http://crypto-
      js.googlecode.com/svn/tags/3.0.2/build/rollups/hmac-sha256.js"></script>;
     <script src="http://crypto-
      js.googlecode.com/svn/tags/3.0.2/build/components/enc-base64-min.js"></script>;
     var hash = CryptoJS.HmacSHA256("Message", "secret");
     var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
     document.write(hashInBase64);
}
</code>```

答:
Hi my below code is working fine for HmacSHA256 not for RSASHA256,</p>

```<code> function aaa(message,secret) {
 var hash = CryptoJS.HmacSHA256("Message", "secret");
 var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
 return aaa
 }
</code>```

Body:
I have written javascript to for RSASHA256 but gettitng error crypto.js is not defined.

 function aaa(message,secret) {
     ;
     ;
     var hash = CryptoJS.HmacSHA256("Message", "secret");
     var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
     document.write(hashInBase64);
}

Body:
Hi my below code is working fine for HmacSHA256 not for RSASHA256,

 function aaa(message,secret) {
 var hash = CryptoJS.HmacSHA256("Message", "secret");
 var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
 return aaa
 }


问:
Global Variable to store password for postgres connection in PHP web application
I have a yii2 framework php project in netbeans connected to postgres database.
In the config folder there is a file called db.php which contains the db credentials.

In some files (which is called by the controller) there is pg_connect() which connects to the database, so every time the project is deployed and the password of the db is different , need to change the password of the pg_connect() in all these files , is there a way to use db.php for the password or use a global variable to store the password.

答:
see the \common\config\main.php or \common\config\main.php for global config

```<code>'components' => [
  'db' => [
    'class' => 'yii\db\Connection',
    'dsn' => 'pgsql:host=localhost;dbname=db_name',
    'username' => 'db_username',
    'password' => 'db_password',
    'charset' => 'utf8',
    'schemaMap' => [
      'pgsql'=> [
        'class'=>'yii\db\pgsql\Schema',
        'defaultSchema' => 'public' //specify your schema here
      ]
    ], // PostgreSQL
],
</code>```

Body:
see the \common\config\main.php or \common\config\main.php for global config

'components' => [
  'db' => [
    'class' => 'yii\db\Connection',
    'dsn' => 'pgsql:host=localhost;dbname=db_name',
    'username' => 'db_username',
    'password' => 'db_password',
    'charset' => 'utf8',
    'schemaMap' => [
      'pgsql'=> [
        'class'=>'yii\db\pgsql\Schema',
        'defaultSchema' => 'public' //specify your schema here
      ]
    ], // PostgreSQL
],