问:
Select values from a list that don't exist in DB Table
I have a list of values. I am trying to select from that list all values that do not occur in a table.

for instance

var_nos ['Z1234', 'Z1235,  'Z1236']
select *
from db_table
where db_idno not in var_nos
Is this possible?

** after reading, I'm not sure this makes sense.  I want to return the value from var_nos that did not appear in POHED.

Possibly SQL isn't the best way to handle this?

答:
Rather than creating a list, you could declare a temporary table if you want.
However, you can achieve the same result from the following query. It's not as elegant as creating a temp variable for the list you want to exclude from your results.

```<code>SELECT * FROM db_table
WHERE db_idno NOT IN (SELECT db_idno FROM db_table WHERE db_idno NOT IN ('Z1234', 'Z1235,  'Z1236'))
</code>```

I have tested this in MySQL and it works. Let me know how it goes

Body:
Rather than creating a list, you could declare a temporary table if you want.
However, you can achieve the same result from the following query. It's not as elegant as creating a temp variable for the list you want to exclude from your results.

SELECT * FROM db_table
WHERE db_idno NOT IN (SELECT db_idno FROM db_table WHERE db_idno NOT IN ('Z1234', 'Z1235,  'Z1236'))

I have tested this in MySQL and it works. Let me know how it goes


来源: stackexchange

问:
How does append() work behind the scenes that's causing this?
I'm pretty new to Go and trying to track down a bug in my codebase. In the process I've distilled the problem down to a single call to append(), but can't figure out why it's behaving the way it is...

```<code>func main() {
    foo := []string{"a", "b", "c"}
    fmt.Printf("before: %v\n", foo)

    i := 0
    noop(append(foo[:i], foo[i+1:]...)) // -- call append, but do nothing with the result
    fmt.Printf(" after: %v\n", foo)
}

func noop(a interface{}) {} // -- avoid "evaluated but not used" errors
</code>```

Try it here

So, what the heck is really going on here?

答:
I'm also relatively new to go, but the way I understand append is that it appends all the following arguments to the first argument.

So essentially what you are doing is appending foo[1] and foo[2] to foo[0] and foo[1] without actually changing the length of foo.

If you want to preserve the original slice what you want is this

ContentLicense: CC BY-SA 4.0

Body:
I'm pretty new to Go and trying to track down a bug in my codebase. In the process I've distilled the problem down to a single call to append(), but can't figure out why it's behaving the way it is...

func main() {
    foo := []string{"a", "b", "c"}
    fmt.Printf("before: %v\n", foo)

    i := 0
    noop(append(foo[:i], foo[i+1:]...)) // -- call append, but do nothing with the result
    fmt.Printf(" after: %v\n", foo)
}

func noop(a interface{}) {} // -- avoid "evaluated but not used" errors

Try it here

So, what the heck is really going on here?

ContentLicense: CC BY-SA 3.0


问:
When should I return by value, as opposed to returning a unique pointer
What I'm wondering is, how does returning by value a Cat actually differ from returning an std::unique_ptr<Cat> in terms of passing them around, memory management and using them in practice.

Memory management wise, aren't they the same? As both a returned by value object and an object wrapped in a unique_ptr will have their destructors triggered once they go out of scope?

So, how would you compare both pieces of code:

```<code>Cat catFactory(string catName) {
    return Cat(catName);
}

std::unique_ptr<Cat> catFactory(string catName) {
    return std::unique_ptr(new Cat(catName));
}
</code>```

答:
Memory-management wise they are completely different.

Sure, these days the actual functional difference between these trivial examples is pretty slim, assuming move semantics can make that by-value return cheap (in the second example they're responsible for moving the pointer, instead). And, sure, both objects will be destroyed at the same time if you just let everything go out of scope right away.

But the code is far less simple with the dynamic allocation, and adds a "why?" factor.

You can't really rationalise about the difference any further without inspecting how the result is going to be used after the function returns. Then all the typical considerations about automatic vs dynamic memory allocation come back into play.

In conclusion, there's really no generic, catch-all way to tell you whether a factory should dynamically-allocate or return by value. However, personally I would prefer the latter for simplicity (unless you know that you can't), especially if your object types are typically moveable (which likely won't have much effect in the function itself due to RVO, but may help you at the callsite).

Body:
What I'm wondering is, how does returning by value a Cat actually differ from returning an std::unique_ptr<Cat> in terms of passing them around, memory management and using them in practice.

Memory management wise, aren't they the same? As both a returned by value object and an object wrapped in a unique_ptr will have their destructors triggered once they go out of scope?

So, how would you compare both pieces of code:

Cat catFactory(string catName) {
    return Cat(catName);
}

std::unique_ptr<Cat> catFactory(string catName) {
    return std::unique_ptr(new Cat(catName));
}


问:
Android Studio 3.0 Canary 2: attribute 'android:versionCode' not found
I've updated Android Studio to the latest canary build and now I can't run my app.

Every time when I try to build the project I get the following error:

```<code>Error:F:\...\**app_name**\app\build\intermediates\instant-run-support\debug\slice_0\AndroidManifest.xml:2 attribute 'android:versionCode' not found
</code>```

I tried to manually open the file and the attribute is clearly there:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="****"
      android:versionCode="1"
      android:versionName="1.0"
      split="lib_slice_0_apk">
</manifest>
</code>```

I've tried to clean the project, invalidate cache, restart android studio but nothing helped.

This is my build.gradle (app) file:

```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "****"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
}
</code>```

答: Update Android studio to Canary 3. They solved the problem</p>

Body:
I've updated Android Studio to the latest canary build and now I can't run my app.

Every time when I try to build the project I get the following error:

Error:F:\...\**app_name**\app\build\intermediates\instant-run-support\debug\slice_0\AndroidManifest.xml:2 attribute 'android:versionCode' not found

I tried to manually open the file and the attribute is clearly there:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="****"
      android:versionCode="1"
      android:versionName="1.0"
      split="lib_slice_0_apk">
</manifest>

I've tried to clean the project, invalidate cache, restart android studio but nothing helped.

This is my build.gradle (app) file:

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "****"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
}


问:
Slik Slider- Creating `center` slider
I want to use Slik Slider for creating a center slider. But using Slik Slider I faced a problem and it doesn't work correctly. Actually the center item is not highlighted. My codes and my JSFiddle are following. How can I fix that?

HTML:

```<code><div id=costumers>
      <div id="listSlider-right-icon">
            <i id="listSlider-right-arrow" class="fa fa-2x fa-square color-green">
                <i class="play-icon fa fa-play color-white"></i>
            </i>
        </div>
      <div id="listSlider">
            <div class="costumers_box">
              <h3>
              1
              </h3>
            </div>
            <div class="costumers_box">
              <h3>
              2
              </h3>
            </div>

            <div class="costumers_box">
              <h3>
              3
              </h3>
            </div>
            <div class="costumers_box">
              <h3>
              4
              </h3>
            </div>
            <div class="costumers_box">
              <h3>
              5
              </h3>
            </div>
            <div class="costumers_box">
              <h3>
              6
              </h3>
            </div>
            <div class="costumers_box">
              <h3>
              7
              </h3>
            </div>
            <div class="costumers_box">
              <h3>
              8
              </h3>
            </div>
        </div>
        <div id="listSlider-left-icon">
            <i id="listSlider-left-arrow" class="fa fa-2x fa-square color-green">
                <i class="play-icon fa fa-play color-white"></i>
            </i>
        </div>
      </div>
</code>```

CSS:

```<code>#listSlider{
    display: flex;
    justify-content: space-around;
    width: 70%;
    margin-top: 110px;
}
.costumers_box{
    background-color: #333333;
    width: 160px;
    height: 110px;
    border-radius: 5px;
    margin-left: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.costumers_box h3{
    color: white;
}
#costumers{
    width: 100%;
    height: 250px;
    background-color: #383838;
    margin-bottom: 30px;
    position: relative;
    display: flex;
    justify-content: center;
}
#listSlider-left-icon, #listSlider-right-icon{
    position: absolute;
    margin-top: 150px;
    cursor: pointer;
}
#listSlider-right-icon{
    right: 10%;
}
#listSlider-left-icon{
    left: 10%;
}

#listSlider-left-arrow i, #listSlider-right-arrow i{
    font-size: 12px;
    position: absolute;
    left: 50%;
    top: 0.6em;
    margin-left: -7px;
}
#listSlider-left-arrow i{
     transform: rotate(180deg);
}
#listSlider-right-arrow i{
    margin-left: -5px;
    top: 0.7em;
}
.color-white{
    color: white;
}
.color-green{
    color: #01a89e;
}
</code>```

and here is my JSFiddle

答:
I don't know HOW you want to highlight it, but you can use this CSS selector and add anything you want (I added a yellow background-color and a red border):

```<code>.slick-center {
  background: yellow;
  border: 5px solid red;
}
</code>```

Here's the fiddle: https://jsfiddle.net/mam1h3Lk/2/

If that doesn't work, you have to make the CSS selector more specific:

```<code>div.costumers_box.slick-slide.slick-current.slick-active.slick-center {
  background: yellow;
  border: 5px solid red;
}
</code>```

Title: Slik Slider- Creating `center` slider

Body:
I want to use Slik Slider for creating a center slider. But using Slik Slider I faced a problem and it doesn't work correctly. Actually the center item is not highlighted. My codes and my JSFiddle are following. How can I fix that?

HTML:

              1

              2

              3

              4

              5

              6

              7

              8

CSS:

#listSlider{
    display: flex;
    justify-content: space-around;
    width: 70%;
    margin-top: 110px;
}
.costumers_box{
    background-color: #333333;
    width: 160px;
    height: 110px;
    border-radius: 5px;
    margin-left: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.costumers_box h3{
    color: white;
}
#costumers{
    width: 100%;
    height: 250px;
    background-color: #383838;
    margin-bottom: 30px;
    position: relative;
    display: flex;
    justify-content: center;
}
#listSlider-left-icon, #listSlider-right-icon{
    position: absolute;
    margin-top: 150px;
    cursor: pointer;
}
#listSlider-right-icon{
    right: 10%;
}
#listSlider-left-icon{
    left: 10%;
}

#listSlider-left-arrow i, #listSlider-right-arrow i{
    font-size: 12px;
    position: absolute;
    left: 50%;
    top: 0.6em;
    margin-left: -7px;
}
#listSlider-left-arrow i{
     transform: rotate(180deg);
}
#listSlider-right-arrow i{
    margin-left: -5px;
    top: 0.7em;
}
.color-white{
    color: white;
}
.color-green{
    color: #01a89e;
}

and here is my JSFiddle

Body:
I don't know HOW you want to highlight it, but you can use this CSS selector and add anything you want (I added a yellow background-color and a red border):

.slick-center {
  background: yellow;
  border: 5px solid red;
}

Here's the fiddle: https://jsfiddle.net/mam1h3Lk/2/

If that doesn't work, you have to make the CSS selector more specific:

div.costumers_box.slick-slide.slick-current.slick-active.slick-center {
  background: yellow;
  border: 5px solid red;
}


答:
Returning by value should be considered the default. (*) Deviating from the default practice, by returning std::unique_ptr<Cat>, should require justification.

There are three main reasons to return a pointer:

Polymorphism. This is the best reason to return std::unique_ptr<Cat> instead of Cat: that you might actually be creating an object of a type derived from Cat. If you need this polymorphism, you absolutely need to return a pointer of some sort. This is why factory functions usually return pointers.

Cat cannot be moved cheaply or cannot be moved at all. "Inherently" unmovable types are rare; you should usually try to fix Cat by making it cheaply movable. But of course Cat could be a type owned by someone else, to which you cannot add a move constructor (or perhaps even a copy constructor). In that case, there is not much you can do other than use unique_ptr (and complain to the owner).

The function has the potential to fail and be unable to construct any valid Cat. In that case, one possibility is return by value anyway but throw an exception if the Cat cannot be constructed; the other, in C++11/C++14, is to make the function return std::unique_ptr<Cat> and have it return a null pointer when no Cat can be constructed. In C++17, however, you should start returning std::optional<Cat> instead of std::unique_ptr<Cat> in that case, to avoid unnecessary heap allocation.

(*) This also applies to passing objects when the function being called needs its own copy of the value, e.g., a constructor that will initialize a class member from one of its arguments. Accept the object by value and move.

Title: When should I return by value, as opposed to returning a unique pointer


问:
LAMP with Hudson: How to run SQL Statement every hour
I'm using CentOS 5.5, Apache, MySQL and PHP. I also installed Hudson. Now I would like to run an SQL Statement every hour. What is the easiest way? Should I use Cron or Hudson?</p>

答:
cron is pluggable as long your box is with crond enable,

use less resource unlike java-based hudson,

As a Java-based web application, Hudson is heavyweight. A low-memory or embedded system is better-off with cron. Even Hudson’s remote job invocation installs and starts a Java-based runtime. You can, however, use the SSH plugin if even one box can run the main Hudson instance.

Cron’s scheduling is more precise if things have to happen exactly at certain time intervals. Hudson’s assumption is that your periodic builds aren’t dependent on when they start within a minute or two.

ContentLicense: CC BY-SA 2.5


问:
How to share health checks between multiple backends?
I have two backends in order to maintain two sets of rules in my application. One for the main website accessed via the browser (cookied sessions), and one for the API (stateless and authenticated by an API key).

The config looks like this (greatly simplified).

```<code>defaults
    option httpchk HEAD /ping

backend web
    cookie _srv insert indirect
    server srv1 10.0.0.1:80 cookie srv1 check inter 10s
    server srv2 10.0.0.2:80 cookie srv2 check inter 10s

backend api
    stick-table type string len 50 expire 1d store http_req_cnt
    stick on url_param(key)
    server srv1 10.0.0.1:80 check inter 10s
    server srv2 10.0.0.2:80 check inter 10s
</code>```

As shown, both backends use the same servers, except that the API need not set a cookie. There is (or will be) much more to separate the logic, such as rate limiting rules.

My question is how can I avoid duplicating the health checks? It's waste of resources to ping the same endpoint twice for each server. I would like to let the web backend do the health check and mark the api backend as up or down along with it. Is this possible? Or perhaps there's a better way to separate the back ends but keep common functions.

答:
track [<proxy>/]<server>

This option enables ability to set the current state of the server by tracking another one. It is possible to track a server which itself tracks another server, provided that at the end of the chain, a server has health checks enabled. If  is omitted the current one is used. If disable-on-404 is used, it has to be enabled on both proxies.

http://cbonte.github.io/haproxy-dconv/1.6/configuration.html#5.2-track

This goes in the server line.

```<code>backend api
    server srv1 10.0.0.1:80 track web/srv1
    server srv2 10.0.0.2:80 track web/srv2
</code>```

This is from 1.6, but later versions should be the same.
The feature exists in 1.5 and 1.4, also.  It may exist in previous versions, but those are unmaintained and you shouldn't be using them.

Body:
I have two backends in order to maintain two sets of rules in my application. One for the main website accessed via the browser (cookied sessions), and one for the API (stateless and authenticated by an API key).

The config looks like this (greatly simplified).

defaults
    option httpchk HEAD /ping

backend web
    cookie _srv insert indirect
    server srv1 10.0.0.1:80 cookie srv1 check inter 10s
    server srv2 10.0.0.2:80 cookie srv2 check inter 10s

backend api
    stick-table type string len 50 expire 1d store http_req_cnt
    stick on url_param(key)
    server srv1 10.0.0.1:80 check inter 10s
    server srv2 10.0.0.2:80 check inter 10s

As shown, both backends use the same servers, except that the API need not set a cookie. There is (or will be) much more to separate the logic, such as rate limiting rules.

My question is how can I avoid duplicating the health checks? It's waste of resources to ping the same endpoint twice for each server. I would like to let the web backend do the health check and mark the api backend as up or down along with it. Is this possible? Or perhaps there's a better way to separate the back ends but keep common functions.

Body:
track [<proxy>/]<server>

This option enables ability to set the current state of the server by tracking another one. It is possible to track a server which itself tracks another server, provided that at the end of the chain, a server has health checks enabled. If  is omitted the current one is used. If disable-on-404 is used, it has to be enabled on both proxies.

http://cbonte.github.io/haproxy-dconv/1.6/configuration.html#5.2-track

This goes in the server line.

backend api
    server srv1 10.0.0.1:80 track web/srv1
    server srv2 10.0.0.2:80 track web/srv2

This is from 1.6, but later versions should be the same.
The feature exists in 1.5 and 1.4, also.  It may exist in previous versions, but those are unmaintained and you shouldn't be using them.


问:
Change border color of a single cell inside a Table
I have a named table as range (list object) and I need to change the edge top border color of one cell but the code doesn´t works, i need some help. Here is part of the code:</p>

```<code>With ws
    .Unprotect Password:="pAtRiCiA"

    For Each ctrl In Me.Controls
        If Left(ctrl.Name, 5) = "texto" Then
            If ultimafila - 1 <> 8 Then
                If ctrl.Name = "textoCausas" Then
                    If Not IsError(Application.Match(Me.textoCausas.Value, ws.ListObjects(ActiveSheet.Name).ListColumns(1).DataBodyRange, 0)) Then
                        .Cells(ultimafila, ctrl.TabIndex) = ""
                        .ListObjects(ActiveSheet.Name).ListColumns(1).DataBodyRange(ultimafila, 1).Borders(xlEdgeTop).LineStyle = xlContinuous
                        .ListObjects(ActiveSheet.Name).ListColumns(1).DataBodyRange(ultimafila, 1).Borders(xlEdgeTop).ColorIndex = 3
                        .ListObjects(ActiveSheet.Name).ListColumns(1).DataBodyRange(ultimafila, 1).Borders(xlEdgeTop).Weight = xlThick
                    Else
                        .Cells(ultimafila, ctrl.TabIndex) = ctrl.Value
                    End If
                Else
                    .Cells(ultimafila, ctrl.TabIndex) = ctrl.Value
                End If
            Else
                .Cells(ultimafila, ctrl.TabIndex) = ctrl.Value
            End If
        End If
    Next ctrl
    .Cells(ultimafila, 2) = txtControles.Value

    .Rows(ultimafila).AutoFit
    .Rows(ultimafila).RowHeight = .Cells(ultimafila, 1).Height + 12
    .Protect Password:="pAtRiCiA", DrawingObjects:=True, Contents:=True, Scenarios:=True
End With
</code>```

答:
With this test code:

```<code>Sub Test()

    With ActiveSheet.ListObjects(1).ListColumns(1).DataBodyRange(6, 1).Borders(xlEdgeTop)
        .LineStyle = xlContinuous
        .ColorIndex = 3
        .Weight = xlThick
    End With

End Sub
</code>```

I get this result:

So, your formatting code works fine for me.

Do you maybe have some Conditional Formatting or some other formatting applied to that sheet?

Body:
I have a named table as range (list object) and I need to change the edge top border color of one cell but the code doesn´t works, i need some help. Here is part of the code:

With ws
    .Unprotect Password:="pAtRiCiA"

    For Each ctrl In Me.Controls
        If Left(ctrl.Name, 5) = "texto" Then
            If ultimafila - 1 <> 8 Then
                If ctrl.Name = "textoCausas" Then
                    If Not IsError(Application.Match(Me.textoCausas.Value, ws.ListObjects(ActiveSheet.Name).ListColumns(1).DataBodyRange, 0)) Then
                        .Cells(ultimafila, ctrl.TabIndex) = ""
                        .ListObjects(ActiveSheet.Name).ListColumns(1).DataBodyRange(ultimafila, 1).Borders(xlEdgeTop).LineStyle = xlContinuous
                        .ListObjects(ActiveSheet.Name).ListColumns(1).DataBodyRange(ultimafila, 1).Borders(xlEdgeTop).ColorIndex = 3
                        .ListObjects(ActiveSheet.Name).ListColumns(1).DataBodyRange(ultimafila, 1).Borders(xlEdgeTop).Weight = xlThick
                    Else
                        .Cells(ultimafila, ctrl.TabIndex) = ctrl.Value
                    End If
                Else
                    .Cells(ultimafila, ctrl.TabIndex) = ctrl.Value
                End If
            Else
                .Cells(ultimafila, ctrl.TabIndex) = ctrl.Value
            End If
        End If
    Next ctrl
    .Cells(ultimafila, 2) = txtControles.Value

    .Rows(ultimafila).AutoFit
    .Rows(ultimafila).RowHeight = .Cells(ultimafila, 1).Height + 12
    .Protect Password:="pAtRiCiA", DrawingObjects:=True, Contents:=True, Scenarios:=True
End With

Body:
With this test code:

Sub Test()

    With ActiveSheet.ListObjects(1).ListColumns(1).DataBodyRange(6, 1).Borders(xlEdgeTop)
        .LineStyle = xlContinuous
        .ColorIndex = 3
        .Weight = xlThick
    End With

End Sub

I get this result:

So, your formatting code works fine for me.

Do you maybe have some Conditional Formatting or some other formatting applied to that sheet?


问:
Android Files USB Stick Access?
I want access to a file: "/mnt/media_rw/72Ab-289A/myFile.mp3"
This file is located on my USB Stick on my Moto G5 Android 7 Smartphone.

But it's not possible... I can't read the /mnt/media_rw/ folder.

The permissions: WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE are set, so this is not the problem.

I've tried it for 5 hours, with google, Environment.getExternalStorageDirectory(), ContextCompat.getExternalFilesDirs, File.readFiles, and much more... nothing is working.

Is there anyone out there and can help me, with a complete solution?

答:
It seems that it's something with the USB or Drive Permissions. On my ODROID C2 with Android 6 it's working fine. But with my Moto G5 (Android 7) and Asus Zen Tablet (Android 6) it's not working.

I can select a file with "Intent.ACTION_OPEN_DOCUMENT" File Picker, and on all devices the Document Path is the same... but, some of the Volumes are not there:

Asus Zen (Android 6)

Volume: /storage/emulated/0

selected file: /storage/7C23-16EA/m_BlueforLabrusca.mp3

.
.
.

ODroid C2 (Android 6)

Volume: /storage/emulated/0

Volume: /storage/internal

Volume: /storage/7C23-16EA

selected file: /storage/7C23-16EA/m_BlueforLabrusca.mp3

```<code>StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
Class<?> StorageVolume = Class.forName("android.os.storage.StorageVolume");
Method getVolumeListMethod = StorageManager.class.getDeclaredMethod("getVolumeList");
Method methodGetPath = StorageVolume.getDeclaredMethod("getPath");

Object[] storageVolumeList = (Object[]) getVolumeListMethod.invoke(storageManager);
    final int length = Array.getLength(storageVolumeList);
            for (int i = 0; i < length; i++) {

                Object storageVolumeElement = Array.get(storageVolumeList, i);
                String path = (String) methodGetPath.invoke(storageVolumeElement);
                path = new File(path).getAbsolutePath();

                volumes.add(new File(path));

                Log.i("!!!","Volume: " + path);
            }
</code>```

Title: Android Files USB Stick Access?

Body:
It seems that it's something with the USB or Drive Permissions. On my ODROID C2 with Android 6 it's working fine. But with my Moto G5 (Android 7) and Asus Zen Tablet (Android 6) it's not working.

I can select a file with "Intent.ACTION_OPEN_DOCUMENT" File Picker, and on all devices the Document Path is the same... but, some of the Volumes are not there:

Asus Zen (Android 6)

Volume: /storage/emulated/0

selected file: /storage/7C23-16EA/m_BlueforLabrusca.mp3

.
.
.

ODroid C2 (Android 6)

Volume: /storage/emulated/0

Volume: /storage/internal

Volume: /storage/7C23-16EA

selected file: /storage/7C23-16EA/m_BlueforLabrusca.mp3

StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
Class<?> StorageVolume = Class.forName("android.os.storage.StorageVolume");
Method getVolumeListMethod = StorageManager.class.getDeclaredMethod("getVolumeList");
Method methodGetPath = StorageVolume.getDeclaredMethod("getPath");

Object[] storageVolumeList = (Object[]) getVolumeListMethod.invoke(storageManager);
    final int length = Array.getLength(storageVolumeList);
            for (int i = 0; i < length; i++) {

                Object storageVolumeElement = Array.get(storageVolumeList, i);
                String path = (String) methodGetPath.invoke(storageVolumeElement);
                path = new File(path).getAbsolutePath();

                volumes.add(new File(path));

                Log.i("!!!","Volume: " + path);
            }


问:
How can I import CSV UTF-8 file with Chinese characters into MySQL?
I've tried importing the following CSV file with UTF-8 encoding into MySQL, but the Chinese characters are not correctly populating. I also changed the column collate to utf8 - default collation and big5-big5_chinese_ci , but the data is still not populating the correct characters.

Data I'm trying to import:
Data I'm trying to import into MySQL

SQL Query I'm using to import data:

```<code>LOAD DATA LOCAL INFILE 'C:\\Users\\Ulises.Sotomoyor\\Downloads\\Insights.csv'
INTO TABLE unpaid_media.insights
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(@Date, Section, Language, Insights)
SET Date = str_to_date(@Date, '%m/%d/%Y')
</code>```

MySQL Table Setting/Collation:
MySQL Table Setting/Collation

答:
Query used for the solution:</p>

```<code>LOAD DATA LOCAL INFILE 'C:\\Users\\Ulises.Sotomoyor\\Downloads\\Insights.csv'
     INTO TABLE unpaid_media.insights
     CHARACTER SET utf8mb4
     FIELDS TERMINATED BY ','
     ENCLOSED BY '"'
     LINES TERMINATED BY '\r\n'
     IGNORE 1 LINES
     (@Date, Section, Language, Insights)
     SET Date = str_to_date(@Date, '%m/%d/%Y')
</code>```

Body:
I've tried importing the following CSV file with UTF-8 encoding into MySQL, but the Chinese characters are not correctly populating. I also changed the column collate to utf8 - default collation and big5-big5_chinese_ci , but the data is still not populating the correct characters.

Data I'm trying to import:
Data I'm trying to import into MySQL

SQL Query I'm using to import data:

LOAD DATA LOCAL INFILE 'C:\\Users\\Ulises.Sotomoyor\\Downloads\\Insights.csv'
INTO TABLE unpaid_media.insights
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(@Date, Section, Language, Insights)
SET Date = str_to_date(@Date, '%m/%d/%Y')

MySQL Table Setting/Collation:
MySQL Table Setting/Collation

Body:
Query used for the solution:

LOAD DATA LOCAL INFILE 'C:\\Users\\Ulises.Sotomoyor\\Downloads\\Insights.csv'
     INTO TABLE unpaid_media.insights
     CHARACTER SET utf8mb4
     FIELDS TERMINATED BY ','
     ENCLOSED BY '"'
     LINES TERMINATED BY '\r\n'
     IGNORE 1 LINES
     (@Date, Section, Language, Insights)
     SET Date = str_to_date(@Date, '%m/%d/%Y')


答:
You could use 'not in'.

```<code>select *
from db_table where db_idno not in (
    select * from (
        select 'Z1234' db_idno
        union select 'Z1235'
        union select 'Z1236'
    ) exclude
)
</code>```

Tested on MySQL.

Title: Select values from a list that don't exist in DB Table

Body:
I have a list of values. I am trying to select from that list all values that do not occur in a table.

for instance

var_nos ['Z1234', 'Z1235,  'Z1236']
select *
from db_table
where db_idno not in var_nos
Is this possible?

** after reading, I'm not sure this makes sense.  I want to return the value from var_nos that did not appear in POHED.

Possibly SQL isn't the best way to handle this?

Body:
You could use 'not in'.

select *
from db_table where db_idno not in (
    select * from (
        select 'Z1234' db_idno
        union select 'Z1235'
        union select 'Z1236'
    ) exclude
)

Tested on MySQL.


问:
Get IP Address from Mac Address
Is it possible to determine a device's IP address from its MAC address over a local network?  If possible, I'd like to be able to do this from the command line.

I need to connect my raspberry pi to my school wireless network and ssh/vnc into it, but I don't want to have to bring peripherals ( mouse, keyboard, monitor ) just to check which IP address it's been dynamically allocated.

答:
It's an old post, but I needed this recently.

I've tried to ping all devices on local network, this represented 65k+ different ip addresses. I somehow managed to launch the pings in parralel in batch with start command, but with so much commands it quickly gets a mess of command prompts opening and closing, and seem to be bad enough for my laptop.

Then, I tried with java and its isReachable() method, which tries a ping. Enclosed this on a fixed thread pool and here i go again... pings done, arp -a gives me the IP.... i try a second time, arp-a gives nothing... wtf

The VERY IMPORTANT thing, if you want to scan your network, is to check your arp table for your wanted IP after EACH ping. In Java I managed to scan all 60k+ ip addresses in like 30secs, and couldn't do better with batch... because yeah, I had to do it in windows

Hope it'll help somebody...

Title: Get IP Address from Mac Address


问:
HTML blank screen
Why does this result in a blank screen?

01_using_javascript.html:

```<code><!DOCTYPE html>
  <html>
    <head>
      <title> Test </title>
      <script src="01_using_javascript.js"> </script>
    </head>

    <body>
        <p id="demo"></p>
    </body>
  </html>
</code>```

01_using_javascript.js:

```<code>document.getElementById("demo").innerHTML = Hi;
</code>```

答: Change the line in 01_using_javascript.js to document.getElementById("demo").innerHTML = "Hi";.  The browser does not recognise Hi on it's own.

Title: HTML blank screen

Body:
Why does this result in a blank screen?

01_using_javascript.html:

<!DOCTYPE html>

      <title> Test </title>

01_using_javascript.js:

document.getElementById("demo").innerHTML = Hi;


问:
Laravel Form::Model Binding - PUT/PATCH Update Routing not working
I have routes set up to to create a person record as follows:

```<code>Route::get('bodymaker/create', 'BodyMakerController@create')->name('bodymaker.create');
Route::post('bodymaker', 'BodyMakerController@store')->name('bodymaker.store');
Route::get('bodymaker/{id}/edit', 'BodyMakerController@edit')->name('bodymaker.edit');
Route::put('bodymaker/{id}/update', 'BodyMakerController@update')->name('bodymaker.update');
Route::patch('bodymaker/{id}', 'BodyMakerController@update')->name('bodymaker.update');
</code>```

The controller methods to generate a new record works properly and look like this:

```<code>public function create()
{
    return View::make('bodymaker.create');
}

public function store(Request $request)
{
    $person = new Person;

    $person->first_name = $request->first_name;
    $person->last_name = $request->last_name;
    $person->save();

    return View::make('person.store', ['person'=>$person]);
}
</code>```

NOW... my problem is getting the edit/update form to bind properly...

```<code>public function edit($id)
{
    $person = Person::findOrFail($id);

    return View::make('person.edit', ['person'=>$person]);
}

public function update($id)
{
// This route fails when I pass in the Request $request like in the store method.
//But how does the update method receive the form values differently than the store method(?)
    $person = Person::findOrFail($id);

    $person->first_name = $request->first_name;
    $person->last_name = $request->last_name;
    $person->save();

    return View::make('person.update', ['person'=>$person]);
}
</code>```

The form for the update looks like this

```<code>{{ Form::model($person, ['route' => ['person.edit', $person->id], 'method' => 'PUT'] }}

        {{ csrf_field() }}
        {!!  Form::text('first_name'), Input::old('first_name')  !!}
        {!!  Form::text('last_name'), Input::old('last_name')  !!}
        {!! Form::submit('Update Person') !!}

{!!  Form::close()  !!}
</code>```

I can't seem to get the form to update the record, only been able to generate a new record.  Something about the syntax for the Form::model binding that I'm not understanding. The PUT request is failing when I pass in the Request as an argument so I don't understand the difference between POST & PUT as used inside Laravel either, though I'm not sure that's my problem

Here is my artisan route:list

```<code>| web,auth |||GET|HEAD| bodymaker/{id}/edit  | bodymaker.edit  | App\Http\Controllers\BodyMakerController@edit
| web,auth |||PUT     | bodymaker/{id}/update| bodymaker.update| App\Http\Controllers\BodyMakerController@update
</code>```

答:
Your controller update method signature should look like this, with $request as the first argument and $id as the second. And I consolidated some of the logic too, but this is optional.

```<code>public function update(Request $request, $id)
{
    $person = Person::findOrFail($id);
    $person->update($request->all());

    return view('person.update', compact('person'));
}
</code>```

Also, not that it should matter, given that the URL structure is identical, but you're using the person.edit instead of the person.update route in your form defintion. But I see that you have two routes called person.update. One is for PUT and the other PATCH. You may want to be careful re-using the same route names.

Finally, if using the Laravel Form helpers, you don't need to add the csrf_field() yourself. This is added automatically.

Body:
I have routes set up to to create a person record as follows:

Route::get('bodymaker/create', 'BodyMakerController@create')->name('bodymaker.create');
Route::post('bodymaker', 'BodyMakerController@store')->name('bodymaker.store');
Route::get('bodymaker/{id}/edit', 'BodyMakerController@edit')->name('bodymaker.edit');
Route::put('bodymaker/{id}/update', 'BodyMakerController@update')->name('bodymaker.update');
Route::patch('bodymaker/{id}', 'BodyMakerController@update')->name('bodymaker.update');

The controller methods to generate a new record works properly and look like this:

public function create()
{
    return View::make('bodymaker.create');
}

public function store(Request $request)
{
    $person = new Person;

    $person->first_name = $request->first_name;
    $person->last_name = $request->last_name;
    $person->save();

    return View::make('person.store', ['person'=>$person]);
}

NOW... my problem is getting the edit/update form to bind properly...

public function edit($id)
{
    $person = Person::findOrFail($id);

    return View::make('person.edit', ['person'=>$person]);
}

public function update($id)
{
// This route fails when I pass in the Request $request like in the store method.
//But how does the update method receive the form values differently than the store method(?)
    $person = Person::findOrFail($id);

    $person->first_name = $request->first_name;
    $person->last_name = $request->last_name;
    $person->save();

    return View::make('person.update', ['person'=>$person]);
}

The form for the update looks like this

{{ Form::model($person, ['route' => ['person.edit', $person->id], 'method' => 'PUT'] }}

        {{ csrf_field() }}
        {!!  Form::text('first_name'), Input::old('first_name')  !!}
        {!!  Form::text('last_name'), Input::old('last_name')  !!}
        {!! Form::submit('Update Person') !!}

{!!  Form::close()  !!}

I can't seem to get the form to update the record, only been able to generate a new record.  Something about the syntax for the Form::model binding that I'm not understanding. The PUT request is failing when I pass in the Request as an argument so I don't understand the difference between POST & PUT as used inside Laravel either, though I'm not sure that's my problem

Here is my artisan route:list

| web,auth |||GET|HEAD| bodymaker/{id}/edit  | bodymaker.edit  | App\Http\Controllers\BodyMakerController@edit
| web,auth |||PUT     | bodymaker/{id}/update| bodymaker.update| App\Http\Controllers\BodyMakerController@update

Body:
Your controller update method signature should look like this, with $request as the first argument and $id as the second. And I consolidated some of the logic too, but this is optional.

public function update(Request $request, $id)
{
    $person = Person::findOrFail($id);
    $person->update($request->all());

    return view('person.update', compact('person'));
}

Also, not that it should matter, given that the URL structure is identical, but you're using the person.edit instead of the person.update route in your form defintion. But I see that you have two routes called person.update. One is for PUT and the other PATCH. You may want to be careful re-using the same route names.

Finally, if using the Laravel Form helpers, you don't need to add the csrf_field() yourself. This is added automatically.


问:
Change z-index for the clicked button relative to the wanted section
I have a parallax JavaScript code with 5 sections (with class background), each section 1 image + text with a content wrapper.

They actually have the following z-index::

.background:nth-child(1) { z-index: 5; }

.background:nth-child(2) { z-index: 4; }

.background:nth-child(3) { z-index: 3; }

.background:nth-child(4) { z-index: 2; }

.background:nth-child(5) { z-index: 1; }
```

<pre class="lang-js prettyprint-override"><code>var currentSlideNumber = 0;
</code>```

(Will tell which slide I'm at so I can make transitions in the left-menu, and with scroll.)

And I also have, a left-menu fixed to chose where do I want to go without having to scroll through the sections, my problem is that I can't make the higher sections show after being in a lower one ( I'm in .background:nth-child(1), I can't make it show the .background:nth-child(5) but has I have the z-index higher in the 1st it just sits behind it)

Any ideas how I should code so that I can get and higher z-index in the (for example) 5th comparing to the 1st but also if I get back clicking at the first the z-index would return to normal.

I want it to be capable of showing the slide with z-index when called from the left-menu.

Any ideas how can I do it?

答:
When you show a slide by clicking an option in the menu, you can apply a slide-active class to the respective slide. You'll also need to remove this class from any previously active slides:

```<code>document.querySelector('.slide-active').classList.remove('slide-active')

// Assumes currentSlideNumber is an array index, ie 0 - (n - 1). Otherwise use currentSlideNumber - 1
document.querySelectorAll('.background')[currentSlideNumber].classList.add('slide-active')
</code>```

And the CSS:

```<code>.slide-active {
    z-index: 999
}
</code>```

In this way, you can remove unique z-index from each slide and just DOM ordering to have the top slide to show by default (i.e. placing it last in the markup).

Body:
I have a parallax JavaScript code with 5 sections (with class background), each section 1 image + text with a content wrapper.

They actually have the following z-index::

.background:nth-child(1) { z-index: 5; }

.background:nth-child(2) { z-index: 4; }

.background:nth-child(3) { z-index: 3; }

.background:nth-child(4) { z-index: 2; }

.background:nth-child(5) { z-index: 1; }

var currentSlideNumber = 0;

(Will tell which slide I'm at so I can make transitions in the left-menu, and with scroll.)

And I also have, a left-menu fixed to chose where do I want to go without having to scroll through the sections, my problem is that I can't make the higher sections show after being in a lower one ( I'm in .background:nth-child(1), I can't make it show the .background:nth-child(5) but has I have the z-index higher in the 1st it just sits behind it)

Any ideas how I should code so that I can get and higher z-index in the (for example) 5th comparing to the 1st but also if I get back clicking at the first the z-index would return to normal.

I want it to be capable of showing the slide with z-index when called from the left-menu.

Any ideas how can I do it?

Body:
When you show a slide by clicking an option in the menu, you can apply a slide-active class to the respective slide. You'll also need to remove this class from any previously active slides:

document.querySelector('.slide-active').classList.remove('slide-active')

// Assumes currentSlideNumber is an array index, ie 0 - (n - 1). Otherwise use currentSlideNumber - 1
document.querySelectorAll('.background')[currentSlideNumber].classList.add('slide-active')

And the CSS:

.slide-active {
    z-index: 999
}

In this way, you can remove unique z-index from each slide and just DOM ordering to have the top slide to show by default (i.e. placing it last in the markup).


问:
Template code creates exponential number of elements
I noticed this strange behaviour with my jQuery code, when it pulled a JSON from an AJAX request to create the elements with a template. What I am trying to do is, with the JSON, which is technically an array of few objects, I am constructing a series of cards, which show something to the user.

I have drilled down the problem to the below code (without using AJAX) and got the issue replicated here as well.

$(function() {
  // Mimicking the AJAX Request.
  // The getJSON gets an array of objects.
  // I am limiting it to just string array, and lenght of 3 to keep things simple.
  var response = ["Alice", "Bob", "Charlie"];
  // My Code.
  $.each(response, function(index, value) {
    $tmp = $(".template").clone();
    $tmp.find("strong").text("Name");
    $tmp.find("span").text(value);
    $tmp.appendTo("body");
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin: 0;
  padding: 0;
  list-style: none;
  text-align: center;
}
.template {
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px;
  width: 150px;
  line-height: 150px;
  display: inline-block;
  cursor: pointer;
  margin: 5px;
}</code>```

  All
  Names

```
</div>
</div>
</p>

<p><strong>Problem</strong></p>

<p>If you see in the above snippet, you could find that the elements are exponentially increasing. i.e., for the nth element, it displays the cards for n times, starting from one:</p>

```n   card        desc
--- ---------- -----------------------------------
1   1 card      Alice is displayed only once.
2   2 cards     Bob is displayed two times.
3   4 cards     Charlie is displayed four times.
```

<p>And so on... I could find an amusing series here, which resembles the powers of 2: <code>1, 2, 4, 8, 16...</code> (2<sup>0</sup>, 2<sup>1</sup>, 2<sup>2</sup>, 2<sup>3</sup>, 2<sup>4</sup>,... Exponential on 2).</p>

<p>Another strange behaviour that I noticed was, when I use an extra <code><div></code>, this problem doesn't happen. For e.g., consider the same code, but wrap the template by nesting it into another <code><div></code> structure:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() {
  // Mimicking the AJAX Request.
  // The getJSON gets an array of objects.
  // I am limiting it to just string array, and lenght of 3 to keep things simple.
  var response = ["Alice", "Bob", "Charlie"];
  // My Code.
  $.each(response, function(index, value) {
    $tmp = $(".extra .template").clone();
    $tmp.find("strong").text("Name");
    $tmp.find("span").text(value);
    $tmp.appendTo("body");
  });
});</code>```

* {
  margin: 0;
  padding: 0;
  list-style: none;
  text-align: center;
}
.template {
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px;
  width: 150px;
  line-height: 150px;
  display: inline-block;
  cursor: pointer;
  margin: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<div class="extra">
  <div class="template">
    <strong>All</strong>
    <span>Names</span>
  </div>
</div></code>```

I am not sure what exactly is causing the problem here. Is there any crazy mistake that I am doing? :)

答:
The reason is, you are not removing the class template, so every time you append, you have double the number of elements with the class template, so the first way to do is, when you do the clone, you need to remove the class template.

```<code>$tmp = $(".template").clone().removeClass("template");
</code>```

Note: In the below preview I have slightly modified the class, because of styling.

$(function() {
  // Mimicking the AJAX Request.
  // The getJSON gets an array of objects.
  // I am limiting it to just string array, and lenght of 3 to keep things simple.
  var response = ["Alice", "Bob", "Charlie"];
  // My Code.
  $.each(response, function(index, value) {
    // ----------- Change here ---------- //
    $tmp = $(".template").clone().removeClass("template");
    $tmp.find("strong").text("Name");
    $tmp.find("span").text(value);
    $tmp.appendTo("body");
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin: 0;
  padding: 0;
  list-style: none;
  text-align: center;
}
.item {
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px;
  width: 150px;
  line-height: 150px;
  display: inline-block;
  cursor: pointer;
  margin: 5px;
}</code>```

  All
  Names

```

The reason why, second time it worked is, you had enclosed the template inside the extra div, and you are appending the new .templates to the  directly, so the selector .extra .template selects only one. Still this is a mistake because each and every
 you generate bears the template class, which ideally shouldn't.

Hope the explanation is clear.

Body:
I noticed this strange behaviour with my jQuery code, when it pulled a JSON from an AJAX request to create the elements with a template. What I am trying to do is, with the JSON, which is technically an array of few objects, I am constructing a series of cards, which show something to the user.

I have drilled down the problem to the below code (without using AJAX) and got the issue replicated here as well.

$(function() {
  // Mimicking the AJAX Request.
  // The getJSON gets an array of objects.
  // I am limiting it to just string array, and lenght of 3 to keep things simple.
  var response = ["Alice", "Bob", "Charlie"];
  // My Code.
  $.each(response, function(index, value) {
    $tmp = $(".template").clone();
    $tmp.find("strong").text("Name");
    $tmp.find("span").text(value);
    $tmp.appendTo("body");
  });
});

* {
  margin: 0;
  padding: 0;
  list-style: none;
  text-align: center;
}
.template {
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px;
  width: 150px;
  line-height: 150px;
  display: inline-block;
  cursor: pointer;
  margin: 5px;
}

  All
  Names

Problem

If you see in the above snippet, you could find that the elements are exponentially increasing. i.e., for the nth element, it displays the cards for n times, starting from one:

n   card        desc
--- ---------- -----------------------------------
1   1 card      Alice is displayed only once.
2   2 cards     Bob is displayed two times.
3   4 cards     Charlie is displayed four times.

And so on... I could find an amusing series here, which resembles the powers of 2: 1, 2, 4, 8, 16... (20, 21, 22, 23, 24,... Exponential on 2).

Another strange behaviour that I noticed was, when I use an extra
, this problem doesn't happen. For e.g., consider the same code, but wrap the template by nesting it into another
 structure:

$(function() {
  // Mimicking the AJAX Request.
  // The getJSON gets an array of objects.
  // I am limiting it to just string array, and lenght of 3 to keep things simple.
  var response = ["Alice", "Bob", "Charlie"];
  // My Code.
  $.each(response, function(index, value) {
    $tmp = $(".extra .template").clone();
    $tmp.find("strong").text("Name");
    $tmp.find("span").text(value);
    $tmp.appendTo("body");
  });
});

* {
  margin: 0;
  padding: 0;
  list-style: none;
  text-align: center;
}
.template {
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px;
  width: 150px;
  line-height: 150px;
  display: inline-block;
  cursor: pointer;
  margin: 5px;
}

    All
    Names

I am not sure what exactly is causing the problem here. Is there any crazy mistake that I am doing? :)

Body:
The reason is, you are not removing the class template, so every time you append, you have double the number of elements with the class template, so the first way to do is, when you do the clone, you need to remove the class template.

$tmp = $(".template").clone().removeClass("template");

Note: In the below preview I have slightly modified the class, because of styling.

$(function() {
  // Mimicking the AJAX Request.
  // The getJSON gets an array of objects.
  // I am limiting it to just string array, and lenght of 3 to keep things simple.
  var response = ["Alice", "Bob", "Charlie"];
  // My Code.
  $.each(response, function(index, value) {
    // ----------- Change here ---------- //
    $tmp = $(".template").clone().removeClass("template");
    $tmp.find("strong").text("Name");
    $tmp.find("span").text(value);
    $tmp.appendTo("body");
  });
});

* {
  margin: 0;
  padding: 0;
  list-style: none;
  text-align: center;
}
.item {
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px;
  width: 150px;
  line-height: 150px;
  display: inline-block;
  cursor: pointer;
  margin: 5px;
}

<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<div class="item template">
  <strong>All</strong>
  <span>Names</span>
</div>

The reason why, second time it worked is, you had enclosed the template inside the extra div, and you are appending the new .templates to the <body> directly, so the selector .extra .template selects only one. Still this is a mistake because each and every <div> you generate bears the template class, which ideally shouldn't.

Hope the explanation is clear.


问:
Android - onKey events don't fire
I'm having a problem where it seems I can't get key events to fire at all in the emulator (it was working before, but, somehow.. something broke).

Here is some sample code that should fill the second text box with the text of the first when a key is pressed in the first (or if the button is clicked).  But it doesn't do that.

Am I doing something wrong?

Activity class:

```<code>package abc.def;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;

public class Fill extends Activity {
    /** Called when the activity is first created. */
 EditText e1;
 EditText e2;
 Button b;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        e1 = (EditText) findViewById(R.id.EditText01);
        e2 = (EditText) findViewById(R.id.EditText02);
        b = (Button) findViewById(R.id.Button01);

        e1.setOnKeyListener(new OnKeyListener() {
   @Override
   public boolean onKey(View v, int keyCode, KeyEvent event) {
    e2.setText(e1.getText());
    return false;
   }

        });

        b.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View arg0) {
    e2.setText(e1.getText());
   }
        });
    }
}
</code>```

Layout file:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<EditText android:text="" android:id="@+id/EditText01" android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText>
<EditText android:text="" android:id="@+id/EditText02" android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText>
<Button android:text="Click" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
</code>```

答:
You should use e1.getText().toString() to get result.

LogCat will be useful to find out the values that are passed around. You can add the following LogCat for finding out similar issues

Log.d("SOMENAME",e1.getText().toString);

Title: Android - onKey events don't fire

Body:
I'm having a problem where it seems I can't get key events to fire at all in the emulator (it was working before, but, somehow.. something broke).

Here is some sample code that should fill the second text box with the text of the first when a key is pressed in the first (or if the button is clicked).  But it doesn't do that.

Am I doing something wrong?

Activity class:

package abc.def;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;

public class Fill extends Activity {
    /** Called when the activity is first created. */
 EditText e1;
 EditText e2;
 Button b;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        e1 = (EditText) findViewById(R.id.EditText01);
        e2 = (EditText) findViewById(R.id.EditText02);
        b = (Button) findViewById(R.id.Button01);

        e1.setOnKeyListener(new OnKeyListener() {
   @Override
   public boolean onKey(View v, int keyCode, KeyEvent event) {
    e2.setText(e1.getText());
    return false;
   }

        });

        b.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View arg0) {
    e2.setText(e1.getText());
   }
        });
    }
}

Layout file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<EditText android:text="" android:id="@+id/EditText01" android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText>
<EditText android:text="" android:id="@+id/EditText02" android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText>
<Button android:text="Click" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>


问:
Url and port redirection apache 2
My problem is that i configured my dns to redirect two urls towards my server url but one of them must contain the port.
exp

```<code>     www.xxxx.com---> xxx.fff.fff.ggg
     www.yyyy.com---->xxx.fff.fff.ggg:8080
</code>```

but since dns don't accept port in the conf how should i configure the apache2 server to redirect the url to url:port?

thank you

答:
Create name-based virtual host on port 80 (this is routine). In the virtualhost with ServerName www.yyyy.com, redirect all traffic to www.yyyy.com:8080.</p>

```<code># Only in 2.2:
NameVirtualHost *:80
<Virtualhost *:80>
 ServerName www.xxxx.com
</virtualhost>
<Virtualhost *:80>
 ServerName www.yyyy.com
 Redirect / http://www.yyyy.com:8080/
</virtualhost>
</code>```

Title: Url and port redirection apache 2

Body:
My problem is that i configured my dns to redirect two urls towards my server url but one of them must contain the port.
exp

     www.xxxx.com---> xxx.fff.fff.ggg
     www.yyyy.com---->xxx.fff.fff.ggg:8080

but since dns don't accept port in the conf how should i configure the apache2 server to redirect the url to url:port?

thank you

Body:
Create name-based virtual host on port 80 (this is routine). In the virtualhost with ServerName www.yyyy.com, redirect all traffic to www.yyyy.com:8080.

# Only in 2.2:
NameVirtualHost *:80
<Virtualhost *:80>
 ServerName www.xxxx.com
</virtualhost>
<Virtualhost *:80>
 ServerName www.yyyy.com
 Redirect / http://www.yyyy.com:8080/
</virtualhost>


问:
Decimal to BCD to ASCII
Perhaps this task is a bit more complicated than what I've written below, but the code that follows is my take on decimal to BCD. The task is to take in a decimal number, convert it to BCD and then to ASCII so that it can be displayed on a microcontroller. As far as I'm aware the code works sufficiently for the basic operation of converting to BCD however I'm stuck when it comes to converting this into ASCII. The overall output is ASCII so that an incremented value can be displayed on an LCD.

My code so far:

```<code>int dec2bin(int a){              //Decimal to binary function
    int bin;
    int i =1;
    while (a!=0){
    bin+=(a%2)*i;
    i*=10;
    a/=2;
    }
    return bin;
}

unsigned int ConverttoBCD(int val){

    unsigned int unit = 0;
    unsigned int ten = 0;
    unsigned int hundred = 0;

    hundred = (val/100);
    ten = ((val-hundred*100)/10);
    unit = (val-(hundred*100+ten*10));
    uint8_t ret1 = dec2bin(unit);
    uint8_t ret2 = dec2bin((ten)<<4);
    uint8_t ret3 = dec2bin((hundred)<<8);
    return(ret3+ret2+ret1);
}
</code>```

答:
The idea to convert to BCD for an ASCII representation of a number is actually the "correct one". Given BCD, you only need to add '0' to each digit for getting the corresponding ASCII value.

But your code has several problems. The most important one is that you try to stuff a value shifted left by 8 bits in an 8bit type. This can never work, those 8 bits will be zero, think about it! Then I absolutely do not understand what your dec2bin() function is supposed to do.

So I'll present you one possible correct solution to your problem. The key idea is to use a char for each individual BCD digit. Of course, a BCD digit only needs 4 bits and a char has at least 8 of them -- but you need char anyways for your ASCII representation and when your BCD digits are already in individual chars, all you have to do is indeed add '0' to each.

While at it: Converting to BCD by dividing and multiplying is a waste of resources. There's a nice algorithm called Double dabble for converting to BCD only using bit shifting and additions. I'm using it in the following example code:

```<code>#include <stdio.h>
#include <string.h>

// for determining the number of value bits in an integer type,
// see https://stackoverflow.com/a/4589384/2371524 for this nice trick:
#define IMAX_BITS(m) ((m) /((m)%0x3fffffffL+1) /0x3fffffffL %0x3fffffffL *30 \
                  + (m)%0x3fffffffL /((m)%31+1)/31%31*5 + 4-12/((m)%31+3))

// number of bits in unsigned int:
#define UNSIGNEDINT_BITS IMAX_BITS((unsigned)-1)

// convert to ASCII using BCD, return the number of digits:
int toAscii(char *buf, int bufsize, unsigned val)
{
    // sanity check, a buffer smaller than one digit is pointless
    if (bufsize < 1) return -1;

    // initialize output buffer to zero
    // if you don't have memset, use a loop here
    memset(buf, 0, bufsize);
    int scanstart = bufsize - 1;
    int i;

    // mask for single bits in value, start at most significant bit
    unsigned mask = 1U << (UNSIGNEDINT_BITS - 1);
    while (mask)
    {
        // extract single bit
        int bit = !!(val & mask);

        for (i = scanstart; i < bufsize; ++i)
        {
            // this is the "double dabble" trick -- in each iteration,
            // add 3 to each element that is greater than 4. This will
            // generate the correct overflowing bits while shifting for
            // BCD
            if (buf[i] > 4) buf[i] += 3;
        }

        // if we have filled the output buffer from the right far enough,
        // we have to scan one position earlier in the next iteration
        if (buf[scanstart] > 7) --scanstart;

        // check for overflow of our buffer:
        if (scanstart < 0) return -1;

        // now just shift the bits in the BCD digits:
        for (i = scanstart; i < bufsize - 1; ++i)
        {
            buf[i] <<= 1;
            buf[i] &= 0xf;
            buf[i] |= (buf[i+1] > 7);
        }
        // shift in the new bit from our value:
        buf[bufsize-1] <<= 1;
        buf[bufsize-1] &= 0xf;
        buf[bufsize-1] |= bit;

        // next bit:
        mask >>= 1;
    }

    // find first non-zero digit:
    for (i = 0; i < bufsize - 1; ++i) if (buf[i]) break;
    int digits = bufsize - i;

    // eliminate leading zero digits
    // (again, use a loop if you don't have memmove)
    // (or, if you're converting to a fixed number of digits and *want*
    //  the leading zeros, just skip this step entirely, including the
    //  loop above)
    memmove(buf, buf + i, digits);

    // convert to ascii:
    for (i = 0; i < digits; ++i) buf[i] += '0';

    return digits;
}

int main(void)
{
    // some simple test code:
    char buf[10];

    int digits = toAscii(buf, 10, 471142);
    for (int i = 0; i < digits; ++i)
    {
        putchar(buf[i]);
    }

    puts("");
}
</code>```

You won't need this IMAX_BITS() "magic macro" if you actually know your target platform and how many bits there are in the integer type you want to convert.

Title: Decimal to BCD to ASCII

Body:
Perhaps this task is a bit more complicated than what I've written below, but the code that follows is my take on decimal to BCD. The task is to take in a decimal number, convert it to BCD and then to ASCII so that it can be displayed on a microcontroller. As far as I'm aware the code works sufficiently for the basic operation of converting to BCD however I'm stuck when it comes to converting this into ASCII. The overall output is ASCII so that an incremented value can be displayed on an LCD.

My code so far:

int dec2bin(int a){              //Decimal to binary function
    int bin;
    int i =1;
    while (a!=0){
    bin+=(a%2)*i;
    i*=10;
    a/=2;
    }
    return bin;
}

unsigned int ConverttoBCD(int val){

    unsigned int unit = 0;
    unsigned int ten = 0;
    unsigned int hundred = 0;

    hundred = (val/100);
    ten = ((val-hundred*100)/10);
    unit = (val-(hundred*100+ten*10));
    uint8_t ret1 = dec2bin(unit);
    uint8_t ret2 = dec2bin((ten)<<4);
    uint8_t ret3 = dec2bin((hundred)<<8);
    return(ret3+ret2+ret1);
}

Body:
The idea to convert to BCD for an ASCII representation of a number is actually the "correct one". Given BCD, you only need to add '0' to each digit for getting the corresponding ASCII value.

But your code has several problems. The most important one is that you try to stuff a value shifted left by 8 bits in an 8bit type. This can never work, those 8 bits will be zero, think about it! Then I absolutely do not understand what your dec2bin() function is supposed to do.

So I'll present you one possible correct solution to your problem. The key idea is to use a char for each individual BCD digit. Of course, a BCD digit only needs 4 bits and a char has at least 8 of them -- but you need char anyways for your ASCII representation and when your BCD digits are already in individual chars, all you have to do is indeed add '0' to each.

While at it: Converting to BCD by dividing and multiplying is a waste of resources. There's a nice algorithm called Double dabble for converting to BCD only using bit shifting and additions. I'm using it in the following example code:

#include <stdio.h>
#include <string.h>

// for determining the number of value bits in an integer type,
// see https://stackoverflow.com/a/4589384/2371524 for this nice trick:
#define IMAX_BITS(m) ((m) /((m)%0x3fffffffL+1) /0x3fffffffL %0x3fffffffL *30 \
                  + (m)%0x3fffffffL /((m)%31+1)/31%31*5 + 4-12/((m)%31+3))

// number of bits in unsigned int:
#define UNSIGNEDINT_BITS IMAX_BITS((unsigned)-1)

// convert to ASCII using BCD, return the number of digits:
int toAscii(char *buf, int bufsize, unsigned val)
{
    // sanity check, a buffer smaller than one digit is pointless
    if (bufsize < 1) return -1;

    // initialize output buffer to zero
    // if you don't have memset, use a loop here
    memset(buf, 0, bufsize);
    int scanstart = bufsize - 1;
    int i;

    // mask for single bits in value, start at most significant bit
    unsigned mask = 1U << (UNSIGNEDINT_BITS - 1);
    while (mask)
    {
        // extract single bit
        int bit = !!(val & mask);

        for (i = scanstart; i < bufsize; ++i)
        {
            // this is the "double dabble" trick -- in each iteration,
            // add 3 to each element that is greater than 4. This will
            // generate the correct overflowing bits while shifting for
            // BCD
            if (buf[i] > 4) buf[i] += 3;
        }

        // if we have filled the output buffer from the right far enough,
        // we have to scan one position earlier in the next iteration
        if (buf[scanstart] > 7) --scanstart;

        // check for overflow of our buffer:
        if (scanstart < 0) return -1;

        // now just shift the bits in the BCD digits:
        for (i = scanstart; i < bufsize - 1; ++i)
        {
            buf[i] <<= 1;
            buf[i] &= 0xf;
            buf[i] |= (buf[i+1] > 7);
        }
        // shift in the new bit from our value:
        buf[bufsize-1] <<= 1;
        buf[bufsize-1] &= 0xf;
        buf[bufsize-1] |= bit;

        // next bit:
        mask >>= 1;
    }

    // find first non-zero digit:
    for (i = 0; i < bufsize - 1; ++i) if (buf[i]) break;
    int digits = bufsize - i;

    // eliminate leading zero digits
    // (again, use a loop if you don't have memmove)
    // (or, if you're converting to a fixed number of digits and *want*
    //  the leading zeros, just skip this step entirely, including the
    //  loop above)
    memmove(buf, buf + i, digits);

    // convert to ascii:
    for (i = 0; i < digits; ++i) buf[i] += '0';

    return digits;
}

int main(void)
{
    // some simple test code:
    char buf[10];

    int digits = toAscii(buf, 10, 471142);
    for (int i = 0; i < digits; ++i)
    {
        putchar(buf[i]);
    }

    puts("");
}

You won't need this IMAX_BITS() "magic macro" if you actually know your target platform and how many bits there are in the integer type you want to convert.


问:
ListView displays nothing
I would like to send selected item from listview to another listview with sharedprefences. I can save item but cannot see this item another listview. Activity class

```<code>TextView textUrun = (TextView) view.findViewById(R.id.textUrun);
            TextView textFiyat = (TextView) view.findViewById(R.id.textFiyat);
            String yemek = textUrun.getText().toString();
            String fiyat = textFiyat.getText().toString();
            DataProvider dataProvider = new DataProvider(yemek,fiyat);
            list.add(dataProvider);
            String jsonurun = gson.toJson(list);
            SharedPreferences sharedPreferences = getSharedPreferences("yemekbilgi", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("yemek",jsonurun);
            editor.apply();
            Toast.makeText(getApplicationContext(),"Listeye Kaydedildi",Toast.LENGTH_LONG).show();
</code>```

This is list class which should display items.Listele1

```<code>SharedPreferences sharedPreferences = getSharedPreferences("urun1", Context.MODE_PRIVATE);
    List<DataProvider> list;
    String jsonurun = sharedPreferences.getString("liste1", "");
    Gson gson = new Gson();
    DataProvider[] providers = gson.fromJson(jsonurun, DataProvider[].class);
    list = Arrays.asList(providers);
    listDataAdapter = new ListDataAdapter(getApplicationContext(), list);
    listView = (ListView) findViewById(R.id.liste1);
    listView.setAdapter(listDataAdapter);
</code>```

Finally,this is Adapter Class

```<code>public class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();

public ListDataAdapter(@NonNull Context context,List<DataProvider> list) {
    super(context, R.layout.be_layout, list);
}

static class LayoutHandler{
    TextView ad,fiyat;
}

@Override
public void add(@Nullable Object object) {
    super.add(object);
    list.add(object);
}

@Override
public int getCount() {
    return list.size();
}

@Nullable
@Override
public Object getItem(int position) {
    return list.get(position);
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    View view = convertView;
    LayoutHandler layoutHandler;
    if (view == null){
        LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = layoutInflater.inflate(R.layout.child_layout,parent,false);
        layoutHandler = new LayoutHandler();
        layoutHandler.ad = (TextView) view.findViewById(R.id.textUrun);
        layoutHandler.fiyat = (TextView) view.findViewById(R.id.textFiyat);
        view.setTag(layoutHandler);
    }
    else
        layoutHandler = (LayoutHandler) view.getTag();
    DataProvider dataProvider = (DataProvider) this.getItem(position);
    layoutHandler.ad.setText(dataProvider.getAd());
    layoutHandler.fiyat.setText(dataProvider.getFiyat());
    return view;
}
</code>```

}

答:
You passed in a List, but you never assigned it.

```<code>public class ListDataAdapter extends ArrayAdapter<DataProvider> {
    List<DataProvider> list;  // don't assign here

    public ListDataAdapter(@NonNull Context context, @LayoutRes int resource,List<DataProvider> list) {
        super(context, resource, list);
        this.list = list;   // see here
    }
</code>```

It's worth pointing out, though, that you could also not do the above and entirely remove list, add(), and getItem(), getCount() definitions, then it'll likely work.

Any usage of list.get(position) should instead be getItem(position)

Title: ListView displays nothing

Body:
I would like to send selected item from listview to another listview with sharedprefences. I can save item but cannot see this item another listview. Activity class

TextView textUrun = (TextView) view.findViewById(R.id.textUrun);
            TextView textFiyat = (TextView) view.findViewById(R.id.textFiyat);
            String yemek = textUrun.getText().toString();
            String fiyat = textFiyat.getText().toString();
            DataProvider dataProvider = new DataProvider(yemek,fiyat);
            list.add(dataProvider);
            String jsonurun = gson.toJson(list);
            SharedPreferences sharedPreferences = getSharedPreferences("yemekbilgi", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("yemek",jsonurun);
            editor.apply();
            Toast.makeText(getApplicationContext(),"Listeye Kaydedildi",Toast.LENGTH_LONG).show();

This is list class which should display items.Listele1

SharedPreferences sharedPreferences = getSharedPreferences("urun1", Context.MODE_PRIVATE);
    List<DataProvider> list;
    String jsonurun = sharedPreferences.getString("liste1", "");
    Gson gson = new Gson();
    DataProvider[] providers = gson.fromJson(jsonurun, DataProvider[].class);
    list = Arrays.asList(providers);
    listDataAdapter = new ListDataAdapter(getApplicationContext(), list);
    listView = (ListView) findViewById(R.id.liste1);
    listView.setAdapter(listDataAdapter);

Finally,this is Adapter Class

public class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();

public ListDataAdapter(@NonNull Context context,List<DataProvider> list) {
    super(context, R.layout.be_layout, list);
}

static class LayoutHandler{
    TextView ad,fiyat;
}

@Override
public void add(@Nullable Object object) {
    super.add(object);
    list.add(object);
}

@Override
public int getCount() {
    return list.size();
}

@Nullable
@Override
public Object getItem(int position) {
    return list.get(position);
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    View view = convertView;
    LayoutHandler layoutHandler;
    if (view == null){
        LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = layoutInflater.inflate(R.layout.child_layout,parent,false);
        layoutHandler = new LayoutHandler();
        layoutHandler.ad = (TextView) view.findViewById(R.id.textUrun);
        layoutHandler.fiyat = (TextView) view.findViewById(R.id.textFiyat);
        view.setTag(layoutHandler);
    }
    else
        layoutHandler = (LayoutHandler) view.getTag();
    DataProvider dataProvider = (DataProvider) this.getItem(position);
    layoutHandler.ad.setText(dataProvider.getAd());
    layoutHandler.fiyat.setText(dataProvider.getFiyat());
    return view;
}

}

Body:
You passed in a List, but you never assigned it.

public class ListDataAdapter extends ArrayAdapter<DataProvider> {
    List<DataProvider> list;  // don't assign here

    public ListDataAdapter(@NonNull Context context, @LayoutRes int resource,List<DataProvider> list) {
        super(context, resource, list);
        this.list = list;   // see here
    }

It's worth pointing out, though, that you could also not do the above and entirely remove list, add(), and getItem(), getCount() definitions, then it'll likely work.

Any usage of list.get(position) should instead be getItem(position)


问:
Is there any replicate function in Kotlin?
replicate(n:Int,x:T):List<T>  is a list of length n with x the value of every element.

I wrote a mutable version replicate as below:

```<code>fun <T> mutableReplicate(n:Int, x:T) : MutableList<T>{
    val xs = mutableListOf<T>()
    for (i in 1..n){
        xs.add(x)
    }
    return xs
}
</code>```

Is there any bulid-in immutable replicate function in Kotlin?

How to write ourselves an immutable replicate function in Kotlin?

答:
If you need a read-only list, you can implement replicate the following way:

```<code>fun <T> replicate(n: Int, x: T): List<T> = object : AbstractList<T>() {
    override val size: Int = n
    override fun get(index: Int): T =
        if (index in 0..lastIndex) x else throw IndexOutOfBoundsException("$n")

}
</code>```

It has an advantage that it requires a constant amount of memory no matter how large n is.

Body:
replicate(n:Int,x:T):List<T>  is a list of length n with x the value of every element.

I wrote a mutable version replicate as below:

fun <T> mutableReplicate(n:Int, x:T) : MutableList<T>{
    val xs = mutableListOf<T>()
    for (i in 1..n){
        xs.add(x)
    }
    return xs
}

Is there any bulid-in immutable replicate function in Kotlin?

How to write ourselves an immutable replicate function in Kotlin?

Body:
If you need a read-only list, you can implement replicate the following way:

fun <T> replicate(n: Int, x: T): List<T> = object : AbstractList<T>() {
    override val size: Int = n
    override fun get(index: Int): T =
        if (index in 0..lastIndex) x else throw IndexOutOfBoundsException("$n")

}

It has an advantage that it requires a constant amount of memory no matter how large n is.


问:
Should I truncate my ints to shorts before computing bitwise ops on them?
Suppose I have a bitwise expression f: int -> int that is dependent only on the two lowest bytes of the input. In general, would it be any faster to compute (uint32)f'((uint16)x), where f': short -> short? Or is there overhead involved in the conversion? Assume f is too complicated for the compiler to figure this out on its own.

答:
Shorter integers are not faster. Generally speaking, the fastest types have the same size as a native CPU word (so use 32-bit integers on x86, and 64-bit integers on AMD64/x64). Additionally, unsigned integers are faster than signed integers for certain operations ( performance of unsigned vs signed integers ).

Non-word-sized integers are slower than word-sized integers because the processor hardware has to provide additional padding when loading the value, and then truncate it when storing it; there can also be alignment issues (mainly when the ISA allows non-aligned value storage - though even word-sized integers can be non-aligned too).

Recent versions of C come with typdefs of known fast types, with their names indicating the maximum sized values they can accomodate, for example int_fast8_t for the fastest type to perform octet operations on (even though it might even be a 128-bit type when compiled).

In your question, you wrote you're only performing operations on 16-bit values ( "the two lowest bytes of the input"), which means you'll want to use uint_fast16_t. You will want uint (for unsigned) because the lower 16-bits of any integer (even signed integers, like int) represent an unsigned value.

These "fast integer" types are defined in the stdint.h which comes with your compiler, it can be included directly with #include <stdint.h> or indirectly via #include <inttypes.h>. stdint.h will also include limits.h.

More information can be seen in the Wikibook on C:

https://en.wikibooks.org/wiki/C_Programming/stdint.h

stdint.h is a header file in the C standard library introduced in the C99 standard library section 7.18 to allow programmers to write more portable code by providing a set of typedefs that specify exact-width integer types, together with the defined minimum and maximum allowable values for each type, using macros

https://en.wikibooks.org/wiki/C_Programming/inttypes.h

```<code>Fast & fixed integer types | signed         | unsigned
---------------------------+----------------+---------------
 8 bit                     | int_fast8_t    | uint_fast8_t
16 bit                     | int_fast16_t   | uint_fast16_t
32 bit                     | int_fast32_t   | uint_fast32_t
64 bit                     | int_fast64_t   | uint_fast64_t
</code>```

C++

As you can see, these definitions are only mandated by C99 (not C90, nor C++03), however C++11 does improve C90 compatibility by incorporating stdint.h as <cstdint> (i.e. #include <cstdint>).

Microsoft Visual Studio's C++ compiler and toolchain (as of Visual Studio 2017) is not a conforming C99 compiler (this is by-design), however as Visual C++ 2012 and higher is a conforming C++11 compiler you can use <cstdint> as-intended - it is only Visual Studio 2010 and older (2008, 2005, etc) that lack the header.

I note that Microsoft endorses the use of the Clang toolchain with Visual Studio if you wish to compile C99 code: https://blogs.msdn.microsoft.com/vcblog/2015/12/04/clang-with-microsoft-codegen-in-vs-2015-update-1/

Java:

If you're using Java then the size of most primitive types is strictly defined (as opposed to C and C++ where they only need to be capable of storing values from within a certain minimum range as it's valid for a C compiler to use a 128-bit native integer for ushort): https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html - I don't believe there is any way to achieve "fast" native integer arithmetic in pure Java.

C# / .NET:

In C# / .NET the story is similar to Java (as System.Byte, Int16, etc) are strictly defined, and in C# the short, int and long keywords are always aliases for Int16, Int32 and Int64 unlike in C where their definition is vendor-defined.

.NET does have the platform-sized System.IntPtr type, but you cannot perform bitwise or arithmetic operations on it besides addition and subtraction (and the overhead of using the type in the first place would wipe-out any performance gains from using this type - though I note IntPtr is not necessarily word-sized either anyway: The sizeof(void*) does not have to equal sizeof(uint_fast32_t) (because pointers must be large enough to store every possible valid address, yet the native word-size could be smaller, such as a CPU with a 32-bit word size, but with a 64-bit address bus, in which case sizeof(void*) == 8 but sizeof(uint_fast32_t) == 4 - and the reverse is possible: a 64-bit word machine with only a 32-bit address bus (sizeof(void*) == 4, sizeof(uint_fast32_t) == 8).

Python, JavaScript, Ruby, PHP

These are the other 4 top languages on GitHub - they all share in common a weakly-typed design and so do not directly expose any "fast int" functionality or typing system (JavaScript doesn't even let you differentiate between float and int with its Number type)... but if you want performance you wouldn't be using these languages :)

Further reading:

What is uint_fast32_t and why should it be used instead of the regular int and uint32_t?

Exotic architectures the standards committees care about

What's the difference between "int" and "int_fast16_t"?

In practice:

In typical desktop software development targeting x86 and x64 you can take many things for granted, but in more exotic environments things tend to be different: consider the MIPS/NEC VR3400 (similar to the VR3400i used in the Nintendo 64), it's capable of native 64-bit operations (i.e. it has a native 64-bit word size), yet 32-bit operations are actually faster than 64-bit operations, and it supports both 32 and 40-bit address spaces - which means that had stdint.h existed at the time (this was 1995, predating C99) the definitions for "least", "fast", and pointer integer types would be very different to x86.

Body:
Shorter integers are not faster. Generally speaking, the fastest types have the same size as a native CPU word (so use 32-bit integers on x86, and 64-bit integers on AMD64/x64). Additionally, unsigned integers are faster than signed integers for certain operations ( performance of unsigned vs signed integers ).

Non-word-sized integers are slower than word-sized integers because the processor hardware has to provide additional padding when loading the value, and then truncate it when storing it; there can also be alignment issues (mainly when the ISA allows non-aligned value storage - though even word-sized integers can be non-aligned too).

Recent versions of C come with typdefs of known fast types, with their names indicating the maximum sized values they can accomodate, for example int_fast8_t for the fastest type to perform octet operations on (even though it might even be a 128-bit type when compiled).

In your question, you wrote you're only performing operations on 16-bit values ( "the two lowest bytes of the input"), which means you'll want to use uint_fast16_t. You will want uint (for unsigned) because the lower 16-bits of any integer (even signed integers, like int) represent an unsigned value.

These "fast integer" types are defined in the stdint.h which comes with your compiler, it can be included directly with #include <stdint.h> or indirectly via #include <inttypes.h>. stdint.h will also include limits.h.

More information can be seen in the Wikibook on C:

https://en.wikibooks.org/wiki/C_Programming/stdint.h

stdint.h is a header file in the C standard library introduced in the C99 standard library section 7.18 to allow programmers to write more portable code by providing a set of typedefs that specify exact-width integer types, together with the defined minimum and maximum allowable values for each type, using macros

https://en.wikibooks.org/wiki/C_Programming/inttypes.h

Fast & fixed integer types | signed         | unsigned
---------------------------+----------------+---------------
 8 bit                     | int_fast8_t    | uint_fast8_t
16 bit                     | int_fast16_t   | uint_fast16_t
32 bit                     | int_fast32_t   | uint_fast32_t
64 bit                     | int_fast64_t   | uint_fast64_t

C++

As you can see, these definitions are only mandated by C99 (not C90, nor C++03), however C++11 does improve C90 compatibility by incorporating stdint.h as <cstdint> (i.e. #include <cstdint>).

Microsoft Visual Studio's C++ compiler and toolchain (as of Visual Studio 2017) is not a conforming C99 compiler (this is by-design), however as Visual C++ 2012 and higher is a conforming C++11 compiler you can use <cstdint> as-intended - it is only Visual Studio 2010 and older (2008, 2005, etc) that lack the header.

I note that Microsoft endorses the use of the Clang toolchain with Visual Studio if you wish to compile C99 code: https://blogs.msdn.microsoft.com/vcblog/2015/12/04/clang-with-microsoft-codegen-in-vs-2015-update-1/

Java:

If you're using Java then the size of most primitive types is strictly defined (as opposed to C and C++ where they only need to be capable of storing values from within a certain minimum range as it's valid for a C compiler to use a 128-bit native integer for ushort): https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html - I don't believe there is any way to achieve "fast" native integer arithmetic in pure Java.

C# / .NET:

In C# / .NET the story is similar to Java (as System.Byte, Int16, etc) are strictly defined, and in C# the short, int and long keywords are always aliases for Int16, Int32 and Int64 unlike in C where their definition is vendor-defined.

.NET does have the platform-sized System.IntPtr type, but you cannot perform bitwise or arithmetic operations on it besides addition and subtraction (and the overhead of using the type in the first place would wipe-out any performance gains from using this type - though I note IntPtr is not necessarily word-sized either anyway: The sizeof(void*) does not have to equal sizeof(uint_fast32_t) (because pointers must be large enough to store every possible valid address, yet the native word-size could be smaller, such as a CPU with a 32-bit word size, but with a 64-bit address bus, in which case sizeof(void*) == 8 but sizeof(uint_fast32_t) == 4 - and the reverse is possible: a 64-bit word machine with only a 32-bit address bus (sizeof(void*) == 4, sizeof(uint_fast32_t) == 8).

Python, JavaScript, Ruby, PHP

These are the other 4 top languages on GitHub - they all share in common a weakly-typed design and so do not directly expose any "fast int" functionality or typing system (JavaScript doesn't even let you differentiate between float and int with its Number type)... but if you want performance you wouldn't be using these languages :)

Further reading:

What is uint_fast32_t and why should it be used instead of the regular int and uint32_t?

Exotic architectures the standards committees care about

What's the difference between "int" and "int_fast16_t"?

In practice:

In typical desktop software development targeting x86 and x64 you can take many things for granted, but in more exotic environments things tend to be different: consider the MIPS/NEC VR3400 (similar to the VR3400i used in the Nintendo 64), it's capable of native 64-bit operations (i.e. it has a native 64-bit word size), yet 32-bit operations are actually faster than 64-bit operations, and it supports both 32 and 40-bit address spaces - which means that had stdint.h existed at the time (this was 1995, predating C99) the definitions for "least", "fast", and pointer integer types would be very different to x86.


问:
Identifying specific parts of a document using CRF
My goal is given a set of documents (mostly in financial domain), we need to identify specific parts of it like Company Name or Type of the document, etc.

The training is assumed to be done on acouple of 100's of documents. Obviously I would have a skewed class distribution (with None dominating around 99.9% of the examples).
I plan to use CRF (CRFsuite on Sklearn) and have gone through the necessary literature . I needed some advice on the following fronts :

Will the dataset be sufficient to train the CRF? Considering each document can be split into around 100 tokens (each token being a training instance) , we would get 10000 instances in total.

Will the data set be too skewed for training a CRF? For ex: for 100 documents I would have around 400 instances of given class and around 8000 instances of None

答:
Nobody knows that, you have to try it on your dataset, check resulting quality, maybe inspect the CRF model (e.g. https://github.com/TeamHG-Memex/eli5 has sklearn-crfsuite support - a shameless plug), try to come up with better features or decide to annotate more examples, etc. This is just a general data science work. Dataset size looks on a lower side, but depending on how structured is the data and how good are features a few hundred documents may be enough to get started. As the dataset is small, you may have to invest more time in feature engineering.

I don't think class imbalance would be a problem, at least it is unlikely to be your main problem.


答:
As a rule of thumb, never use smaller-than-int types except for storage of large volumes of data where you only need a smaller range, and the larger type would waste lots of memory or impact cache coherency or such.

On most cpu architectures, including x86, narrow types are at best no faster, and at worst slower, than 32-bit or larger types.

Title: Should I truncate my ints to shorts before computing bitwise ops on them?

Body: Suppose I have a bitwise expression f: int -> int that is dependent only on the two lowest bytes of the input. In general, would it be any faster to compute (uint32)f'((uint16)x), where f': short -> short? Or is there overhead involved in the conversion? Assume f is too complicated for the compiler to figure this out on its own.


问:
AWS upload a file to a specific user using s3 bucket
Hi StackOverFlow community,

I have no code to show for this question and I am missing alot of knowledge around AWS so i don't even know what to search or look for.

Here is what i want to achieve

Use Case:

User Signs up

Goes to his/her account.

Uploads a new profile picture.

Traditional Web Server

You would upload the file with the id of the user. (from previous request or session)

That way you can generate a name for the file, store it somewhere and reference that in the Database. How ever you decide. At the end the newly uploaded image, src path is in the Db and linked to the user.

I am trying to achieve the same thing on AWS.

These are the things that i think i understand.

S3 is used to store binary/static content
AWs Cognito is used to authenticate users and (I'm am not very confident here) is the equivalent of sessions.
Lambda is a web services that only accepts JSON.

How am I suppose to use those tools to achieve the desired effect.

I don't have code to try and if someone can point me in the direction of an example i would happily attempt and then return here if i have any futher questions.
I am just not sure if i have the right idea, am i on the right track. I keep searching but i can't find an example that could fulfill that use case.

Thanks in advance.

答:
You need to write a web application (just like with traditional web servers). Your web application can then use AWS services.

User Signs Up

The users would connect to your web application and perform whatever sign-up process you wish to implement. The authentication and user store could be done with Amazon Cognito, or your own application logic and a database.

Goes to their account

Again, this is a user navigating around your web application.

Uploads a profile picture

They would be uploading to your web application. Your application can then store this picture in an Amazon S3 bucket. It is also possible to code a web page to upload directly to Amazon S3, but your web application would have to create the dynamic code behind the page to make this possible.

General comments

All of the above tasks are exactly the same as with non-AWS solutions. However, you can take advantage of various AWS services to assist, such as Cognito and S3.

You could go one step further and write totally serverless applications by using AWS Lambda and AWS API Gateway, but that's a more difficult step to take.


问:
How to Use array[i] in for loop
I am trying to search for a value in an array. Does the array need a definative number? How would I search for the number? Thanks for helping!</p>

```<code>#include <stdio.h>
#include <conio.h>
#include <iostream>
#include "windows.h"

using namespace std;
int main() {
    int userinput;

    int arrayofnumber[10] = { 5, 3, 77, 43, 6, 22, 7, 9, 84, 26 };

    int NumberInArray = sizeof(arrayofnumber) / sizeof(arrayofnumber[0]);

    cout << "What Number Would You Like To Search For? \n";
    cout << "Number of Values in Array = " << NumberInArray << endl;
    cin >> userinput;

    for (int i = 0; i >= NumberInArray; i++) {

        if (userinput == NumberInArray[i]) {
            cout << "We Found IT! It = " << NumberInArray[i] << endl;
        }

    }

    return 0;
}
</code>```

答:
```<code>for (int i = 0; i < NumberInArray; i++) {
    if (userinput == arrayofnumber[i]) {
        cout << "We Found IT! It = " << arrayofnumber[i] << endl;
        break;
    }
}
</code>```

Your for loop condition i >= NumberInArray is wrong. It should be i < NumberInArray.

NumberInArray[i] is illegal. You should do arrayofnumber[i].

Added break so that when the number is found, you can get out of the loop.

Title: How to Use array[i] in for loop

Body:
I am trying to search for a value in an array. Does the array need a definative number? How would I search for the number? Thanks for helping!

#include <stdio.h>
#include <conio.h>
#include <iostream>
#include "windows.h"

using namespace std;
int main() {
    int userinput;

    int arrayofnumber[10] = { 5, 3, 77, 43, 6, 22, 7, 9, 84, 26 };

    int NumberInArray = sizeof(arrayofnumber) / sizeof(arrayofnumber[0]);

    cout << "What Number Would You Like To Search For? \n";
    cout << "Number of Values in Array = " << NumberInArray << endl;
    cin >> userinput;

    for (int i = 0; i >= NumberInArray; i++) {

        if (userinput == NumberInArray[i]) {
            cout << "We Found IT! It = " << NumberInArray[i] << endl;
        }

    }

    return 0;
}

Body:
for (int i = 0; i < NumberInArray; i++) {
    if (userinput == arrayofnumber[i]) {
        cout << "We Found IT! It = " << arrayofnumber[i] << endl;
        break;
    }
}

Your for loop condition i >= NumberInArray is wrong. It should be i < NumberInArray.

NumberInArray[i] is illegal. You should do arrayofnumber[i].

Added break so that when the number is found, you can get out of the loop.